Write a snake game in Python
- User
Write a snake game in Python
- Assistant
Here's a simple implementation of the classic Snake game in Python using the Pygame library:
import pygame import random # Initialize Pygame pygame.init() # Set up the game window width, height = 800, 600 window = pygame.display.set_mode((width, height)) pygame.display.set_caption("Snake Game") # Define colors black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) # Set up the snake snake_size = 20 snake_speed = 15 snake_x = width // 2 snake_y = height // 2 snake_dx = 0 snake_dy = 0 snake_body = [] snake_length = 1 # Set up the food food_size = 20 food_x = round(random.randrange(0, width - food_size) / 20.0) * 20.0 food_y = round(random.randrange(0, height - food_size) / 20.0) * 20.0 # Game loop clock = pygame.time.Clock() game_over = False while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: game_over = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: snake_dx = -snake_size snake_dy = 0 elif event.key == pygame.K_RIGHT: snake_dx = snake_size snake_dy = 0 elif event.key == pygame.K_UP: snake_dx = 0 snake_dy = -snake_size elif event.key == pygame.K_DOWN: snake_dx = 0 snake_dy = snake_size # Move the snake snake_x += snake_dx snake_y += snake_dy # Check for collision with the boundaries if snake_x >= width or snake_x < 0 or snake_y >= height or snake_y < 0: game_over = True # Check for collision with the food if snake_x == food_x and snake_y == food_y: food_x = round(random.randrange(0, width - food_size) / 20.0) * 20.0 food_y = round(random.randrange(0, height - food_size) / 20.0) * 20.0 snake_length += 1 # Draw the game objects window.fill(black) pygame.draw.rect(window, red, [food_x, food_y, food_size, food_size]) snake_head = [] snake_head.append(snake_x) snake_head.append(snake_y) snake_body.append(snake_head) if len(snake_body) > snake_length: del snake_body[0] for segment in snake_body[:-1]: if segment == snake_head: game_over = True for segment in snake_body: pygame.draw.rect(window, white, [segment[0], segment[1], snake_size, snake_size]) pygame.display.update() clock.tick(snake_speed) # Quit the game pygame.quit()This code sets up a basic Snake game using Pygame. The game window is created, and the snake and food are represented as rectangles. The snake moves continuously in the direction specified by the arrow keys, and the player's objective is to eat the food by colliding with it. Each time the snake eats the food, its length increases by one segment. The game ends if the snake collides with the boundaries of the window or with its own body.
You can run this code to play the Snake game. Feel free to customize and enhance the game further by adding features like scoring, levels, or obstacles.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.