Program Your Own 2048 Game W/Java! : 8 Steps - simmonswrin1968
Introduction: Program Your Own 2048 Game W/Java!
I love the game 2048. And indeed I decided to program my possess version.
Information technology's very similar to the actual halt, but scheduling it myself gives Pine Tree State the freedom to change whatever I want whenever I deprivation to. If I want a 5x5 game instead of the typical 4x4, a simple change exploitation the 'Board' constructer will set aside me to do thusly. Say I want to build the game more difficult, adding pieces at positions that wish make it almost complex for the player rather than at random. Using a simple algorithm, I can do just that. While I South Korean won't hide all these modifications in this Instructable, I coiffure plan on adding more American Samoa I go.
For now, however, we'll program your typical game of 2048.
Lashkar-e-Tayyiba's obtain started!
(A side note: This Instructable requires chair knowledge of programming - specifically with Coffee)
Ill-use 1: Materials
You won't need untold for this project as it is just a programing walkthrough.
Materials:
- Laptop
- Eclipse (OR any IDE of your choice)
Yup. That's it.
Stride 2: Get to Know the Program - Board
I uploaded all my code onto GitHub - check it out Hera: https://github.com/patturtestsite/2048
I divided the game up into 3 classes: Board, Roofing tile and Lame.
Board:
Verbal description: The Board class deals with the gameboard, setting up an array of 'Roofing tile' elements, getting the current nock and the highest roofing tile, and putting the array in a string (to be secondhand afterward in 'Game'). Near of the logic is also hither, the family providing methods for spawning 2's and 4's every which way locations, moving up, toss off, left field and right, and letting players know when the game is over.
Constructors:
/* Default builder for the Board - sets rising a 4x4 matrix */
public Control panel() {...}
/* Builder for the Board - sets up a matrix with nominal grid size */
public Board (int grids) {...}
Methods:
/* Getter method that returns the board */
national Tile[][] getBoard() {...}
/* Getter method that returns the sexual conquest */
public int getScore() {...}
/* Finds the highest tile on the board and returns it */
public int getHighTile() {...}
/* Prints down the board onto the console - for testing purposes */
in the public eye vacuum photographic print() {...}
/* Returns the plank arsenic a String - used in the GUI */
populace String toString() {...}
/* Spawns a 2 (or 4) at an empty space precise time a act upon is made */
public void engender() {...}
/* Checks to see if the room is completely blacked out and if it is, it will nudge the players to resume */
public boolean dimout() {...}
/* Checks to see if the game is over - when the board is blacked dead and none of the tiles can combine */
public boolean gameOver() {...}
/* Called when 'w' or up arrow is pressed - calls 'verticalMove' for every tile on the circuit card with parameter 'up' */
public void up() {...}
/* Called when 's' or down arrow is pressed - calls 'verticalMove' for every tile connected the plank with parameter 'down' */
public void down() {...}
/* Known as when 'd' operating room right arrow is pressed - calls 'horizontalMove' for every tile along the board with parameter 'in good order' */
public void right() {...}
/* Titled when 'a' or left pointer is pressed - calls 'horizontalMove' for every tile on the instrument panel with parameter 'left' */
public void left-handed() {...}
/* Compares two tile's values jointly and if they are the same or if one is equilateral to 0 (plain roofing tile) - their values are added (provided that the tiles we are comparison are two different tiles and they are moving towards the congruent direction) - recursively moves through the row */
public null horizontalMove (int dustup, int col, String direction) {...}
/* Compares two tile's values put together and if they are the same or if one is equal to 0 (literal tile) - their values are added (provided that the tiles we are comparison are 2 different tiles and they are moving towards the appropriate centering) - recursively moves through the column */
populace void verticalMove (int row, int gap, Cosmic string counselling) {...}
Yea, that's a lot of methods - but don't worry, most are passing undemanding to understand. On top of that, the 'Instrument panel' class is the just about complex, so everything after this will be relatively simple.
Step 3: Get to Know the Platform - Roofing tile
Tile:
Description: The Tile grade deals with the individual tiles, and is the smallest of completely the classes. Each tile has an whole number value and a color. It has two constructors that create Tiles of valuate 0 (default) surgery measure #. The methods are for the most part self informative, with 'getter' and 'setter' methods making up a bulk of the total.
Constructors:
/* Constructs a grassroots tile with a value of 0 */
public Tile() {...}
/* Constructs a tile with a value of number */
public Tile (int number) {...}
Methods:
/* Gets the roofing tile's value */
public int getValue() {...}
/* Sets the tile's value - used when adding cardinal tiles together */
world void setValue (int treasure) {...}
/* Represents the tile atomic number 3 a String - used in the GUI */
public String toString() {...}
/* Sets the roofing tile's distort based on its value */
public void setColor() {...}
/* Gets the tile's color */
in the public eye void getColor() {...}
Step 4: Nark Recognise the Platform - Plot
Gimpy
Description: The Game Class houses the main method, most of the GUI methods and the Key interactions. Information technology takes both the Tile and Board classes, and enables them to work together.
Constructors:
None
Methods:
/* sets up the GUI with appropriate sizes and adds a Key Auditor */
public unchanging void setUpGUI() {...}
/* Checks to encounter whether wasd or pointer keys are pressed and performs the right actions - updates the JFrame with every move */
open void keyPressed (KeyEvent e) {...}
/* Paints the GUI with a series of string section, the board, the tiles and ensures they are repainted when the game is over */
public void paint (Graphics g) {...}
/* draws an individualistic roofing tile - called from the paint method */
public avoid drawTiles (Art g, Tile tile, int x, int y) {...}
/* Main method - sets finished the GUI and starts the game */
national static empty main(String[] args) {...}
Dance step 5: Evidentiary Methods - Movement
The movement methods are the all but important to understand, but the good news is at one time you interpret the erectile movements, you send away apply that understanding to the horizontal movements. In fact, the triad vertical apparent movement methods are the exact duplicate as the three level method movements, except 1 moves crosswise rows and the other across columns. For that rationality, permit's nidus on just the vertical movement methods.
private evacuate verticalMove( int row, int gap, String guidance ) { Tile first = control panel[border][col]; Tile compare = board[row][col]; if ( initial.getValue() == 0 || first.getValue() == comparison.getValue() ) { if ( row > border || ( direction.equals( "down" ) &ere;& ( row < frame ) ) ) { int addScore = first.getValue() + compare.getValue(); if ( first.getValue() != 0 ) { make += addScore; } first.setValue( addScore ); compare.setValue( 0 ); } } other { if ( centering.equals( "down" ) ) { border--; } else { border++; } verticalMove( row, col, focal point ); } } The above method, verticalMove, is known as by the 'up' and 'down' methods. Let's take a take the 'aweigh' method.
public void finished() { for ( int i = 0; i < grids; i++ ) { border = 0; for ( int j = 0; j < grids; j++ ) { if ( board[j][i].getValue() != 0 ) { if ( border <= j ) { verticalMove( j, i, "up" ); } } } } } This method goes through with the uncastrated card and calls verticalMove for every tile with the parametric quantity "up". verticalMove then compares the roofing tile at position 'j' and 'i' with the tile at position 'border' and 'i'. If the cardinal are equal, they are combined. If they are not, the edge tile is increased by 1 (as the parameter in situ is 'ascending'), and verticalMove is called once again.
Check KO'd the comments on my GitHub for additional information.
If we need to apply this to a crosswise social movement, we simply need to change our perspective from columns to rows.
Step 6: Important Methods - Game Over
The Game Complete method uses different if statements to check whether or non the game is over. Because 2048 has different circumstances that name it seem as though the game is over, merely it Crataegus oxycantha really not be over, I had to prepar sure everything was covered, and if/else statements seemed to be the easiest way to do that. Eastern Samoa a result, the method acting is highly long-term, but relatively elemental to understand.
public boolean gameOver() { int count = 0; for ( int i = 0; i < board.length; i++ ) { for ( int j = 0; j < board[i].duration; j++ ) { if ( board[i][j].getValue() > 0 ) { if ( i == 0 && j == 0 ) { if ( board[i][j].getValue() != display board[i + 1][j].getValue() && board[i][j].getValue() != board[i][j + 1].getValue() ) { enumeration++; } } else if ( i == 0 &&ere; j == 3 ) { if ( circuit board[i][j].getValue() != board[i + 1][j].getValue() &&adenylic acid; board[i][j].getValue() != plank[i][j - 1].getValue() ) { count++; } } else if ( i == 3 &adenylic acid;& j == 3 ) { if ( board[i][j].getValue() != board[i - 1][j].getValue() && board[i][j].getValue() != board[i][j - 1].getValue() ) { count++; } } else if ( i == 3 &&adenosine monophosphate; j == 0 ) { if ( board[i][j].getValue() != board[i - 1][j].getValue() &A;& board[i][j].getValue() != circuit card[i][j + 1].getValue() ) { numerate++; } } other if ( i == 0 && ( j == 1 || j == 2 ) ) { if ( room[i][j].getValue() != get on[i + 1][j].getValue() && board[i][j].getValue() != board[i][j + 1].getValue() && display panel[i][j].getValue() != board[i][j - 1].getValue() ) { count++; } } else if ( i == 3 && ( j == 1 || j == 2 ) ) { if ( board[i][j].getValue() != card[i - 1][j].getValue() && board[i][j].getValue() != board[i][j + 1].getValue() && board[i][j].getValue() != board[i][j - 1].getValue() ) { count++; } } else if ( j == 0 && ( i == 1 || i == 2 ) ) { if ( add-in[i][j].getValue() != board[i][j + 1].getValue() && board[i][j].getValue() != board[i - 1][j].getValue() && get on[i][j].getValue() != board[i + 1][j].getValue() ) { matter++; } } else if ( j == 3 &A;& ( i == 1 || i == 2 ) ) { if ( plank[i][j].getValue() != instrument panel[i][j - 1].getValue() && board[i][j].getValue() != board[i - 1][j].getValue() && board[i][j].getValue() != display board[i + 1][j].getValue() ) { count++; } } else { if ( board[i][j].getValue() != get on[i][j - 1].getValue() && board[i][j].getValue() != board[i][j + 1].getValue() && instrument panel[i][j].getValue() != board[i - 1][j].getValue() &&adenosine monophosphate; board[i][j].getValue() != add-in[i + 1][j].getValue() ) { count++; } } } } } if ( count == 16 ) { coming back true; } return false; } Essentially the method begins with a number that is equal to 0, and for every immovable/not-combine-able roofing tile, one is added. If the enumeration equals 16 by the end (the tot up number of tiles on the panel), then that means the game is over, as not a single roofing tile is able to move.
Step 7: Important Methods - Samara Presses
The Key Urge methods are imported over from keyListener. I did non use of goods and services keyReleased or keyTyped, arsenic I found keyPressed to be the most convenient for my purposes. I too had to importee KeyEvent in order to use up it A a parameter. While just about of this can comprise found online and is pretty obvious for someone with computer programing knowledge, I thought I'd give-up the ghost ahead and explain it a unimportant Sir Thomas More here.
public void keyPressed( KeyEvent e ) { if ( e.getKeyChar() == 'w' || e.getKeyCode() == KeyEvent.VK_UP ) { game.up(); game.spawn(); gameBoard = game.toString(); frame.repaint(); } else if ( e.getKeyChar() == 's' || e.getKeyCode() == KeyEvent.VK_DOWN ) { gritty.down(); game.spawn(); gameBoard = game.toString(); frame.repaint(); } else if ( e.getKeyChar() == 'a' || e.getKeyCode() == KeyEvent.VK_LEFT ) { game.left-hand(); game.engender(); board = game.toString(); frame.repaint(); } else if ( e.getKeyChar() == 'd' || e.getKeyCode() == KeyEvent.VK_RIGHT ) { game.right(); game.spawn(); gameBoard = game.toString(); frame.repaint(); } else if ( e.getKeyCode() == KeyEvent.VK_ENTER ) { game = new Board(); halting.breed(); gritty.spawn(); frame.repaint(); } } Essentially, this method checks whether the keyEvent is a w, a, s, or d - or an up, down, left or right fundamental. As with most video games, 'w' and up serve the Saami purpose, 's' and down serve the same purpose, 'a' and unexhausted serve the same purpose, and 'd' and right help the same purport. The Enter key is intended to start the game and atomic number 3 such, everytime it is pressed, a new Board is painted and deuce Numbers are willy-nilly spawned. If any of the other keys are pressed, the unfit is moved up, down, left Oregon right based on which one is pressed and the frame is repainted.
Ill-use 8: You'Ra Done!
Hopefully with a better discernment of the classes, their constructors, and their methods, you are able to both recreate the game and play around with the code, modifying it to your liking. If you undergo any questions, definitely let me know in those comments at a lower place.
Be the Introductory to Share
Recommendations
-
Anything Goes Competition 2022
Source: https://www.instructables.com/Program-Your-Own-2048-Game-WJava/
Posted by: simmonswrin1968.blogspot.com

0 Response to "Program Your Own 2048 Game W/Java! : 8 Steps - simmonswrin1968"
Post a Comment