This is an implementation of the "2048" game originally created by Gabriele Cirulli in a command line interface using C++. The game starts with a board of 4x4 squares, with two random squares containing a 2 or a 4 and the rest empty. At each turn, the player moves by sliding the tiles up, down, left, or right using the w, a, s, d keys. Adjacent tiles with identical values combine in the slide direction and a 2 or 4 appears in a random empty space. The objective is to continue to combine tiles until a value of 2048 is reached. The game is lost if the board becomes full and no more combinations are possible.
In addition to the base gameplay elements, the following features have been implemented:
- The user may reset the game at any point by inputting
q - The user may view a short gameplay explanation at any point by inputting
t - At the beginning of each game, the player will be prompted to watch an "AI" play the game.
- At the completion of a game, the player will be prompted to play again or exit the program.
- Turns are tracked on a per-game basis
- High scores are tracked on a per-session basis.
Code structure and functionality is as follows:
gameclass- Initialization function
- seeds random number generator, zeros board, and adds two tiles
gameBoardvariable- 4x4 integer array
zeroBoardfunction- resets
gameBoardto all zeros
- resets
addTilefunction- picks a random empty tile and adds a 2 or 4 to it, with 90% chance for 2
mergeLinefunction- used for all merge operations. Takes a vector of four tiles and merges them to the left. This is simpler than having separate logic for each direction.
movefunction- takes wasd char input
- properly transforms and inputs each line or column, depending on move direction from the
gameBoardvariable into themergeLinefunction - transforms the line or column back and saves it to the
gameBoardvariable - returns boolean whether the move affected the board
displayBoardfunction- displays the current board to the command line
printTutorialfunction- displays a summary of how the game works to the command line
hasWonfunction- returns boolean whether the player has won
highScorefunction- returns the integer value of the highest tile currently on the board
- Initialization function
mainfunction- Initializes a new instance of the
gameclass and variables to track user input, turns, etc - Prompts the player for AI mode vs normal mode
- Loops until the game is won, there are no valid moves, or the player quits:
- Prompts for input, or ai generates input
- uses the
game.movefunction to complete that input- If the move was valid, displays the board and moves to next turn, else prompts the user to try again indefinately
- Displays outcome (won vs ran out of moves)
- Prompts to restart the game
- Initializes a new instance of the