2048 Game
2048 in a linux command line.
In this Code I am going to be recreating the classicThe Rules
-
If 2 of the same numbers touch they will combine and add up to the value of both added together (e.g. if a 2 block touches another 2 block they will combine and become one 4 block).
-
You can use the 2 common layouts of cursor keys (arrow keys or wasd).
-
If there is no empty cells left with no valid moves then the game will end..
The Aim
The aim of the game is to get one of the tiles upto a score of 2048 by combining other tiles.
The functions in depth
Initilise Function
First we set a seed for our random number generator using the system time as the seed.
Then we set the gameOver
and the moved
variables to false to get it ready.
Then we use for loops in order to create the board.
Then run the generateRandomTile function to create the first tiles in the game.
Run Function
This just makes sure that if the game isnt over it prints the board out and starts looking for user input and if the game is over it prints an end message.
Generate Random Tile Function
We first check if there are any empty cells on the board.
If there are no empty cells then the game will end.
A random number generator will get a random number and devide it by the empty cells variable with the modulo operator then use the remainder of that operation + 1 and put this number in the randomIndex variable. We then use for loops to look through the grid while empty cells increments by one after every cell that isnt occupied and when the empty cells variable becomes the same as the random index it will pass to another if statement.
The final if statement will get a random number and divide it by 2 and the results should be limited to 0 or 1 we then add 1 to the result so that the only results should be 1 or 2 then we multiply that by 2 so that the only result that we should get is 2 or 4 this is then set to the index on the board and the function is exited.
Print Board Function
First we use linux system commands to clear the previous grid