create the code for snake game
- User
create the code for snake game
Assistant
A classic request! Here's a simple implementation of the Snake game in Python using the Pygame library. This code covers the basic gameplay mechanics:
Snake Game Code (Python + Pygame)
import pygame import sys import random import time # Game Constants WIDTH, HEIGHT = 800, 600 BLOCK_SIZE = 20 FPS = 10 # Colors WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) class SnakeGame: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption('Snake Game') self.clock = pygame.time.Clock() self.reset_game() def reset_game(self): self.snake = [(200, 200), (220, 200), (240, 200)] self.direction = 'RIGHT' self.apple = self.generate_apple() self.score = 0 def generate_apple(self): while True: x = random.randint(0, WIDTH - BLOCK_SIZE) // BLOCK_SIZE * BLOCK_SIZE y = random.randint(0, HEIGHT - BLOCK_SIZE) // BLOCK_SIZE * BLOCK_SIZE apple = (x, y) if apple not in self.snake: return apple def run(self): 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 self.direction != 'DOWN': self.direction = 'UP' elif event.key == pygame.K_DOWN and self.direction != 'UP': self.direction = 'DOWN' elif event.key == pygame.K_LEFT and self.direction != 'RIGHT': self.direction = 'LEFT' elif event.key == pygame.K_RIGHT and self.direction != 'LEFT': self.direction = 'RIGHT' elif event.key == pygame.K_r: self.reset_game() # Move snake head = self.snake[-1] if self.direction == 'UP': new_head = (head[0], head[1] - BLOCK_SIZE) elif self.direction == 'DOWN': new_head = (head[0], head[1] + BLOCK_SIZE) elif self.direction == 'LEFT': new_head = (head[0] - BLOCK_SIZE, head[1]) elif self.direction == 'RIGHT': new_head = (head[0] + BLOCK_SIZE, head[1]) self.snake.append(new_head) # Check collision with apple if self.snake[-1] == self.apple: self.score += 1 self.apple = self.generate_apple() else: self.snake.pop(0) # Check collision with wall or self if (self.snake[-1][0] < 0 or self.snake[-1][0] >= WIDTH or self.snake[-1][1] < 0 or self.snake[-1][1] >= HEIGHT or self.snake[-1] in self.snake[:-1]): time.sleep(1) # pause for 1 sec before resetting self.reset_game() # Draw everything self.screen.fill(BLACK) for x, y in self.snake: pygame.draw.rect(self.screen, GREEN, (x, y, BLOCK_SIZE, BLOCK_SIZE)) pygame.draw.rect(self.screen, RED, (*self.apple, BLOCK_SIZE, BLOCK_SIZE)) font = pygame.font.Font(None, 36) text = font.render(f'Score: {self.score}', True, WHITE) self.screen.blit(text, (10, 10)) pygame.display.flip() self.clock.tick(FPS) if __name__ == '__main__': game = SnakeGame() game.run()How to run:
- Install Pygame: Run
pip install pygamein your terminal/command prompt. - Save the code: Copy the code above and save it in a file named
snake_game.py. - Run the game: Execute
python snake_game.pyin your terminal/command prompt.
Gameplay:
- Use arrow keys (↑, ↓, ←, →) to control the snake.
- Eat the red apple to score points and grow the snake.
- Avoid hitting the walls or the snake's own body.
- Press
Rto reset the game after a collision. - The game runs at 10 frames per second (FPS).
Explanation:
The code consists of:
- Game Constants: Define the window size, block size, and frame rate.
- Colors: Define RGB values for colors used in the game.
SnakeGameclass: Encapsulates the game logic, initialization, and main loop.__init__: Initializes Pygame, sets up the window, and resets the game state.reset_game: Resets the snake, direction, apple, and score.generate_apple: Randomly generates a new apple position not occupied by the snake.run: The main game loop, handling events, moving the snake, checking collisions, and drawing everything.
Feel free to modify the code to add features like:
- Smoother animations (increase FPS)
- Scorekeeping and high scores
- Different levels or obstacles
- Sound effects
Happy gaming!
- Install Pygame: Run
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.