Danro/Assets/Scripts/Prizes/PrizeStandPrize.cs
Danil Iarosh 78d7679e2b
Some checks failed
Gitea Actions Demo / Explore-Gitea-Actions (push) Has been cancelled
feat(prizes, ui): complete Mar 24-Apr 2 sprint ahead of schedule
- завершен спринт 24 марта - 2 апреля с опережением плана и закрытием задач раньше срока
- расширена и стабилизирована система призов:
  добавлены и доработаны QR-tier конфиги, новые типы и модели данных,
  сохранение `qrCodes` в `prizes.json`, fallback-логика и синхронизация
  через `PrizeSystemManager`, `PrizeDatabase` и `LevelPrizeConfig`
- переработан flow настройки QR-призов:
  добавлены `QRCodeSettingsModal` и связанный UI-код,
  разнесены короткий текст приза и полный текст сообщения,
  добавлены шаблоны форматирования, корректная подстановка текста
  в QR и в UI-модалках, а также сохранение конфигурации между запусками
- доработан flow суперприза и текстовых настроек:
  добавлены fallback-правила показа, корректная обработка пустых строк
  и строк из одних пробелов, обновлены binders и показ текста в меню
- реализована и обновлена отдельная настройка витрины:
  добавлена `PrizeStandSettingsModal`, обновлена навигация строк,
  логика выбора ячейки и порогов очков, циклический выбор ячеек,
  ускорение изменения значений и исправления для keyboard/gamepad UX
- доработана игровая модалка витрины `PrizeStandModal`:
  добавлен вывод очков игрока, форматируемый текст счета,
  улучшено отображение ячеек и связанная логика выбора приза
- исправлен подсчет очков и интеграция с prize flow:
  `ScoreSystem` переведен на событийное обновление текущего счета,
  добавлены `CurrentScore`, `CurrentScoreChanged` и корректный display score,
  витрина и связанные UI-элементы теперь получают актуальные очки,
  а не нулевые или несвоевременные preview-значения
- переработаны модальные окна и навигация UI:
  улучшены `Modal`, `ModalManager`, `UIRowPointer`, `RulesModal`,
  `QRCodeModal`, `PrizeStandModal`, `LevelPrizeSettingsModal` и др.,
  чтобы фокус, указатель и submit работали консистентно без мыши
- обновлен win/prize UI:
  доработаны `WinBannerController`, `GameEndUIController`,
  `MainMenu`, `QRCodeUIController`, `TopPanelTextController` и настройки UI,
  улучшены тексты баннеров, отображение призов и итогового счета
- обновлены сцены и ассеты под новый flow:
  `MainMenu`, `Level UI`, prefab'ы строк настроек и кнопок,
  глобальные префабы, шрифты TMP, иконки, recovery-данные и ресурсы UI
- добавлены вспомогательные UI-компоненты и служебные скрипты:
  `ButtonTextFocusColor`, `SelectableDescriptionTarget`, `QRTier`
  и другие изменения, поддерживающие новый конфигурируемый prize UI
2026-04-01 12:47:17 +03:00

161 lines
5.6 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Collections.Generic;
using UnityEngine;
using RR.Common.Controls;
using RR.Common.Managers;
using RR.Common.UI;
using RR.Game2D.Behaviour;
using RR.Game2D.Core.Managers;
namespace RR.Common.Prizes
{
/// <summary>
/// Исполнитель приза «Витрина».
/// Показывает модальное окно с выбором ячейки, затем открывает её
/// через <see cref="PrizeStandController"/>. Количество ячеек берётся из ComSystemManager.
/// </summary>
public class PrizeStandPrize : PrizeBase
{
public override PrizeType Type => PrizeType.PrizeStand;
public override bool IsGiving => _isGiving;
private readonly Func<PrizeStandModal> _resolveModal;
private bool _isGiving;
private PrizeStandModal _activeModal;
/// <param name="resolveModal">Делегат для поиска модального окна в текущих сценах.</param>
public PrizeStandPrize(Func<PrizeStandModal> resolveModal)
{
_resolveModal = resolveModal;
}
public override void Execute(MonoBehaviour host, LevelPrizeConfig config)
{
if (_isGiving)
{
Debug.LogWarning("[PrizeStandPrize] Уже идёт выдача.");
return;
}
_isGiving = true;
// Отписываемся от предыдущего модального окна, если было
if (_activeModal != null)
_activeModal.OnBoxSelected -= OnBoxSelected;
_activeModal = _resolveModal?.Invoke();
if (_activeModal != null)
{
_activeModal.OnBoxSelected += OnBoxSelected;
var stand = ComSystemManager.GetPrizeStandController();
PrizeStandConnectionInfo connectionInfo = PrizeSystemManager.Instance != null
? PrizeSystemManager.Instance.GetPrizeStandConnectionInfo()
: new PrizeStandConnectionInfo(stand != null, stand != null ? stand.GetBoxesCount() : 0);
float gameTime = GameManager.Instance != null ? GameManager.Instance.GetPendingOrCurrentWinGameTime() : 0f;
int finalScore = ScoreSystem.Instance != null
? ScoreSystem.Instance.GetDisplayScore(gameTime, true)
: 0;
PrizeStandSettings settings = PrizeSystemManager.Instance != null
? PrizeSystemManager.Instance.GetPrizeStandSettings()
: new PrizeStandSettings();
_activeModal.Show(
BuildAvailability(settings, connectionInfo, finalScore),
connectionInfo.IsConnected,
connectionInfo.ConnectedBoxesCount,
gameTime,
finalScore,
true);
}
else
{
Debug.LogError("[PrizeStandPrize] PrizeStandModal не найден на сцене.");
_isGiving = false;
InvokeResult(false);
}
}
private async void OnBoxSelected(int boxNumber)
{
// Отписываемся сразу после выбора
if (_activeModal != null)
{
_activeModal.OnBoxSelected -= OnBoxSelected;
_activeModal = null;
}
if (boxNumber <= 0)
{
_isGiving = false;
InvokeResult(false);
return;
}
PrizeStandController stand = ComSystemManager.GetPrizeStandController();
if (stand == null)
{
Debug.LogError("[PrizeStandPrize] Витрина не подключена.");
_isGiving = false;
InvokeResult(false);
return;
}
bool success = false;
void OnResult(bool s, string m)
{
stand.OpeningFinished -= OnResult;
success = s;
if (!s) Debug.LogWarning($"[PrizeStandPrize] Ошибка: {m}");
}
stand.OpeningFinished += OnResult;
try
{
await stand.OpenBoxAsync(boxNumber);
}
catch (Exception ex)
{
Debug.LogError($"[PrizeStandPrize] Исключение: {ex.Message}");
stand.OpeningFinished -= OnResult;
}
_isGiving = false;
InvokeResult(success);
}
private static IReadOnlyList<PrizeStandBoxAvailability> BuildAvailability(
PrizeStandSettings settings,
PrizeStandConnectionInfo connectionInfo,
int finalScore)
{
List<PrizeStandBoxAvailability> result = new();
if (settings?.boxes == null)
return result;
foreach (PrizeStandBoxConfig box in settings.boxes)
{
if (box == null || box.boxNumber <= 0)
continue;
bool isConnectedBox = connectionInfo.IsConnected
&& (connectionInfo.ConnectedBoxesCount <= 0 || box.boxNumber <= connectionInfo.ConnectedBoxesCount);
bool isUnlocked = finalScore >= box.requiredScore;
result.Add(new PrizeStandBoxAvailability(
box.boxNumber,
box.requiredScore,
isUnlocked,
isConnectedBox));
}
return result;
}
}
}