forked from ericclack/pygamezero_candy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcandy4.py
97 lines (81 loc) · 2.46 KB
/
candy4.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import random
# The size of the board in tiles
TILESW = 20
TILESH = 14
# The pixel size of the screen
WIDTH = TILESW * 40
HEIGHT = (TILESH+1) * 40
# How likely is a new tile each tick?
NEW_TILE_PROB = 0.9
TITLE = 'Candy Crush'
last_dt = 0
cursor = Actor('selected', topleft=(0,0))
score = 0
def random_tile():
tiles = [1,2,3,4,5,6,7,8]
return random.choice(tiles + tiles + [9])
board = []
for row in range(TILESH):
# Make a list of 10 random tiles
tiles = [random_tile() for _ in range(TILESW)]
board.append(tiles)
def draw():
screen.clear()
for y in range(TILESH):
for x in range(TILESW):
tile = board[y][x]
if tile:
screen.blit(str(tile), (x * 40, y * 40))
cursor.draw()
screen.draw.text("Score: %s" % score, bottomleft=(0,HEIGHT), fontsize=60)
def cursor_tile_pos():
return (int(cursor.x // 40)-1, int(cursor.y // 40))
def drop_tiles(x,y):
# Loop backwards through the rows from x,y to the top
for row in range(y,0,-1):
# Copy the tile above down
board[row][x] = board[row-1][x]
# Finally blank the tile at the top
board[0][x] = None
def check_matches():
global score
for y in range(TILESH):
for x in range(TILESW-2):
if board[y][x] == board[y][x+1] == board[y][x+2]:
if board[y][x] == 9:
for x2 in range(TILESW):
board[y][x2] = None
else:
board[y][x] = None
board[y][x+1] = None
board[y][x+2] = None
score += 50
def check_gaps():
# Work from the bottom up
for y in range(TILESH-1,-1,-1):
for x in range(TILESW):
if board[y][x] is None:
drop_tiles(x,y)
def on_key_up(key):
global score
x, y = cursor_tile_pos()
if key == keys.LEFT and x > 0:
cursor.x -= 40
if key == keys.RIGHT and x < TILESW-2:
cursor.x += 40
if key == keys.UP and y > 0:
cursor.y -= 40
if key == keys.DOWN and y < TILESH-1:
cursor.y += 40
if key == keys.SPACE:
score += -1
board[y][x], board[y][x+1] = board[y][x+1], board[y][x]
def add_new_tiles():
for x in range(TILESW):
if board[0][x] is None and random.random() < NEW_TILE_PROB:
board[0][x] = random.randint(1,8)
def every_second():
check_matches()
check_gaps()
add_new_tiles()
clock.schedule_interval(every_second, 0.25)