Java 2048 and java2048

Source: Internet
Author: User

Java 2048 and java2048

Functional requirements: 2048 basic interface, capable of achieving 2048 of game functions.

General idea: two classes: Game and GameListener.

Game is responsible for implementing the interface and rewriting the painting method.

GameListener handles keyboard and mouse events. The moving method, adding method, winning/losing judgment, and the appearance of random numbers must be implemented in the keyboard listening method.

Implementation Analysis: To achieve 2048 games, first consider what 2048 games have?

Interface implementation:

The 2048 game interface is very simple, that is, some squares and numbers. To implement this interface, we can consider using Java's plotting function. Specifically, the Graphics object provided by the JFrame class is used for drawing. The 2048 interface consists of a large rectangular background and many small squares containing numbers. The method of drawing a rectangle of a Graphics object can be used to draw a background and a small square. The number in the small square can be drawn using the drawString method of graphics. You only need to pay attention to the color when drawing. The main class to be supported by interface implementation is the JFrame class.

The basic interface implementation code is nothing to say, but there are some buttons and so on.

Private void initUI () {setTitle ("2048"); setdefaclocloseoperation (3); setSize (600,700); setLocationRelativeTo (null); this. setLayout (null); // Add the score jl2 = new JLabel ("score: 0"); jl2.setFont (new Font ("", Font. BOLD, 30); jl2.setBounds (20, 30,200, 50); this. add (jl2); // add the start button ImageIcon start = new ImageIcon ("res/start.png"); // start the game icon and replace it with startJB = new JButton (start ); startJB. setBounds (280, 40,120, 30); startJB. setFocusable (false); startJB. setBorderPainted (false); // The border of the set button is blank startJB. setFocusPainted (false); startJB. setContentAreaFilled (false); // set the fill color in the border of the button. // Add the backstep button ImageIcon back = new ImageIcon ("res/backicon.png"); // The game end icon, just replace it with backJB = new JButton (back); backJB. setBounds (430, 40,120, 30); backJB. setFocusable (false); backJB. setBorderPainted (false); backJB. setFocusPainted (false); backJB. setContentAreaFilled (false); this. add (startJB); this. add (backJB); setVisible (true); GameListener gl = new GameListener (this, arry, jl2, startJB, backJB); addKeyListener (gl); startJB. addActionListener (gl); backJB. addActionListener (gl );}

Draw squares and numbers:

The drawing of squares and numbers is also based on the drawing of rectangles of the canvas object of JFrame.

Public void buffPaint (Graphics g) {Image image = createImage (600,600); Graphics g2 = image. getGraphics (); g2.setColor (Color. LIGHT_GRAY); Graphics2D g2d = (Graphics2D) g2; g2d. setRenderingHint (RenderingHints. KEY_ANTIALIASING, RenderingHints. VALUE_ANTIALIAS_ON); g2.fillRoundRect (0, 0, Draw2048.RD, Draw2048.RD, 20, 20); g2.setColor (Color. GRAY); for (int r = 0; r <arry. length; r ++) {for (int c = 0; C <arry [r]. length; c ++) {g2.fillRect (20 + c * (Draw2048.D + Draw2048.space), 20 + r * (Draw2048.D + Draw2048.space), Draw2048.D, callback );}} for (int r = 0; r <arry. length; r ++) {for (int c = 0; c <arry [r]. length; c ++) {if (arry [r] [c]! = 0) {g2.setColor (255,250,240); g2.fillRect (20 + c * (Draw2048.D + Draw2048.space), 20 + r * (Draw2048.D + Draw2048.space), Draw2048.D, callback ); g2.setColor (new Color (0,191,255); g2.setFont (new Font ("", Font. BOLD, Draw2048.FSIZE); g2.drawString (arry [r] [c] + "", 50 + c * (Draw2048.D + Draw2048.space ), 90 + r * (Draw2048.D + Draw2048.space) ;}} g. fig (image, 50,150, this );}
Draw2048 is an interface that defines constants related to square drawing, D square side length, and space square interval. The side length of the large rectangle in the RD background. The advantage of using interfaces is that you can easily implement interface changes (such as changing to a 5*5 grid) and improve program scalability. In addition, the interface needs to be constantly updated, so you need to call the paint method to repaint continuously. If you directly write the painting here in the paint method, the constant re-painting will makeThe interface is flashing all the time.. HereThe solution is to use image buffering.First, draw the image in the image, and draw the image at one time, so that the interface will not flash.

Mobile implementation:

To move the square, you can use the redrawing of the canvas. The number in the square is saved using a two-dimensional array. Each movement changes the value of the array, and then draws the data to the interface based on the value of the array. Of course, you cannot rely on your mind to control the game. We need an input device, that is, a keyboard. Therefore, you need to add a keyboard listener to the interface. Different mobile algorithms are implemented when you press different keys. It is worth noting that it should be clarified when compiling the corresponding mobile algorithm in the listener class.Loop usage and termination (especially the use of break statements)Otherwise, various bugs may occur. The keyListener class is required for mobile implementation.

The following is the implementation of upward movement. The movement in other directions is similar. Just think about it yourself:

// Upward movement algorithm
For (int r = 0; r <arry. length; r ++) for (int c = 0; c <arry [r]. length; c ++) {if (arry [r] [c]> max) // returns the maximum value of the array, used to determine whether the player's square reaches 2048 max = arry [r] [c]; if (arry [r] [c] = 0) {for (int r1 = r + 1; r1 <arry [c]. length; r1 ++) if (arry [r1] [c]! = 0) {arry [r] [c] = arry [r1] [c]; arry [r1] [c] = 0; count ++; // determines whether a movement has occurred and serves as one of the criteria for winning or losing the result, break ;}}}

Loop every value through a double loop. If it is 0, it can move up. Traverse the column where the value is located, locate the first value not 0, and move the value (that is, the value of two numbers ). After moving, exit the inner loop and traverse the next value.

Number addition:

Use an independent algorithm to traverse the array, add two adjacent numbers in the moving direction, and set the value to 0. The algorithm implementation here is very similar to the moving algorithm,Note that break and loop are also used.. Note that the addition of numbers must be completed before the numbers are moved. Otherwise, a space is displayed after the numbers are moved.

 

// Add algorithms to the left
For (int r = 0; r <arry. length; r ++) for (int c = 0; c <arry [r]. length; c ++) if (arry [r] [c]! = 0) for (int c1 = c + 1; c1 <arry [r]. length; c1 ++) if (arry [r] [c] = arry [r] [c1]) {arry [r] [c] * = 2; score + = arry [r] [c]; arry [r] [c1] = 0; count ++; // you can determine whether a sum is added and is used as one of the conditions for determining whether to win or lose. Break;} else if (arry [r] [c1]! = 0) {break ;}

It also traverses every value of the array. If this value is not 0, findAdjacent identicalEnd the inmost loop by adding the values. IfTwo Adjacent values are different,Also ends the innermost loop. The use of two break statements avoids the Skip addition between numbers.

Winning or losing judgment:

The rule for winning 2048 is that the sum of the numbers is 2048, so you only need to judge whether there is a number in the array equal to 2048. If yes, the corresponding winning information will be output.

The 2048 drop rule is that the interface is full (the array is full, and there is no movement, adding numbers ). The personal judgment method is to add the global variable count and determine whether the array is full. If the value of count is equal to 0, it indicates that the player cannot be moved or added. When the array is full, it can be judged that the player has already lost.

The emergence of random numbers:

A random number is moved or added, so count is used for determination. When the condition is true, the corresponding algorithm is called for implementation.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.