-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake-game.py
More file actions
611 lines (538 loc) · 21.6 KB
/
snake-game.py
File metadata and controls
611 lines (538 loc) · 21.6 KB
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
"""Snake Eater Made with PyGame."""
import sys
import time
import random
from typing import Union, Iterable, Optional
from threading import Thread
import log21
import pygame
# Colors (R, G, B)
BLACK = pygame.Color(0, 0, 0)
WHITE = pygame.Color(255, 255, 255)
RED = pygame.Color(255, 0, 0)
GREEN = pygame.Color(0, 255, 0)
BLUE = pygame.Color(0, 0, 255)
LIGHT_GRAY = pygame.Color(200, 200, 200)
class SnakeGame:
current_difficulty: float
def __init__(
self,
frame_size_x: int = 720,
frame_size_y: int = 480,
font: Union[str, bytes, Iterable[Union[str, bytes]]] = 'consolas',
base_difficulty: float = 10,
difficulty_modifier: float = 2.5,
fps: int = 60,
big_food_chance: float = 0.02,
big_food_score: int = 3,
big_food_time: float = 6
) -> None:
"""Snake Game class.
Args:
frame_size_x (int, optional): Frame size x. Defaults to 720.
frame_size_y (int, optional): Frame size y. Defaults to 480.
font (Union[str, bytes, Iterable[Union[str, bytes]]], optional): Font.
Defaults to 'consolas'.
base_difficulty (float, optional): Base difficulty. Defaults to 10.
difficulty_modifier (float, optional): Difficulty modifier. Defaults to 2.5.
fps(int, optional): Fps. Defaults to 60.
big_food_chance (float, optional): Big food chance. Defaults to 0.02.
big_food_score (int, optional): Big food score. Defaults to 3.
big_food_time (float, optional): Big food time. Defaults to 6.
"""
self.__frame_size_x = (frame_size_x // 10) * 10
self.__frame_size_y = (frame_size_y // 10) * 10
self.font = font
self.base_difficulty = base_difficulty
self.current_difficulty = base_difficulty
self.difficulty_modifier = difficulty_modifier
self.fps = fps
self.big_food_chance = big_food_chance
self.big_food_score = big_food_score
self.big_food_time = big_food_time
self.big_food_time_left = 0
self.getting_big_score = 0
# Checks for errors encountered
check_errors = pygame.init()
# pygame.init() example output -> (6, 0)
# second number in tuple gives number of errors
if check_errors[1] > 0:
log21.error(
f'Had {check_errors[1]} errors when initialising game, exiting...'
)
sys.exit(-1)
else:
log21.info('Game successfully initialised')
# Initialise game window
pygame.display.set_caption('Snake Eater')
self.game_window = pygame.display.set_mode(
(frame_size_x, frame_size_y), pygame.RESIZABLE
)
# Game variables
self.snake_pos = [100, 50]
self.snake_body = [[100, 50], [100 - 10, 50], [100 - (2 * 10), 50]]
self.food_pos = [
random.randrange(1, (self.frame_size_x // 10)) * 10,
random.randrange(1, (self.frame_size_y // 10)) * 10
]
self.food_spawn = True
self.big_food_pos = [0, 0]
self.direction = 'RIGHT'
self.change_to = self.direction
self.score = 0
self.eating_score = False
self.in_the_danger_zone = False
self.__running = False
def game_over(self):
"""Game Over function."""
self.__running = False
my_font = pygame.font.SysFont('times new roman', 90)
game_over_surface = my_font.render('YOU DIED', True, RED)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (self.frame_size_x // 2, self.frame_size_y // 4)
self.game_window.fill(BLACK)
self.game_window.blit(game_over_surface, game_over_rect)
self.show_score(color=RED, font='times', size=20)
pygame.display.flip()
time.sleep(3)
def show_score(
self,
*,
color: pygame.Color = WHITE,
font: Optional[Union[str, bytes, Iterable[Union[str, bytes]]]] = None,
size: int = 16,
draw: bool = True
):
"""Show score function."""
font = font or self.font
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Score : ' + str(self.score), True, color)
score_rect = score_surface.get_rect()
score_rect.topleft = (self.frame_size_x // 25, self.frame_size_y // 25)
red_rect = pygame.Rect(
score_rect[0] - 5, score_rect[1] - 5, score_rect[2] + 10, score_rect[3] + 10
)
if draw:
pygame.draw.rect(self.game_window, RED, red_rect, width=4)
self.game_window.blit(score_surface, score_rect)
return red_rect
def show_difficulty(
self,
*,
color: pygame.Color = WHITE,
font: Optional[Union[str, bytes, Iterable[Union[str, bytes]]]] = None,
size: int = 16
):
"""Show difficulty function."""
font = font or self.font
difficulty_font = pygame.font.SysFont(font, size)
if self.current_difficulty < 25:
difficulty_text = 'Baby'
elif self.current_difficulty < 40:
difficulty_text = 'Beginner'
elif self.current_difficulty < 60:
difficulty_text = 'Intermediate'
elif self.current_difficulty < 120:
difficulty_text = 'Expert'
elif self.current_difficulty < 250:
difficulty_text = 'Master'
elif self.current_difficulty < 400:
difficulty_text = 'Insane'
else:
difficulty_text = 'GOD'
difficulty_surface = difficulty_font.render(
'Difficulty : ' + difficulty_text, True, color
)
difficulty_rect = difficulty_surface.get_rect()
difficulty_rect.topleft = (
self.frame_size_x * 24 // 25 - difficulty_rect.width,
self.frame_size_y // 25
)
if self.current_difficulty >= 250:
red_rect = pygame.Rect(
difficulty_rect[0] - 5, difficulty_rect[1] - 5, difficulty_rect[2] + 10,
difficulty_rect[3] + 10
)
pygame.draw.rect(self.game_window, RED, red_rect, width=4)
self.game_window.blit(difficulty_surface, difficulty_rect)
def show_eating_score(
self,
*,
color: pygame.Color = RED,
font: Optional[Union[str, bytes, Iterable[Union[str, bytes]]]] = None,
size: int = 20
):
"""Show eating score function."""
font = font or self.font
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Stop EATING Score!!', True, color)
score_rect = score_surface.get_rect()
score_rect.midtop = (self.frame_size_x // 2, self.frame_size_y - 25)
self.game_window.blit(score_surface, score_rect)
def show_danger_zone(
self,
*,
color: pygame.Color = RED,
font: Optional[Union[str, bytes, Iterable[Union[str, bytes]]]] = None,
size: int = 20
):
"""Show danger zone function."""
font = font or self.font
score_font = pygame.font.SysFont(font, size)
score_surface = score_font.render('Danger Zone!!', True, color)
score_rect = score_surface.get_rect()
score_rect.midtop = (self.frame_size_x // 2, self.frame_size_y - 25)
self.game_window.blit(score_surface, score_rect)
def show_pause(
self,
*,
color: pygame.Color = RED,
size: int = 30,
font: Optional[Union[str, bytes, Iterable[Union[str, bytes]]]] = None,
):
"""Show pause function."""
font = font or self.font
pause_font = pygame.font.SysFont(font, size)
pause_surface = pause_font.render('Paused', True, color)
pause_rect = pause_surface.get_rect()
pause_rect.midtop = (
self.frame_size_x // 2, self.frame_size_y // 2 - pause_rect[3] // 2
)
self.game_window.blit(pause_surface, pause_rect)
def big_food_time_bar(
self,
*,
color: pygame.Color = WHITE,
border_color: pygame.Color = LIGHT_GRAY,
bar_thickness: int = 15,
draw: bool = True
) -> int:
"""Show big food time bar function."""
border_x = self.frame_size_x // 10 - 5
border_y = (self.frame_size_y * 19) // 20 - bar_thickness - 5
border_w = (self.frame_size_x * 8) // 10 + 10
border_h = bar_thickness + 10
bar_rect = pygame.Rect(
border_x + 5, border_y + 5,
(border_w - 10) * self.big_food_time_left / self.big_food_time,
bar_thickness
)
if draw:
# Draw the border
# Top Line
pygame.draw.rect(
self.game_window, border_color,
pygame.Rect(border_x + 5, border_y, border_w - 10, 3)
)
# Bottom Line
pygame.draw.rect(
self.game_window, border_color,
pygame.Rect(
border_x + 5, border_y + border_h - 5 + 2, border_w - 10, 3
)
)
# Left line
pygame.draw.rect(
self.game_window, border_color,
pygame.Rect(border_x, border_y + 5, 3, border_h - 10)
)
# Right Line
pygame.draw.rect(
self.game_window, border_color,
pygame.Rect(
border_x + border_w - 5 + 2, border_y + 5, 3, border_h - 10
)
)
for x in (border_x, border_x + border_w - 5):
for y in (border_y, border_y + border_h - 5):
pygame.draw.rect(self.game_window, BLACK, pygame.Rect(x, y, 5, 5))
pygame.draw.rect(self.game_window, color, bar_rect)
return border_y
def do_drawings(self):
"""Draw the things that need to be drawn."""
self.game_window.fill(BLACK)
for pos in self.snake_body:
# Snake body
# .draw.rect(play_surface, color, xy-coordinate)
# xy-coordinate -> .Rect(x, y, size_x, size_y)
pygame.draw.rect(
self.game_window, GREEN, pygame.Rect(pos[0], pos[1], 10, 10)
)
# Show score
self.show_score(
color=RED if self.eating_score or self.in_the_danger_zone else WHITE
)
# Show difficulty
self.show_difficulty()
# Snake food
pygame.draw.rect(
self.game_window, WHITE,
pygame.Rect(self.food_pos[0], self.food_pos[1], 10, 10)
)
# Big food
if self.big_food_time_left > 0:
pygame.draw.rect(
self.game_window, WHITE,
pygame.Rect(self.big_food_pos[0], self.big_food_pos[1], 20, 20)
)
self.big_food_time_bar()
def main_loop(self):
"""Main loop function."""
while self.__running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.__running = False
return
# Change the frame size when the window is resized
elif event.type == pygame.VIDEORESIZE:
self.frame_size_x, self.frame_size_y = event.size
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
# W -> Up; S -> Down; A -> Left; D -> Right
if event.key in [pygame.K_UP, ord('w'), ord('k')]:
self.change_to = 'UP'
if event.key in [pygame.K_DOWN, ord('s'), ord('j')]:
self.change_to = 'DOWN'
if event.key in [pygame.K_LEFT, ord('a'), ord('h')]:
self.change_to = 'LEFT'
if event.key in [pygame.K_RIGHT, ord('d'), ord('l')]:
self.change_to = 'RIGHT'
if event.key in [pygame.K_PAUSE, ord('p')]:
self.change_to = 'PAUSE'
self.show_pause(font='consolas')
pygame.display.update()
# Esc -> Create event to quit the game
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
self.do_drawings()
# Making sure the snake cannot move in the opposite direction
# instantaneously
if self.change_to == 'PAUSE':
time.sleep(self.tick)
continue
if self.change_to == 'UP' and self.direction != 'DOWN':
self.direction = 'UP'
if self.change_to == 'DOWN' and self.direction != 'UP':
self.direction = 'DOWN'
if self.change_to == 'LEFT' and self.direction != 'RIGHT':
self.direction = 'LEFT'
if self.change_to == 'RIGHT' and self.direction != 'LEFT':
self.direction = 'RIGHT'
# Refresh game screen
pygame.display.update()
time.sleep(self.tick)
def __run(self):
while self.__running:
if self.change_to == 'PAUSE':
time.sleep(self.tick)
continue
# Moving the snake
if self.direction == 'UP':
self.snake_pos[1] -= 10
if self.direction == 'DOWN':
self.snake_pos[1] += 10
if self.direction == 'LEFT':
self.snake_pos[0] -= 10
if self.direction == 'RIGHT':
self.snake_pos[0] += 10
# Snake eating and growing mechanism
self.snake_body.insert(0, list(self.snake_pos))
if self.snake_pos[0] == self.food_pos[0] and self.snake_pos[
1] == self.food_pos[1]:
self.score += 1
self.food_spawn = False
elif self.getting_big_score > 0:
self.getting_big_score -= 1
self.score += 1
else:
self.snake_body.pop()
if self.big_food_time_left > 0:
if (
(self.big_food_pos[0] <= self.snake_pos[0] <= self.big_food_pos[0] + 10) \
and \
(self.big_food_pos[1] <= self.snake_pos[1] <= self.big_food_pos[1] + 10)
):
self.getting_big_score = self.big_food_score
self.big_food_time_left = 0
self.big_food_pos = [0, 0]
# Getting out of bounds
if self.snake_pos[0] < 0:
self.snake_pos[0] = self.frame_size_x - 10
if self.snake_pos[0] > self.frame_size_x - 10:
self.snake_pos[0] = 0
if self.snake_pos[1] < 0:
self.snake_pos[1] = self.frame_size_y - 10
if self.snake_pos[1] > self.frame_size_y - 10:
self.snake_pos[1] = 0
# Game Over condition
# Touching the snake body
for block in self.snake_body[1:]:
if self.snake_pos[0] == block[0] and self.snake_pos[1] == block[1]:
self.game_over()
# Show score
rect = self.show_score(draw=False)
self.eating_score = False
# Decrease score if snake is in score box
if self.score > 0 and self.snake_pos[0] - rect[0] in range(
rect[2]) and self.snake_pos[1] - rect[1] in range(rect[3]):
self.eating_score = True
self.show_score(color=RED)
self.show_eating_score(color=RED)
self.score -= 1
self.snake_body.pop()
# Set difficulty
self.current_difficulty = (
self.score * self.difficulty_modifier + self.base_difficulty
)
self.in_the_danger_zone = False
# Decrease score if snake is in Insane or GOD difficulty box
if self.score > 0 and self.current_difficulty >= 250:
self.in_the_danger_zone = True
self.show_score(color=RED)
self.show_danger_zone(color=RED)
self.score -= 1
self.snake_body.pop()
if self.big_food_chance > 0:
bar_y = self.big_food_time_bar(draw=False)
else:
bar_y = self.frame_size_y
# Spawning food on the screen
if not self.food_spawn:
self.food_pos = [
random.randrange(1, self.frame_size_x // 10) * 10,
random.randrange(1 + (rect[1] + rect[3]) // 10, bar_y // 10 - 1) *
10
]
self.food_spawn = True
if self.eating_score:
time.sleep(1 / self.base_difficulty)
else:
time.sleep(1 / self.current_difficulty)
def big_food_handler(self):
"""Spawn big food every few seconds."""
while self.__running:
if self.change_to == 'PAUSE':
time.sleep(self.tick)
continue
if self.big_food_time_left > 0:
self.big_food_time_left -= 0.01
time.sleep(0.01)
continue
spawn_big_food = random.random() <= self.big_food_chance
if spawn_big_food:
rect = self.show_score(draw=False)
if self.big_food_chance > 0:
bar_y = self.big_food_time_bar(draw=False)
else:
bar_y = self.frame_size_y
self.big_food_pos = [
random.randrange(1, self.frame_size_x // 20 - 1) * 20,
random.randrange(1 + (rect[1] + rect[3]) // 20, bar_y // 20 - 1) *
20
]
self.big_food_pos[0] += 10
if self.big_food_pos[0] > self.frame_size_x - 10:
self.big_food_pos[0] = 0
self.big_food_time_left = self.big_food_time
continue
time.sleep(1)
def run(self):
"""Run the game."""
threads = []
self.__running = True
threads.append(Thread(target=self.__run, daemon=True))
threads[-1].start()
if 0 < self.big_food_chance < 1:
threads.append(Thread(target=self.big_food_handler, daemon=True))
threads[-1].start()
self.main_loop()
self.__running = False
for thread in threads:
thread.join()
@property
def frame_size_x(self) -> int:
"""Get the width of the game frame."""
return self.__frame_size_x
@frame_size_x.setter
def frame_size_x(self, value: int):
self.__frame_size_x = (value // 10) * 10
if self.game_window.get_width() != value:
self.game_window = pygame.display.set_mode(
(self.frame_size_x, self.frame_size_y), pygame.RESIZABLE
)
if self.food_spawn and self.food_pos[0] > self.frame_size_x - 10:
self.food_spawn = False
@property
def frame_size_y(self) -> int:
"""Get the height of the game frame."""
return self.__frame_size_y
@frame_size_y.setter
def frame_size_y(self, value: int):
self.__frame_size_y = (value // 10) * 10
if self.game_window.get_height() != value:
self.game_window = pygame.display.set_mode(
(self.frame_size_x, self.frame_size_y), pygame.RESIZABLE
)
if self.food_spawn and self.food_pos[1] > self.frame_size_y - 10:
self.food_spawn = False
@property
def fps(self) -> int:
"""Get the number of frames per second."""
return self.__fps
@fps.setter
def fps(self, value: int):
self.__fps = value
self.__tick = 1 / value
@property
def tick(self) -> float:
"""Get the time between each frame."""
return self.__tick
@property
def in_the_danger_zone(self) -> bool:
"""When the difficulty is insane or higher, the difficulty box becomes a Danger
Zone!"""
return self.__in_the_danger_zone
@in_the_danger_zone.setter
def in_the_danger_zone(self, value: bool):
self.__in_the_danger_zone = value
def __del__(self):
pygame.quit()
def main(
frame_size_x: int = 720,
frame_size_y: int = 480,
base_difficulty: float = 10,
difficulty_modifier: float = 2.5,
fps: int = 90,
big_food_chance: float = 0.02,
big_food_score: int = 3,
big_food_time: float = 6
):
"""Run the game.
Args:
frame_size_x (int): The width of the game frame. (default: 720)
frame_size_y (int): The height of the game frame. (default: 480)
base_difficulty (float): The base difficulty of the game. (default: 10)
difficulty_modifier (float): The difficulty modifier of the game. It increases
the difficulty based on the current score. (default: 2.5)
fps (int): The number of frames per second.
big_food_chance (float): The chance of a big food spawning. (Must be between 0
and 1.)
big_food_score (int): The score to earn for eating a BIG FOOD. (default: 3)
big_food_time (float): The time in seconds for a big food to stay. (default: 6)
"""
if big_food_chance > 1:
log21.error(f'big_food_chance must be between 0 and 1, not {big_food_chance}')
sys.exit(1)
game = SnakeGame(
frame_size_x=frame_size_x,
frame_size_y=frame_size_y,
base_difficulty=base_difficulty,
difficulty_modifier=difficulty_modifier,
fps=fps,
big_food_chance=big_food_chance,
big_food_score=big_food_score,
big_food_time=big_food_time
)
game.run()
if __name__ == '__main__':
log21.argumentify(main)