Amazing-Python-Scripts
102 строки · 2.7 Кб
1import pygame2import random3
4# Initialize pygame
5pygame.init()6
7# Set the screen dimensions
8screen_width = 6409screen_height = 48010
11# Set the colors
12black = pygame.Color(0, 0, 0)13white = pygame.Color(255, 255, 255)14red = pygame.Color(255, 0, 0)15
16# Create the game window
17screen = pygame.display.set_mode((screen_width, screen_height))18pygame.display.set_caption("Snake Game")19
20# Set the game clock
21clock = pygame.time.Clock()22
23# Set the snake's initial position and speed
24snake_position = [100, 50]25snake_body = [[100, 50], [90, 50], [80, 50]]26snake_speed = 1027
28# Set the initial food position
29food_position = [random.randrange(1, screen_width // 10) * 10,30random.randrange(1, screen_height // 10) * 10]31food_spawn = True32
33# Set the initial game score
34score = 035
36# Set the game over flag
37game_over = False38
39# Game loop
40while not game_over:41# Handle events42for event in pygame.event.get():43if event.type == pygame.QUIT:44game_over = True45
46# Handle snake movement47keys = pygame.key.get_pressed()48for key in keys:49if keys[pygame.K_LEFT]:50snake_position[0] -= snake_speed51if keys[pygame.K_RIGHT]:52snake_position[0] += snake_speed53if keys[pygame.K_UP]:54snake_position[1] -= snake_speed55if keys[pygame.K_DOWN]:56snake_position[1] += snake_speed57
58# Check for collision with the food59if pygame.Rect(snake_position[0], snake_position[1], 10, 10).colliderect(60pygame.Rect(food_position[0], food_position[1], 10, 10)):61score += 162food_spawn = False63
64# Spawn new food if the previous one was eaten65if not food_spawn:66food_position = [random.randrange(1, screen_width // 10) * 10,67random.randrange(1, screen_height // 10) * 10]68food_spawn = True69
70# Update the snake's body71snake_body.insert(0, list(snake_position))72if len(snake_body) > score + 1:73snake_body.pop()74
75# Check for collision with the snake's own body76if snake_position in snake_body[1:]:77game_over = True78
79# Check for collision with the screen boundaries80if snake_position[0] < 0 or snake_position[0] >= screen_width or \81snake_position[1] < 0 or snake_position[1] >= screen_height:82game_over = True83
84# Set the screen background85screen.fill(black)86
87# Draw the snake88for pos in snake_body:89pygame.draw.rect(screen, white, pygame.Rect(pos[0], pos[1], 10, 10))90
91# Draw food92pygame.draw.rect(screen, red, pygame.Rect(93food_position[0], food_position[1], 10, 10))94
95# Update the screen96pygame.display.flip()97
98# Set the game speed99clock.tick(20)100
101# Quit the game
102pygame.quit()103