Implementing the game logic

Now that we've built all the components required to make an implementation of the 2048 game, let's move on to more interesting things: spawning, moving, and combining tiles.

It's only logical that we begin with spawning new tiles in random empty cells. The algorithm for doing so is as follows:

  1. Find all cells that are currently empty.
  2. Pick a random one from those found in step 1.
  3. Create a new tile at the position determined in step 2.
  4. Add it to the internal grid (Board.b), and to the board widget itself (using add_widget()) for Kivy to render it.

The sequence of actions should be self-evident; the following Python implementation of this algorithm is also very straightforward:

# In main.py, a method of class Board: def new_tile(self, ...

Get Kivy Blueprints now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.