Creating a Snake Game Using Pygame: Step-by-Step Guide
The Snake game is a classic and popular arcade game. In this tutorial, we will create a simple version of the Snake game using the Pygame library in Python. Below are step-by-step instructions for creating a game.
Step 1: Initializing Pygame and Setting the Game Window
import pygame
import random
import json
# Инициализация Pygame
pygame.init()
# Установка размеров окна
width = 800
height = 600
cell_size = 20
# Цвета
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# Создание окна
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption('Змейка')
# Часы для управления обновлением экрана
clock = pygame.time.Clock()
In this step we include the Pygame library, initialize the game window and set its size. We also determine the colors that will be used in the game.
Step 2: Functions for displaying text and generating apples
# Функция для вывода текста на экран
def draw_text(text, font, color, surface, x, y):
text_obj = font.render(text, True, color)
text_rect = text_obj.get_rect()
text_rect.topleft = (x, y)
surface.blit(text_obj, text_rect)
# Генерация новых координат для яблока
def generate_new_apple():
return [random.randrange(1, (width//cell_size)) * cell_size,
random.randrange(1, (height//cell_size)) * cell_size]
This step involves defining functions to display text on the screen and generate new coordinates for the apple.
Step 3: Load and save the leaderboard
# Загрузка таблицы рекордов
def load_high_scores():
try:
with open("high_scores.json", "r") as file:
high_scores = json.load(file)
except FileNotFoundError:
high_scores = {"scores": []}
return high_scores
# Сохранение таблицы рекордов
def save_high_scores(high_scores):
with open("high_scores.json", "w") as file:
json.dump(high_scores, file)
In this step, we create functions to load and save the high score table in JSON format.
Step 4: Display the leaderboard
# Отображение таблицы рекордов
def display_high_scores(high_scores):
font = pygame.font.Font(None, 36)
draw_text("High Scores:", font, white, game_display, 10, 40)
for i, score in enumerate(high_scores["scores"]):
draw_text(str(i+1) + ". " + str(score), font, white, game_display, 10, 70 + i * 30)
This step enables the function to display the high score table on the screen.
Step 5: Main Game Loop
# Основная функция игры
def game_loop():
# Начальные координаты змейки
snake = [[width // 2, height // 2]]
snake_direction = 'RIGHT'
# Начальные координаты яблока
apple_pos = generate_new_apple()
# Начальный счет
score = 0
# Загрузка рекордов
high_scores = load_high_scores()
# Основной цикл игры
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
save_high_scores(high_scores)
pygame.quit()
quit()
# Управление змейкой
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT and snake_direction != 'RIGHT':
snake_direction = 'LEFT'
elif event.key == pygame.K_RIGHT and snake_direction != 'LEFT':
snake_direction = 'RIGHT'
elif event.key == pygame.K_UP and snake_direction != 'DOWN':
snake_direction = 'UP'
elif event.key == pygame.K_DOWN and snake_direction != 'UP':
snake_direction = 'DOWN'
In this step we create the main game loop that handles snake control and other events.
Step 6: Moving the Snake and Checking for Collisions
# Перемещение змейки
if snake_direction == 'UP':
snake.insert(0, [snake[0][0], snake[0][1] - cell_size])
elif snake_direction == 'DOWN':
snake.insert(0, [snake[0][0], snake[0][1] + cell_size])
elif snake_direction == 'LEFT':
snake.insert(0, [snake[0][0] - cell_size, snake[0][1]])
elif snake_direction == 'RIGHT':
snake.insert(0, [snake[0][0] + cell_size, snake[0][1]])
# Если змейка коснулась границ экрана
if not (0 <= snake[0][0] < width and 0 <= snake[0][1] < height):
if score > 0:
high_scores["scores"].append(score)
high_scores["scores"].sort(reverse=True)
if len(high_scores["scores"]) > 5:
high_scores["scores"].pop()
save_high_scores(high_scores)
return
# Если змейка съела яблоко
if snake[0] == apple_pos:
apple_pos = generate_new_apple()
score += 1
else:
# Удаление последнего сегмента змейки, если не съела яблоко
snake.pop()
This step implements moving the snake, handling collisions, and checking whether the apple has been eaten.
Step 7: Displaying Game Objects
# Рисуем фон
game_display.fill(black)
# Рисуем змейку
for segment in snake:
pygame.draw.rect(game_display, white, [segment[0], segment[1], cell_size, cell_size])
# Рисуем яблоко
pygame.draw.rect(game_display, red, [apple_pos[0], apple_pos[1], cell_size, cell_size])
# Отображаем счет
font = pygame.font.Font(None, 36)
draw_text("Score: {}".format(score), font, white, game_display, 10, 10)
# Отображаем таблицу рекордов
display_high_scores(high_scores)
# Обновляем экран
pygame.display.update()
# Ограничиваем частоту кадров
clock.tick(10)
# Запускаем игру
game_loop()
In this step we display game objects such as the snake, apple and score, as well as update the screen and limit the frame rate.
You now have a simple version of the Snake game created using the Pygame library in Python. You can improve it by adding new features and improvements.