-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnake.py
More file actions
191 lines (157 loc) · 6.2 KB
/
Copy pathsnake.py
File metadata and controls
191 lines (157 loc) · 6.2 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
"""Snake — arrow keys to steer, eat food to grow and speed up.
Hitting a wall or yourself ends the game; press R to restart, Q to quit.
Run with: python snake.py
"""
import random
import sys
import pygame
# --- Configuration ---------------------------------------------------------
CELL = 20 # pixel size of one grid cell
COLS, ROWS = 30, 24 # grid dimensions
WIDTH, HEIGHT = COLS * CELL, ROWS * CELL
HUD_HEIGHT = 40 # score bar at the top
START_SPEED = 8.0 # moves per second at the start
SPEED_STEP = 0.4 # speed added per food eaten
MAX_SPEED = 22.0 # cap so it stays playable
# Colors (R, G, B)
BG = (18, 18, 22)
GRID = (28, 28, 34)
SNAKE = (80, 220, 120)
SNAKE_HEAD = (140, 250, 170)
FOOD = (230, 90, 90)
TEXT = (235, 235, 235)
DIM = (150, 150, 160)
UP, DOWN, LEFT, RIGHT = (0, -1), (0, 1), (-1, 0), (1, 0)
def new_food(snake):
"""Return a random empty cell for the next food."""
free = [
(x, y)
for x in range(COLS)
for y in range(ROWS)
if (x, y) not in snake
]
return random.choice(free) if free else None
def draw_cell(surface, pos, color):
x, y = pos
rect = pygame.Rect(x * CELL, y * CELL + HUD_HEIGHT, CELL, CELL)
pygame.draw.rect(surface, color, rect.inflate(-2, -2), border_radius=4)
def draw_grid(surface):
for x in range(COLS):
pygame.draw.line(
surface, GRID,
(x * CELL, HUD_HEIGHT), (x * CELL, HEIGHT + HUD_HEIGHT),
)
for y in range(ROWS + 1):
pygame.draw.line(
surface, GRID,
(0, y * CELL + HUD_HEIGHT), (WIDTH, y * CELL + HUD_HEIGHT),
)
def initial_state():
mid = (COLS // 2, ROWS // 2)
snake = [mid, (mid[0] - 1, mid[1]), (mid[0] - 2, mid[1])]
return {
"snake": snake,
"direction": RIGHT,
"pending": RIGHT,
"food": new_food(snake),
"score": 0,
"speed": START_SPEED,
"alive": True,
}
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT + HUD_HEIGHT))
pygame.display.set_caption("Snake")
clock = pygame.time.Clock()
font = pygame.font.SysFont("consolas,menlo,monospace", 22)
big = pygame.font.SysFont("consolas,menlo,monospace", 44, bold=True)
state = initial_state()
move_accumulator = 0.0
turns = {
pygame.K_UP: UP, pygame.K_DOWN: DOWN,
pygame.K_LEFT: LEFT, pygame.K_RIGHT: RIGHT,
pygame.K_w: UP, pygame.K_s: DOWN,
pygame.K_a: LEFT, pygame.K_d: RIGHT,
}
while True:
dt = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit()
sys.exit()
if event.key == pygame.K_r and not state["alive"]:
state = initial_state()
move_accumulator = 0.0
elif event.key in turns and state["alive"]:
nd = turns[event.key]
# Ignore reversals into the neck.
if (nd[0] != -state["direction"][0] or
nd[1] != -state["direction"][1]):
state["pending"] = nd
# --- Update -------------------------------------------------------
if state["alive"]:
move_accumulator += dt
step_time = 1.0 / state["speed"]
while move_accumulator >= step_time and state["alive"]:
move_accumulator -= step_time
state["direction"] = state["pending"]
hx, hy = state["snake"][0]
dx, dy = state["direction"]
head = (hx + dx, hy + dy)
hit_wall = not (0 <= head[0] < COLS and 0 <= head[1] < ROWS)
# Tail tip moves away unless we're about to eat.
body = state["snake"] if head == state["food"] \
else state["snake"][:-1]
hit_self = head in body
if hit_wall or hit_self:
state["alive"] = False
break
state["snake"].insert(0, head)
if head == state["food"]:
state["score"] += 1
state["speed"] = min(
MAX_SPEED, state["speed"] + SPEED_STEP)
state["food"] = new_food(state["snake"])
if state["food"] is None: # board filled — you win
state["alive"] = False
else:
state["snake"].pop()
# --- Draw ---------------------------------------------------------
screen.fill(BG)
pygame.draw.rect(screen, (24, 24, 30), (0, 0, WIDTH, HUD_HEIGHT))
draw_grid(screen)
if state["food"] is not None:
draw_cell(screen, state["food"], FOOD)
for i, seg in enumerate(state["snake"]):
draw_cell(screen, seg, SNAKE_HEAD if i == 0 else SNAKE)
score_surf = font.render(f"Score: {state['score']}", True, TEXT)
speed_surf = font.render(
f"Speed: {state['speed']:.1f}", True, DIM)
screen.blit(score_surf, (12, 9))
screen.blit(speed_surf, (WIDTH - speed_surf.get_width() - 12, 9))
if not state["alive"]:
won = state["food"] is None
title = "You Win!" if won else "Game Over"
overlay = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
overlay.fill((0, 0, 0, 160))
screen.blit(overlay, (0, HUD_HEIGHT))
title_surf = big.render(title, True, TEXT)
info_surf = font.render(
"Press R to restart • Q to quit", True, DIM)
screen.blit(
title_surf,
title_surf.get_rect(
center=(WIDTH // 2, HEIGHT // 2 + HUD_HEIGHT - 20)),
)
screen.blit(
info_surf,
info_surf.get_rect(
center=(WIDTH // 2, HEIGHT // 2 + HUD_HEIGHT + 24)),
)
pygame.display.flip()
if __name__ == "__main__":
main()