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.txt"
Класс Змейки
class Snake:
def init(self, x, y):
self.angle = -90 # Направление вверх
self.turn_direction = 0 # -1 для поворота влево, 1 для поворота вправо, 0 для прямого движения
self.speed = 5 # Увеличена скорость для соответствия spacing
self.turn_speed = 3 # градусов за кадр
self.radius = 10
self.length = 5 # Начальная длина змейки
self.spacing = 20 # Расстояние между сегментами увеличено до 20
# История пути (path tracking)
self.path = [] # Список позиций головы
self.path_length = self.spacing * self.length # Общее расстояние, на которое сегменты должны следовать
# Инициализируем начальную позицию головы
self.head_pos = {'x': x, 'y': y}
self.path.append((self.head_pos['x'], self.head_pos['y']))
print(f"[DEBUG] Snake initialized with head at ({x}, {y})")
def turn(self, direction):
self.turn_direction = direction
print(f"[DEBUG] Snake turn direction set to {direction}")
def grow(self):
self.length += 1
self.path_length = self.spacing * self.length
print(f"[DEBUG] Snake grew to length {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
# Обновляем позицию головы
self.head_pos['x'] += dx
self.head_pos['y'] += dy
self.path.append((self.head_pos['x'], self.head_pos['y']))
print(f"[DEBUG] Snake head moved to ({self.head_pos['x']:.2f}, {self.head_pos['y']:.2f})")
# Проверка выхода за границы экрана
if not (0 <= self.head_pos['x'] <= WIDTH and 0 <= self.head_pos['y'] <= HEIGHT):
print("[DEBUG] Snake collided with wall")
return True # Возвращаем True для обработки столкновения с границей
# Очищаем историю пути, чтобы она не была слишком длинной
while self.calculate_path_length() > self.path_length:
removed_position = self.path.pop(0)
print(f"[DEBUG] Removed position from path: {removed_position}")
return False # Нет столкновения с границей
def calculate_path_length(self):
length = 0
for i in range(1, len(self.path)):
prev = self.path[i-1]
curr = self.path[i]
length += math.hypot(curr[0] - prev[0], curr[1] - prev[1])
return length
def get_segment_position(self, index):
target_length = self.spacing * index
accumulated_length = 0
for i in range(len(self.path)-1, 0, -1):
prev = self.path[i-1]
curr = self.path[i]
segment = math.hypot(curr[0] - prev[0], curr[1] - prev[1])
if accumulated_length + segment >= target_length:
ratio = (target_length - accumulated_length) / segment if segment != 0 else 0
x = curr[0] + (prev[0] - curr[0]) * ratio
y = curr[1] + (prev[1] - curr[1]) * ratio
return (x, y)
accumulated_length += segment
return self.path[0]
def draw(self, surface):
# Рисуем сегменты змейки
for i in range(1, self.length + 1):
pos = self.get_segment_position(i)
x, y = pos
# Эффект свечения
alpha = 0.3 * (1 - i / self.length)
glow_surface = pygame.Surface((self.radius * 2 + 8, self.radius * 2 + 8), pygame.SRCALPHA)
pygame.draw.circle(glow_surface, (80, 220, 80, int(255 * alpha)), (self.radius + 4, self.radius + 4), self.radius + 4)
surface.blit(glow_surface, (x - self.radius - 4, y - self.radius - 4))
# Рисуем тело змейки
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, start_delay_frames):
if start_delay_frames > 0:
# Пропускаем проверку в течение начальной задержки
return False
# Голова змейки
head_x, head_y = self.head_pos['x'], self.head_pos['y']
for i in range(2, self.length + 1):
segment_x, segment_y = self.get_segment_position(i)
distance = math.hypot(head_x - segment_x, head_y - segment_y)
if distance < self.radius * 2:
print("[DEBUG] Snake collided with itself")
return True
return False
Assistant
Класс Еды
class Food:
def init(self):
self.radius = 6
self.respawn()
print(f"[DEBUG] Food initialized at ({self.x}, {self.y})")
while True:
events = pygame.event.get()
if main_menu.active:
main_menu.handle_events(events)
main_menu.update()
main_menu.draw(SCREEN)
elif main_menu.game_instance and main_menu.game_instance.active:
main_menu.game_instance.handle_events(events)
main_menu.game_instance.update()
main_menu.game_instance.draw(SCREEN)
elif main_menu.game_instance and main_menu.game_instance.game_over_menu:
# Игра окончена, показываем GameOverMenu
game_over_screen = GameOverScreen(main_menu.game_instance.game_over_menu)
game_over_screen.handle_events(events)
game_over_screen.update()
game_over_screen.draw(SCREEN)
else:
main_menu.show_menu()
pygame.display.flip()
CLOCK.tick(FPS)
Запуск Игры
if name == "main":
main()
После проигрыша и нажатия на клавишу главного меню игра перезапускается, а не загружает главное меню. И ещё при нажатии на Esc и последующем нажатии на кнопку главного меню игра крашится с ошибкой а не загружает меню.
The issues you're experiencing with your Snake game primarily stem from how the menu interactions are handled, especially concerning mouse clicks and state transitions. Let's address both problems you've mentioned:
After losing the game and selecting the Main Menu, the game restarts instead of loading the Main Menu.
Pressing Esc to pause and then selecting the Main Menu causes the game to crash.
1. Menu Selection Handling
Issue:
When you click on a menu option with the mouse, the selected_index isn't being updated appropriately. This results in the game possibly interpreting the selection incorrectly, leading to unexpected behaviors like restarting the game instead of navigating to the Main Menu.
Solution:
Update the selected_index when a mouse click occurs on a specific button. This ensures that the correct option is selected based on where the user clicks.
Implementation:
Modify the handle_event method in the Menu class to update the selected_index when a mouse button is pressed. Here's how you can do it:
class Menu:
def __init__(self, title, options, on_select):
# ... existing initialization code ...
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()
print(f"[DEBUG] '{self.title}' Menu initialized")
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 # **Set the selected index based on click**
print(f"[DEBUG] '{self.title}' Menu option '{self.options[idx]}' clicked")
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)
print(f"[DEBUG] '{self.title}' Menu selection moved to {self.selected_index}")
elif event.key == pygame.K_DOWN:
self.selected_index = (self.selected_index + 1) % len(self.options)
print(f"[DEBUG] '{self.title}' Menu selection moved to {self.selected_index}")
elif event.key in [pygame.K_RETURN, pygame.K_SPACE]:
print(f"[DEBUG] '{self.title}' Menu option '{self.options[self.selected_index]}' selected 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
print(f"[DEBUG] '{self.title}' Menu fade-in completed")
elif self.fade_out and self.alpha > 0:
self.alpha -= 5
if self.alpha <= 0:
self.alpha = 0
self.show_menu_surface = False
print(f"[DEBUG] '{self.title}' Menu fade-out completed")
# Call callback after fade out
if self.on_select:
if self.title == "Главное Меню" or self.title == "Game Over":
self.on_select(self.selected_index)
Explanation:
Setting selected_index: When a mouse button is pressed (pygame.MOUSEBUTTONDOWN), the code now identifies which button was clicked by iterating through self.buttons. It sets self.selected_index to the index of the clicked button (idx). This ensures that when fade_out completes, the correct option is processed.
Callback Execution: After the fade-out animation, the on_select callback is invoked with the correct selected_index, ensuring the intended action is taken (e.g., navigating to the Main Menu or restarting the game).
2. Handling Pause and Returning to Main Menu
Issue:
When you pause the game using Esc and then attempt to return to the Main Menu, the game crashes. This is likely due to state inconsistencies or lingering references to game objects that should have been cleared or reset.
Solution:
Ensure that when transitioning back to the Main Menu from the Pause Menu, all game-related states are appropriately reset. This includes stopping the current game instance and ensuring that no references to it persist, which might cause the crash.
Implementation:
Ensure Proper Cleanup: When returning to the Main Menu from the Pause Menu, make sure the game instance is properly reset.
Modify the return_to_menu Method in the Game Class:
class Game:
def __init__(self, on_return_to_menu):
# ... existing initialization code ...
self.pause_menu = PauseMenu(self.resume, self.return_to_menu)
# ... rest of the initialization ...
def return_to_menu(self):
self.save_high_score()
self.active = False
print("[DEBUG] Returning to MainMenu")
# **Ensure that any game-specific resources are cleaned up here if necessary**
Adjust the Main Loop to Reset the Game Instance:
Ensure that when returning to the Main Menu, the game instance is set to None to prevent any lingering references.
def main():
main_menu = MainMenu()
game_over_screen = None
while True:
events = pygame.event.get()
if main_menu.active:
main_menu.handle_events(events)
main_menu.update()
main_menu.draw(SCREEN)
elif main_menu.game_instance and main_menu.game_instance.active:
main_menu.game_instance.handle_events(events)
main_menu.game_instance.update()
main_menu.game_instance.draw(SCREEN)
elif main_menu.game_instance and main_menu.game_instance.game_over_menu:
# Show GameOverMenu
game_over_screen = GameOverScreen(main_menu.game_instance.game_over_menu)
game_over_screen.handle_events(events)
game_over_screen.update()
game_over_screen.draw(SCREEN)
else:
main_menu.show_menu()
pygame.display.flip()
CLOCK.tick(FPS)
Ensure MainMenu.show_menu Properly Resets the Game Instance:
class MainMenu:
def __init__(self):
# ... existing initialization code ...
self.game_instance = None # Initially no game
print("[DEBUG] MainMenu initialized")
def show_menu(self):
print("[DEBUG] Returning to MainMenu")
if self.game_instance:
self.game_instance.save_high_score()
self.game_instance = None
self.active = True
Explanation:
Cleanup on Return: By setting self.game_instance to None in the show_menu method, you ensure that the game instance is effectively terminated, and no references to it remain. This prevents potential crashes from trying to access or update a game instance that's no longer active.
Consistent State Management: Ensuring that self.active is correctly managed across different states (MainMenu, Game, PauseMenu, GameOverMenu) avoids conflicts where multiple states might try to control the game simultaneously.
Additional Recommendations
Implement a State Machine:
Managing game states (e.g., Main Menu, Playing, Paused, Game Over) can become complex as the game grows. Implementing a state machine can help manage transitions more cleanly and avoid conflicts.
Error Logging:
Implement more robust error handling and logging to capture and understand crashes better. This can be done by wrapping critical sections in try-except blocks and logging errors using Python's logging module.
Consistent Menu Handling:
Ensure that all menus (MainMenu, PauseMenu, GameOverMenu) inherit from a common base class if they share similar behaviors. This promotes code reuse and consistency.
Testing Transitions:
Rigorously test all possible transitions between states (e.g., Play → Pause → Main Menu, Play → Game Over → Main Menu) to ensure they behave as expected.
Complete Revised Menu Class Example
Here's the updated Menu class with the necessary changes:
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()
print(f"[DEBUG] '{self.title}' Menu 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)
print(f"[DEBUG] Buttons for '{self.title}' Menu 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 # Update selected index based on click
print(f"[DEBUG] '{self.title}' Menu option '{self.options[idx]}' clicked")
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)
print(f"[DEBUG] '{self.title}' Menu selection moved to {self.selected_index}")
elif event.key == pygame.K_DOWN:
self.selected_index = (self.selected_index + 1) % len(self.options)
print(f"[DEBUG] '{self.title}' Menu selection moved to {self.selected_index}")
elif event.key in [pygame.K_RETURN, pygame.K_SPACE]:
print(f"[DEBUG] '{self.title}' Menu option '{self.options[self.selected_index]}' selected 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
print(f"[DEBUG] '{self.title}' Menu fade-in completed")
elif self.fade_out and self.alpha > 0:
self.alpha -= 5
if self.alpha <= 0:
self.alpha = 0
self.show_menu_surface = False
print(f"[DEBUG] '{self.title}' Menu fade-out completed")
# Call callback after fade out
if self.on_select:
if self.title in ["Главное Меню", "Game Over"]:
self.on_select(self.selected_index)
# Fill the menu surface with transparency
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
)
)
Conclusion
By ensuring that the selected_index is correctly updated when users interact with the menu using the mouse and by properly managing the game state transitions when navigating between different menus, you should be able to resolve both issues you've encountered. Additionally, adopting a more robust state management approach can help prevent similar issues in the future.
Feel free to implement these changes and test your game. If you encounter further issues or specific error messages, please provide them for more detailed assistance.