Pls Programme a snake game
- User
Pls Programme a snake game
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Pls Programme a snake game
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's program a classic Snake game!
For a graphical and interactive game, the pygame library is ideal in Python. If you don't have it installed, open your terminal or command prompt and run:
pip install pygame
Here's the Python code for a Snake game using pygame:
import pygame
import random
import sys
# --- Game Constants ---
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
GRID_SIZE = 20 # Each segment of the snake and food will be 20x20 pixels
# Colors (RGB tuples)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0) # Snake color
RED = (255, 0, 0) # Food color
GRAY = (150, 150, 150) # Game Over text background
# Snake Speed (frames per second)
SNAKE_SPEED = 10
# Directions
UP = (0, -GRID_SIZE)
DOWN = (0, GRID_SIZE)
LEFT = (-GRID_SIZE, 0)
RIGHT = (GRID_SIZE, 0)
# --- Game Initialization ---
def init_game():
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Python Snake Game")
clock = pygame.time.Clock()
font = pygame.font.SysFont("Arial", 24)
return screen, clock, font
# --- Snake Class ---
class Snake:
def __init__(self):
# Initial snake position (center of the screen)
self.segments = [(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)]
self.direction = RIGHT # Initial direction
self.grow = False # Flag to make snake grow after eating food
def move(self):
head_x, head_y = self.segments[0]
dx, dy = self.direction
new_head = (head_x + dx, head_y + dy)
# Check for collision with walls
if not (0 <= new_head[0] < SCREEN_WIDTH and 0 <= new_head[1] < SCREEN_HEIGHT):
return "wall_collision"
# Check for collision with self (excluding the very first segment before it moves)
if new_head in self.segments[1:]:
return "self_collision"
self.segments.insert(0, new_head) # Add new head
if not self.grow:
self.segments.pop() # Remove tail if not growing
else:
self.grow = False # Reset grow flag
return None # No collision
def change_direction(self, new_dir):
# Prevent immediately reversing direction (e.g., cannot go down if currently going up)
if (new_dir == UP and self.direction == DOWN) or \
(new_dir == DOWN and self.direction == UP) or \
(new_dir == LEFT and self.direction == RIGHT) or \
(new_dir == RIGHT and self.direction == LEFT):
return
self.direction = new_dir
def eat_food(self):
self.grow = True
def draw(self, screen):
for segment in self.segments:
pygame.draw.rect(screen, GREEN, (segment[0], segment[1], GRID_SIZE, GRID_SIZE))
# Optional: Add a small black border to each segment for better visibility
pygame.draw.rect(screen, BLACK, (segment[0], segment[1], GRID_SIZE, GRID_SIZE), 1)
# --- Food Class ---
class Food:
def __init__(self):
self.position = self.generate_new_position()
def generate_new_position(self):
# Ensure food spawns on the grid
x = random.randrange(0, SCREEN_WIDTH, GRID_SIZE)
y = random.randrange(0, SCREEN_HEIGHT, GRID_SIZE)
return (x, y)
def draw(self, screen):
pygame.draw.rect(screen, RED, (self.position[0], self.position[1], GRID_SIZE, GRID_SIZE))
# --- Main Game Loop ---
def main():
screen, clock, font = init_game()
snake = Snake()
food = Food()
score = 0
game_over = False
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if not game_over:
if event.key == pygame.K_UP:
snake.change_direction(UP)
elif event.key == pygame.K_DOWN:
snake.change_direction(DOWN)
elif event.key == pygame.K_LEFT:
snake.change_direction(LEFT)
elif event.key == pygame.K_RIGHT:
snake.change_direction(RIGHT)
elif event.key == pygame.K_r: # 'R' key to restart
snake = Snake()
food = Food()
score = 0
game_over = False
if not game_over:
collision_result = snake.move()
if collision_result:
game_over = True
# Check if snake eats food
if snake.segments[0] == food.position:
snake.eat_food()
score += 1
# Generate new food position, ensuring it's not on the snake
while True:
new_food_pos = food.generate_new_position()
if new_food_pos not in snake.segments:
food.position = new_food_pos
break
# --- Drawing ---
screen.fill(BLACK) # Clear screen
snake.draw(screen)
food.draw(screen)
# Display score
score_text = font.render(f"Score: {score}", True, WHITE)
screen.blit(score_text, (5, 5))
# Game Over screen
if game_over:
game_over_text = font.render("Game Over!", True, WHITE)
restart_text = font.render("Press 'R' to Restart", True, WHITE)
# Center the text
text_rect = game_over_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 - 20))
restart_rect = restart_text.get_rect(center=(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2 + 20))
# Optional: Add a translucent background for text
pygame.draw.rect(screen, GRAY, (text_rect.left - 10, text_rect.top - 10, text_rect.width + 20, text_rect.height + restart_rect.height + 40), 0, 10) # Added border radius
screen.blit(game_over_text, text_rect)
screen.blit(restart_text, restart_rect)
pygame.display.flip() # Update the full display Surface to the screen
clock.tick(SNAKE_SPEED) # Control game speed
if __name__ == "__main__":
main()
snake_game.py).pip install pygame.python snake_game.py