Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Kivy Blueprints

You're reading from   Kivy Blueprints Build your very own app-store-ready, multi-touch games and applications with Kivy!

Arrow left icon
Product type Paperback
Published in Jan 2015
Publisher Packt
ISBN-13 9781783987849
Length 282 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
 Vasilkov Vasilkov
Author Profile Icon Vasilkov
Vasilkov
Arrow right icon
View More author details
Toc

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, *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...
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images