Soon after joining the 2048 craze, I was able to consistently reach the 2048 tile and was ready to begin my pursuit of the 4096 tile to truly prove my skill. However, I quickly grew tired of the tedious task of quickly and repeatedly selecting the right direction and got frustrated with my flawed mushy human brain slipping up. Having never done any kind of game A.I., I decided 2048 would be the perfect game to try my hand at it, so I downloaded the source code and got cracking.
I quickly noticed the fantastic readability of the code, which is always greatly appreciated when tinkering with someone else’s work. I found the spot in “keyboard_input_manager.js” where input from the player was taken in and added a few keys that could step through the A.I., enable/disable the A.I. to automatically play, and enable/disable messages for debugging and testing. Most of the work, of course, was spent in the function that determines the best direction each turn (with the addition of some helper functions in grid.js to help analyze the current state of the grid).
With a quick Google search, you can easily find some optimized A.I. for 2048 that uses a heuristic to mathematically find the best move possible. My goal instead was to try and implement my very human strategy in code form. When I got started, I found that the A.I. could get pretty far with some very simple rules. For example: Always go right if you can. If you can’t right, randomly choose between up or down. If you can’t go up or down either, go left. This surprisingly could consistently get you up to around 512 but would always lose there.
I then found that once I tried to make the A.I. smarter than that, the code required to do so quickly became more complex and verbose. For example: If the rightmost column is full, and the the right most column is sorted high to low from top to bottom, but the tile to the left of the bottom right tile is greater than the bottom right tile, then move up if possible (in order to unblock it). This was just single clause in a long if/else if/else if/else if statement. It also became harder to observe.
I learned that using a heuristic would undoubtedly be much more elegant than trying to emulate a human strategy in code form. Unfortunately, I wasn’t able to get a winning A.I. going, but I got pretty close, consistently getting to the 1024 tile. The code can be downloaded here. Press “X” to put it in auto-play mode.