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.
Sure! Let's create a simple Snake game using Python and the Pygame library. This classic game involves controlling a snake to eat food while avoiding crashing into walls or itself. Below, I'll provide the full code along with explanations to help you understand each part.
Before we start, make sure you have the following installed:
Python: You can download Python from python.org.
Pygame library: Install it using pip with the following command:
pip install pygame
import pygame
import random
# Initialize Pygame
pygame.init()
# ----------------------------
# Define Colors (R, G, B)
# ----------------------------
WHITE = (255, 255, 255)
YELLOW = (255, 255, 102)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
# ----------------------------
# Game Window Dimensions
# ----------------------------
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 400
# Create the game window
game_window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('Snake Game')
# Set the game clock
clock = pygame.time.Clock()
# ----------------------------
# Snake and Food Settings
# ----------------------------
SNAKE_BLOCK = 10 # Size of each block of the snake
SNAKE_SPEED = 15 # Initial speed of the snake
# ----------------------------
# Fonts for Text Display
# ----------------------------
SCORE_FONT = pygame.font.SysFont('arial', 25)
MESSAGE_FONT = pygame.font.SysFont('arial', 35)
# ----------------------------
# Functions
# ----------------------------
def display_score(score):
"""Display the current score on the screen."""
value = SCORE_FONT.render(f"Score: {score}", True, YELLOW)
game_window.blit(value, [0, 0])
def draw_snake(snake_block, snake_list):
"""Draw the snake on the screen."""
for block in snake_list:
pygame.draw.rect(game_window, BLACK, [block[0], block[1], snake_block, snake_block])
def show_message(message, color):
"""Display a message in the center of the screen."""
msg = MESSAGE_FONT.render(message, True, color)
msg_rect = msg.get_rect(center=(WINDOW_WIDTH / 2, WINDOW_HEIGHT / 2))
game_window.blit(msg, msg_rect)
# ----------------------------
# Main Game Function
# ----------------------------
def game_loop():
game_over = False
game_close = False
# Starting position of the snake
x = WINDOW_WIDTH / 2
y = WINDOW_HEIGHT / 2
# Initial movement direction
x_change = 0
y_change = 0
# Initial snake body
snake_list = []
snake_length = 1
# Initial food position
food_x = round(random.randrange(0, WINDOW_WIDTH - SNAKE_BLOCK) / 10.0) * 10.0
food_y = round(random.randrange(0, WINDOW_HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0
while not game_over:
while game_close:
game_window.fill(BLUE)
show_message("You Lost! Press C to Play Again or Q to Quit", RED)
display_score(snake_length - 1)
pygame.display.update()
# Event handling when the game is over
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:
game_loop()
if event.type == pygame.QUIT:
game_over = True
game_close = False
# Event handling for movement
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 x_change == 0:
x_change = -SNAKE_BLOCK
y_change = 0
elif event.key == pygame.K_RIGHT and x_change == 0:
x_change = SNAKE_BLOCK
y_change = 0
elif event.key == pygame.K_UP and y_change == 0:
y_change = -SNAKE_BLOCK
x_change = 0
elif event.key == pygame.K_DOWN and y_change == 0:
y_change = SNAKE_BLOCK
x_change = 0
# Check for boundaries collision
if x >= WINDOW_WIDTH or x < 0 or y >= WINDOW_HEIGHT or y < 0:
game_close = True
x += x_change
y += y_change
game_window.fill(BLUE)
pygame.draw.rect(game_window, GREEN, [food_x, food_y, SNAKE_BLOCK, SNAKE_BLOCK])
# Update snake's body
snake_head = [x, y]
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
# Check if the snake collided with itself
for block in snake_list[:-1]:
if block == snake_head:
game_close = True
draw_snake(SNAKE_BLOCK, snake_list)
display_score(snake_length - 1)
pygame.display.update()
# Check if the snake has eaten the food
if x == food_x and y == food_y:
food_x = round(random.randrange(0, WINDOW_WIDTH - SNAKE_BLOCK) / 10.0) * 10.0
food_y = round(random.randrange(0, WINDOW_HEIGHT - SNAKE_BLOCK) / 10.0) * 10.0
snake_length += 1
clock.tick(SNAKE_SPEED)
pygame.quit()
quit()
# Start the game
game_loop()
pygame for game functionality and random for generating random positions for the food.pygame.init() initializes all the Pygame modules.WINDOW_WIDTH and WINDOW_HEIGHT for the game window size.pygame.display.set_mode() creates the window where everything will be drawn.pygame.display.set_caption() sets the title of the game window.pygame.time.Clock() will be used to control the game's frame rate.SNAKE_BLOCK defines the size of each block of the snake. SNAKE_SPEED controls how fast the snake moves.pygame.font.SysFont().display_score(score): Renders the current score and displays it on the screen.draw_snake(snake_block, snake_list): Draws each block of the snake onto the game window.show_message(message, color): Displays a message in the center of the screen when the game ends.game_loop() function)game_over and game_close control the main loop and the end-of-game loop.x_change and y_change track the direction the snake is moving.snake_list keeps track of all segments of the snake's body.food_x and food_y for the food's location.Event Handling:
Game Logic:
clock.tick(SNAKE_SPEED).Save the Code: Copy the code into a file named snake_game.py.
Run the Game: Open your terminal or command prompt, navigate to the directory containing snake_game.py, and run:
python snake_game.py
C to play again or Q to quit.SNAKE_SPEED to make the game faster or slower.SNAKE_BLOCK to make the snake and food larger or smaller.WINDOW_WIDTH and WINDOW_HEIGHT for a bigger or smaller game area.Feel free to experiment with the code, add new features, or improve the game's appearance. This is a great way to practice Python programming and game development concepts.
If you have any questions or need further assistance, don't hesitate to ask!
Not yet included in a published release.