Create Snake with Python
- User
Create Snake with 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.
Create Snake with Python
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course! Here is a complete, well-commented Snake game using Python's pygame library. It's a classic project and a great way to learn the fundamentals of game development.
First, you need to install the pygame library. Open your terminal or command prompt and type:
pip install pygame
Create a new Python file (e.g., snake_game.py) and paste the following code into it.
import pygame
import sys
import random
# --- Constants ---
# Screen dimensions
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 600
# Grid dimensions
GRID_SIZE = 20
GRID_WIDTH = SCREEN_WIDTH // GRID_SIZE
GRID_HEIGHT = SCREEN_HEIGHT // GRID_SIZE
# Colors (R, G, B)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 128, 0)
RED = (255, 0, 0)
DARK_GREEN = (0, 100, 0)
# Snake movement directions
UP = (0, -1)
DOWN = (0, 1)
LEFT = (-1, 0)
RIGHT = (1, 0)
# Game speed
FPS = 10
# --- Game Classes ---
class Snake:
"""Represents the snake."""
def __init__(self):
self.length = 1
# The snake is a list of segments, with the head at index 0
self.positions = [((SCREEN_WIDTH // 2), (SCREEN_HEIGHT // 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.color = GREEN
self.score = 0
def get_head_position(self):
"""Returns the position of the snake's head."""
return self.positions[0]
def turn(self, point):
"""Changes the snake's direction, preventing 180-degree turns."""
if self.length > 1 and (point[0] * -1, point[1] * -1) == self.direction:
return # Prevent the snake from reversing on itself
else:
self.direction = point
def move(self):
"""Moves the snake one step in its current direction."""
cur = self.get_head_position()
x, y = self.direction
# Calculate the new head position
new = (((cur[0] + (x * GRID_SIZE)) % SCREEN_WIDTH), (cur[1] + (y * GRID_SIZE)) % SCREEN_HEIGHT)
# Check for collision with itself
if len(self.positions) > 2 and new in self.positions[2:]:
self.reset() # Game over
else:
self.positions.insert(0, new)
# If the snake has grown longer than its length, remove the tail segment
if len(self.positions) > self.length:
self.positions.pop()
def reset(self):
"""Resets the snake to its initial state after a game over."""
self.length = 1
self.positions = [((SCREEN_WIDTH // 2), (SCREEN_HEIGHT // 2))]
self.direction = random.choice([UP, DOWN, LEFT, RIGHT])
self.score = 0
def draw(self, surface):
"""Draws the snake on the game screen."""
for i, p in enumerate(self.positions):
# The head is a slightly different color
color = self.color if i != 0 else DARK_GREEN
r = pygame.Rect((p[0], p[1]), (GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, color, r)
pygame.draw.rect(surface, BLACK, r, 1)
def handle_keys(self):
"""Handles keyboard input for controlling the snake."""
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.turn(UP)
elif event.key == pygame.K_DOWN:
self.turn(DOWN)
elif event.key == pygame.K_LEFT:
self.turn(LEFT)
elif event.key == pygame.K_RIGHT:
self.turn(RIGHT)
class Food:
"""Represents the food item."""
def __init__(self):
self.position = (0, 0)
self.color = RED
self.randomize_position()
def randomize_position(self):
"""Places the food at a new random location on the grid."""
self.position = (random.randint(0, GRID_WIDTH - 1) * GRID_SIZE,
random.randint(0, GRID_HEIGHT - 1) * GRID_SIZE)
def draw(self, surface):
"""Draws the food on the game screen."""
r = pygame.Rect((self.position[0], self.position[1]), (GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, self.color, r)
pygame.draw.rect(surface, BLACK, r, 1)
# --- Main Game Logic ---
def draw_grid(surface):
"""Draws the background grid."""
for y in range(0, int(GRID_HEIGHT)):
for x in range(0, int(GRID_WIDTH)):
if (x + y) % 2 == 0:
r = pygame.Rect((x * GRID_SIZE, y * GRID_SIZE), (GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, (30, 30, 30), r)
else:
r = pygame.Rect((x * GRID_SIZE, y * GRID_SIZE), (GRID_SIZE, GRID_SIZE))
pygame.draw.rect(surface, (40, 40, 40), r)
def main():
"""The main function to run the game."""
pygame.init()
# Setup the game window and clock
clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), 0, 32)
pygame.display.set_caption("Python Snake")
surface = pygame.Surface(screen.get_size())
surface = surface.convert()
# Create game objects
snake = Snake()
food = Food()
font = pygame.font.SysFont("monospace", 16)
# The main game loop
while True:
snake.handle_keys()
snake.move()
# Check for collision between snake head and food
if snake.get_head_position() == food.position:
snake.length += 1
snake.score += 1
food.randomize_position()
# Prevent food from spawning on the snake
while food.position in snake.positions:
food.randomize_position()
# --- Drawing everything ---
draw_grid(surface)
snake.draw(surface)
food.draw(surface)
# Blit everything to the main screen
screen.blit(surface, (0, 0))
# Display the score
score_text = font.render(f"Score: {snake.score}", True, WHITE)
screen.blit(score_text, (5, 10))
# Update the display
pygame.display.update()
# Control the game speed
clock.tick(FPS)
# Run the game
if __name__ == "__main__":
main()
pygame installed.snake_game.py.python snake_game.pyYou should see a window pop up, and you can control the snake with the arrow keys.
Constants and Setup: We define constants for screen size, grid size, colors, and directions. This makes the code cleaner and easier to modify. pygame.init() starts the engine.
Snake Class:
__init__: Initializes the snake's properties. It starts as a single block in the center of the screen. self.positions is a list of coordinates for each segment of the snake's body.get_head_position: A simple helper to get the coordinates of the snake's head (the first element in the positions list).turn: Changes the snake's direction based on key presses. It includes a crucial check to prevent the snake from reversing into itself.move: This is the core of the snake's logic. It calculates the new position of the head based on the current direction. It then inserts this new head into the positions list. If the snake hasn't eaten food, it removes the last segment (pop()), creating the illusion of movement.reset: This is called when the snake collides with itself, resetting the score and the snake's position.draw: Iterates through the positions list and draws a green rectangle for each segment.Food Class:
__init__: Creates a food object and gives it an initial random position.randomize_position: Calculates a new random position on the grid for the food to appear.draw: Draws the red food block on the screen.Main Game Loop (main function):
clock to control the game's speed, and creates instances of our Snake and Food classes.while True: This loop runs continuously.snake.handle_keys() checks for any key presses to change the snake's direction.snake.move() updates the snake's position.draw_grid), and then the snake and food are drawn in their new positions. The score is also rendered and displayed.pygame.display.update(): This makes everything that has been drawn visible on the screen.clock.tick(FPS): This is very important. It pauses the game for a short time to ensure the loop runs at a consistent speed (10 frames per second in this case). Without this, the game would run as fast as your computer could handle, making it unplayable.