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:
Find all cells that are currently empty.
Pick a random one from those found in step 1.
Create a new tile at the position determined in step 2.
Add it to the internal grid (
Board.b
), and to the board widget itself (usingadd_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, *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 size=self.cell_size...