Skip to main content

2048 AI

Expectimax agent consistently reaching 4096 and 8192 tiles, with custom Java Swing interface for interactive play and heuristic tuning.

Overview

For my final project in CIS 1200, I decided to build the 2048 game in Java Swing. But beyond creating the basic UI and tile merging logic, I decided to take it a step further by implementing something I had read about: the Expectimax algorithm.

The expectimax algorithm finds the most optimal move by picking the move that maximizes an expected heuristic to a certain depth. Since it is optimal for tiles of large values to be close to each other and the largest tiles to be near the borders or at the corners, the heuristic is higher when these are all true on the board. When calculating the heuristic at a certain depth, the algorithm calculates all possible outcomes for what value tile appears at which position after each step, before recursively applying the function to maximize the expected heuristic until the final depth is reached.

Current Board StateMAX: Evaluate All MovesUp | Down | Left | RightCHANCE: Random Tile SpawnAll possible positions & values (2 or 4)Recursive EvaluationCalculate heuristic for each outcomeContinue to depth 5Expected ValueWeighted average across all spawn outcomesSelect Optimal MoveExecute Move

The video below is a demo of the Expectimax-based agent choosing the most optimal moves under uncertainty, to a depth of 5.

With tuned heuristics, the agent consistently reaches 4096 and often 8192 tiles.

Key Languages, Platforms, and Frameworks Used

Java

Swing