write the game snake in python
- User
write the game snake in python
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
write the game snake in python
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import pygame
import random
import sys
# --- Constants ---
GRID_SIZE = 20
WIDTH = 600
HEIGHT = 480
SNAKE_COLOR = (0, 255, 0) # Green
FOOD_COLOR = (255, 0, 0) # Red
BACKGROUND_COLOR = (0, 0, 0) # Black
FONT_COLOR = (255, 255, 255) # White
FONT_SIZE = 20
FPS = 10 # Frames per second
# --- Snake Class ---
class Snake:
def __init__(self, initial_length=5):
self.body = [(WIDTH // 2, HEIGHT // 2)] # Starting position
self.direction = (1, 0) # Initial direction: right
self.length = initial_length
def move(self):
head_x, head_y = self.body[0]
new_head = (head_x + self.direction[0] * GRID_SIZE, head_y + self.direction[1] * GRID_SIZE)
# Check for collision with walls
if (
new_head[0] < 0
or new_head[0] >= WIDTH
or new_head[1] < 0
or new_head[1] >= HEIGHT
):
return False # Game over
# Check for collision with itself
if new_head in self.body:
return False # Game over
self.body.insert(0, new_head) # Add new head
self.body.pop() # Remove tail
return True # Game continues
def grow(self):
self.length += 1
def draw(self, screen):
for x, y in self.body:
pygame.draw.rect(screen, SNAKE_COLOR, (x, y, GRID_SIZE, GRID_SIZE))
# --- Food Class ---
class Food:
def __init__(self):
self.x = random.randint(0, (WIDTH // GRID_SIZE) - 1) * GRID_SIZE
self.y = random.randint(0, (HEIGHT // GRID_SIZE) - 1) * GRID_SIZE
def respawn(self):
self.x = random.randint(0, (WIDTH // GRID_SIZE) - 1) * GRID_SIZE
self.y = random.randint(0, (HEIGHT // GRID_SIZE) - 1) * GRID_SIZE
def draw(self, screen):
pygame.draw.rect(screen, FOOD_COLOR, (self.x, self.y, GRID_SIZE, GRID_SIZE))
# --- Game Functions ---
def main():
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Snake Game")
clock = pygame.time.Clock()
snake = Snake()
food = Food()
score = 0
game_over = False
# --- Game Loop ---
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake.direction != (1, 0):
snake.direction = (-1, 0)
elif event.key == pygame.K_RIGHT and snake.direction != (-1, 0):
snake.direction = (1, 0)
elif event.key == pygame.K_UP and snake.direction != (0, -1):
snake.direction = (0, 1)
elif event.key == pygame.K_DOWN and snake.direction != (0, 1):
snake.direction = (0, -1)
# --- Game Logic ---
if not snake.move():
game_over = True
print("Game Over! Score:", score)
break
if snake.body[0][0] == food.x and snake.body[0][1] == food.y:
snake.grow()
food.respawn()
score += 1
# --- Drawing ---
screen.fill(BACKGROUND_COLOR)
snake.draw(screen)
food.draw(screen)
# --- Display Score ---
font = pygame.font.Font(None, FONT_SIZE)
score_text = font.render("Score: " + str(score), True, FONT_COLOR)
screen.blit(score_text, (10, 10))
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Key improvements and explanations:
Snake, Food) and functions (main) for better readability and maintainability.__init__: Initializes the snake's body with a starting position and direction.move(): Handles snake movement, collision detection (walls and self), and updating the snake's body. Crucially, it returns True if the game continues and False if the game is over.grow(): Increases the snake's length.draw(): Draws the snake's body on the screen.__init__: Randomly places the food on the grid.respawn(): Places the food in a new random location when eaten.draw(): Draws the food on the screen.snake.move() to update the snake's position and check for game over.pygame.display.flip() to update the display.clock.tick(FPS) to control the game speed.sys.exit(): Properly exits the program after quitting Pygame.if __name__ == "__main__":: Ensures that the main() function is only called when the script is run directly (not when it's imported as a module).head_x, head_y).How to run the code:
Install Pygame:
pip install pygame
Save the code: Save the code as a .py file (e.g., snake.py).
Run the file:
python snake.py
Now you can play the Snake game! Use the arrow keys to control the snake's direction.