o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
create snake game
- User
create snake game
- Assistant
create snake game
Certainly! Let's create a classic Snake game using Python. We'll use the Pygame library, which is a popular choice for creating games in Python. If you don't have Pygame installed, you can install it using pip:
pip install pygame
Below is the complete code for the Snake game. You can copy this code into a file named snake_game.py and run it.
import pygame
import sys
import time
import random
# Initialize Pygame
pygame.init()
# Set up display
window_width = 600
window_height = 400
game_window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('Snake Game')
# Define colors
BLACK = pygame.Color(0, 0, 0) # Background
WHITE = pygame.Color(255, 255, 255) # Snake
RED = pygame.Color(255, 0, 0) # Food
GREEN = pygame.Color(0, 255, 0) # Score
BLUE = pygame.Color(0, 0, 255) # Game Over text
# FPS (frames per second) controller
fps_controller = pygame.time.Clock()
# Game variables
snake_position = [100, 50]
snake_body = [[100, 50],
[90, 50],
[80, 50]]
food_position = [random.randrange(1, (window_width // 10)) * 10,
random.randrange(1, (window_height // 10)) * 10]
food_spawn = True
direction = 'RIGHT'
change_to = direction
score = 0
# Display Score function
def show_score(choice=1):
font = pygame.font.SysFont('arial', 20)
score_surface = font.render('Score : ' + str(score), True, GREEN)
score_rect = score_surface.get_rect()
if choice == 1:
score_rect.topleft = (10, 10)
else:
score_rect.midtop = (window_width / 2, window_height / 1.25)
game_window.blit(score_surface, score_rect)
# Game Over function
def game_over():
font = pygame.font.SysFont('arial', 50)
game_over_surface = font.render('GAME OVER', True, BLUE)
game_over_rect = game_over_surface.get_rect()
game_over_rect.midtop = (window_width / 2, window_height / 4)
game_window.fill(BLACK)
game_window.blit(game_over_surface, game_over_rect)
show_score(0)
pygame.display.flip()
time.sleep(2)
pygame.quit()
sys.exit()
# Main Logic
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Whenever a key is pressed down
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP or event.key == ord('w'):
if direction != 'DOWN':
change_to = 'UP'
if event.key == pygame.K_DOWN or event.key == ord('s'):
if direction != 'UP':
change_to = 'DOWN'
if event.key == pygame.K_LEFT or event.key == ord('a'):
if direction != 'RIGHT':
change_to = 'LEFT'
if event.key == pygame.K_RIGHT or event.key == ord('d'):
if direction != 'LEFT':
change_to = 'RIGHT'
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(pygame.QUIT))
# Validate direction
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Move the snake
if direction == 'UP':
snake_position[1] -= 10
if direction == 'DOWN':
snake_position[1] += 10
if direction == 'LEFT':
snake_position[0] -= 10
if direction == 'RIGHT':
snake_position[0] += 10
# Snake body growing mechanism
snake_body.insert(0, list(snake_position))
if snake_position == food_position:
score += 10
food_spawn = False
else:
snake_body.pop()
# Spawn new food
if not food_spawn:
food_position = [random.randrange(1, (window_width // 10)) * 10,
random.randrange(1, (window_height // 10)) * 10]
food_spawn = True
# Clear screen and draw background
game_window.fill(BLACK)
# Draw snake
for pos in snake_body:
pygame.draw.rect(game_window, WHITE, pygame.Rect(pos[0], pos[1], 10, 10))
# Draw food
pygame.draw.rect(game_window, RED, pygame.Rect(food_position[0], food_position[1], 10, 10))
# Game Over conditions
# Snake hits boundaries
if snake_position[0] < 0 or snake_position[0] > window_width - 10:
game_over()
if snake_position[1] < 0 or snake_position[1] > window_height - 10:
game_over()
# Snake hits itself
for block in snake_body[1:]:
if snake_position == block:
game_over()
# Display score
show_score()
# Refresh game screen
pygame.display.update()
# Frame Per Second /Refresh Rate
fps_controller.tick(15)
pip install pygame
snake_game.py.python snake_game.py
WSADEscImports and Initialization:
pygame, sys, time, random.pygame.init().Display Setup:
Colors:
Game Variables:
snake_position: Stores the x and y coordinates of the snake's head.snake_body: List of segments that make up the snake's body.food_position: Randomly generated x and y coordinates for the food.direction: Current direction of the snake's movement.change_to: The direction that the snake will move towards, based on user input.score: Player's score.Functions:
show_score():
game_over():
Main Game Loop:
Enjoy playing the classic Snake game! Feel free to modify and enhance the code to add more features and make it your own.
Not yet included in a published release.
fps_controller.tick(15).