-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake_game.py
More file actions
92 lines (78 loc) · 2.73 KB
/
Copy pathsnake_game.py
File metadata and controls
92 lines (78 loc) · 2.73 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
import pygame
import sys
import random
import time
# Initialize Pygame
pygame.init()
# Set up some constants
WIDTH, HEIGHT = 640, 480
SCORE_FONT_SIZE = 20
GAME_OVER_FONT_SIZE = 40
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
# Set up the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
# Set up the font
font = pygame.font.Font(None, SCORE_FONT_SIZE)
game_over_font = pygame.font.Font(None, GAME_OVER_FONT_SIZE)
# Set up the snake and food
snake = [(200, 200), (220, 200), (240, 200)]
food = (random.randint(0, WIDTH - 20) // 20 * 20, random.randint(0, HEIGHT - 20) // 20 * 20)
direction = "RIGHT"
# Set up the score
score = 0
# Game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction!= "DOWN":
direction = "UP"
elif event.key == pygame.K_DOWN and direction!= "UP":
direction = "DOWN"
elif event.key == pygame.K_LEFT and direction!= "RIGHT":
direction = "LEFT"
elif event.key == pygame.K_RIGHT and direction!= "LEFT":
direction = "RIGHT"
# Move the snake
head = snake[-1]
if direction == "UP":
new_head = (head[0], head[1] - 20)
elif direction == "DOWN":
new_head = (head[0], head[1] + 20)
elif direction == "LEFT":
new_head = (head[0] - 20, head[1])
elif direction == "RIGHT":
new_head = (head[0] + 20, head[1])
snake.append(new_head)
# Check for collision with food
if snake[-1] == food:
score += 1
food = (random.randint(0, WIDTH - 20) // 20 * 20, random.randint(0, HEIGHT - 20) // 20 * 20)
else:
snake.pop(0)
# Check for collision with wall or self
if (snake[-1][0] < 0 or snake[-1][0] >= WIDTH or
snake[-1][1] < 0 or snake[-1][1] >= HEIGHT or
snake[-1] in snake[:-1]):
screen.fill(BLACK)
game_over_text = game_over_font.render("Game Over! Final Score: " + str(score), True, WHITE)
screen.blit(game_over_text, (WIDTH // 2 - game_over_text.get_width() // 2, HEIGHT // 2 - game_over_text.get_height() // 2))
pygame.display.update()
time.sleep(1)
break
# Draw everything
screen.fill(BLACK)
for x, y in snake:
pygame.draw.rect(screen, GREEN, (x, y, 20, 20))
pygame.draw.rect(screen, RED, (food[0], food[1], 20, 20))
score_text = font.render("Score: " + str(score), True, WHITE)
screen.blit(score_text, (10, 10))
pygame.display.update()
# Cap the frame rate
pygame.time.Clock().tick(10)