import os # Добавлено для работы с путями
import random
from typing import Any , List , Dict , Optional
import pygame
--- Определение пути к директории со скриптом ---
Это гарантирует, что ресурсы будут искаться относительно местоположения файла игры.
BASE_DIR = os.path.dirname ( os.path.abspath ( file ) )
--- Константы для новых возможностей ---
DIFFICULTY_LEVELS = {
"Легко" : {"fps" : 10 , "obstacle_spawn_interval" : 10000 , "poison_spawn_interval" : 12000 ,
"bonus_apple_trigger" : 7} ,
"Средне" : {"fps" : 15 , "obstacle_spawn_interval" : 7000 , "poison_spawn_interval" : 8000 ,
"bonus_apple_trigger" : 5} ,
"Сложно" : {"fps" : 20 , "obstacle_spawn_interval" : 4000 , "poison_spawn_interval" : 5000 ,
"bonus_apple_trigger" : 3} ,
}
SNAKE_TYPES = {
"Классика" : {"color" : (0 , 128 , 0) , "head_color" : (0 , 100 , 0) , "eye_color" : (255 , 255 , 0)} ,
"Лазурь" : {"color" : (0 , 100 , 255) , "head_color" : (0 , 80 , 200) , "eye_color" : (255 , 165 , 0)} ,
"Багрянец" : {"color" : (180 , 0 , 0) , "head_color" : (150 , 0 , 0) , "eye_color" : (0 , 255 , 255)} ,
}
OBSTACLE_TYPES = {
"Статичный блок" : {"color" : (139 , 69 , 19) , "behavior" : "static"} ,
"Движущийся блок" : {"color" : (100 , 100 , 100) , "behavior" : "move_slow_hz"} ,
"Временная стена" : {"color" : (70 , 70 , 70) , "behavior" : "temporary"} ,
}
--- Конец констант ---
def load_high_score( filename='high_score.txt' ) -> int :
filepath = os.path.join ( BASE_DIR , filename )
try :
with open ( filepath , 'r' ) as f :
return int ( f.read ( ) )
except FileNotFoundError :
return 0
except ValueError :
print ( f"Предупреждение: Не удалось прочитать рекорд из {filepath}. Возвращено 0." )
return 0
class SnakeGame :
BLOCK_SIZE: int
def __init__( self ) :
self.score = 0
self.bonus_active = False
self.bonus_pos: Optional [ List [ int ] ] = None
self.last_bonus_spawn = 0
self.apples_eaten = 0
self.direction = 'RIGHT'
self.bonus_duration = 10000
self.food_pos: List [ int ] = [ 0 , 0 ]
self.has_eyes = True
self.bonus_move_interval = 10000
self.bonus_move_timer = 0
pygame.init ( )
self.snake_pos: List [ int ] = [ 0 , 0 ]
self.snake_length = 1
self.snake_list: List [ List [ int ] ] = [ ]
self.running = True
self.WINDOW_WIDTH = 800
self.WINDOW_HEIGHT = 600
self.BLOCK_SIZE = 20
self.FPS = 15
self.current_difficulty_level = "Средне"
self.current_snake_type = "Классика"
self.obstacle_spawn_interval = 7000
self.poison_apple_spawn_interval = 8000
self.bonus_apple_trigger = 5 # Сколько яблок съесть для бонуса
self.WHITE = (255 , 255 , 255)
self.BLACK = (0 , 0 , 0)
self.RED = (213 , 50 , 80) # Яблоко
self.BLUE = (50 , 153 , 213) # Фон по умолчанию
self.YELLOW = (255 , 255 , 0)
self.BONUS_ORANGE = (255 , 165 , 0)
self.POISON_APPLE_COLOR = (139 , 0 , 0) # Темно-красный
self.EYES_BLACK = (0 , 0 , 0)
self.display = pygame.display.set_mode ( (self.WINDOW_WIDTH , self.WINDOW_HEIGHT) )
pygame.display.set_caption ( 'Змейка' )
self.clock = pygame.time.Clock ( )
self.background_surface = None
os.path.join ( BASE_DIR , "background.png" )
try :
self.background_surface = pygame.image.load ( "background.png" ).convert ( )
self.background_surface = pygame.transform.scale (
self.background_surface ,
(self.WINDOW_WIDTH , self.WINDOW_HEIGHT)
)
except pygame.error as e :
print ( f"Не удалось загрузить '{"background.png"}'. Ошибка: {e}. Используется синий цвет фона." )
self.high_score_filename = 'high_score.txt' # Имя файла для рекорда
self.high_score = load_high_score ( self.high_score_filename )
self.paused = False
self.waiting_for_start = True
self.obstacles: List [ Dict [ str , Any ] ] = [ ]
self.poison_apple_pos: Optional [ List [ int ] ] = None
self.obstacle_duration = 15000
self.last_obstacle_spawn = 0
self.last_poison_apple_spawn = 0
self.apply_difficulty ( self.current_difficulty_level )
self.reset_game ( )
def apply_difficulty( self , level_name: str ) :
if level_name in DIFFICULTY_LEVELS :
settings = DIFFICULTY_LEVELS [ level_name ]
self.FPS = settings [ "fps" ]
self.obstacle_spawn_interval = settings [ "obstacle_spawn_interval" ]
self.poison_apple_spawn_interval = settings [ "poison_spawn_interval" ]
self.bonus_apple_trigger = settings [ "bonus_apple_trigger" ]
self.current_difficulty_level = level_name
print (
f"Сложность установлена на '{level_name}': FPS={self.FPS}, Интервал препятствий={self.obstacle_spawn_interval}" )
else :
print ( f"Предупреждение: Уровень сложности '{level_name}' не найден. Используются значения по умолчанию." )
def save_high_score( self ) :
filepath = os.path.join ( BASE_DIR , self.high_score_filename )
try :
with open ( filepath , 'w' ) as f :
f.write ( str ( self.high_score ) )
except IOError as e :
print ( f"Ошибка сохранения рекорда в {filepath}: {e}" )
def reset_game( self ) :
self.apply_difficulty ( self.current_difficulty_level )
self.snake_list = [ ]
self.snake_length = 1
start_x = round ( random.randrange ( self.BLOCK_SIZE * 5 , (
self.WINDOW_WIDTH - self.BLOCK_SIZE * 6) ) / self.BLOCK_SIZE ) * self.BLOCK_SIZE
start_y = round ( random.randrange ( self.BLOCK_SIZE * 5 , (
self.WINDOW_HEIGHT - self.BLOCK_SIZE * 6) ) / self.BLOCK_SIZE ) * self.BLOCK_SIZE
self.snake_pos = [ start_x , start_y ]
self.food_pos = self.generate_food_position ( )
self.bonus_pos = None
self.direction = random.choice ( [ 'RIGHT' , 'LEFT' , 'UP' , 'DOWN' ] )
self.score = 0
self.apples_eaten = 0
self.bonus_active = False
current_ticks = pygame.time.get_ticks ( )
self.last_bonus_spawn = current_ticks
self.bonus_move_timer = current_ticks
self.last_obstacle_spawn = current_ticks
self.last_poison_apple_spawn = current_ticks
self.obstacles = [ ]
self.poison_apple_pos = None
def generate_safe_position( self ) -> List [ int ] :
attempts = 0
max_attempts = 100 # Предотвращение бесконечного цикла, если места нет
while attempts < max_attempts :
x = round (
random.randrange ( 0 , (self.WINDOW_WIDTH - self.BLOCK_SIZE) // self.BLOCK_SIZE ) ) * self.BLOCK_SIZE
y = round (
random.randrange ( 0 , (self.WINDOW_HEIGHT - self.BLOCK_SIZE) // self.BLOCK_SIZE ) ) * self.BLOCK_SIZE
pos = [ x , y ]
if pos in self.snake_list :
attempts += 1
continue
collides_with_obstacle = False
for obs in self.obstacles :
if self.is_point_in_obstacle_rect ( pos [ 0 ] , pos [ 1 ] , obs ) :
collides_with_obstacle = True
break
if collides_with_obstacle :
attempts += 1
continue
if self.food_pos and pos == self.food_pos : attempts += 1; continue
if self.bonus_pos and pos == self.bonus_pos : attempts += 1; continue
if self.poison_apple_pos and pos == self.poison_apple_pos : attempts += 1; continue
if not (self.BLOCK_SIZE <= x <= self.WINDOW_WIDTH - self.BLOCK_SIZE * 2 and
self.BLOCK_SIZE <= y <= self.WINDOW_HEIGHT - self.BLOCK_SIZE * 2) :
attempts += 1
continue
return pos
# Если не удалось найти безопасное место после max_attempts, возвращаем случайное в центре
print ( "Предупреждение: Не удалось найти полностью безопасное место. Генерирую позицию в центре." )
return [ self.WINDOW_WIDTH // 2 , self.WINDOW_HEIGHT // 2 ]
def generate_food_position( self ) -> List [ int ] :
return self.generate_safe_position ( )
def generate_bonus_position( self ) -> List [ int ] :
return self.generate_safe_position ( )
def generate_obstacle_data( self ) -> Optional [ Dict [ str , Any ] ] :
if not OBSTACLE_TYPES : return None # Если нет типов препятствий
obstacle_type_name = random.choice ( list ( OBSTACLE_TYPES.keys ( ) ) )
obstacle_info = OBSTACLE_TYPES [ obstacle_type_name ]
size_blocks = random.randint ( 1 , 3 )
for _ in range ( 20 ) : # Больше попыток для размещения препятствия
x = round ( random.randrange ( 0 , (
self.WINDOW_WIDTH - size_blocks * self.BLOCK_SIZE) // self.BLOCK_SIZE ) ) * self.BLOCK_SIZE
y = round ( random.randrange ( 0 , (
self.WINDOW_HEIGHT - size_blocks * self.BLOCK_SIZE) // self.BLOCK_SIZE ) ) * self.BLOCK_SIZE
temp_rect = pygame.Rect ( x , y , size_blocks * self.BLOCK_SIZE , size_blocks * self.BLOCK_SIZE )
# Проверка на столкновение с головой змеи
if temp_rect.collidepoint ( self.snake_pos [ 0 ] , self.snake_pos [ 1 ] ) :
continue
collides_with_snake_body = False
for segment in self.snake_list :
if temp_rect.collidepoint ( segment [ 0 ] , segment [ 1 ] ) :
collides_with_snake_body = True
break
if collides_with_snake_body :
continue
if self.food_pos and temp_rect.collidepoint ( self.food_pos [ 0 ] , self.food_pos [ 1 ] ) : continue
if self.bonus_pos and temp_rect.collidepoint ( self.bonus_pos [ 0 ] , self.bonus_pos [ 1 ] ) : continue
if self.poison_apple_pos and temp_rect.collidepoint ( self.poison_apple_pos [ 0 ] ,
self.poison_apple_pos [ 1 ] ) : continue
collides_with_other_obstacle = False
for obs_existing in self.obstacles :
existing_rect = pygame.Rect ( obs_existing [ 'x' ] , obs_existing [ 'y' ] ,
obs_existing [ 'size' ] * self.BLOCK_SIZE ,
obs_existing [ 'size' ] * self.BLOCK_SIZE )
if temp_rect.colliderect ( existing_rect ) :
collides_with_other_obstacle = True
break
if collides_with_other_obstacle :
continue
obstacle_data = {
'x' : x , 'y' : y , 'size' : size_blocks ,
'type' : obstacle_type_name ,
'color' : obstacle_info [ 'color' ] ,
'behavior' : obstacle_info [ 'behavior' ] ,
'spawn_time' : pygame.time.get_ticks ( ) ,
'move_dir' : 1 if random.random ( ) > 0.5 else -1 ,
'last_move_time' : pygame.time.get_ticks ( )
}
return obstacle_data
return None
def is_point_in_obstacle_rect( self , x: int , y: int , obstacle_data: Dict [ str , Any ] ) -> bool :
obs_rect = pygame.Rect ( obstacle_data [ 'x' ] , obstacle_data [ 'y' ] ,
obstacle_data [ 'size' ] * self.BLOCK_SIZE ,
obstacle_data [ 'size' ] * self.BLOCK_SIZE )
return obs_rect.collidepoint ( x , y )
def show_selection_screen( self , title: str , options: List [ str ] , current_selection_value: str ) -> Optional [
str ] :
try :
selected_index = options.index ( current_selection_value )
except ValueError :
selected_index = 0 # Если текущее значение не найдено, выбираем первое
font_large = pygame.font.SysFont ( "bahnschrift" , 50 )
font_medium = pygame.font.SysFont ( "bahnschrift" , 35 )
selecting = True
while selecting :
if self.background_surface :
self.display.blit ( self.background_surface , (0 , 0) )
else :
self.display.fill ( self.BLUE )
title_surf = font_large.render ( title , True , self.BLACK )
title_rect = title_surf.get_rect ( center = (self.WINDOW_WIDTH // 2 , self.WINDOW_HEIGHT // 4) )
self.display.blit ( title_surf , title_rect )
for i , option_text in enumerate ( options ) :
color = self.YELLOW if i == selected_index else self.WHITE
text_surf = font_medium.render ( option_text , True , color )
text_rect = text_surf.get_rect (
center = (self.WINDOW_WIDTH // 2 , self.WINDOW_HEIGHT // 2 + i * 60) ) # Увеличил отступ
self.display.blit ( text_surf , text_rect )
pygame.display.flip ( )
for event in pygame.event.get ( ) :
if event.type == pygame.QUIT :
self.running = False
return None
if event.type == pygame.KEYDOWN :
if event.key == pygame.K_UP :
selected_index = (selected_index - 1 + len ( options )) % len ( options )
elif event.key == pygame.K_DOWN :
selected_index = (selected_index + 1) % len ( options )
elif event.key == pygame.K_RETURN :
return options [ selected_index ]
elif event.key == pygame.K_ESCAPE :
return None # Выход из меню выбора по Escape
self.clock.tick ( 30 )
return None # На случай непредвиденного выхода из цикла
def show_initial_setup_screens( self ) :
difficulty_options = list ( DIFFICULTY_LEVELS.keys ( ) )
chosen_difficulty = self.show_selection_screen ( "Выберите сложность" , difficulty_options ,
self.current_difficulty_level )
if chosen_difficulty is None : # Если пользователь нажал Escape или закрыл окно
if self.show_exit_confirmation ( ) : # Предложить выйти из игры
self.running = False
else : # Если отказался выходить, показать меню заново (или предыдущее)
self.show_initial_setup_screens ( ) # Рекурсивный вызов, но с проверкой running
return
self.apply_difficulty ( chosen_difficulty )
snake_type_options = list ( SNAKE_TYPES.keys ( ) )
chosen_snake_type = self.show_selection_screen ( "Выберите тип змейки" , snake_type_options ,
self.current_snake_type )
if chosen_snake_type is None :
self.show_initial_setup_screens ( ) # Возврат к выбору сложности (или предложить выйти)
return
self.current_snake_type = chosen_snake_type
self.waiting_for_start = False
self.reset_game ( )
def show_pause_menu( self ) :
paused_menu = True
selected_option = 0
options = [
{"text" : "Продолжить" , "action" : "continue"} ,
{"text" : "Перезапустить игру" , "action" : "restart_confirm"} ,
{"text" : "Изменить настройки" , "action" : "change_settings"} ,
{"text" : "Выйти из игры" , "action" : "exit_confirm"}
]
font_style = pygame.font.SysFont ( "bahnschrift" , 40 )
while paused_menu and self.running : # Добавил self.running
if self.background_surface :
self.display.blit ( self.background_surface , (0 , 0) )
else :
self.display.fill ( self.BLUE )
for i , option in enumerate ( options ) :
color = self.YELLOW if i == selected_option else self.WHITE
msg = font_style.render ( option [ "text" ] , True , color )
msg_rect = msg.get_rect ( center = (self.WINDOW_WIDTH // 2 , self.WINDOW_HEIGHT // 2 - 75 + i * 60) )
self.display.blit ( msg , msg_rect )
pygame.display.update ( )
for event in pygame.event.get ( ) :
if (
event.type == pygame.QUIT) :
if self.show_exit_confirmation ( ) : self.running = False
paused_menu = False
self.paused = False # Выход из меню и паузы
elif event.type == pygame.KEYDOWN :
if event.key == pygame.K_ESCAPE :
paused_menu = False
self.paused = False
elif event.key == pygame.K_UP :
selected_option = (selected_option - 1 + len ( options )) % len ( options )
elif event.key == pygame.K_DOWN :
selected_option = (selected_option + 1) % len ( options )
elif event.key == pygame.K_RETURN :
action = options [ selected_option ] [ "action" ]
if action == "continue" :
paused_menu = False
self.paused = False
elif action == "restart_confirm" :
if self.show_restart_confirmation ( ) :
paused_menu = False
self.paused = False
elif action == "change_settings" :
self.waiting_for_start = True
paused_menu = False
self.paused = False
elif action == "exit_confirm" :
if self.show_exit_confirmation ( ) :
self.running = False
paused_menu = False
self.paused = False # Даже если не вышли, меню закрываем
self.clock.tick ( self.FPS ) # Используем FPS игры, чтобы меню не было слишком быстрым
def show_confirmation_dialog( self , question: str ) -> bool :
confirming = True
selected_option = 0 # 0 для "Да", 1 для "Нет"
font_large = pygame.font.SysFont ( "bahnschrift" , 55 )
font_small = pygame.font.SysFont ( "bahnschrift" , 30 )
options_conf = [ {"text" : "Да"} , {"text" : "Нет"} ]
while confirming and self.running :
if self.background_surface :
self.display.blit ( self.background_surface , (0 , 0) )
else :
self.display.fill ( self.BLUE )
msg = font_large.render ( question , True , self.BLACK )
msg_rect = msg.get_rect ( center = (self.WINDOW_WIDTH // 2 , self.WINDOW_HEIGHT // 2 - 60) )
self.display.blit ( msg , msg_rect )
for i , option in enumerate ( options_conf ) :
color = self.YELLOW if i == selected_option else self.WHITE
msg_opt = font_small.render ( option [ "text" ] , True , color )
msg_rect_opt = msg_opt.get_rect (
center = (self.WINDOW_WIDTH // 2 , self.WINDOW_HEIGHT // 2 + 30 + i * 50) )
self.display.blit ( msg_opt , msg_rect_opt )
pygame.display.update ( )
for event in pygame.event.get ( ) :
if event.type == pygame.QUIT :
# При закрытии окна в диалоге подтверждения, считаем "Нет" и продолжаем игру (или выходим если это был выход)
if question == 'Выйти из игры?' : self.running = False; return True
return False
if event.type == pygame.KEYDOWN :
if event.key == pygame.K_ESCAPE : return False # "Нет" по Escape
if event.key == pygame.K_LEFT or event.key == pygame.K_UP : selected_option = 0 # "Да"
if event.key == pygame.K_RIGHT or event.key == pygame.K_DOWN : selected_option = 1 # "Нет"
if event.key == pygame.K_RETURN :
return selected_option == 0 # True если "Да", False если "Нет"
self.clock.tick ( self.FPS )
return False # Если вышли из цикла не через return
def show_restart_confirmation( self ) -> bool :
if self.show_confirmation_dialog ( 'Перезапустить игру?' ) :
self.reset_game ( )
return True
return False
def show_exit_confirmation( self ) -> bool :
return self.show_confirmation_dialog ( 'Выйти из игры?' )
def game_over_screen( self ) :
if self.score > self.high_score :
self.high_score = self.score
self.save_high_score ( )
font_large = pygame.font.SysFont ( "bahnschrift" , 55 )
font_small = pygame.font.SysFont ( "bahnschrift" , 30 )
game_over_options = [
{"text" : "Перезапустить (те же настройки)" , "action_func" : self.reset_game_and_play} ,
{"text" : "Изменить настройки и играть" , "action_func" : self.restart_with_setup} ,
{"text" : "Выйти из игры" , "action_func" : self.confirm_and_quit_game_action}
]
selected_option_idx = 0
waiting_for_input = True
while waiting_for_input and self.running :
if self.background_surface :
self.display.blit ( self.background_surface , (0 , 0) )
else :
self.display.fill ( self.BLUE )
msg = font_large.render ( 'Игра окончена!' , True , self.RED )
msg_rect = msg.get_rect ( center = (self.WINDOW_WIDTH // 2 , self.WINDOW_HEIGHT // 3) )
self.display.blit ( msg , msg_rect )
score_text_render = f'Ваш счет: {self.score} | Рекорд: {self.high_score}'
if self.score > 0 and self.score == self.high_score : # Проверяем, что это действительно новый рекорд
score_text_render = f'Новый рекорд: {self.score}!'
score_msg = font_small.render ( score_text_render , True , self.BLACK )
score_rect = score_msg.get_rect ( center = (self.WINDOW_WIDTH // 2 , self.WINDOW_HEIGHT // 3 + 70) )
self.display.blit ( score_msg , score_rect )
for i , option_data in enumerate ( game_over_options ) :
color = self.YELLOW if i == selected_option_idx else self.WHITE
opt_surf = font_small.render ( option_data [ "text" ] , True , color )
opt_rect = opt_surf.get_rect (
center = (self.WINDOW_WIDTH // 2 , self.WINDOW_HEIGHT // 2 + 50 + i * 50) )
self.display.blit ( opt_surf , opt_rect )
pygame.display.flip ( )
for event in pygame.event.get ( ) :
if event.type == pygame.QUIT :
if self.show_exit_confirmation ( ) : self.running = False
waiting_for_input = False # Выход из цикла game_over
if event.type == pygame.KEYDOWN :
if event.key == pygame.K_ESCAPE :
if self.show_exit_confirmation ( ) : self.running = False
waiting_for_input = False
elif event.key == pygame.K_UP :
selected_option_idx = (selected_option_idx - 1 + len ( game_over_options )) % len (
game_over_options )
elif event.key == pygame.K_DOWN :
selected_option_idx = (selected_option_idx + 1) % len ( game_over_options )
elif event.key == pygame.K_RETURN :
game_over_options [ selected_option_idx ] [ "action_func" ] ( )
waiting_for_input = False
self.clock.tick ( self.FPS )
def reset_game_and_play( self ) :
self.reset_game ( )
# self.waiting_for_start остается False
def restart_with_setup( self ) :
self.waiting_for_start = True
self.reset_game ( )
def confirm_and_quit_game_action( self ) :
if self.show_exit_confirmation ( ) :
self.running = False
def handle_events( self ) :
for event in pygame.event.get ( ) :
if event.type == pygame.QUIT :
if self.show_exit_confirmation ( ) :
self.running = False
elif event.type == pygame.KEYDOWN :
if event.key == pygame.K_ESCAPE :
if not self.waiting_for_start : # Если не на экране настроек
self.paused = not self.paused
if self.paused :
self.show_pause_menu ( )
if not self.paused and not self.waiting_for_start :
if event.key == pygame.K_LEFT and self.direction != 'RIGHT' :
self.direction = 'LEFT'
elif event.key == pygame.K_RIGHT and self.direction != 'LEFT' :
self.direction = 'RIGHT'
elif event.key == pygame.K_UP and self.direction != 'DOWN' :
self.direction = 'UP'
elif event.key == pygame.K_DOWN and self.direction != 'UP' :
self.direction = 'DOWN'
def update_game_state( self ) -> bool :
if self.paused :
return True
head_pos = list ( self.snake_pos )
if self.direction == 'RIGHT' :
head_pos [ 0 ] += self.BLOCK_SIZE
elif self.direction == 'LEFT' :
head_pos [ 0 ] -= self.BLOCK_SIZE
elif self.direction == 'UP' :
head_pos [ 1 ] -= self.BLOCK_SIZE
elif self.direction == 'DOWN' :
head_pos [ 1 ] += self.BLOCK_SIZE
if not (0 <= head_pos [ 0 ] < self.WINDOW_WIDTH and 0 <= head_pos [ 1 ] < self.WINDOW_HEIGHT) :
return False
# Проверка столкновения с собой (кроме случая, когда змейка только появляется и ее длина 1)
if len ( self.snake_list ) > 1 and head_pos in self.snake_list [ :-1 ] :
return False
for obs in self.obstacles :
if self.is_point_in_obstacle_rect ( head_pos [ 0 ] , head_pos [ 1 ] , obs ) :
return False
self.snake_list.append ( list ( head_pos ) )
ate_something = False
if head_pos == self.food_pos :
self.score += 1
self.apples_eaten += 1
self.snake_length += 1
self.food_pos = self.generate_food_position ( )
ate_something = True
if self.apples_eaten % self.bonus_apple_trigger == 0 and not self.bonus_active :
bonus_candidate_pos = self.generate_bonus_position ( )
if bonus_candidate_pos : # Проверяем, что позиция сгенерирована
self.bonus_pos = bonus_candidate_pos
self.bonus_active = True
self.last_bonus_spawn = pygame.time.get_ticks ( )
self.bonus_move_timer = pygame.time.get_ticks ( )
elif self.bonus_pos and head_pos == self.bonus_pos :
self.score += 5
self.snake_length += 3
self.bonus_pos = None
self.bonus_active = False
ate_something = True
elif self.poison_apple_pos and head_pos == self.poison_apple_pos :
self.score = max ( 0 , self.score - 3 )
self.snake_length = max ( 1 , self.snake_length - 2 )
# Если после съедания яда длина стала 0, то игра окончена
if self.snake_length < 1 : return False
self.poison_apple_pos = None
self.last_poison_apple_spawn = pygame.time.get_ticks ( )
ate_something = True
if not ate_something :
if len ( self.snake_list ) > self.snake_length :
self.snake_list.pop ( 0 )
# Если после укорачивания (например, ядом) список стал пустым, но длина > 0 (быть не должно, но на всякий)
if not self.snake_list and self.snake_length > 0 :
self.snake_list.append ( list ( head_pos ) ) # Восстанавливаем голову
elif self.snake_list : # Только если список не пуст
self.snake_pos = list ( self.snake_list [ -1 ] ) # Голова - это последний элемент
else : # Если змейка исчезла полностью
return False
current_time = pygame.time.get_ticks ( )
# Обновление препятствий
new_obstacles_list = [ ]
for obs in self.obstacles :
if obs [ 'behavior' ] == "temporary" and current_time - obs [ 'spawn_time' ] > self.obstacle_duration :
continue
if obs [ 'type' ] == "Движущийся блок" and current_time - obs.get ( 'last_move_time' ,
0 ) > 500 : # Каждые 0.5 сек
obs [ 'x' ] += obs [ 'move_dir' ] * self.BLOCK_SIZE
obs [ 'last_move_time' ] = current_time
if obs [ 'x' ] < 0 or obs [ 'x' ] + obs [ 'size' ] * self.BLOCK_SIZE > self.WINDOW_WIDTH :
obs [ 'move_dir' ] *= -1
obs [ 'x' ] = max ( 0 , min ( obs [ 'x' ] ,
self.WINDOW_WIDTH - obs [ 'size' ] * self.BLOCK_SIZE ) ) # Коррекция
new_obstacles_list.append ( obs )
self.obstacles = new_obstacles_list
if current_time - self.last_obstacle_spawn >= self.obstacle_spawn_interval :
new_obstacle = self.generate_obstacle_data ( )
if new_obstacle :
self.obstacles.append ( new_obstacle )
self.last_obstacle_spawn = current_time
# Ядовитое яблоко
poison_apple_despawn_time = 10000 # Время жизни ядовитого яблока
if self.poison_apple_pos and current_time - self.last_poison_apple_spawn > poison_apple_despawn_time :
self.poison_apple_pos = None
# Не сбрасываем self.last_poison_apple_spawn, чтобы новое появилось через интервал ПОСЛЕ исчезновения
if not self.poison_apple_pos and \
current_time - self.last_poison_apple_spawn >= self.poison_apple_spawn_interval :
poison_candidate_pos = self.generate_food_position ( )
if poison_candidate_pos : # Проверяем, что позиция сгенерирована
self.poison_apple_pos = poison_candidate_pos
self.last_poison_apple_spawn = current_time # Время появления
# Бонус
if self.bonus_active :
if self.bonus_pos and current_time - self.bonus_move_timer >= self.bonus_move_interval :
bonus_candidate_pos = self.generate_bonus_position ( )
if bonus_candidate_pos : self.bonus_pos = bonus_candidate_pos
self.bonus_move_timer = current_time
if current_time - self.last_bonus_spawn >= self.bonus_duration :
self.bonus_pos = None
self.bonus_active = False
return True
def draw_elements( self ) :
if self.background_surface :
self.display.blit ( self.background_surface , (0 , 0) )
else :
self.display.fill ( self.BLUE )
if self.food_pos : # Проверка, что еда существует
pygame.draw.rect ( self.display , self.RED ,
[ self.food_pos [ 0 ] , self.food_pos [ 1 ] , self.BLOCK_SIZE , self.BLOCK_SIZE ] )
if self.bonus_pos :
pygame.draw.rect ( self.display , self.BONUS_ORANGE ,
[ self.bonus_pos [ 0 ] , self.bonus_pos [ 1 ] , self.BLOCK_SIZE , self.BLOCK_SIZE ] )
remaining_bonus_time = max ( 0 , self.bonus_duration - (
pygame.time.get_ticks ( ) - self.last_bonus_spawn) ) // 1000
font = pygame.font.SysFont ( "bahnschrift" , 20 )
timer_text = font.render ( f"Бонус: {remaining_bonus_time}с" , True , self.YELLOW )
self.display.blit ( timer_text , (self.WINDOW_WIDTH - timer_text.get_width ( ) - 10 , 10) )
for obs_data in self.obstacles :
pygame.draw.rect (
self.display , obs_data [ 'color' ] ,
[ obs_data [ 'x' ] , obs_data [ 'y' ] , obs_data [ 'size' ] * self.BLOCK_SIZE ,
obs_data [ 'size' ] * self.BLOCK_SIZE ]
)
if self.poison_apple_pos :
pygame.draw.rect ( self.display , self.POISON_APPLE_COLOR ,
[ self.poison_apple_pos [ 0 ] , self.poison_apple_pos [ 1 ] , self.BLOCK_SIZE ,
self.BLOCK_SIZE ] )
# Змейка
snake_skin = SNAKE_TYPES [ self.current_snake_type ]
for i , pos_segment in enumerate ( self.snake_list ) :
color = snake_skin [ "head_color" ] if i == len ( self.snake_list ) - 1 else snake_skin [ "color" ]
pygame.draw.rect ( self.display , color ,
[ pos_segment [ 0 ] , pos_segment [ 1 ] , self.BLOCK_SIZE , self.BLOCK_SIZE ] )
if self.has_eyes and i == len ( self.snake_list ) - 1 : # Голова
eye_size = max ( 2 , self.BLOCK_SIZE // 5 ) # Минимальный размер глаза 2
pupil_size = max ( 1 , eye_size // 2 )
eye_color = snake_skin [ "eye_color" ]
# Позиционирование глаз
# (Логика глаз может быть сложной, это упрощенный вариант)
center_x , center_y = pos_segment [ 0 ] + self.BLOCK_SIZE // 2 , pos_segment [
1 ] + self.BLOCK_SIZE // 2
eye_offset_main = self.BLOCK_SIZE // 4
eye_offset_secondary = self.BLOCK_SIZE // 6
if self.direction == 'UP' :
eye1_pos = (center_x - eye_offset_main , center_y - eye_offset_secondary - eye_size // 2)
eye2_pos = (center_x + eye_offset_main - eye_size , center_y - eye_offset_secondary - eye_size // 2)
elif self.direction == 'DOWN' :
eye1_pos = (center_x - eye_offset_main , center_y + eye_offset_secondary - eye_size // 2)
eye2_pos = (center_x + eye_offset_main - eye_size , center_y + eye_offset_secondary - eye_size // 2)
elif self.direction == 'LEFT' :
eye1_pos = (center_x - eye_offset_secondary - eye_size // 2 , center_y - eye_offset_main)
eye2_pos = (center_x - eye_offset_secondary - eye_size // 2 , center_y + eye_offset_main - eye_size)
else : # RIGHT
eye1_pos = (center_x + eye_offset_secondary - eye_size // 2 , center_y - eye_offset_main)
eye2_pos = (center_x + eye_offset_secondary - eye_size // 2 , center_y + eye_offset_main - eye_size)
pygame.draw.rect ( self.display , eye_color , [ *eye1_pos , eye_size , eye_size ] )
pygame.draw.rect ( self.display , self.EYES_BLACK , [ eye1_pos [ 0 ] + (eye_size - pupil_size) // 2 ,
eye1_pos [ 1 ] + (eye_size - pupil_size) // 2 ,
pupil_size , pupil_size ] )
pygame.draw.rect ( self.display , eye_color , [ *eye2_pos , eye_size , eye_size ] )
pygame.draw.rect ( self.display , self.EYES_BLACK , [ eye2_pos [ 0 ] + (eye_size - pupil_size) // 2 ,
eye2_pos [ 1 ] + (eye_size - pupil_size) // 2 ,
pupil_size , pupil_size ] )
font_style_ui = pygame.font.SysFont ( "bahnschrift" , 25 )
score_msg = font_style_ui.render ( f'Счет: {self.score}' , True , self.BLACK )
self.display.blit ( score_msg , [ 10 , 10 ] )
difficulty_msg = font_style_ui.render ( f'{self.current_difficulty_level}' , True , self.BLACK )
self.display.blit ( difficulty_msg , [ 10 , 35 ] )
if self.paused :
# Исправленная строка для создания поверхности с альфа-каналом
pause_surface = pygame.Surface ( (self.WINDOW_WIDTH , self.WINDOW_HEIGHT) , pygame.SRCALPHA )
pause_surface.fill ( (0 , 0 , 0 , 128) ) # Полупрозрачный черный
self.display.blit ( pause_surface , (0 , 0) )
font_pause_text = pygame.font.SysFont ( "bahnschrift" , 70 )
pause_text_render = font_pause_text.render ( "ПАУЗА" , True , self.WHITE )
pause_text_rect = pause_text_render.get_rect (
center = (self.WINDOW_WIDTH // 2 , self.WINDOW_HEIGHT // 2 - 100) )
self.display.blit ( pause_text_render , pause_text_rect )
# Меню паузы отрисовывается в show_pause_menu() поверх этого
pygame.display.flip ( )
def run( self ) :
while self.running :
if self.waiting_for_start :
self.show_initial_setup_screens ( )
if not self.running :
break
self.handle_events ( )
if not self.paused and not self.waiting_for_start :
if not self.update_game_state ( ) :
self.game_over_screen ( )
if not self.running : break
if not self.waiting_for_start : # Не рисуем основной экран, если идет настройка (она сама рисует)
self.draw_elements ( )
self.clock.tick ( self.FPS )
pygame.quit ( )
if name == "main":
game = SnakeGame()
game.run()