Write a snake game in Python, please!
- User
Write a snake game in Python, please!
Assistant
Certainly! Below is a simple implementation of the classic snake game in Python. The game is played in a terminal, and the snake will move around the screen to collect food, getting longer with each piece of food it consumes. The game ends when the snake hits the wall or itself.
import curses import random import time # Game window dimensions WIDTH = 100 HEIGHT = 30 # Colors WHITE = curses.color_pair(1) GREEN = curses.color_pair(2) RED = curses.color_pair(3) # Initialize curses stdscr = curses.initscr() curses.noecho() curses.cbreak() stdscr.keypad(True) # Game variables snake_body = [(WIDTH // 2, HEIGHT // 2)] # Head position direction = "right" # Direction the snake is facing food_pos = [random.randint(0, WIDTH - 1), random.randint(0, HEIGHT - 1)] score = 0 # Draw the game area def draw_game(): stdscr.clear() stdscr.border(0) stdscr.addstr(0, WIDTH // 2, "SCORE: " + str(score)) for i in range(WIDTH): for j in range(HEIGHT): if (i, j) == food_pos: stdscr.addch(j, i, "o", GREEN) elif (i, j) in snake_body: stdscr.addch(j, i, "@", WHITE) else: stdscr.addch(j, i, " ") stdscr.refresh() # Move the snake def move_snake(): # Get the next coordinates based on the direction next_pos = [(snake_body[-1][0] + 1, snake_body[-1][1]) if direction == "right" else (snake_body[-1][0] - 1, snake_body[-1][1]) if direction == "left" else (snake_body[-1][0], snake_body[-1][1] + 1) if direction == "down" else (snake_body[-1][0], snake_body[-1][1] - 1) if direction == "up" else (snake_body[-1][0], snake_body[-1][1])] # Check if the new position is out of bounds or collides with the snake if (0 <= next_pos[0] < WIDTH and 0 <= next_pos[1] < HEIGHT and next_pos not in snake_body): # Move the head snake_body.append(next_pos) # Remove the last segment of the snake snake_body.pop(0) # Draw the new snake draw_game() # Check if the snake ate the food if food_pos == next_pos: food_pos = [random.randint(0, WIDTH - 1), random.randint(0, HEIGHT - 1)] score += 1 print(f"Score: {score}", end="\r") # Handle user input def handle_input(ch): # Handle up, down, left, right keys if ch == curses.KEY_UP and direction != "down": direction = "up" elif ch == curses.KEY_DOWN and direction != "up": direction = "down" elif ch == curses.KEY_LEFT and direction != "right": direction = "left" elif ch == curses.KEY_RIGHT and direction != "left": direction = "right" # Game loop running = True while running: # Handle user input ch = stdscr.getch() handle_input(ch) # Move the snake move_snake() # Check for game over conditions if food_pos == snake_body[0]: print(f"Game Over!\nYour score is: {score}") running = False elif len(
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.