Project 0: 2048
An introductory project - get familiar with Java and the workflow of an assignment.
Prerequisites to running the code.
Instructions: https://fa22.datastructur.es/materials/proj/proj0/
Solution: https://github.com/tomthestrom/cs61b/tree/master/proj0/game2048
In this project I implemented the tile moving & merging functionality. I think the main goal of this project was just to get more familiar with writing Java and navigating a code base, most of the project had already been implemented, all that was left was a couple of methods.
Helper methods:
public static boolean emptySpaceExists(Board b)
public static boolean emptySpaceExists(Board b) This method should return true if any of the tiles in the given board are null. You should NOT modify the Board.java file in any way for this project. For this method, you’ll want to use the tile(int col, int row) and size() methods of the Board class. No other methods are necessary.
Solution:
/** Returns true if at least one space on the Board is empty.
* Empty spaces are stored as null.
*/
public static boolean emptySpaceExists(Board b) {
for (int i = 0; i < b.size(); i += 1) {
for (int j = 0; j < b.size(); j += 1) {
if (b.tile(i, j) == null) {
return true;
}
}
}
return false;
}public static boolean maxTileExists(Board b)
public static boolean maxTileExists(Board b) This method should return true if any of the tiles in the board are equal to the winning tile value 2048.
Solution:
public static boolean atLeastOneMoveExists(Board b)
public static boolean atLeastOneMoveExists(Board b)This method is more challenging. It should return true if there are any valid moves. By a “valid move”, we mean that if there is a button (UP, DOWN, LEFT, or RIGHT) that a user can press while playing 2048 that causes at least one tile to move, then such a keypress is considered a valid move.
There are two ways that there can be valid moves:
There is at least one empty space on the board.
There are two adjacent tiles with the same value.
Solution:
Main Task: Building the Game Logic
public void tilt(Side side)
public void tilt(Side side)The tilt method does the work of actually moving all the tiles around. For example, if we have the board given by:
And press up, tilt will modify the board instance variable so that the state of the game is now:
In addition to modifying the board, the score instance variable must be updated to reflect the total value of all tile merges (if any). For the example above, we merged two 4s into an 8, and two 2s into a 4, so the score should be incremented by 8 + 4 = 12.
All movements of tiles on the board must be completed using the move method provided by the Board class. All tiles of the board must be accessed using the tile method provided by the Board class. Due to some details in the GUI implementation, you should only call move on a given tile once per call to tilt. We’ll discuss this constraint further in the Tips section of this document.
Solution:
Last updated