In the fad game 2048, you press arrow keys to move tiles across a board in one of four possible directions. Let’s explore an algorithm for accomplishing this.
Note: Throughout this exploration, we will only ever be considering a single column. This is because in a true 2048 board with 4 columns, each column is independent from the rest when it comes to merging tiles upward.
What happens when we press the UP arrow in the game 2048? The tiles should move up until they either can’t move anymore, or until they join. Here’s an example of a merging a column:
It turns out that we can split the 2048 Merge into three parts: A move-up, a join-up, and another move-up. What do move-up and join-up mean?
Move-up is an procedure that moves each tile in a column up as far as it can go. If a tile hits the edge, it must stop. If a tile hits another tile, it must stop. No joining involved. Let’s do that step on the first example:
This is the move-up procedure. We can envision writing this procedure by looping through the column spaces from top to bottom; if we encounter a tile, we move it up a certain number of blank spaces.
When does joining come to play in our algorithm? This brings us to the Join-up step.
In the join-up step, each tile is merged into the tile above it, if the tile above it is of same value. It is important to note that when a tile joins up, it leaves an empty space where it used to be.
Let’s see what that looks like after completing the previous move-up step:
Notice that the 8 didn’t move. That’s because when it was time for the 8 to try to join up, the space above it was empty. Tiles only join up in this step if the tile above is of the same value, so the 8 doesn’t do anything.
At the beginning, we mentioned that the 2048 merge can be split into three parts: move-up, a join-up, and another move-up. We’ve done the first move-up and the join-up, so all there’s left to do is a second move-up. Let’s show that on the example we’ve been using:
After the second move-up step, we have reached the goal of merging the original column up! When writing a merge-column function, we could break it into three smaller functions in order: one that does the move-up step, one that does the join-up step, and then the move-up function again.
We have all of the parts of a perfectly fine 2048 Merging algorithm. These simple rules are all it takes to power an addicting and popular game. There are more things we could do: perhaps you may find it useful to keep track of whether or not a tile has been moved as a result of attempting a merge (this could be useful when deciding whether to add a new tile when implementing a full 2048 game).
There are many other ways to achieve the merge effect, and some solutions can get very clever and efficient. ◼