Book Image

Kivy Blueprints

Book Image

Kivy Blueprints

Overview of this book

Table of Contents (17 chapters)
Kivy Blueprints
About the Author
About the Reviewers
The Python Ecosystem

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, a method of class Board:
def new_tile(self, *args):
    empty_cells = [(x, y) for x, y in all_cells()  # Step 1
                   if self.b[x][y] is None]

    x, y = random.choice(empty_cells)  # Step 2
    tile = Tile(pos=self.cell_pos(x, y),  # Step 3