Create 2048 Game with Javascript for Browser

Erdoğan Bavaş
2 min readJul 28, 2020

Play this game on https://erdoganb.com/game/2048

In this post, I will try to describe how to make a very simple version of the 2048 game. You can find the codes of the project here and watch speed code video above.

I think this kind of small games are very useful as software practice. 2048 is a mobile game created by Italian developer Gabriele Cirulli and has become very popular. The aim is to combine the numbers on the squares to prevent the squares from filling.

We start with HTML as usual. We have a wrapper div, a grid div and 16 cells as squares of our game. We will also have an element that is not here, but we will use for numbers with the number class we will add with Javascript.

CSS side is too short. Here we have achieved a compatible structure for each screen dimensions using vmin. By using cell:nth-child(4n+1) we give left margin to the first and every 5th cell class named element with the same parent.

We came to the Javascript section. Here we will create a more aggregated structure using the modules. Our main javascript file is 2048. and we start our grid and game using the init method of the grid module. Then we listen to the keyup event and run the slide method when the arrow keys are pressed.

We also create the necessary values in our grid.js file. We check that the game is active with a variable called playable. In the directionRoots array, we keep the indexes of the squares on the slide direction edge. Then, when slide happens, we use these indices to check the squares and number if they have opposite to the slide direction.

In our number.js file, we do the sliding and merging numbers. We give the top, left values of the cell to number to move. With the transition value we provide with CSS, this move does not happen as jump, but an animation.

--

--