Tuesday, July 15, 2014

2048 AI Implementation in C#

Background

There have been many AI implementation for the 2048 game, but very few of them are in C#. In my version of the AI, Windows Forms is used as the platform. The game board is rendered using GDI+. I did not make the game and AI from scratch, so I'd like to give credit for the code base of the basic game play to BioPhysEngr, while the heuristics have been borrowed from Nicola Pezzotti's post.

While the interface isn't very fancy as there is no score or undo button, you can play around with which AI algorithm is used and how deep to for the recursion to process each move decision.

Implemented Algorithms
  • Minimax - slowest performing algorithm.
  • Minimax with Alpha-Beta Pruning - noticeably faster than regular minimax, but still not good at reaching 2048 tile.
  • Expectimax -  best performing in terms of speed and achieving the 2048 tile. 
Rating Heuristics

All of the algorithms depend on some sort of heuristic to measure the value of the game board. I have decided to use a path technique as described by Nicola. The idea is to keep the tiles in decreasing order in an winding "S" line, both vertically and horizontally:
This is the only heuristic used other than zero moves means worst possible score is given. If you would like to improve this algorithm, simply edit the rate() method. The source code can be found here.

Interface



The interface allows you to play around with the depth of the AI algorithm and implementation. You can either let AI run the game by clicking "Start AI" button or you can play manually using the arrow keys on your keyboard. When you play manually the AI score is computed for each possible move. This way you can test out how "smart" the AI is and if it makes any sense.

2 comments: