import pygame
import sys
import time
import random
# Initialize Pygame
pygame.init()
# Set up display
CELL_SIZE = 20
CELL_NUMBER = 30
SCREEN_WIDTH = CELL_SIZE * CELL_NUMBER
SCREEN_HEIGHT = CELL_SIZE * CELL_NUMBER
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Snake Game')
# Set up game clock
clock = pygame.time.Clock()
# Define colors
RED = pygame.Color('red')
GREEN = pygame.Color('green')
BLACK = pygame.Color('black')
WHITE = pygame.Color('white')
# Set up font
font = pygame.font.SysFont('arial', 25)
def show_score(score):
"""Display the current score on the screen."""
score_surface = font.render(f'Score: {score}', True, WHITE)
score_rect = score_surface.get_rect()
screen.blit(score_surface, score_rect)
def game_over(score):
"""Handle game over state."""
game_over_font = pygame.font.SysFont('arial', 50)
game_over_surface = game_over_font.render('Game Over', True, RED)
game_over_rect = game_over_surface.get_rect(center=(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2))
screen.blit(game_over_surface, game_over_rect)
pygame.display.flip()
time.sleep(2)
pygame.quit()
sys.exit()
def main():
# Initial snake position and body
snake_pos = [SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2]
snake_body = [list(snake_pos), [snake_pos[0] - CELL_SIZE, snake_pos[1]], [snake_pos[0] - (2 * CELL_SIZE), snake_pos[1]]]
direction = 'RIGHT'
change_to = direction
# Initial food position
food_pos = [random.randrange(1, CELL_NUMBER) * CELL_SIZE, random.randrange(1, CELL_NUMBER) * CELL_SIZE]
food_spawn = True
# Initial score
score = 0
while True:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Key press events
elif event.type == pygame.KEYDOWN:
if event.key in (pygame.K_UP, pygame.K_w) and direction != 'DOWN':
change_to = 'UP'
elif event.key in (pygame.K_DOWN, pygame.K_s) and direction != 'UP':
change_to = 'DOWN'
elif event.key in (pygame.K_LEFT, pygame.K_a) and direction != 'RIGHT':
change_to = 'LEFT'
elif event.key in (pygame.K_RIGHT, pygame.K_d) and direction != 'LEFT':
change_to = 'RIGHT'
elif event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
# Validate direction change
if change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
elif change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
elif change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
elif change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
# Move the snake
if direction == 'UP':
snake_pos[1] -= CELL_SIZE
elif direction == 'DOWN':
snake_pos[1] += CELL_SIZE
elif direction == 'LEFT':
snake_pos[0] -= CELL_SIZE
elif direction == 'RIGHT':
snake_pos[0] += CELL_SIZE
# Snake body growing mechanism
snake_body.insert(0, list(snake_pos))
if snake_pos == food_pos:
score += 1
food_spawn = False
else:
snake_body.pop()
# Spawn new food
if not food_spawn:
food_pos = [random.randrange(1, CELL_NUMBER) * CELL_SIZE, random.randrange(1, CELL_NUMBER) * CELL_SIZE]
food_spawn = True
# Clear screen
screen.fill(BLACK)
# Draw snake
for block in snake_body:
pygame.draw.rect(screen, GREEN, pygame.Rect(block[0], block[1], CELL_SIZE, CELL_SIZE))
# Draw food
pygame.draw.rect(screen, RED, pygame.Rect(food_pos[0], food_pos[1], CELL_SIZE, CELL_SIZE))
# Check for collisions with boundaries
if (snake_pos[0] < 0 or snake_pos[0] >= SCREEN_WIDTH or
snake_pos[1] < 0 or snake_pos[1] >= SCREEN_HEIGHT):
game_over(score)
# Check for collisions with itself
if snake_pos in snake_body[1:]:
game_over(score)
# Display score
show_score(score)
# Refresh game screen
pygame.display.update()
# Set game speed
clock.tick(15)
if __name__ == '__main__':
main()