def handle_selection(self, selected_index):
if selected_index == 0:
print("[ОТЛАДКА] Меню паузы: Выбрана опция 'Возобновить'")
self.fade.start_fade_out()
self.on_resume()
elif selected_index == 1:
print("[ОТЛАДКА] Меню паузы: Выбрана опция 'Главное Меню'")
self.fade.start_fade_out()
self.on_main_menu()
def handle_event(self, event):
# Не обрабатываем события во время затемнения
if not self.fade.finished:
return
self.menu.handle_event(event)
def show(self):
self.is_active = True
self.fade.start_fade_in()
print("[ОТЛАДКА] Меню паузы показано")
def hide(self):
self.is_active = False
self.fade.start_fade_out()
print("[ОТЛАДКА] Меню паузы скрыто")
def update(self):
if not self.is_active:
return
self.fade.update()
if self.fade.finished:
self.menu.update()
def draw(self, surface):
if not self.is_active:
return
self.menu.draw(surface)
self.fade.draw(surface)
Класс Змейки остается неизменным, используя список сегментов
class Snake:
def init(self, x, y):
self.angle = -90 # Направление вверх
self.turn_direction = 0 # -1 для поворота влево, 1 для поворота вправо, 0 для прямого движения
self.speed = 5 # Скорость змейки
self.turn_speed = 3 # Градусов за кадр
self.radius = 10
self.length = 5 # Начальная длина змейки
self.spacing = 20 # Расстояние между сегментами
# Список сегментов. Первый элемент - голова
self.segments = [(x, y)]
print(f"[ОТЛАДКА] Змея инициализирована с головой в позиции ({x}, {y})")
def turn(self, direction):
# Избегаем обратного поворота
if direction * self.turn_direction < 0:
return
self.turn_direction = direction
print(f"[ОТЛАДКА] Направление поворота змейки установлено на {direction}")
def grow(self):
self.length += 1
print(f"[ОТЛАДКА] Змея выросла до длины {self.length}")
def update(self):
# Обновляем угол направления
self.angle += self.turn_direction * self.turn_speed
self.angle %= 360 # Угол остаётся в диапазоне [0, 360)
radians = math.radians(self.angle)
dx = math.cos(radians) * self.speed
dy = math.sin(radians) * self.speed
# Новая позиция головы
new_head_x = self.segments[0][0] + dx
new_head_y = self.segments[0][1] + dy
self.segments.insert(0, (new_head_x, new_head_y))
print(f"[ОТЛАДКА] Головка змейки переместилась в позицию ({new_head_x:.2f}, {new_head_y:.2f})")
# Удаляем последний сегмент, если длина превышена
if len(self.segments) > self.length:
removed_segment = self.segments.pop()
print(f"[ОТЛАДКА] Удалён сегмент хвоста из позиции: {removed_segment}")
# Проверка выхода за границы экрана
if not (0 <= new_head_x <= WIDTH and 0 <= new_head_y <= HEIGHT):
print("[ОТЛАДКА] Змея столкнулась со стеной")
return True
return False
def draw(self, surface):
# Рисуем сегменты змейки
for idx, (x, y) in enumerate(self.segments):
if idx == 0:
# Головка змейки
pygame.draw.circle(surface, SNAKE_COLOR, (int(x), int(y)), self.radius)
pygame.draw.circle(surface, (64, 255, 64), (int(x), int(y)), self.radius, 2)
else:
# Тело змейки
pygame.draw.circle(surface, SNAKE_COLOR, (int(x), int(y)), self.radius)
pygame.draw.circle(surface, (64, 255, 64), (int(x), int(y)), self.radius, 2)
def check_self_collision(self):
head = self.segments[0]
body = self.segments[1:]
for idx, segment in enumerate(body, start=1):
distance = math.hypot(head[0] - segment[0], head[1] - segment[1])
if distance < self.radius * 2:
print(f"[ОТЛАДКА] Змея столкнулась сама с собой на сегменте {idx} в позиции ({segment[0]:.2f}, {segment[1]:.2f})")
return True
return False
Класс Еды остается неизменным
class Food:
def init(self):
self.radius = 6
self.respawn()
print(f"[ОТЛАДКА] Еда инициализирована в позиции ({self.x}, {self.y})")
def handle_selection(self, selected_index):
if selected_index == 0:
print("[ОТЛАДКА] Меню паузы: Выбрана опция 'Возобновить'")
self.fade.start_fade_out()
self.on_resume()
elif selected_index == 1:
print("[ОТЛАДКА] Меню паузы: Выбрана опция 'Главное Меню'")
self.fade.start_fade_out()
self.on_main_menu()
def handle_event(self, event):
# Не обрабатываем события во время затемнения
if not self.fade.finished:
return
self.menu.handle_event(event)
def show(self):
self.is_active = True
self.fade.start_fade_in()
print("[ОТЛАДКА] Меню паузы показано")
def hide(self):
self.is_active = False
self.fade.start_fade_out()
print("[ОТЛАДКА] Меню паузы скрыто")
def update(self):
if not self.is_active:
return
self.fade.update()
if self.fade.finished:
self.menu.update()
def draw(self, surface):
if not self.is_active:
return
self.menu.draw(surface)
self.fade.draw(surface)
Класс Змейки остается неизменным, используя список сегментов
class Snake:
def init(self, x, y):
self.angle = -90 # Направление вверх
self.turn_direction = 0 # -1 для поворота влево, 1 для поворота вправо, 0 для прямого движения
self.speed = 5 # Скорость змейки
self.turn_speed = 3 # Градусов за кадр
self.radius = 10
self.length = 5 # Начальная длина змейки
self.spacing = 20 # Расстояние между сегментами
# Список сегментов. Первый элемент - голова
self.segments = [(x, y)]
print(f"[ОТЛАДКА] Змея инициализирована с головой в позиции ({x}, {y})")
def turn(self, direction):
# Избегаем обратного поворота
if direction * self.turn_direction < 0:
return
self.turn_direction = direction
print(f"[ОТЛАДКА] Направление поворота змейки установлено на {direction}")
def grow(self):
self.length += 1
print(f"[ОТЛАДКА] Змея выросла до длины {self.length}")
def update(self):
# Обновляем угол направления
self.angle += self.turn_direction * self.turn_speed
self.angle %= 360 # Угол остаётся в диапазоне [0, 360)
radians = math.radians(self.angle)
dx = math.cos(radians) * self.speed
dy = math.sin(radians) * self.speed
# Новая позиция головы
new_head_x = self.segments[0][0] + dx
new_head_y = self.segments[0][1] + dy
self.segments.insert(0, (new_head_x, new_head_y))
print(f"[ОТЛАДКА] Головка змейки переместилась в позицию ({new_head_x:.2f}, {new_head_y:.2f})")
# Удаляем последний сегмент, если длина превышена
if len(self.segments) > self.length:
removed_segment = self.segments.pop()
print(f"[ОТЛАДКА] Удалён сегмент хвоста из позиции: {removed_segment}")
# Проверка выхода за границы экрана
if not (0 <= new_head_x <= WIDTH and 0 <= new_head_y <= HEIGHT):
print("[ОТЛАДКА] Змея столкнулась со стеной")
return True
return False
def draw(self, surface):
# Рисуем сегменты змейки
for idx, (x, y) in enumerate(self.segments):
if idx == 0:
# Головка змейки
pygame.draw.circle(surface, SNAKE_COLOR, (int(x), int(y)), self.radius)
pygame.draw.circle(surface, (64, 255, 64), (int(x), int(y)), self.radius, 2)
else:
# Тело змейки
pygame.draw.circle(surface, SNAKE_COLOR, (int(x), int(y)), self.radius)
pygame.draw.circle(surface, (64, 255, 64), (int(x), int(y)), self.radius, 2)
def check_self_collision(self):
head = self.segments[0]
body = self.segments[1:]
for idx, segment in enumerate(body, start=1):
distance = math.hypot(head[0] - segment[0], head[1] - segment[1])
if distance < self.radius * 2:
print(f"[ОТЛАДКА] Змея столкнулась сама с собой на сегменте {idx} в позиции ({segment[0]:.2f}, {segment[1]:.2f})")
return True
return False
Класс Еды остается неизменным
class Food:
def init(self):
self.radius = 6
self.respawn()
print(f"[ОТЛАДКА] Еда инициализирована в позиции ({self.x}, {self.y})")
It looks like you've developed a comprehensive Snake game using Pygame with various features such as menus, fading effects, particle systems, and score tracking. However, upon inspecting your code, there are a few critical issues that need to be addressed to ensure smooth functionality and to prevent potential runtime errors. Below, I'll outline the main problems and provide guidance on how to fix them.
1. Duplicate Class Definitions
Issue:
Your code contains multiple definitions of the same classes (GameOverMenu, PauseMenu, MainMenu, Game, Snake, Food, ParticleSystem). This redundancy can lead to unexpected behaviors, where the last defined class overrides previous ones. Moreover, it clutters the code, making it harder to maintain and debug.
Solution:
Ensure each class is defined only once. Remove all the redundant class definitions to maintain clarity and prevent conflicts. Here's how you can streamline your code:
Action: Keep the first definition of each class and remove the subsequent duplicates.
Organize the Code:
Group related classes together.
Consider placing each class in its own module (separate .py file) for better organization, especially as the project grows.
Example:
# Remove all duplicate class definitions.
# Ensure each class like GameOverMenu, PauseMenu, MainMenu, etc., is defined only once.
2. Class Dependencies and Interactions
Issue:
Some classes reference attributes or methods that may not exist due to the multiple definitions or incomplete initializations. For example, the Game class references self.game_over_menu in the draw method, but self.game_over_menu might not be properly initialized or handled due to duplicate class definitions.
Solution:
After removing duplicate classes, ensure that:
Proper Initialization:
Initialize all necessary attributes in the __init__ methods.
For instance, if self.game_over_menu is used in the Game class, ensure it's properly initialized before usage.
Consistent Method Definitions:
Verify that methods like handle_event, update, and draw are correctly implemented and called across different classes.
Example:
class Game:
def __init__(self, on_game_over, on_exit):
# Existing initializations...
self.game_over_menu = None # Initialize if necessary
# Rest of the code...
def draw(self, surface):
# Drawing game elements
if self.is_paused:
self.pause_menu.draw(surface)
if self.game_over_menu:
self.game_over_menu.draw(surface)
3. Event Handling Enhancements
Issue:
The handle_events methods in your classes handle both keyboard and mouse inputs, but there might be overlapping or conflicting event handling, especially after removing duplicate classes.
Solution:
Ensure that event handling is centralized and that each game state manages its own events without interference. Here's how:
Centralize Event Handling:
Let the GameManager handle high-level events like quitting the game.
Delegate specific events to the current active state (e.g., main menu, playing, paused).
Prevent Event Propagation Conflicts:
Ensure that only the active state responds to events.
For example, if the game is paused, only the PauseMenu should handle the events until it's resumed.
Example:
class GameManager:
def handle_events(self, events):
if self.state == GameState.MAIN_MENU:
self.main_menu.handle_events(events)
elif self.state == GameState.PLAYING:
self.game.handle_events(events)
elif self.state == GameState.GAME_OVER:
self.game_over_menu.handle_event(events)
4. Code Organization and Readability
Issue:
The extensive use of print statements for debugging ([ОТЛАДКА]) is helpful during development but can clutter the console during regular gameplay.
Solution:
Implement a logging system that can toggle debug messages on and off. This approach maintains cleaner code and more manageable output.
Implementation:
Create a Logger:
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='[%(levelname)s] %(message)s')
# Use logging instead of print statements
logging.debug("This is a debug message")
logging.info("This is an info message")
logging.warning("This is a warning message")
logging.error("This is an error message")
Replace Print Statements:
Update your debug messages to use the logger.
# Replace
print("[ОТЛАДКА] Some debug message")
# With
logging.debug("Some debug message")
Control Logging Level:
Set the logging level as needed (e.g., DEBUG, INFO, WARNING).
# For debugging purposes
logging.getLogger().setLevel(logging.DEBUG)
# For production
logging.getLogger().setLevel(logging.INFO)
5. Enhancements and Best Practices
Suggestions:
Modularize the Code:
Split the code into separate modules/files, such as menu.py, game.py, snake.py, etc. This structure improves maintainability and readability.
Use Pygame's Clock Effectively:
Ensure that the game loop manages frame rates accurately to prevent lag or too-fast gameplay.
Resource Management:
Handle resource loading (like fonts and images) outside of the main game loop to optimize performance.
Error Handling:
Implement try-except blocks where file operations or other potential failure points occur to gracefully handle errors.
Code Comments and Documentation:
Maintain clear comments and perhaps even docstrings for classes and methods to explain their purpose and usage.
6. Final Cleaned-Up Structure
Here's a simplified and cleaned-up structure of your game, addressing the duplicate class definitions and organizing the main components. This example assumes that all classes are defined once and are properly interacting with each other.
import pygame
import sys
import random
import math
import os
import logging
# Configure logging
logging.basicConfig(level=logging.DEBUG, format='[%(levelname)s] %(message)s')
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
SCREEN = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Игра Змейка")
# Colors
BACKGROUND_COLOR = (20, 21, 31)
SNAKE_COLOR = (50, 205, 50)
FOOD_COLOR = (255, 69, 0)
PARTICLE_COLOR = (255, 69, 0)
SNAKE_GLOW_COLOR = (80, 220, 80, 76) # RGBA for transparency
FOOD_GLOW_COLOR = (255, 100, 50, 76)
# Fonts
FONT = pygame.font.SysFont('Arial', 20)
BIG_FONT = pygame.font.SysFont('Arial', 50)
# FPS
FPS = 60
CLOCK = pygame.time.Clock()
# High score file
HIGH_SCORE_FILE = "high_score.txt"
# Game states
class GameState:
MAIN_MENU = 'main_menu'
PLAYING = 'playing'
GAME_OVER = 'game_over'
PAUSED = 'paused'
# FadeScreen class
class FadeScreen:
def __init__(self, duration=30):
self.surface = pygame.Surface((WIDTH, HEIGHT))
self.surface.fill((0, 0, 0))
self.alpha = 0
self.duration = duration
self.fade_in = True
self.fade_out = False
self.finished = False
def start_fade_in(self):
self.alpha = 255
self.fade_in = True
self.fade_out = False
self.finished = False
logging.debug("FadeScreen: Starting fade-in")
def start_fade_out(self):
self.alpha = 0
self.fade_in = False
self.fade_out = True
self.finished = False
logging.debug("FadeScreen: Starting fade-out")
def update(self):
if self.fade_in:
self.alpha -= 255 / self.duration
if self.alpha <= 0:
self.alpha = 0
self.fade_in = False
self.finished = True
logging.debug("FadeScreen: Fade-in completed")
elif self.fade_out:
self.alpha += 255 / self.duration
if self.alpha >= 255:
self.alpha = 255
self.fade_out = False
self.finished = True
logging.debug("FadeScreen: Fade-out completed")
self.surface.set_alpha(int(self.alpha))
def draw(self, surface):
if not self.finished:
surface.blit(self.surface, (0, 0))
# Menu class
class Menu:
def __init__(self, title, options, on_select):
self.title = title
self.options = options
self.on_select = on_select
self.selected_index = 0
self.alpha = 0
self.show_menu_surface = True
self.fade_in = True
self.fade_out = False
self.menu_surface = pygame.Surface((WIDTH, HEIGHT), pygame.SRCALPHA)
self.setup_buttons()
logging.debug(f"Menu '{self.title}' initialized")
def setup_buttons(self):
self.buttons = []
button_width = 200
button_height = 50
spacing = 20
total_height = len(self.options) * (button_height + spacing) - spacing
start_y = HEIGHT // 2 - total_height // 2
for idx, option in enumerate(self.options):
rect = pygame.Rect(
WIDTH//2 - button_width//2,
start_y + idx * (button_height + spacing),
button_width,
button_height
)
self.buttons.append(rect)
logging.debug(f"Menu '{self.title}' buttons set up")
def handle_event(self, event):
if event.type == pygame.MOUSEBUTTONDOWN:
for idx, button in enumerate(self.buttons):
if button.collidepoint(event.pos):
self.selected_index = idx
logging.debug(f"Menu '{self.title}': Option '{self.options[idx]}' selected via click")
self.fade_out = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.selected_index = (self.selected_index - 1) % len(self.options)
logging.debug(f"Menu '{self.title}': Option '{self.options[self.selected_index]}' selected via UP key")
elif event.key == pygame.K_DOWN:
self.selected_index = (self.selected_index + 1) % len(self.options)
logging.debug(f"Menu '{self.title}': Option '{self.options[self.selected_index]}' selected via DOWN key")
elif event.key in [pygame.K_RETURN, pygame.K_SPACE]:
logging.debug(f"Menu '{self.title}': Option '{self.options[self.selected_index]}' activated via keyboard")
self.on_select(self.selected_index)
self.fade_out = True
def update(self):
if self.fade_in and self.alpha < 255:
self.alpha += 5
if self.alpha >= 255:
self.alpha = 255
self.fade_in = False
logging.debug(f"Menu '{self.title}' fully appeared")
elif self.fade_out and self.alpha > 0:
self.alpha -= 5
if self.alpha <= 0:
self.alpha = 0
self.show_menu_surface = False
logging.debug(f"Menu '{self.title}' fully disappeared")
if self.on_select:
self.on_select(self.selected_index)
self.menu_surface.fill((0, 0, 0, self.alpha))
def draw(self, surface):
if self.show_menu_surface:
surface.blit(self.menu_surface, (0, 0))
# Draw title
title_text = BIG_FONT.render(self.title, True, (255, 255, 255))
surface.blit(title_text, (WIDTH//2 - title_text.get_width()//2, HEIGHT//2 - 200))
# Draw buttons
for idx, button in enumerate(self.buttons):
color = (150, 150, 150) if idx != self.selected_index else (100, 100, 255)
pygame.draw.rect(surface, color, button)
# Draw button text
option_text = FONT.render(self.options[idx], True, (255, 255, 255))
surface.blit(
option_text,
(
button.x + button.width//2 - option_text.get_width()//2,
button.y + button.height//2 - option_text.get_height()//2
)
)
# GameOverMenu class
class GameOverMenu(Menu):
def __init__(self, score, high_score, on_restart, on_main_menu):
self.score = score
self.high_score = high_score
self.on_restart = on_restart
self.on_main_menu = on_main_menu
options = ["Перезапустить", "Главное Меню"]
super().__init__("Игра окончена", options, self.handle_selection)
self.fade = FadeScreen()
self.fade.start_fade_in()
logging.debug("GameOverMenu initialized")
def handle_selection(self, selected_index):
if selected_index == 0:
logging.debug("GameOverMenu: 'Перезапустить' selected")
self.on_restart()
elif selected_index == 1:
logging.debug("GameOverMenu: 'Главное Меню' selected")
self.on_main_menu()
def handle_event(self, event):
if not self.fade.finished:
return
super().handle_event(event)
def update(self):
self.fade.update()
if self.fade.finished:
super().update()
def draw(self, surface):
super().draw(surface)
self.fade.draw(surface)
# PauseMenu class
class PauseMenu(Menu):
def __init__(self, on_resume, on_main_menu):
self.on_resume = on_resume
self.on_main_menu = on_main_menu
options = ["Возобновить", "Главное Меню"]
super().__init__("Пауза", options, self.handle_selection)
self.fade = FadeScreen()
self.fade.start_fade_out()
self.is_active = False
logging.debug("PauseMenu initialized")
def handle_selection(self, selected_index):
if selected_index == 0:
logging.debug("PauseMenu: 'Возобновить' selected")
self.fade.start_fade_out()
self.on_resume()
elif selected_index == 1:
logging.debug("PauseMenu: 'Главное Меню' selected")
self.fade.start_fade_out()
self.on_main_menu()
def handle_event(self, event):
if not self.fade.finished:
return
super().handle_event(event)
def show(self):
self.is_active = True
self.fade.start_fade_in()
logging.debug("PauseMenu shown")
def hide(self):
self.is_active = False
self.fade.start_fade_out()
logging.debug("PauseMenu hidden")
def update(self):
if not self.is_active:
return
self.fade.update()
if self.fade.finished:
super().update()
def draw(self, surface):
if not self.is_active:
return
super().draw(surface)
self.fade.draw(surface)
# Snake class
class Snake:
def __init__(self, x, y):
self.angle = -90 # Initial direction: up
self.turn_direction = 0 # -1 left, 1 right, 0 straight
self.speed = 5
self.turn_speed = 3 # Degrees per frame
self.radius = 10
self.length = 5
self.spacing = 20
self.segments = [(x, y)]
logging.debug(f"Snake initialized at ({x}, {y})")
def turn(self, direction):
if direction * self.turn_direction < 0:
return
self.turn_direction = direction
logging.debug(f"Snake turn direction set to {direction}")
def grow(self):
self.length += 1
logging.debug(f"Snake grew to length {self.length}")
def update(self):
self.angle += self.turn_direction * self.turn_speed
self.angle %= 360
radians = math.radians(self.angle)
dx = math.cos(radians) * self.speed
dy = math.sin(radians) * self.speed
new_head_x = self.segments[0][0] + dx
new_head_y = self.segments[0][1] + dy
self.segments.insert(0, (new_head_x, new_head_y))
logging.debug(f"Snake head moved to ({new_head_x:.2f}, {new_head_y:.2f})")
if len(self.segments) > self.length:
removed_segment = self.segments.pop()
logging.debug(f"Snake tail segment removed from {removed_segment}")
# Check for wall collision
if not (0 <= new_head_x <= WIDTH and 0 <= new_head_y <= HEIGHT):
logging.debug("Snake collided with wall")
return True
return False
def draw(self, surface):
for idx, (x, y) in enumerate(self.segments):
if idx == 0:
pygame.draw.circle(surface, SNAKE_COLOR, (int(x), int(y)), self.radius)
pygame.draw.circle(surface, (64, 255, 64), (int(x), int(y)), self.radius, 2)
else:
pygame.draw.circle(surface, SNAKE_COLOR, (int(x), int(y)), self.radius)
pygame.draw.circle(surface, (64, 255, 64), (int(x), int(y)), self.radius, 2)
def check_self_collision(self):
head = self.segments[0]
body = self.segments[1:]
for idx, segment in enumerate(body, start=1):
distance = math.hypot(head[0] - segment[0], head[1] - segment[1])
if distance < self.radius * 2:
logging.debug(f"Snake collided with itself at segment {idx} ({segment[0]:.2f}, {segment[1]:.2f})")
return True
return False
# Food class
class Food:
def __init__(self):
self.radius = 6
self.respawn()
logging.debug(f"Food initialized at ({self.x}, {self.y})")
def respawn(self):
self.x = random.randint(self.radius, WIDTH - self.radius)
self.y = random.randint(self.radius, HEIGHT - self.radius)
logging.debug(f"Food respawned at ({self.x}, {self.y})")
def draw(self, surface):
# Glow effect
glow_surface = pygame.Surface((self.radius * 2 + 8, self.radius * 2 + 8), pygame.SRCALPHA)
pygame.draw.circle(glow_surface, FOOD_GLOW_COLOR, (self.radius + 4, self.radius + 4), self.radius + 4)
surface.blit(glow_surface, (self.x - self.radius - 4, self.y - self.radius - 4))
# Draw food
pygame.draw.circle(surface, FOOD_COLOR, (int(self.x), int(self.y)), self.radius)
pygame.draw.circle(surface, (255, 99, 71), (int(self.x), int(self.y)), self.radius, 2)
# ParticleSystem class
class ParticleSystem:
def __init__(self):
self.particles = []
logging.debug("ParticleSystem initialized")
def emit(self, x, y):
for _ in range(20):
angle = random.uniform(0, 2 * math.pi)
speed = random.uniform(1, 4)
self.particles.append({
'x': x,
'y': y,
'dx': math.cos(angle) * speed,
'dy': math.sin(angle) * speed,
'life': 1.0,
'color': PARTICLE_COLOR
})
logging.debug(f"Emitted 20 particles at ({x}, {y})")
def update(self):
original_count = len(self.particles)
self.particles = [p for p in self.particles if p['life'] > 0]
removed_particles = original_count - len(self.particles)
if removed_particles > 0:
logging.debug(f"Removed {removed_particles} particles")
for p in self.particles:
p['x'] += p['dx']
p['y'] += p['dy']
p['life'] -= 0.02
def draw(self, surface):
for p in self.particles:
if p['life'] <= 0:
continue
alpha = max(int(255 * p['life']), 0)
particle_surface = pygame.Surface((4, 4), pygame.SRCALPHA)
particle_surface.fill((*p['color'], alpha))
surface.blit(particle_surface, (int(p['x']), int(p['y'])))
# Game class
class Game:
def __init__(self, on_game_over, on_exit):
self.snake = Snake(WIDTH / 2, HEIGHT / 2)
self.food = Food()
self.particles = ParticleSystem()
self.score = 0
self.high_score = self.load_high_score()
self.on_game_over = on_game_over
self.on_exit = on_exit
self.is_paused = False
self.active = True
self.game_over = False
self.start_delay_frames = FPS * 2 # 2 seconds delay
self.pause_menu = PauseMenu(self.resume, self.return_to_main_menu)
logging.debug("Game initialized")
def load_high_score(self):
if not os.path.exists(HIGH_SCORE_FILE):
try:
with open(HIGH_SCORE_FILE, 'w') as f:
f.write('0')
logging.debug(f"High score file created: {HIGH_SCORE_FILE}")
except Exception as e:
logging.error(f"Failed to create high score file: {e}")
return 0
try:
with open(HIGH_SCORE_FILE, 'r') as f:
high_score = int(f.read())
logging.debug(f"High score loaded: {high_score}")
return high_score
except ValueError:
logging.warning("High score file corrupted. Resetting to 0.")
return 0
except Exception as e:
logging.error(f"Error loading high score: {e}")
return 0
def save_high_score(self):
try:
with open(HIGH_SCORE_FILE, 'w') as f:
f.write(str(self.high_score))
logging.debug(f"High score {self.high_score} saved to {HIGH_SCORE_FILE}")
except Exception as e:
logging.error(f"Error saving high score: {e}")
def handle_events(self, events):
if self.is_paused:
self.pause_menu.handle_event(events)
return
for event in events:
if event.type == pygame.QUIT:
self.save_high_score()
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
self.toggle_pause()
elif not self.is_paused and not self.game_over:
if event.key == pygame.K_LEFT:
self.snake.turn(-1)
logging.debug("Left key pressed")
elif event.key == pygame.K_RIGHT:
self.snake.turn(1)
logging.debug("Right key pressed")
elif event.type == pygame.KEYUP:
if not self.is_paused and not self.game_over:
if event.key in [pygame.K_LEFT, pygame.K_RIGHT]:
self.snake.turn(0)
logging.debug("Left or Right key released")
def toggle_pause(self):
self.is_paused = not self.is_paused
if self.is_paused:
self.pause_menu.show()
logging.debug("Game paused")
else:
self.pause_menu.hide()
logging.debug("Game resumed")
def resume(self):
self.is_paused = False
self.pause_menu.hide()
logging.debug("Game resumed via PauseMenu")
def return_to_main_menu(self):
self.save_high_score()
self.active = False
self.game_over = False
self.pause_menu.hide()
logging.debug("Returning to Main Menu from Game")
def update(self):
if not self.is_paused and not self.game_over:
collision_with_wall = self.snake.update()
self.particles.update()
self.check_collisions()
if collision_with_wall:
self.handle_game_over()
if self.start_delay_frames <= 0:
if self.snake.check_self_collision():
self.handle_game_over()
else:
self.start_delay_frames -=1
if self.start_delay_frames == 0:
logging.debug("Collision checks activated")
def handle_game_over(self):
self.save_high_score()
self.game_over = True
self.active = False
self.on_game_over(self.score, self.high_score)
logging.debug("Game over handled")
def check_collisions(self):
head = self.snake.segments[0]
distance = math.hypot(head[0] - self.food.x, head[1] - self.food.y)
if distance < self.snake.radius + self.food.radius:
logging.debug("Snake ate the food")
self.snake.grow()
self.particles.emit(self.food.x, self.food.y)
self.food.respawn()
self.score += 10
if self.score > self.high_score:
self.high_score = self.score
logging.debug(f"New high score: {self.high_score}")
def draw(self, surface):
surface.fill(BACKGROUND_COLOR)
self.food.draw(surface)
self.snake.draw(surface)
self.particles.draw(surface)
# Draw score
score_text = FONT.render(f"Счёт: {self.score}", True, (255, 255, 255))
high_score_text = FONT.render(f"Рекорд: {self.high_score}", True, (255, 255, 255))
surface.blit(score_text, (20, 20))
surface.blit(high_score_text, (20, 50))
if self.is_paused:
self.pause_menu.draw(surface)
if self.game_over_menu:
self.game_over_menu.draw(surface)
# MainMenu class
class MainMenu:
def __init__(self, on_start_game, on_exit_game):
self.menu = Menu(
title="Главное Меню",
options=["Начать игру", "Выйти"],
on_select=self.handle_selection
)
self.on_start_game = on_start_game
self.on_exit_game = on_exit_game
self.active = True
logging.debug("MainMenu initialized")
def handle_selection(self, selected_index):
if selected_index == 0:
logging.debug("MainMenu: 'Начать игру' selected")
self.on_start_game()
elif selected_index == 1:
logging.debug("MainMenu: 'Выйти' selected")
self.on_exit_game()
def handle_events(self, events):
self.menu.handle_event(events)
def update(self):
self.menu.update()
def draw(self, surface):
self.menu.draw(surface)
def show_menu(self):
logging.debug("Returning to MainMenu")
self.active = True
# GameManager class
class GameManager:
def __init__(self):
self.state = GameState.MAIN_MENU
self.main_menu = MainMenu(self.start_game, self.exit_game)
self.game = None
self.game_over_menu = None
logging.debug("GameManager initialized")
def start_game(self):
self.game = Game(self.game_over, self.show_main_menu)
self.state = GameState.PLAYING
logging.debug("Game started")
def exit_game(self):
logging.debug("Exiting game")
if self.game:
self.game.save_high_score()
pygame.quit()
sys.exit()
def game_over(self, score, high_score):
self.state = GameState.GAME_OVER
self.game_over_menu = GameOverMenu(score, high_score, self.start_game, self.show_main_menu)
logging.debug("Transitioning to GameOverMenu")
def show_main_menu(self):
if self.game:
self.game = None
self.game_over_menu = None
self.main_menu = MainMenu(self.start_game, self.exit_game)
self.state = GameState.MAIN_MENU
logging.debug("Returned to MainMenu")
def handle_events(self, events):
if self.state == GameState.MAIN_MENU:
self.main_menu.handle_events(events)
elif self.state == GameState.PLAYING:
self.game.handle_events(events)
elif self.state == GameState.GAME_OVER:
for event in events:
self.game_over_menu.handle_event(event)
def update(self):
if self.state == GameState.MAIN_MENU:
self.main_menu.update()
elif self.state == GameState.PLAYING:
self.game.update()
elif self.state == GameState.GAME_OVER:
self.game_over_menu.update()
# Optionally reset game_over_menu after it's done
if self.game_over_menu.fade.finished and not self.game_over_menu.show_menu_surface:
self.game_over_menu = None
def draw(self, surface):
if self.state == GameState.MAIN_MENU:
self.main_menu.draw(surface)
elif self.state == GameState.PLAYING:
self.game.draw(surface)
elif self.state == GameState.GAME_OVER:
if self.game_over_menu:
self.game_over_menu.draw(surface)
def run(self):
while True:
events = pygame.event.get()
self.handle_events(events)
self.update()
self.draw(SCREEN)
pygame.display.flip()
CLOCK.tick(FPS)
# Main function
def main():
game_manager = GameManager()
game_manager.run()
# Run the game
if __name__ == "__main__":
main()
7. Additional Recommendations
Testing:
After restructuring, thoroughly test each component individually (unit testing) to ensure they work as expected.
Test edge cases, such as what happens when the snake collides with the wall or itself.
Performance Optimization:
Monitor the game's performance, especially the particle system, which can be resource-intensive.
Optimize the number of particles or their lifespan to balance visual effects and performance.
User Experience Enhancements:
Add sounds for events like eating food, game over, or menu navigation.
Implement difficulty levels by adjusting snake speed or food spawn rates.
Code Documentation:
Add docstrings to classes and methods to describe their purpose and usage.
Maintain clear and concise comments throughout the code to explain complex logic.
Version Control:
Use a version control system like Git to track changes, manage different versions, and collaborate if working with others.
Error Logging and Handling:
Enhance error handling to provide more informative messages or fallback mechanisms in case of failures.
By addressing the duplicate class definitions and organizing your code as shown above, you should have a more stable and maintainable Snake game. Implementing the additional recommendations will further enhance the game's quality and your development experience.
If you encounter specific issues or errors after restructuring, feel free to provide the error messages or describe the behavior, and I can assist you further in troubleshooting.