"""Snake - a Pygame.net game project. Steer the snake, eat the yellow pellets and avoid running into yourself. The snake wraps around the edges of the board. Run it: pip install pygame-ce (or: pip install pygame) python snake.py Controls: Arrow keys or WASD to steer, P to pause, Space or R to restart. License: MIT - https://pygame.net/licenses/ """ import asyncio import random import pygame CELL = 20 COLS, ROWS = 32, 22 HUD = 40 WIDTH, HEIGHT = COLS * CELL, ROWS * CELL + HUD FPS = 60 BG = (16, 26, 48) GRID = (24, 37, 64) SNAKE = (91, 147, 230) HEAD = (157, 194, 255) FOOD = (244, 197, 49) TEXT = (230, 236, 247) DIRECTIONS = { pygame.K_UP: (0, -1), pygame.K_w: (0, -1), pygame.K_DOWN: (0, 1), pygame.K_s: (0, 1), pygame.K_LEFT: (-1, 0), pygame.K_a: (-1, 0), pygame.K_RIGHT: (1, 0), pygame.K_d: (1, 0), } class Snake: def __init__(self): mid = (COLS // 2, ROWS // 2) self.body = [mid, (mid[0] - 1, mid[1]), (mid[0] - 2, mid[1])] self.direction = (1, 0) self.queued = [] # buffered turns so quick key presses are not lost self.grow = 0 @property def head(self): return self.body[0] def turn(self, new_dir): last = self.queued[-1] if self.queued else self.direction # Ignore reversing straight into the neck and duplicate presses. if new_dir != last and (new_dir[0] + last[0], new_dir[1] + last[1]) != (0, 0): if len(self.queued) < 3: self.queued.append(new_dir) def step(self): if self.queued: self.direction = self.queued.pop(0) x, y = self.head dx, dy = self.direction new_head = ((x + dx) % COLS, (y + dy) % ROWS) self.body.insert(0, new_head) if self.grow > 0: self.grow -= 1 else: self.body.pop() def hit_self(self): return self.head in self.body[1:] class Game: def __init__(self, seed=None): self.rng = random.Random(seed) self.font = pygame.font.Font(None, 30) self.big = pygame.font.Font(None, 64) self.best = 0 self.reset() def reset(self): self.snake = Snake() self.score = 0 self.step_time = 0.12 # seconds per move; shrinks as you score self.timer = 0.0 self.state = "playing" # playing, paused, over self.food = self.place_food() def place_food(self): free = [(c, r) for c in range(COLS) for r in range(ROWS) if (c, r) not in self.snake.body] return self.rng.choice(free) def handle_event(self, event): if event.type != pygame.KEYDOWN: return if self.state == "over" and event.key in (pygame.K_SPACE, pygame.K_r, pygame.K_RETURN): self.reset() elif event.key == pygame.K_p and self.state != "over": self.state = "paused" if self.state == "playing" else "playing" elif event.key in DIRECTIONS and self.state == "playing": self.snake.turn(DIRECTIONS[event.key]) def update(self, dt): if self.state != "playing": return self.timer += dt while self.timer >= self.step_time: self.timer -= self.step_time self.snake.step() if self.snake.hit_self(): self.state = "over" self.best = max(self.best, self.score) return if self.snake.head == self.food: self.score += 1 self.snake.grow += 2 self.step_time = max(0.055, self.step_time * 0.97) self.food = self.place_food() def draw(self, surface): surface.fill(BG) for c in range(COLS): for r in range(ROWS): if (c + r) % 2 == 0: surface.fill(GRID, (c * CELL, HUD + r * CELL, CELL, CELL)) fx, fy = self.food pygame.draw.rect(surface, FOOD, (fx * CELL + 4, HUD + fy * CELL + 4, CELL - 8, CELL - 8), border_radius=3) for i, (x, y) in enumerate(self.snake.body): color = HEAD if i == 0 else SNAKE pygame.draw.rect(surface, color, (x * CELL + 1, HUD + y * CELL + 1, CELL - 2, CELL - 2), border_radius=4) pygame.draw.rect(surface, (11, 18, 34), (0, 0, WIDTH, HUD)) surface.blit(self.font.render(f"Score {self.score}", True, TEXT), (14, 11)) best = self.font.render(f"Best {self.best}", True, TEXT) surface.blit(best, (WIDTH - best.get_width() - 14, 11)) if self.state == "paused": self.banner(surface, "Paused", "Press P to continue") elif self.state == "over": self.banner(surface, "Game over", "Press Space to play again") def banner(self, surface, title, hint): shade = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA) shade.fill((0, 0, 0, 150)) surface.blit(shade, (0, 0)) t = self.big.render(title, True, FOOD) h = self.font.render(hint, True, TEXT) surface.blit(t, t.get_rect(center=(WIDTH // 2, HEIGHT // 2 - 20))) surface.blit(h, h.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 30))) async def main(): pygame.init() screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Snake - Pygame.net") clock = pygame.time.Clock() game = Game() running = True while running: dt = clock.tick(FPS) / 1000 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False else: game.handle_event(event) game.update(dt) game.draw(screen) pygame.display.flip() await asyncio.sleep(0) # lets the browser draw when running on the web pygame.quit() if __name__ == "__main__": asyncio.run(main())