Write A snake game
- User
Write A snake game
- Assistant
Here's a simple implementation of the classic Snake game using Python and the Pygame library:
pythonimport 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_x = round(random.randrange(0, width - snake_size) / snake_size) * snake_size food_y = round(random.randrange(0, height - snake_size) / snake_size) * snake_size # Set up the game clock clock = pygame.time.Clock() # Game loop running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and snake_dx != snake_size: snake_dx = -snake_size snake_dy = 0 elif event.key == pygame.K_RIGHT and snake_dx != -snake_size: snake_dx = snake_size snake_dy = 0 elif event.key == pygame.K_UP and snake_dy != snake_size: snake_dx = 0 snake_dy = -snake_size elif event.key == pygame.K_DOWN and snake_dy != -snake_size: 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 < 0 or snake_x >= width or snake_y < 0 or snake_y >= height: running = False # Check for collision with the food if snake_x == food_x and snake_y == food_y: food_x = round(random.randrange(0, width - snake_size) / snake_size) * snake_size food_y = round(random.randrange(0, height - snake_size) / snake_size) * snake_size snake_length += 1 # Update the snake body snake_head = [snake_x, snake_y] snake_body.append(snake_head) if len(snake_body) > snake_length: del snake_body[0] # Check for collision with the snake body for segment in snake_body[:-1]: if segment == snake_head: running = False # Clear the window window.fill(black) # Draw the snake for segment in snake_body: pygame.draw.rect(window, white, [segment[0], segment[1], snake_size, snake_size]) # Draw the food pygame.draw.rect(window, red, [food_x, food_y, snake_size, snake_size]) # Update the display pygame.display.update() # Set the game clock clock.tick(snake_speed) # Quit the game pygame.quit()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.