-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSnakeGame.py
More file actions
654 lines (543 loc) · 24.7 KB
/
Copy pathSnakeGame.py
File metadata and controls
654 lines (543 loc) · 24.7 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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
import pygame
import random
import json
import os
import time
from enum import Enum
# Basic setup stuff - colors and game settings
class Color:
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)
ORANGE = (255, 165, 0)
CYAN = (0, 255, 255)
PINK = (255, 192, 203)
GOLD = (255, 215, 0)
GRAY = (128, 128, 128)
DARK_GRAY = (64, 64, 64)
class Direction(Enum):
UP = 1
DOWN = 2
LEFT = 3
RIGHT = 4
class PowerUpType(Enum):
SPEED_BOOST = 1
SLOW_DOWN = 2
INVINCIBILITY = 3
DOUBLE_POINTS = 4
# Snake skins with their unlock requirements
SNAKE_SKINS = {
'classic': {
'color': Color.GREEN,
'name': 'Classic Green',
'unlock_score': 0,
'unlocked': True
},
'ocean': {
'color': Color.BLUE,
'name': 'Ocean Blue',
'unlock_score': 10,
'unlocked': False
},
'sunset': {
'color': Color.ORANGE,
'name': 'Sunset Orange',
'unlock_score': 25,
'unlocked': False
},
'royal': {
'color': Color.PURPLE,
'name': 'Royal Purple',
'unlock_score': 50,
'unlocked': False
},
'golden': {
'color': Color.GOLD,
'name': 'Golden Champion',
'unlock_score': 100,
'unlocked': False
},
'bubblegum': {
'color': Color.PINK,
'name': 'Bubblegum',
'unlock_score': 75,
'unlocked': False
}
}
class SnakeGame:
def __init__(self, width=800, height=600):
pygame.init()
self.width = width
self.height = height
self.display = pygame.display.set_mode((self.width, self.height))
pygame.display.set_caption('Snake Game - Enhanced Edition')
self.clock = pygame.time.Clock()
# Game speed - higher = faster
self.base_speed = 15
self.speed = self.base_speed
# Size of each snake segment
self.block_size = 20
# Fonts for different purposes
self.font = pygame.font.SysFont('arial', 35)
self.small_font = pygame.font.SysFont('arial', 20)
# Load or create save file for skins
self.save_file = 'snake_save.json'
self.load_progress()
# Current skin selection
self.current_skin = 'classic'
# Track high score across all games
self.high_score = self.progress_data.get('high_score', 0)
# Menu state
self.in_menu = True
self.menu_option = 0 # 0 = Play, 1 = Skins, 2 = Quit
self.reset_game()
def load_progress(self):
"""Load saved progress from file"""
if os.path.exists(self.save_file):
try:
with open(self.save_file, 'r') as f:
self.progress_data = json.load(f)
# Update the global SNAKE_SKINS with saved unlock status
for skin_id, unlocked in self.progress_data.get('unlocked_skins', {}).items():
if skin_id in SNAKE_SKINS:
SNAKE_SKINS[skin_id]['unlocked'] = unlocked
except:
self.progress_data = {'unlocked_skins': {}, 'high_score': 0}
else:
self.progress_data = {'unlocked_skins': {}, 'high_score': 0}
def save_progress(self):
"""Save progress to file"""
unlocked = {skin_id: skin['unlocked'] for skin_id, skin in SNAKE_SKINS.items()}
self.progress_data = {
'unlocked_skins': unlocked,
'high_score': self.high_score
}
with open(self.save_file, 'w') as f:
json.dump(self.progress_data, f)
def check_skin_unlocks(self):
"""Check if we unlocked any new skins and return list of newly unlocked"""
newly_unlocked = []
for skin_id, skin_data in SNAKE_SKINS.items():
if not skin_data['unlocked'] and self.high_score >= skin_data['unlock_score']:
skin_data['unlocked'] = True
newly_unlocked.append(skin_data['name'])
if newly_unlocked:
self.save_progress()
return newly_unlocked
def reset_game(self):
"""Start everything fresh"""
# Snake starts in the middle of the screen
self.snake_pos = [self.width // 2, self.height // 2]
# Snake body is a list of segments - starts with 3 segments
self.snake_body = [
[self.width // 2, self.height // 2],
[self.width // 2 - self.block_size, self.height // 2],
[self.width // 2 - (2 * self.block_size), self.height // 2]
]
# Snake starts moving to the right
self.direction = Direction.RIGHT
self.change_to = self.direction
# Obstacles - initialize before spawning food (food needs to check obstacles)
self.obstacles = []
self.spawn_obstacles(5)
# Put the first food somewhere random
self.food_pos = self.spawn_food()
self.food_spawn = True
# Power-ups
self.power_up_pos = None
self.power_up_type = None
self.power_up_spawn_timer = 0
self.active_power_up = None
self.power_up_end_time = 0
# Points multiplier
self.points_multiplier = 1
# Invincibility flag
self.invincible = False
self.score = 0
self.speed = self.base_speed
def spawn_obstacles(self, count):
"""Create random obstacles on the map"""
for _ in range(count):
while True:
x = random.randrange(2, (self.width // self.block_size) - 2) * self.block_size
y = random.randrange(2, (self.height // self.block_size) - 2) * self.block_size
obstacle = [x, y]
# Make sure obstacle isn't on the snake or food
# Only check food_pos if it exists (during initial setup it might not)
food_conflict = hasattr(self, 'food_pos') and obstacle == self.food_pos
if (obstacle not in self.snake_body and
not food_conflict and
obstacle not in self.obstacles):
self.obstacles.append(obstacle)
break
def spawn_power_up(self):
"""Spawn a random power-up"""
while True:
x = random.randrange(1, (self.width // self.block_size)) * self.block_size
y = random.randrange(1, (self.height // self.block_size)) * self.block_size
pos = [x, y]
# Make sure it's not on snake, food, or obstacles
if (pos not in self.snake_body and
pos != self.food_pos and
pos not in self.obstacles):
self.power_up_pos = pos
self.power_up_type = random.choice(list(PowerUpType))
break
def spawn_food(self):
"""Pick a random spot for food that's aligned with the grid"""
while True:
x = random.randrange(1, (self.width // self.block_size)) * self.block_size
y = random.randrange(1, (self.height // self.block_size)) * self.block_size
pos = [x, y]
# Make sure food doesn't spawn on obstacles or snake
if pos not in self.obstacles and pos not in self.snake_body:
return pos
def handle_input(self):
"""Check what keys the player is pressing"""
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
# Only care about key presses
if event.type == pygame.KEYDOWN:
# Menu controls
if self.in_menu:
if event.key == pygame.K_UP:
self.menu_option = (self.menu_option - 1) % 3
elif event.key == pygame.K_DOWN:
self.menu_option = (self.menu_option + 1) % 3
elif event.key == pygame.K_RETURN:
if self.menu_option == 0: # Play
self.in_menu = False
elif self.menu_option == 1: # Skins
self.show_skin_menu()
elif self.menu_option == 2: # Quit
return False
elif event.key == pygame.K_ESCAPE:
return False
# Game controls
else:
if event.key == pygame.K_UP and self.direction != Direction.DOWN:
self.change_to = Direction.UP
elif event.key == pygame.K_DOWN and self.direction != Direction.UP:
self.change_to = Direction.DOWN
elif event.key == pygame.K_LEFT and self.direction != Direction.RIGHT:
self.change_to = Direction.LEFT
elif event.key == pygame.K_RIGHT and self.direction != Direction.LEFT:
self.change_to = Direction.RIGHT
# Press ESC to go back to menu
elif event.key == pygame.K_ESCAPE:
self.in_menu = True
return True
def update_snake(self):
"""Move the snake in whatever direction it's going"""
self.direction = self.change_to
# Figure out where the head should move based on direction
if self.direction == Direction.UP:
self.snake_pos[1] -= self.block_size
elif self.direction == Direction.DOWN:
self.snake_pos[1] += self.block_size
elif self.direction == Direction.LEFT:
self.snake_pos[0] -= self.block_size
elif self.direction == Direction.RIGHT:
self.snake_pos[0] += self.block_size
# Add new head position to the body
self.snake_body.insert(0, list(self.snake_pos))
# Check for power-up collection
if self.power_up_pos and self.snake_pos == self.power_up_pos:
self.activate_power_up(self.power_up_type)
self.power_up_pos = None
self.power_up_type = None
# Did we eat the food?
if self.snake_pos[0] == self.food_pos[0] and self.snake_pos[1] == self.food_pos[1]:
self.score += (1 * self.points_multiplier)
self.food_spawn = False
# Add more obstacles as score increases
if self.score % 10 == 0 and self.score > 0:
self.spawn_obstacles(1)
else:
# If we didn't eat food, remove the tail segment so snake doesn't grow
self.snake_body.pop()
# Need to spawn new food if we just ate it
if not self.food_spawn:
self.food_pos = self.spawn_food()
self.food_spawn = True
# Power-up spawning logic - spawn every 15-25 seconds randomly
self.power_up_spawn_timer += 1
if not self.power_up_pos and self.power_up_spawn_timer > random.randint(225, 375):
self.spawn_power_up()
self.power_up_spawn_timer = 0
# Check if power-up expired
if self.active_power_up and time.time() >= self.power_up_end_time:
self.deactivate_power_up()
def activate_power_up(self, power_type):
"""Apply power-up effect"""
self.active_power_up = power_type
self.power_up_end_time = time.time() + 5 # 5 second duration
if power_type == PowerUpType.SPEED_BOOST:
self.speed = self.base_speed + 10
elif power_type == PowerUpType.SLOW_DOWN:
self.speed = max(5, self.base_speed - 5)
elif power_type == PowerUpType.INVINCIBILITY:
self.invincible = True
elif power_type == PowerUpType.DOUBLE_POINTS:
self.points_multiplier = 2
def deactivate_power_up(self):
"""Remove power-up effect"""
if self.active_power_up == PowerUpType.SPEED_BOOST or self.active_power_up == PowerUpType.SLOW_DOWN:
self.speed = self.base_speed
elif self.active_power_up == PowerUpType.INVINCIBILITY:
self.invincible = False
elif self.active_power_up == PowerUpType.DOUBLE_POINTS:
self.points_multiplier = 1
self.active_power_up = None
def check_game_over(self):
"""See if the snake crashed into something"""
# Don't die if invincible
if self.invincible:
return False
# Hit the wall?
if (self.snake_pos[0] < 0 or self.snake_pos[0] >= self.width or
self.snake_pos[1] < 0 or self.snake_pos[1] >= self.height):
return True
# Hit an obstacle?
if self.snake_pos in self.obstacles:
return True
# Hit itself? Check if head position matches any body segment
for block in self.snake_body[1:]:
if self.snake_pos[0] == block[0] and self.snake_pos[1] == block[1]:
return True
return False
def draw_everything(self):
"""Render all the game elements on screen"""
self.display.fill(Color.BLACK)
# Get current snake color based on selected skin
snake_color = SNAKE_SKINS[self.current_skin]['color']
# If invincible, make snake flash
if self.invincible and int(time.time() * 10) % 2 == 0:
snake_color = Color.CYAN
# Draw each segment of the snake
for pos in self.snake_body:
pygame.draw.rect(self.display, snake_color,
pygame.Rect(pos[0], pos[1], self.block_size, self.block_size))
# Draw the food
pygame.draw.rect(self.display, Color.RED,
pygame.Rect(self.food_pos[0], self.food_pos[1],
self.block_size, self.block_size))
# Draw obstacles
for obstacle in self.obstacles:
pygame.draw.rect(self.display, Color.GRAY,
pygame.Rect(obstacle[0], obstacle[1],
self.block_size, self.block_size))
# Draw power-up if it exists
if self.power_up_pos:
power_up_color = self.get_power_up_color(self.power_up_type)
pygame.draw.rect(self.display, power_up_color,
pygame.Rect(self.power_up_pos[0], self.power_up_pos[1],
self.block_size, self.block_size))
# Draw a small symbol to indicate what it does
symbol = self.get_power_up_symbol(self.power_up_type)
symbol_text = self.small_font.render(symbol, True, Color.BLACK)
self.display.blit(symbol_text, [self.power_up_pos[0] + 3, self.power_up_pos[1]])
# Show the score and high score
score_text = self.font.render(f'Score: {self.score}', True, Color.WHITE)
self.display.blit(score_text, [10, 10])
high_score_text = self.small_font.render(f'High Score: {self.high_score}', True, Color.WHITE)
self.display.blit(high_score_text, [10, 50])
# Show active power-up info
if self.active_power_up:
time_left = max(0, self.power_up_end_time - time.time())
power_up_name = self.active_power_up.name.replace('_', ' ').title()
power_text = self.small_font.render(f'{power_up_name}: {time_left:.1f}s', True, Color.YELLOW)
self.display.blit(power_text, [self.width - 250, 10])
pygame.display.update()
def get_power_up_color(self, power_type):
"""Get the color for a power-up type"""
colors = {
PowerUpType.SPEED_BOOST: Color.YELLOW,
PowerUpType.SLOW_DOWN: Color.BLUE,
PowerUpType.INVINCIBILITY: Color.CYAN,
PowerUpType.DOUBLE_POINTS: Color.GOLD
}
return colors.get(power_type, Color.WHITE)
def get_power_up_symbol(self, power_type):
"""Get a symbol to show what the power-up does"""
symbols = {
PowerUpType.SPEED_BOOST: '>>',
PowerUpType.SLOW_DOWN: '<<',
PowerUpType.INVINCIBILITY: '★',
PowerUpType.DOUBLE_POINTS: 'x2'
}
return symbols.get(power_type, '?')
def draw_menu(self):
"""Draw the main menu"""
self.display.fill(Color.BLACK)
# Title
title_text = self.font.render('SNAKE GAME', True, Color.GREEN)
self.display.blit(title_text,
[self.width // 2 - title_text.get_width() // 2, 100])
subtitle = self.small_font.render('Enhanced Edition', True, Color.WHITE)
self.display.blit(subtitle,
[self.width // 2 - subtitle.get_width() // 2, 150])
# Menu options
options = ['Play Game', 'Choose Skin', 'Quit']
for i, option in enumerate(options):
color = Color.YELLOW if i == self.menu_option else Color.WHITE
option_text = self.font.render(option, True, color)
self.display.blit(option_text,
[self.width // 2 - option_text.get_width() // 2, 250 + i * 60])
# High score display
high_score_text = self.small_font.render(f'High Score: {self.high_score}', True, Color.WHITE)
self.display.blit(high_score_text,
[self.width // 2 - high_score_text.get_width() // 2, 450])
# Current skin display
current_skin_name = SNAKE_SKINS[self.current_skin]['name']
skin_text = self.small_font.render(f'Current Skin: {current_skin_name}', True, SNAKE_SKINS[self.current_skin]['color'])
self.display.blit(skin_text,
[self.width // 2 - skin_text.get_width() // 2, 500])
# Instructions
instruction = self.small_font.render('Use arrow keys to navigate, Enter to select', True, Color.DARK_GRAY)
self.display.blit(instruction,
[self.width // 2 - instruction.get_width() // 2, 550])
pygame.display.update()
def show_skin_menu(self):
"""Show the skin selection menu"""
in_skin_menu = True
selected_skin = 0
skin_list = list(SNAKE_SKINS.keys())
while in_skin_menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
selected_skin = (selected_skin - 1) % len(skin_list)
elif event.key == pygame.K_DOWN:
selected_skin = (selected_skin + 1) % len(skin_list)
elif event.key == pygame.K_RETURN:
skin_id = skin_list[selected_skin]
if SNAKE_SKINS[skin_id]['unlocked']:
self.current_skin = skin_id
in_skin_menu = False
elif event.key == pygame.K_ESCAPE:
in_skin_menu = False
self.display.fill(Color.BLACK)
# Title
title = self.font.render('Choose Your Skin', True, Color.WHITE)
self.display.blit(title, [self.width // 2 - title.get_width() // 2, 50])
# Display all skins
y_offset = 150
for i, skin_id in enumerate(skin_list):
skin_data = SNAKE_SKINS[skin_id]
is_selected = i == selected_skin
# Skin name
color = Color.YELLOW if is_selected else Color.WHITE
if not skin_data['unlocked']:
color = Color.DARK_GRAY
skin_name = skin_data['name']
if not skin_data['unlocked']:
skin_name += f" (Unlock at {skin_data['unlock_score']} points)"
text = self.small_font.render(skin_name, True, color)
self.display.blit(text, [self.width // 2 - text.get_width() // 2, y_offset])
# Color preview
if skin_data['unlocked']:
pygame.draw.rect(self.display, skin_data['color'],
pygame.Rect(self.width // 2 - 150, y_offset, 20, 20))
y_offset += 40
instruction = self.small_font.render('Enter to select, ESC to go back', True, Color.DARK_GRAY)
self.display.blit(instruction, [self.width // 2 - instruction.get_width() // 2, y_offset + 30])
pygame.display.update()
self.clock.tick(15)
def show_game_over(self):
"""Display game over screen with final score"""
# Update high score if needed
if self.score > self.high_score:
self.high_score = self.score
self.save_progress()
# Check for newly unlocked skins
newly_unlocked = self.check_skin_unlocks()
self.display.fill(Color.BLACK)
game_over_text = self.font.render('Game Over!', True, Color.RED)
score_text = self.font.render(f'Final Score: {self.score}', True, Color.WHITE)
high_score_text = self.small_font.render(f'High Score: {self.high_score}', True, Color.YELLOW)
restart_text = self.small_font.render('Press R to restart or ESC for menu', True, Color.WHITE)
# Center the text on screen
y_pos = self.height // 2 - 120
self.display.blit(game_over_text,
[self.width // 2 - game_over_text.get_width() // 2, y_pos])
y_pos += 60
self.display.blit(score_text,
[self.width // 2 - score_text.get_width() // 2, y_pos])
y_pos += 40
self.display.blit(high_score_text,
[self.width // 2 - high_score_text.get_width() // 2, y_pos])
y_pos += 60
# Show newly unlocked skins
if newly_unlocked:
unlock_text = self.small_font.render('NEW SKIN UNLOCKED!', True, Color.GOLD)
self.display.blit(unlock_text,
[self.width // 2 - unlock_text.get_width() // 2, y_pos])
y_pos += 30
for skin_name in newly_unlocked:
skin_unlock = self.small_font.render(skin_name, True, Color.GREEN)
self.display.blit(skin_unlock,
[self.width // 2 - skin_unlock.get_width() // 2, y_pos])
y_pos += 25
y_pos += 20
self.display.blit(restart_text,
[self.width // 2 - restart_text.get_width() // 2, y_pos])
pygame.display.update()
# Wait for player to decide what to do
waiting = True
while waiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False, False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
return True, False # Restart
elif event.key == pygame.K_ESCAPE:
return False, True # Go to menu
return False, False
def run(self):
"""Main game loop"""
running = True
while running:
# Show menu if we're in menu state
if self.in_menu:
# Handle menu input
if not self.handle_input():
break
# Draw the menu
self.draw_menu()
self.clock.tick(15)
continue
# Handle player input during gameplay
if not self.handle_input():
break
# Move the snake
self.update_snake()
# Check if game is over
if self.check_game_over():
# Show game over screen and see if player wants to restart
restart, to_menu = self.show_game_over()
if restart:
self.reset_game()
elif to_menu:
self.in_menu = True
self.reset_game()
else:
running = False
continue
# Draw everything
self.draw_everything()
# Control game speed
self.clock.tick(self.speed)
pygame.quit()
# Start the game
if __name__ == '__main__':
game = SnakeGame()
game.run()