DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

15-square Game

06.26.2005
| 9660 views |
  • submit to reddit
        py_s60 1.1.3 was released a week ago.
I wonder why there's no more people playing with it.
So, I have created a simple game as an example.

I don't know what this game is called. It has 4x4 square box
with 15 pieces (1 piece missing). You need to move all the
pieces into sorting order.

Since the program is so simple, I decided to make the
moving of a piece smoother by moving it bit by bit.
Hope this doesn't make the code to hard to read.
from appuifw import *
from key_codes import *
import e32, random

# run and break-loop type of app
sleep = e32.ao_sleep
running = 1
def set_exit():
    global running
    running = 0
app.exit_key_handler= set_exit

# canvas and typical colors
c = Canvas()
app.body = c
red, green, blue, gray, white = 0xff0000, 0x00ff00, 0x0000ff, 0x777777, 0xffffff

# randomize number order for pieces
seq = range(1,17)
random.shuffle(seq)
b = [seq[0:4], seq[4:8], seq[8:12], seq[12:16]]

def piece(i, j, n):
    if n < 10:
        c.text( (12+20*i, 20+20*j), unicode(n))
    else:
        c.text( (7+20*i, 20+20*j), unicode(n))

def box(i, j, color, fill=None):
    c.rectangle( [5+20*i, 5+20*j, 25+20*i, 25+20*j], color, fill)

# draw board pieces
for k in range(16):
    j, i = divmod(k, 4)
    piece(i, j, b[j][i])

y, x = divmod(seq.index(16), 4)
box(x, y, white, white)
moving = 0     # cursor to lock if animating

# move cursor in dx, dy direction
def move(dx, dy):
    global x,y, moving
    if moving:
        return
    moving = 1
    if 0 <= x-dx < 4 and 0 <= y-dy < 4:
        b[y][x] = b[y-dy][x-dx]
        animate(x-dx, y-dy, dx, dy, b[y][x])
        x -= dx  # the hole move in opposite direction
        y -= dy
    moving = 0

# moving a piece for x,y to dx, dy direction
def animate(x, y, dx, dy, n):
    if n < 10:
        px = 12
    else:
        px = 7
    for i in range(5):
        c.text( (px+20*x + 4*i*dx, 20+20*y + 4*i*dy), unicode(n))
        sleep(0.05)
        c.text( (px+20*x + 4*i*dx, 20+20*y + 4*i*dy), unicode(n), white)
    c.text( [px+20*(x+dx), 20+20*(y+dy)], unicode(n) )

# bind arrow keys
c.bind(EKeyRightArrow,lambda:move(1, 0))
c.bind(EKeyLeftArrow,lambda:move(-1, 0))
c.bind(EKeyUpArrow,lambda:move(0, -1))
c.bind(EKeyDownArrow,lambda:move(0, 1))

# main loop, just wait
while running:
    sleep(0.1)    

Comments

Snippets Manager replied on Sat, 2006/02/18 - 4:53am

It's called Sam Loyd's fifteen-puzzle. See this page: http://www.cut-the-knot.org/pythagoras/fifteen.shtml Because of the way you do the random shuffle, half the time the puzzle is unsolvable!