import pygame
import sys
import time
from config import COLORS, CELL_SIZE, GUESSES
from drawing_utils import draw_gradient_background, draw_text_centered
def calculate_window_size(word_length, guesses_count, cell_size):
"""Вычисляет размер окна на основе длины слова и количества попыток."""
field_width = word_length * cell_size
field_height = guesses_count * (cell_size + 10)
width = max(480, field_width + 80)
height = max(700, field_height + 220)
return width, height
def wrap_text(text, font, max_width):
"""Разбивает текст на строки, чтобы каждая строка помещалась в max_width."""
words = text.split(' ')
lines = []
current_line = ''
code
for word in words:
test_line = current_line + word + ' '
if font.size(test_line)[0] <= max_width:
current_line = test_line
else:
lines.append(current_line.strip())
current_line = word + ' '
lines.append(current_line.strip())
return lines
import pygame
import sys
import random
import time
import config as app_config
import ui
def initialize_game_session_logic(gs, config_module, selected_choice):
"""Запуск игры на базе выбранной сложности"""
if selected_choice == 'custom':
gs.custom_mode_active = True
gs.custom_guesses_count = config_module.GUESSES
gs.update_display_mode()
else:
gs.difficulty = selected_choice
gs.custom_mode_active = False
gs.custom_guesses_count = config_module.GUESSES
gs.WIDTH, gs.HEIGHT = ui.calculate_window_size(gs.difficulty, config_module.GUESSES, config_module.CELL_SIZE)
gs.update_display_mode()
code
# Выбор секретного слова
if not gs.WORD_SETS.get(gs.difficulty):
print(f"Ошибка: Нет слов для сложности {gs.difficulty}.")
valid_diffs = [d for d, words in gs.WORD_SETS.items() if words]
gs.difficulty = 5 if 5 in valid_diffs else valid_diffs[0] if valid_diffs else None
if not gs.difficulty:
_show_critical_error_screen()
gs.custom_mode_active = False
gs.custom_guesses_count = config_module.GUESSES
gs.WIDTH, gs.HEIGHT = ui.calculate_window_size(gs.difficulty, config_module.GUESSES, config_module.CELL_SIZE)
gs.update_display_mode()
gs.secret_word = random.choice(gs.WORD_SETS[gs.difficulty])
print("Загаданное слово:", gs.secret_word)
gs.reset_for_new_game()
def _show_critical_error_screen():
"""Отображает критическую ошибку и завершает приложение"""
temp_screen = pygame.display.set_mode((480, 200))
temp_screen.fill(app_config.COLORS['MENU_BG_GRAD1'])
err_font = pygame.font.SysFont('Arial', 24)
ui.draw_text_centered(temp_screen, "Ошибка: База слов пуста.", err_font, app_config.COLORS['BLACK'], 240, 70)
ui.draw_text_centered(temp_screen, "Невозможно начать игру.", err_font, app_config.COLORS['BLACK'], 240, 110)
pygame.display.flip()
pygame.time.wait(3000)
pygame.quit()
sys.exit()
gs = GameState()
gs.WORD_SETS = assets.load_words(app_config.WORDS_FILE)
initialized_fonts = assets.initialize_fonts()
for name, font_obj in initialized_fonts.items():
gs.set_font(name, font_obj)
gs.WIDTH = app_config.DEFAULT_WIDTH
gs.HEIGHT = app_config.DEFAULT_HEIGHT
gs.update_display_mode()
while True:
difficulty_choice = ui.show_main_menu_display(gs, app_config)
if difficulty_choice is None:
break
if difficulty_choice == 'custom':
ui.prompt_custom_difficulty_settings(gs, app_config)
game_manager.initialize_game_session_logic(gs, app_config, difficulty_choice)
game_manager.run_game_session_loop(gs, app_config)
if name == "main":
main_application_loop()
pygame.quit()
sys.exit()
Игрой игнорируется значение, указанное в поле "количество попыток" во время "своей сложности", вместо этого всегда отрисовывается 6 полей
Assistant
Проблема, которую вы описали — игра в режиме "своя сложность" игнорирует значение, указанное пользователем для "количества попыток" и по-прежнему отрисовывает стандартные 6 полей — действительно может сбивать с толку.
Однако, судя по вашему коду, проблема возникает в initialize_game_session_logic внутри game_manager.py.
📍 Причина Проблемы
Вот часть центра логики настройки пользовательской сложности в initialize_game_session_logic:
Это перезаписывает введённое количество попыток, введённое ранее в prompt_custom_difficulty_settings, значением по умолчанию (config_module.GUESSES, т.е. стандартное количество — 6).
✅ Решение
Нужно не перезаписывать gs.custom_guesses_count, если пользователь уже установил это значение во время ввода "своей сложности".
Просто удалите строку:
python
gs.custom_guesses_count = config_module.GUESSES
И измените вашу функцию так:
python
def initialize_game_session_logic(gs, config_module, selected_choice):
"""Запуск игры на базе выбранной сложности"""
if selected_choice == 'custom':
gs.custom_mode_active = True
# Удалите эту строку:
# gs.custom_guesses_count = config_module.GUESSES
gs.update_display_mode()
else:
gs.difficulty = selected_choice
gs.custom_mode_active = False
gs.custom_guesses_count = config_module.GUESSES
gs.WIDTH, gs.HEIGHT = ui.calculate_window_size(gs.difficulty, config_module.GUESSES, config_module.CELL_SIZE)
gs.update_display_mode()
len_input_rect = pygame.Rect(gs.WIDTH // 2 - 100, 240, 200, 50)
guess_input_rect = pygame.Rect(gs.WIDTH // 2 - 100, 340, 200, 50)
start_btn_rect = pygame.Rect(gs.WIDTH // 2 - 150, 430, 130, 50)
back_btn_rect = pygame.Rect(gs.WIDTH // 2 + 20, 430, 130, 50)
def _validate_and_start():
redraw_args = (gs, config_module, len_str, guess_str, active_field)
try:
diff = int(len_str)
g_count = int(guess_str)
if not (3 <= diff <= 10):
show_message_box(gs, "Длина слова должна быть 3-10!", 2500, _draw_custom_difficulty_inputs, redraw_args)
return False
if not (1 <= g_count <= 15):
show_message_box(gs, "Попыток должно быть 1-15!", 2500, _draw_custom_difficulty_inputs, redraw_args)
return False
if not (diff in gs.WORD_SETS and gs.WORD_SETS[diff]):
show_message_box(gs, "Нет слов такой длины!", 2500, _draw_custom_difficulty_inputs, redraw_args)
return False
gs.difficulty = diff
gs.custom_guesses_count = g_count
return True
except ValueError:
show_message_box(gs, "Введите число!", 2500, _draw_custom_difficulty_inputs, redraw_args)
return False
running = True
while running:
_draw_custom_difficulty_inputs(gs, config_module, len_str, guess_str, active_field)
# Кнопка "Начать"
pygame.draw.rect(gs.screen, config_module.COLORS['GRAY'], start_btn_rect, border_radius=12)
draw_text_centered(gs.screen, "Начать", gs.get_font('small'), config_module.COLORS['BLACK'], start_btn_rect.centerx, start_btn_rect.centery)
# Кнопка "Назад"
pygame.draw.rect(gs.screen, config_module.COLORS['GRAY'], back_btn_rect, border_radius=12)
draw_text_centered(gs.screen, "Назад", gs.get_font('small'), config_module.COLORS['BLACK'], back_btn_rect.centerx, back_btn_rect.centery)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if len_input_rect.collidepoint(event.pos):
active_field = 'len'
elif guess_input_rect.collidepoint(event.pos):
active_field = 'guess'
elif start_btn_rect.collidepoint(event.pos):
if _validate_and_start():
running = False
elif back_btn_rect.collidepoint(event.pos):
# Возврат в главное меню
return None
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_TAB:
active_field = 'guess' if active_field == 'len' else 'len'
elif event.key == pygame.K_RETURN:
if _validate_and_start():
running = False
elif event.key == pygame.K_BACKSPACE:
if active_field == 'len':
len_str = len_str[:-1]
else:
guess_str = guess_str[:-1]
elif event.unicode.isdigit():
if active_field == 'len' and len(len_str) < 2:
len_str += event.unicode
elif active_field == 'guess' and len(guess_str) < 2:
guess_str += event.unicode
if not running:
break
return gs.difficulty
def _handle_guess_submission():
nonlocal game_is_over, session_running
current_word = gs.get_current_word_being_typed()
final_time = gs.elapsed_game_time + (time.time() - gs.game_start_time) if gs.game_start_time > 0 else gs.elapsed_game_time
pygame.time.delay(200)
if current_word == gs.secret_word:
gs.stats["win"] += 1
game_is_over = True
ui.draw_game_board(gs, config_module, False)
pygame.display.flip()
ui.show_result_screen_display(gs, config_module, True, gs.secret_word, final_time)
session_running = False
else:
gs.current_guess_idx += 1
gs.active_cell_idx = 0
max_guesses = gs.custom_guesses_count if gs.custom_mode_active else config_module.GUESSES
if gs.current_guess_idx >= max_guesses:
gs.stats["lose"] += 1
game_is_over = True
ui.draw_game_board(gs, config_module, False)
pygame.display.flip()
ui.show_result_screen_display(gs, config_module, False, gs.secret_word, final_time)
session_running = False
# Управление таймером
if gs.game_start_time == 0:
gs.game_start_time = time.time() if gs.elapsed_game_time == 0 else gs.game_start_time
while session_running:
gs.clock.tick(config_module.FPS)
grid_start_x, grid_start_y, enter_btn_rect, menu_btn_rect = ui.draw_game_board(gs, config_module, not game_is_over)
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.MOUSEBUTTONDOWN:
if menu_btn_rect.collidepoint(event.pos) and not game_is_over:
if gs.game_start_time > 0:
gs.elapsed_game_time += time.time() - gs.game_start_time
gs.game_start_time = 0
session_running = False
continue
if game_is_over:
continue
if event.type == pygame.KEYDOWN:
typed_word = gs.get_current_word_being_typed()
if event.key == pygame.K_BACKSPACE:
if gs.active_cell_idx > 0:
gs.set_current_word_being_typed(typed_word[:gs.active_cell_idx-1] + typed_word[gs.active_cell_idx:])
gs.active_cell_idx -= 1
elif event.key == pygame.K_RETURN:
if len(typed_word) == gs.difficulty:
_handle_guess_submission()
else:
ui.show_message_box(gs, "Слово слишком короткое!", 1000, lambda: ui.draw_game_board(gs, config_module, True))
elif event.key == pygame.K_LEFT:
gs.active_cell_idx = max(0, gs.active_cell_idx - 1)
elif event.key == pygame.K_RIGHT:
gs.active_cell_idx = min(gs.difficulty, gs.active_cell_idx + 1)
else:
char = event.unicode.lower()
if 'а' <= char <= 'я' and gs.active_cell_idx < gs.difficulty:
new_word = typed_word[:gs.active_cell_idx] + char + typed_word[gs.active_cell_idx+1:]
gs.set_current_word_being_typed(new_word)
gs.active_cell_idx += 1
if len(gs.get_current_word_being_typed()) == gs.difficulty:
_handle_guess_submission()
elif event.type == pygame.MOUSEBUTTONDOWN:
mx, my = event.pos
clicked_cell = False
if gs.current_guess_idx < (gs.custom_guesses_count if gs.custom_mode_active else config_module.GUESSES):
row_y_base = grid_start_y + gs.current_guess_idx * (config_module.CELL_SIZE + 10)
for c in range(gs.difficulty):
cell_rect = pygame.Rect(grid_start_x + c * config_module.CELL_SIZE, row_y_base, config_module.CELL_SIZE, config_module.CELL_SIZE)
if cell_rect.collidepoint(mx, my):
gs.active_cell_idx = min(c, len(gs.get_current_word_being_typed()))
clicked_cell = True
break
if not clicked_cell and enter_btn_rect.collidepoint(mx, my):
if len(gs.get_current_word_being_typed()) == gs.difficulty:
_handle_guess_submission()
else:
ui.show_message_box(gs, "Слово слишком короткое!", 1000, lambda: ui.draw_game_board(gs, config_module, True))
# Остановка таймера при выходе
if gs.game_start_time > 0:
if game_is_over:
gs.game_start_time = 0
gs.elapsed_game_time = 0
else:
gs.elapsed_game_time += time.time() - gs.game_start_time
gs.game_start_time = 0
💡 Ещё лучше:
Чтобы избежать подобных путаниц и сделать функцию более устойчивой, вы можете включить одну проверку:
python
if selected_choice == 'custom':
gs.custom_mode_active = True
if not hasattr(gs, 'custom_guesses_count') or not gs.custom_guesses_count:
gs.custom_guesses_count = config_module.GUESSES
gs.update_display_mode()
Проверка в draw_game_board
Также убедитесь, что вы используете gs.custom_guesses_count, когда нужно вывести поле. В вашем draw_game_board():
python
guesses_to_draw = gs.custom_guesses_count if gs.custom_mode_active else config_module.GUESSES
Это выглядит правильно ✅ — так что основная ошибка была в перезаписи custom_guesses_count.
✅ Результат
После этого изменения:
Пользовательская сложность будет уважать введённое количество попыток.
Игра начнёт отрисовывать именно столько строк, сколько указал игрок.
Игровая логика тоже начнёт учитывать это количество.
Если понадобится, могу помочь также в тестировании или предложить более чистое хранение параметров с объектом GameSettings.