smrth

2048.py

A beautifully typed, Pure-Python Engine for 2048 🎮

CLI • Python

A beautifully typed, Pure-Python Engine for 2048 🎮

Why I Made 2048.py

After playing several 2048 games on various sites online, I couldn't help but notice that the vast majority of them seemed too easy. I later narrowed this down to being a result of tile generation: the value of generated tiles was proportional to those around it. As you progressed in any given game, your average tile increased and thus, generated tiles became higher which makes the game easier. Thanks to Bhargavi Goel's 2017 paper on the mathematics behind 2048, I was able to find that the original game allowed for only 2's and 4's to be generated - regardless of the other tiles on the board. After playing this version, I was shocked at how difficult the game could be. And thus, in my quest to create an algorithm to beat it, I realised that I would need an engine to do so.

Installation

2048.py is available on PyPI as Py2048-Engine. It can be installed with pip:

pip3 install Py2048-Engine

The project is also open sourced on GitHub at 2048.py.

What I Learned

This project was a great opportunity for me to implement a lot of the best-practices I learned. I used Python's Typing module to add Types for every variable, function, and object. Though I loosely used this module in the past, this was the first time I used some of its more powerful components, such as hinting for 2D arrays (which my game board was represented as).

Aditionally, I added full docstrings to all my methods and classes, which works with the type hints to provide a seamless development experience.

This project also demonstrates some of my best designed Exception structures. There's a perfect balance of readability and simplicity. A user simply catches a GameException and can then classify it (due to inheritance structures) as a GameWonException or GameLostException. The base class ships all the useful information you might need, like the final board, number of moves taken, and an exit message.

Extras

The well-typed nature of the project translated beautifully when working with @http-samc/GenDoc, you can check out the completely autogenerated documentation here.

To do some 'research' and prove that the engine works, I played a whole game (nearly 1000 moves) with the built in runTest function and logged my terminal output here.