Write a C++ program which allows the user to play the game 2048, See https://en.wikipedia.org/wiki/2048_(video_game)#Gameplay for the rules of the game. We use the following conventions.

  • The game is played on a 4 x 4 grid consisting of 16 tiles.
  • At the start, all tiles are empty and the program "spawns" two numbers on random tiles.
  • After each subsequent move, the program spawns one new number on an empty random tile.
  • When the program spawns a number (at any stage), it can only be a 2 or a 4. The probability that it spawns a 2 is 90% and for a 4 it is 10%.
  • The program should use keyboard input with "cin" and the screen output with "cout". An empty tile should be represented by "0".
  • To enter a move, the user enters 4 for "left", 8 for "up", 6 for "right", and 2 for "down". In this way, the keyboard number pad can be used to facilitate the input.
  • After the user has entered a move, all numbers on the grid slide as far as possible in the direction given by the user (until they hit another number or the border of the grid). If two equal number collide, they merge into one number with double the value. In one move, each number can contribute to at most one merger. For instance, the row 4, 2, 2, 0 becomes 4, 4, 0, 0 after a left move and not 8, 0, 0, 0.
  • A row 2, 2, 2, 0 becomes 0, 0, 2, 4 after a right move, and 2, 2, 2, 2 becomes 0, 0, 4, 4 after a right move. Similar situations are handled similarly. If it is not clear what the result of a certain move is, just try it out by playing the game (google "play 2048").
  • The game is won when a 2048 appears on the grid. The game is lost when there is no move any more that changes anything.

Figure1: Output of the C++ program during a game. see image.

Academic Honesty!
It is not our intention to break the school's academic policy. Posted solutions are meant to be used as a reference and should not be submitted as is. We are not held liable for any misuse of the solutions. Please see the frequently asked questions page for further questions and inquiries.
Kindly complete the form. Please provide a valid email address and we will get back to you within 24 hours. Payment is through PayPal, Buy me a Coffee or Cryptocurrency. We are a nonprofit organization however we need funds to keep this organization operating and to be able to complete our research and development projects.