Afternoon app – 2048
You may or may have not heard about a popular new game called 2048.
We have some very exciting new work in our development builds, a new source code editor, which I wanted to exercise.
Around the same time, I saw the article linked above about the game 2048. It is a simple four by four grid with numbers that you slide around, trying to add them up to …… 2048!
I downloaded a free version of 2048 onto my iPhone, and there is also browser based version here. I checked it out and it looked pretty interesting, so I decided to implement a simple version of it as an “afternoon app”. An Afternoon app is a simple time-boxed implementation. Since Smalltalk lets you do a lot in a short amount of time, it is a great choice.
I built it and published it on the public repository. You can find it as TwentyFortyEight.
It is an MVC designed app with these three classes.
I reverse engineered it by observation. I tried a couple simple ways to process the moves, then refined them. My #process: method takes an array of the four items in a row or column, and looks like this:
“process an array of the grid”
self compress: array.
self combine: array.
self compress: array.
#compress: slides the elements down to the far end of the array.
#combine: adds adjacent cells of the same number, one pass
The second compress is required in situations where there are two combines in the one pass.
Since you can move four directions, up, down, left, right, it gives #process the row or column for right, down respectively. For left and up it reverses the array for #process, and then flips it back for integration into the grid.
I made an assumption which turned out to process incorrectly in some circumstances. Rather than fix it, I left it as a challenge to find (not too hard, not to trivial) and change for those who want to tinker with the application. There is another needed fix (hint: the new value that appears) which is a very easy fix.
How can the implementation be improved? Other than the needed fix mentioned above, the application does not detect when the game is over, or allow you to restart it. These are easy fixes.
Another relatively easy improvement would be to add the running score. When numbers are combined, their value can be added to the score tally.
A big improvement that would take some more time would be to add animation. This would probably require model restructuring or changes to communicate in terms of the moves in order for the view to animate them. Visually, adding animation would be a big improvement. I welcome any developers to give it a try and share their results. I may give it a shot myself.
What else could you do? You could try using different algorithms for auto-playing the game, in order to discover or test heuristics in order to maximize your score.
If you have any more ideas or any questions, I would be happy to hear from you. Reach me at the email below.
Best Regards and happy Smalltalking!
Cincom Smalltalk Product Manager