write a snake game
- User
write a snake game
- 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 a snake game
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Certainly! I'll help you create a simple Snake game using Python and the Pygame library. This classic game involves controlling a snake to eat food, while avoiding collisions with the walls or itself. Below is the step-by-step code with explanations.
First, ensure you have Python installed on your system. Then, install Pygame by running:
pip install pygame
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 600
SCREEN_HEIGHT = 400
# Colors (R, G, B)
WHITE = (255, 255, 255)
RED = (220, 20, 60)
GREEN = (0, 255, 127)
BLACK = (0, 0, 0)
# Create the screen object
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Snake Game")
# Clock to control the game's frame rate
clock = pygame.time.Clock()
# Snake variables
snake_size = 20
snake_speed = 15
font_style = pygame.font.SysFont(None, 35)
score_font = pygame.font.SysFont(None, 30)
def our_snake(snake_size, snake_list):
"""Draws the snake on the screen."""
for x in snake_list:
pygame.draw.rect(screen, GREEN, [x[0], x[1], snake_size, snake_size])
def message(msg, color):
"""Displays a message on the screen."""
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [SCREEN_WIDTH / 6, SCREEN_HEIGHT / 3])
def gameLoop():
"""Main game loop."""
game_over = False
game_close = False
# Starting position
x1 = SCREEN_WIDTH / 2
y1 = SCREEN_HEIGHT / 2
# Movement variables
x1_change = 0
y1_change = 0
# Snake body list and initial length
snake_List = []
Length_of_snake = 1
# Food position
foodx = round(random.randrange(0, SCREEN_WIDTH - snake_size) / 20.0) * 20.0
foody = round(random.randrange(0, SCREEN_HEIGHT - snake_size) / 20.0) * 20.0
while not game_over:
while game_close:
screen.fill(BLACK)
message("Game Over! Press C-Play Again or Q-Quit", RED)
pygame.display.update()
# Event handling for game over screen
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Event handling for game play
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
# Control the snake
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_size
x1_change = 0
# Check for boundaries
if x1 >= SCREEN_WIDTH or x1 < 0 or y1 >= SCREEN_HEIGHT or y1 < 0:
game_close = True
# Update snake position
x1 += x1_change
y1 += y1_change
# Draw everything
screen.fill(BLACK)
pygame.draw.rect(screen, RED, [foodx, foody, snake_size, snake_size])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
# Keep the length of the snake
if len(snake_List) > Length_of_snake:
del snake_List[0]
# Check if snake collides with itself
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
our_snake(snake_size, snake_List)
# Display score
value = score_font.render("Your Score: " + str(Length_of_snake - 1), True, WHITE)
screen.blit(value, [0, 0])
pygame.display.update()
# Check if snake eats food
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, SCREEN_WIDTH - snake_size) / 20.0) * 20.0
foody = round(random.randrange(0, SCREEN_HEIGHT - snake_size) / 20.0) * 20.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
sys.exit()
gameLoop()
Import Necessary Modules:
pygame is used for game development.sys provides access to system-specific parameters.random is used to place the food at random positions.Initialize Pygame and Set Up the Display:
pygame.init() initializes all imported Pygame modules.pygame.display.set_mode() sets the window size.pygame.display.set_caption() sets the window title.Define Colors and Screen Dimensions:
Define Functions:
our_snake(): Draws the snake on the screen using a list of positions.message(): Displays messages on the screen, such as "Game Over" prompts.Main Game Loop (gameLoop function):
clock.tick(snake_speed) to control the frame rate.Game Over Handling:
Scoring:
Ensure you've saved the code in a file with a .py extension, for example, snake_game.py. Run the game by navigating to the directory in a terminal and executing:
python snake_game.py
snake_speed to make the game faster or slower.snake_size for a bigger or smaller snake.SCREEN_WIDTH and SCREEN_HEIGHT to change the window dimensions.You've now created a basic Snake game using Python and Pygame! This foundational code can be expanded with additional features like levels, obstacles, or improved graphics.
Feel free to ask if you have any questions or need further assistance customizing the game.
Not yet included in a published release.