/
petris.py
executable file
·551 lines (413 loc) · 20.1 KB
/
petris.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
#!/usr/bin/env python
import pygame
from pygame import Rect, Surface
import random
import math
import os
import kezmenu
from tetrominoes import list_of_tetrominoes
from tetrominoes import rotate, flip, Tetromino, X, O
from scores import load_score, write_score
class GameOver(Exception):
"""Exception used for its control flow properties"""
def get_sound(filename):
return pygame.mixer.Sound(os.path.join(os.path.dirname(__file__), "resources", filename))
BGCOLOR = (15, 15, 20)
BORDERCOLOR = (140, 140, 140)
BLOCKSIZE = 30
BORDERWIDTH = 10
MATRIS_OFFSET = 20
MATRIX_WIDTH = 14
MATRIX_HEIGHT = 25
LEFT_MARGIN = 340
WIDTH = MATRIX_WIDTH*BLOCKSIZE + BORDERWIDTH*2 + MATRIS_OFFSET*2 + LEFT_MARGIN
HEIGHT = (MATRIX_HEIGHT-2)*BLOCKSIZE + BORDERWIDTH*2 + MATRIS_OFFSET*2
TRICKY_CENTERX = WIDTH-(WIDTH-(MATRIS_OFFSET+BLOCKSIZE*MATRIX_WIDTH+BORDERWIDTH*2))/2
VISIBLE_MATRIX_HEIGHT = MATRIX_HEIGHT - 3
class Matris(object):
def __init__(self):
self.surface = screen.subsurface(Rect((MATRIS_OFFSET+BORDERWIDTH, MATRIS_OFFSET+BORDERWIDTH),
(MATRIX_WIDTH * BLOCKSIZE, (MATRIX_HEIGHT-2) * BLOCKSIZE)))
self.matrix = dict()
for y in range(MATRIX_HEIGHT):
for x in range(MATRIX_WIDTH):
self.matrix[(y,x)] = None
"""
`self.matrix` is the current state of the tetris board, that is, it records which squares are
currently occupied. It does not include the falling tetromino. The information relating to the
falling tetromino is managed by `self.set_tetrominoes` instead. When the falling tetromino "dies",
it will be placed in `self.matrix`.
"""
self.next_tetromino = Tetromino(color=(random.randint(0,255), random.randint(0,255), random.randint(0,255)),
shape=((O,O,O,O,O,O,O),
(O,X,X,O,X,O,O),
(X,O,O,O,X,O,O),
(X,O,X,O,X,O,O),
(X,O,X,O,X,O,O),
(O,X,X,O,X,X,X),
(O,O,O,O,O,O,O)))
self.set_tetrominoes()
self.tetromino_position = (5, self.tetromino_position[1]) # Making the good luck visible
self.tetromino_rotation = 0
self.downwards_timer = 0
self.base_downwards_speed = 1 # Move down every second
self.movement_keys = {'left': 0, 'right': 0}
self.movement_keys_speed = 0.05
self.movement_keys_timer = (-self.movement_keys_speed)*2
self.level = 1
self.score = 0
self.lines = 0
self.combo = 1 # Combo will increase when you clear lines with several tetrominos in a row
self.paused = False
self.highscore = load_score()
self.played_highscorebeaten_sound = False
self.levelup_sound = get_sound("levelup.wav")
self.gameover_sound = get_sound("gameover.wav")
self.linescleared_sound = get_sound("linecleared.wav")
self.highscorebeaten_sound = get_sound("highscorebeaten.wav")
def set_tetrominoes(self):
self.current_tetromino = self.next_tetromino
self.next_tetromino = random.choice(list_of_tetrominoes)
self.surface_of_next_tetromino = self.construct_surface_of_next_tetromino()
self.tetromino_position = (0, MATRIX_WIDTH//2 - int(math.ceil(len(self.current_tetromino.shape)/2.0)))
self.tetromino_rotation = 0
self.tetromino_block = self.block(self.current_tetromino.color)
self.shadow_block = self.block(self.current_tetromino.color, shadow=True)
def hard_drop(self):
amount = 0
while self.request_movement('down'):
amount += 1
self.score += 10*amount
self.lock_tetromino()
def update(self, timepassed):
self.needs_redraw = False
pressed = lambda key: event.type == pygame.KEYDOWN and event.key == key
unpressed = lambda key: event.type == pygame.KEYUP and event.key == key
events = pygame.event.get()
for event in events:
if pressed(pygame.K_p):
self.surface.fill((0,0,0))
self.needs_redraw = True
self.paused = not self.paused
elif event.type == pygame.QUIT:
self.gameover(full_exit=True)
elif pressed(pygame.K_ESCAPE):
self.gameover()
if self.paused:
return self.needs_redraw
for event in events:
if pressed(pygame.K_SPACE):
self.hard_drop()
elif pressed(pygame.K_UP) or pressed(pygame.K_w):
self.request_rotation()
elif pressed(pygame.K_LEFT) or pressed(pygame.K_a):
self.request_movement('left')
self.movement_keys['left'] = 1
elif pressed(pygame.K_RIGHT) or pressed(pygame.K_d):
self.request_movement('right')
self.movement_keys['right'] = 1
elif unpressed(pygame.K_LEFT) or unpressed(pygame.K_a):
self.movement_keys['left'] = 0
self.movement_keys_timer = (-self.movement_keys_speed)*2
elif unpressed(pygame.K_RIGHT) or unpressed(pygame.K_d):
self.movement_keys['right'] = 0
self.movement_keys_timer = (-self.movement_keys_speed)*2
elif unpressed(pygame.K_f):
self.request_flip()
self.downwards_speed = self.base_downwards_speed ** (1 + self.level/10.)
self.downwards_timer += timepassed
downwards_speed = self.downwards_speed*0.05 if any([pygame.key.get_pressed()[pygame.K_DOWN],
pygame.key.get_pressed()[pygame.K_s]]) else self.downwards_speed
if self.downwards_timer > downwards_speed:
if not self.request_movement('down'):
self.lock_tetromino()
self.downwards_timer %= downwards_speed
if any(self.movement_keys.values()):
self.movement_keys_timer += timepassed
if self.movement_keys_timer > self.movement_keys_speed:
self.request_movement('right' if self.movement_keys['right'] else 'left')
self.movement_keys_timer %= self.movement_keys_speed
return self.needs_redraw
def draw_surface(self):
with_tetromino = self.blend(matrix=self.place_shadow())
for y in range(MATRIX_HEIGHT):
for x in range(MATRIX_WIDTH):
# I hide the 3 first rows by drawing them outside of the surface
block_location = Rect(x*BLOCKSIZE, (y*BLOCKSIZE - 3*BLOCKSIZE), BLOCKSIZE, BLOCKSIZE)
if with_tetromino[(y,x)] is None:
self.surface.fill(BGCOLOR, block_location)
else:
if with_tetromino[(y,x)][0] == 'shadow':
self.surface.fill(BGCOLOR, block_location)
self.surface.blit(with_tetromino[(y,x)][1], block_location)
def gameover(self, full_exit=False):
"""
Gameover occurs when a new tetromino does not fit after the old one has died, either
after a "natural" drop or a hard drop by the player. That is why `self.lock_tetromino`
is responsible for checking if it's game over.
"""
write_score(self.score)
if full_exit:
exit()
else:
raise GameOver("Sucker!")
def place_shadow(self):
posY, posX = self.tetromino_position
while self.blend(position=(posY, posX)):
posY += 1
position = (posY-1, posX)
return self.blend(position=position, shadow=True)
def fits_in_matrix(self, shape, position):
posY, posX = position
for x in range(posX, posX+len(shape)):
for y in range(posY, posY+len(shape)):
if self.matrix.get((y, x), False) is False and shape[y-posY][x-posX]: # outside matrix
return False
return position
def request_rotation(self):
rotation = (self.tetromino_rotation + 1) % 4
shape = self.rotated(rotation)
y, x = self.tetromino_position
position = (self.fits_in_matrix(shape, (y, x)) or
self.fits_in_matrix(shape, (y, x+1)) or
self.fits_in_matrix(shape, (y, x-1)) or
self.fits_in_matrix(shape, (y, x+2)) or
self.fits_in_matrix(shape, (y, x-2)))
# ^ That's how wall-kick is implemented
if position and self.blend(shape, position):
self.tetromino_rotation = rotation
self.tetromino_position = position
self.needs_redraw = True
return self.tetromino_rotation
else:
return False
def request_movement(self, direction):
posY, posX = self.tetromino_position
if direction == 'left' and self.blend(position=(posY, posX-1)):
self.tetromino_position = (posY, posX-1)
self.needs_redraw = True
return self.tetromino_position
elif direction == 'right' and self.blend(position=(posY, posX+1)):
self.tetromino_position = (posY, posX+1)
self.needs_redraw = True
return self.tetromino_position
elif direction == 'up' and self.blend(position=(posY-1, posX)):
self.needs_redraw = True
self.tetromino_position = (posY-1, posX)
return self.tetromino_position
elif direction == 'down' and self.blend(position=(posY+1, posX)):
self.needs_redraw = True
self.tetromino_position = (posY+1, posX)
return self.tetromino_position
else:
return False
def request_flip(self):
flipped = flip(self.current_tetromino.shape)
if self.blend(shape=flipped):
self.needs_redraw = True
self.current_tetromino = Tetromino(shape=flipped, color=self.current_tetromino.color)
return True
return False
def rotated(self, rotation=None):
if rotation is None:
rotation = self.tetromino_rotation
return rotate(self.current_tetromino.shape, rotation)
def block(self, color, shadow=False):
if shadow:
end = [40] # end is the alpha value
else:
end = [] # Adding this to the end will not change the array, thus no alpha value
border = Surface((BLOCKSIZE, BLOCKSIZE), pygame.SRCALPHA, 32)
border.fill(list(map(lambda c: c*0.5, color)) + end)
borderwidth = 2
box = Surface((BLOCKSIZE-borderwidth*2, BLOCKSIZE-borderwidth*2), pygame.SRCALPHA, 32)
boxarr = pygame.PixelArray(box)
for x in range(len(boxarr)):
for y in range(len(boxarr)):
boxarr[x][y] = tuple(list(map(lambda c: min(255, int(c*random.uniform(0.8, 1.2))), color)) + end)
del boxarr # deleting boxarr or else the box surface will be 'locked' or something like that and won't blit.
border.blit(box, Rect(borderwidth, borderwidth, 0, 0))
return border
def lock_tetromino(self):
"""
This method is called whenever the falling tetromino "dies". `self.matrix` is updated,
the lines are counted and cleared, and a new tetromino is chosen.
"""
self.matrix = self.blend()
lines_cleared = self.remove_lines()
self.lines += lines_cleared
if lines_cleared:
if lines_cleared >= 4:
self.linescleared_sound.play()
self.score += 100 * (lines_cleared**2) * self.combo
if not self.played_highscorebeaten_sound and self.score > self.highscore:
if self.highscore != 0:
self.highscorebeaten_sound.play()
self.played_highscorebeaten_sound = True
if self.lines >= self.level*10:
self.levelup_sound.play()
self.level += 1
self.combo = self.combo + 1 if lines_cleared else 1
self.set_tetrominoes()
if not self.blend():
self.gameover_sound.play()
self.gameover()
self.needs_redraw = True
def remove_lines(self):
lines = []
for y in range(MATRIX_HEIGHT):
line = (y, [])
for x in range(MATRIX_WIDTH):
if self.matrix[(y,x)]:
line[1].append(x)
if len(line[1]) == MATRIX_WIDTH:
lines.append(y)
for line in sorted(lines):
for x in range(MATRIX_WIDTH):
self.matrix[(line,x)] = None
for y in range(0, line+1)[::-1]:
for x in range(MATRIX_WIDTH):
self.matrix[(y,x)] = self.matrix.get((y-1,x), None)
return len(lines)
def blend(self, shape=None, position=None, matrix=None, shadow=False):
"""
Does `shape` at `position` fit in `matrix`? If so, return a new copy of `matrix` where all
the squares of `shape` have been placed in `matrix`. Otherwise, return False.
This method is often used simply as a test, for example to see if an action by the player is valid.
It is also used in `self.draw_surface` to paint the falling tetromino and its shadow on the screen.
"""
if shape is None:
shape = self.rotated()
if position is None:
position = self.tetromino_position
copy = dict(self.matrix if matrix is None else matrix)
posY, posX = position
for x in range(posX, posX+len(shape)):
for y in range(posY, posY+len(shape)):
if (copy.get((y, x), False) is False and shape[y-posY][x-posX] # shape is outside the matrix
or # coordinate is occupied by something else which isn't a shadow
copy.get((y,x)) and shape[y-posY][x-posX] and copy[(y,x)][0] != 'shadow'):
return False # Blend failed; `shape` at `position` breaks the matrix
elif shape[y-posY][x-posX]:
copy[(y,x)] = ('shadow', self.shadow_block) if shadow else ('block', self.tetromino_block)
return copy
def construct_surface_of_next_tetromino(self):
shape = self.next_tetromino.shape
surf = Surface((len(shape)*BLOCKSIZE, len(shape)*BLOCKSIZE), pygame.SRCALPHA, 32)
for y in range(len(shape)):
for x in range(len(shape)):
if shape[y][x]:
surf.blit(self.block(self.next_tetromino.color), (x*BLOCKSIZE, y*BLOCKSIZE))
return surf
class Game(object):
def main(self, screen):
clock = pygame.time.Clock()
self.matris = Matris()
screen.blit(construct_nightmare(screen.get_size()), (0,0))
matris_border = Surface((MATRIX_WIDTH*BLOCKSIZE+BORDERWIDTH*2, VISIBLE_MATRIX_HEIGHT*BLOCKSIZE+BORDERWIDTH*2))
matris_border.fill(BORDERCOLOR)
screen.blit(matris_border, (MATRIS_OFFSET,MATRIS_OFFSET))
self.redraw()
while True:
try:
timepassed = clock.tick(50)
if self.matris.update((timepassed / 1000.) if not self.matris.paused else 0):
self.redraw()
except GameOver:
return
def redraw(self):
if not self.matris.paused:
self.blit_next_tetromino(self.matris.surface_of_next_tetromino)
self.blit_info()
self.matris.draw_surface()
pygame.display.flip()
def blit_info(self):
textcolor = (255, 255, 255)
font = pygame.font.Font(None, 30)
width = (WIDTH-(MATRIS_OFFSET+BLOCKSIZE*MATRIX_WIDTH+BORDERWIDTH*2)) - MATRIS_OFFSET*2
def renderpair(text, val):
text = font.render(text, True, textcolor)
val = font.render(str(val), True, textcolor)
surf = Surface((width, text.get_rect().height + BORDERWIDTH*2), pygame.SRCALPHA, 32)
surf.blit(text, text.get_rect(top=BORDERWIDTH+10, left=BORDERWIDTH+10))
surf.blit(val, val.get_rect(top=BORDERWIDTH+10, right=width-(BORDERWIDTH+10)))
return surf
scoresurf = renderpair("Score", self.matris.score)
levelsurf = renderpair("Level", self.matris.level)
linessurf = renderpair("Lines", self.matris.lines)
combosurf = renderpair("Combo", "x{}".format(self.matris.combo))
height = 20 + (levelsurf.get_rect().height +
scoresurf.get_rect().height +
linessurf.get_rect().height +
combosurf.get_rect().height )
area = Surface((width, height))
area.fill(BORDERCOLOR)
area.fill(BGCOLOR, Rect(BORDERWIDTH, BORDERWIDTH, width-BORDERWIDTH*2, height-BORDERWIDTH*2))
area.blit(levelsurf, (0,0))
area.blit(scoresurf, (0, levelsurf.get_rect().height))
area.blit(linessurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height))
area.blit(combosurf, (0, levelsurf.get_rect().height + scoresurf.get_rect().height + linessurf.get_rect().height))
screen.blit(area, area.get_rect(bottom=HEIGHT-MATRIS_OFFSET, centerx=TRICKY_CENTERX))
def blit_next_tetromino(self, tetromino_surf):
area = Surface((BLOCKSIZE*6, BLOCKSIZE*6))
area.fill(BORDERCOLOR)
area.fill(BGCOLOR, Rect(BORDERWIDTH, BORDERWIDTH, BLOCKSIZE*6-BORDERWIDTH*2, BLOCKSIZE*6-BORDERWIDTH*2))
areasize = area.get_size()[0]
tetromino_surf_size = tetromino_surf.get_size()[0]
# ^^ I'm assuming width and height are the same
center = areasize/2 - tetromino_surf_size/2
area.blit(tetromino_surf, (center, center))
screen.blit(area, area.get_rect(top=MATRIS_OFFSET, centerx=TRICKY_CENTERX))
class Menu(object):
running = True
def main(self, screen):
clock = pygame.time.Clock()
menu = kezmenu.KezMenu(
['Play!', lambda: Game().main(screen)],
['Quit', lambda: setattr(self, 'running', False)],
)
menu.position = (50, 50)
menu.enableEffect('enlarge-font-on-focus', font=None, size=60, enlarge_factor=1.2, enlarge_time=0.3)
menu.color = (255,255,255)
menu.focus_color = (40, 200, 40)
nightmare = construct_nightmare(screen.get_size())
highscoresurf = self.construct_highscoresurf()
timepassed = clock.tick(30) / 1000.
while self.running:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
exit()
menu.update(events, timepassed)
timepassed = clock.tick(30) / 1000.
if timepassed > 1: # A game has most likely been played
highscoresurf = self.construct_highscoresurf()
screen.blit(nightmare, (0,0))
screen.blit(highscoresurf, highscoresurf.get_rect(right=WIDTH-50, bottom=HEIGHT-50))
menu.draw(screen)
pygame.display.flip()
def construct_highscoresurf(self):
font = pygame.font.Font(None, 50)
highscore = load_score()
text = "Highscore: {}".format(highscore)
return font.render(text, True, (255,255,255))
def construct_nightmare(size):
surf = Surface(size)
boxsize = 8
bordersize = 1
vals = '1235' # only the lower values, for darker colors and greater fear
arr = pygame.PixelArray(surf)
for x in range(0, len(arr), boxsize):
for y in range(0, len(arr[x]), boxsize):
color = int(''.join([random.choice(vals) + random.choice(vals) for _ in range(3)]), 16)
for LX in range(x, x+(boxsize - bordersize)):
for LY in range(y, y+(boxsize - bordersize)):
if LX < len(arr) and LY < len(arr[x]):
arr[LX][LY] = color
del arr
return surf
if __name__ == '__main__':
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Petris Impossible")
Menu().main(screen)