import pygame
import time
from config import DEFAULT_WIDTH, DEFAULT_HEIGHT, GUESSES
class GameState:
def init(self):
# Pygame essentials (initialized in main)
self.screen = None
self.clock = pygame.time.Clock()
self.fonts = {} # To store 'main', 'small', 'stat', 'timer', 'custom_difficulty_button'
code
# Window dimensions (can be updated)
self.WIDTH = DEFAULT_WIDTH
self.HEIGHT = DEFAULT_HEIGHT
# Game-specific state
self.difficulty = 5 # Current word length
self.secret_word = ''
self.user_guesses = [] # List of guessed words (strings)
self.current_guess_idx = 0 # Index of the current guess row
self.active_cell_idx = 0 # Index of the active cell in the current guess row
self.stats = {"win": 0, "lose": 0}
self.custom_mode_active = False
self.custom_guesses_count = GUESSES # Number of allowed guesses for current game
self.game_start_time = 0 # Timestamp of when the current game started
self.elapsed_game_time = 0 # Accumulated time if game is paused and resumed
self.WORD_SETS = {} # Loaded from assets.py
def update_display_mode(self):
"""Updates the Pygame display mode with current WIDTH and HEIGHT."""
if self.screen is None: # First time setup
pygame.display.set_caption("Wordle на русском")
self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
def set_font(self, name, font_obj):
self.fonts[name] = font_obj
def get_font(self, name, default_fallback_size=32):
font = self.fonts.get(name)
if not font:
print(f"Warning: Font '{name}' not found, using default Arial {default_fallback_size}.")
if not pygame.font.get_init(): pygame.font.init() # Ensure font module is ready
return pygame.font.SysFont('Arial', default_fallback_size)
return font
def reset_for_new_game(self):
"""Resets state variables for the start of a new game."""
num_guesses = self.custom_guesses_count if self.custom_mode_active else GUESSES
self.user_guesses = ['' for _ in range(num_guesses)]
self.current_guess_idx = 0
self.active_cell_idx = 0
self.game_start_time = time.time()
self.elapsed_game_time = 0
def get_current_word_being_typed(self):
"""Returns the string of the word currently being typed by the user."""
if 0 <= self.current_guess_idx < len(self.user_guesses):
current_entry = self.user_guesses[self.current_guess_idx]
return current_entry if isinstance(current_entry, str) else ""
return ""
def set_current_word_being_typed(self, word_str):
"""Sets the string for the word currently being typed."""
if 0 <= self.current_guess_idx < len(self.user_guesses):
self.user_guesses[self.current_guess_idx] = word_str
Переведите комментарии в коде на русский
Assistant
python
# game_state.py
import pygame
import time
from config import DEFAULT_WIDTH, DEFAULT_HEIGHT, GUESSES
class GameState:
def __init__(self):
# Основные компоненты Pygame (инициализируются в main)
self.screen = None
self.clock = pygame.time.Clock()
self.fonts = {} # Для хранения шрифтов: 'main', 'small', 'stat', 'timer', 'custom_difficulty_button'
# Размеры окна (могут обновляться)
self.WIDTH = DEFAULT_WIDTH
self.HEIGHT = DEFAULT_HEIGHT
# Состояние, специфичное для игры
self.difficulty = 5 # Текущая длина слова
self.secret_word = ''
self.user_guesses = [] # Список отгаданных слов (строки)
self.current_guess_idx = 0 # Индекс текущей строки с предположением
self.active_cell_idx = 0 # Индекс активной ячейки в текущей строке с предположением
self.stats = {"win": 0, "lose": 0}
self.custom_mode_active = False
self.custom_guesses_count = GUESSES # Количество разрешённых попыток для текущей игры
self.game_start_time = 0 # Метка времени начала текущей игры
self.elapsed_game_time = 0 # Накопленное время, если игра была приостановлена и возобновлена
self.WORD_SETS = {} # Загружаемые из assets.py
def update_display_mode(self):
"""Обновляет режим отображения Pygame с текущими значениями WIDTH и HEIGHT."""
if self.screen is None: # Первая инициализация
pygame.display.set_caption("Wordle на русском")
self.screen = pygame.display.set_mode((self.WIDTH, self.HEIGHT))
def set_font(self, name, font_obj):
self.fonts[name] = font_obj
def get_font(self, name, default_fallback_size=32):
font = self.fonts.get(name)
if not font:
print(f"Warning: Font '{name}' not found, using default Arial {default_fallback_size}.")
if not pygame.font.get_init():
pygame.font.init() # Убедитесь, что модуль шрифтов готов
return pygame.font.SysFont('Arial', default_fallback_size)
return font
def reset_for_new_game(self):
"""Сбрасывает переменные состояния для начала новой игры."""
num_guesses = self.custom_guesses_count if self.custom_mode_active else GUESSES
self.user_guesses = ['' for _ in range(num_guesses)]
self.current_guess_idx = 0
self.active_cell_idx = 0
self.game_start_time = time.time()
self.elapsed_game_time = 0
def get_current_word_being_typed(self):
"""Возвращает строку слова, которое пользователь сейчас вводит."""
if 0 <= self.current_guess_idx < len(self.user_guesses):
current_entry = self.user_guesses[self.current_guess_idx]
return current_entry if isinstance(current_entry, str) else ""
return ""
def set_current_word_being_typed(self, word_str):
"""Устанавливает строку для текущего вводимого слова."""
if 0 <= self.current_guess_idx < len(self.user_guesses):
self.user_guesses[self.current_guess_idx] = word_str