using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using UnityEngine; using UnityEngine.UI; using Vanguard.Api; using Vanguard.Api.Contracts; using Vanguard.Battle; using Vanguard.Meta; using Vanguard.Shared.Protocol; namespace Vanguard.UI { /// /// Серый боевой экран: доска, рука, часы и кнопки всех легальных интентов. /// Красоту и анимации добавим поверх этой рабочей логики. /// public sealed class BattleView { private static readonly Color Background = new Color(0.035f, 0.045f, 0.065f, 1f); private static readonly Color Panel = new Color(0.07f, 0.085f, 0.115f, 1f); private static readonly Color Card = new Color(0.10f, 0.13f, 0.18f, 1f); private static readonly Color Muted = new Color(0.62f, 0.68f, 0.82f); private static readonly Color Accent = new Color(0.20f, 0.42f, 0.78f, 1f); private readonly MetaService _meta; private readonly Action _onExit; private readonly Dictionary _catalog = new Dictionary(StringComparer.Ordinal); private bool _catalogLoading; private readonly RectTransform _root; private readonly RectTransform _board; private RectTransform _intents; private readonly Text _topInfo; private readonly Text _clock; private readonly Text _status; private readonly Button _concede; private readonly Text _concedeLabel; private readonly Button _reconnect; private readonly RectTransform _result; private RectTransform _logContent; private Text _resultText; private readonly List _logLines = new List(); private GameConnection _connection; private CancellationTokenSource _cts; private MatchConnectionInfo _info; private MatchView _view; private bool _connecting; private bool _sending; private bool _snapshotPending; private bool _finished; private bool _confirmConcede; private bool _showAllIntents; private float _confirmDeadline; private long _clockServerMs; private long _clockReceivedMs; private readonly List _pendingIntents = new List(); private readonly HashSet _highlightKeys = new HashSet(StringComparer.Ordinal); public BattleView(Transform parent, MetaService meta, Action onExit) { _meta = meta; _onExit = onExit; _root = UiKit.CreatePanel(parent, "BattleScreen", Background); var top = UiKit.CreatePanel(_root, "TopBar", Panel); top.anchorMin = new Vector2(0f, 1f); top.anchorMax = new Vector2(1f, 1f); top.pivot = new Vector2(0.5f, 1f); top.anchoredPosition = Vector2.zero; top.sizeDelta = new Vector2(0f, 88f); UiKit.AddHorizontalLayout(top, 20, 14); var title = UiKit.CreateText(top, "Title", "Бой", 32, Color.white, TextAnchor.MiddleLeft); title.fontStyle = FontStyle.Bold; UiKit.SetPreferredHeight(title, 46f, 0f); _topInfo = UiKit.CreateText( top, "Match", string.Empty, 17, Muted, TextAnchor.MiddleLeft); UiKit.SetPreferredHeight(_topInfo, 38f); _clock = UiKit.CreateText( top, "Clock", "—", 22, Color.white, TextAnchor.MiddleRight); UiKit.SetPreferredHeight(_clock, 44f, 0f); _concede = UiKit.CreateButton(top, "Concede", "Сдаться", OnConcedeClicked, 18); _concedeLabel = _concede.GetComponentInChildren(); UiKit.SetPreferredHeight(_concede, 44f, 0f); var left = UiKit.CreatePanel(_root, "BoardPanel", Background); left.anchorMin = Vector2.zero; left.anchorMax = Vector2.one; left.offsetMin = new Vector2(36f, 28f); left.offsetMax = new Vector2(-564f, -108f); UiKit.AddVerticalLayout(left, 8, 8); _board = left; var right = UiKit.CreatePanel(_root, "IntentPanel", Panel); right.anchorMin = new Vector2(1f, 0f); right.anchorMax = new Vector2(1f, 1f); right.pivot = new Vector2(1f, 0.5f); right.offsetMin = new Vector2(-528f, 28f); right.offsetMax = new Vector2(-36f, -108f); UiKit.AddVerticalLayout(right, 14, 10); var actionsTitle = UiKit.CreateText( right, "ActionsTitle", "Действия", 24, Color.white, TextAnchor.MiddleLeft); actionsTitle.fontStyle = FontStyle.Bold; UiKit.SetPreferredHeight(actionsTitle, 32f); var scroll = UiKit.CreateScrollView(right, "IntentScroll", out _intents, 6f); var scrollElement = scroll.gameObject.AddComponent(); scrollElement.flexibleHeight = 1f; scrollElement.minHeight = 200f; _status = UiKit.CreateText( right, "Status", string.Empty, 16, Muted, TextAnchor.UpperLeft); _status.horizontalOverflow = HorizontalWrapMode.Wrap; UiKit.SetPreferredHeight(_status, 74f); var logTitle = UiKit.CreateText( right, "LogTitle", "Журнал", 16, new Color(0.72f, 0.80f, 0.94f), TextAnchor.MiddleLeft); logTitle.fontStyle = FontStyle.Bold; UiKit.SetPreferredHeight(logTitle, 22f); var logScroll = UiKit.CreateScrollView(right, "LogScroll", out _logContent, 3f); var logElement = logScroll.gameObject.AddComponent(); logElement.preferredHeight = 142f; logElement.minHeight = 80f; _reconnect = UiKit.CreateButton(right, "Reconnect", "Переподключиться", OnReconnectClicked, 18); UiKit.SetPreferredHeight(_reconnect, 46f); _reconnect.gameObject.SetActive(false); _result = BuildResultPanel(_root); _result.gameObject.SetActive(false); _root.gameObject.SetActive(false); } public void Show(MatchConnectionInfo info) { _info = info; _view = null; _finished = false; _confirmConcede = false; _concedeLabel.text = "Сдаться"; _concede.interactable = true; _reconnect.gameObject.SetActive(false); _result.gameObject.SetActive(false); _pendingIntents.Clear(); _highlightKeys.Clear(); _showAllIntents = false; _logLines.Clear(); RebuildLog(); _topInfo.text = (info.DeckName ?? string.Empty) + " · " + info.MatchId; SetStatus("Подключаемся к матчу…", Muted); _root.gameObject.SetActive(true); _ = LoadCatalogAsync(); _ = ConnectAsync(); } public void Hide() { _cts?.Cancel(); _cts?.Dispose(); _cts = null; if (_connection != null) { var connection = _connection; _connection = null; _ = connection.DisposeAsync().AsTask(); } _root.gameObject.SetActive(false); _result.gameObject.SetActive(false); _view = null; } public void Tick() { if (_confirmConcede && Time.unscaledTime > _confirmDeadline) { _confirmConcede = false; _concedeLabel.text = "Сдаться"; } UpdateClock(); } private RectTransform BuildResultPanel(Transform parent) { var overlay = UiKit.CreatePanel(parent, "BattleResult", new Color(0f, 0f, 0f, 0.75f)); var card = UiKit.CreateCenteredCard( overlay, "ResultCard", new Vector2(640f, 330f), new Color(0.08f, 0.10f, 0.14f, 1f)); UiKit.AddVerticalLayout(card, 32, 14); var title = UiKit.CreateText(card, "Title", "Матч завершён", 32, Color.white); title.fontStyle = FontStyle.Bold; UiKit.SetPreferredHeight(title, 48f); _resultText = UiKit.CreateText(card, "Text", string.Empty, 22, Muted); UiKit.SetPreferredHeight(_resultText, 90f); var exit = UiKit.CreateButton(card, "Exit", "В меню", OnExitClicked, 21); UiKit.SetPreferredHeight(exit, 52f); return overlay; } private async Task LoadCatalogAsync() { if (_catalogLoading || _catalog.Count > 0) return; _catalogLoading = true; try { var items = await _meta.GetCatalogAsync(); foreach (var item in items) _catalog[item.PrintingId] = item; if (_root.gameObject.activeSelf && _view != null) Render(); } catch (Exception exception) { Debug.LogWarning("Battle catalog load failed: " + exception.Message); } finally { _catalogLoading = false; } } private async Task ConnectAsync() { if (_connecting || _info == null) return; _connecting = true; _reconnect.gameObject.SetActive(false); _cts?.Cancel(); _cts?.Dispose(); _cts = new CancellationTokenSource(); try { if (_connection != null) { await _connection.DisposeAsync(); _connection = null; } var connection = new GameConnection(); _connection = connection; connection.HelloReceived += OnHello; connection.SnapshotReceived += OnSnapshot; connection.EventsReceived += OnEvents; connection.ClockReceived += OnClock; connection.ErrorReceived += OnError; connection.Closed += OnClosed; await connection.ConnectAsync( _info.WsUrl, _info.Ticket, Application.version, _view != null ? _view.EventSeq : 0, _cts.Token); SetStatus("Соединение открыто. Ожидаем состояние…", Muted); } catch (OperationCanceledException) { // экран закрыли } catch (Exception exception) { Debug.LogException(exception); SetStatus("Не удалось подключиться: " + exception.Message, new Color(1f, 0.55f, 0.45f)); _reconnect.gameObject.SetActive(true); } finally { _connecting = false; } } private void OnHello(ServerHello hello) { if (_info != null) _info.Seat = hello.PlayerIndex; } private void OnSnapshot(ServerSnapshot snapshot) { if (!_root.gameObject.activeSelf || snapshot?.View == null) return; _view = snapshot.View; _finished = _view.IsFinished; _pendingIntents.Clear(); _highlightKeys.Clear(); if (_view.Clock != null) { _clockServerMs = _view.Clock.ServerTimeMs; _clockReceivedMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); } Render(); } private void OnEvents(ServerEvents events) { if (events?.Events != null) { foreach (var envelope in events.Events) { var line = Describe(envelope.Event); if (!string.IsNullOrWhiteSpace(line)) _logLines.Add(line); } while (_logLines.Count > 40) _logLines.RemoveAt(0); RebuildLog(); } _ = RequestSnapshotAsync(); } private void RebuildLog() { if (_logContent == null) return; ClearChildren(_logContent); var start = Mathf.Max(0, _logLines.Count - 8); for (var i = start; i < _logLines.Count; i++) { var line = UiKit.CreateText( _logContent, "LogLine", _logLines[i], 13, i == _logLines.Count - 1 ? new Color(0.92f, 0.94f, 1f) : new Color(0.60f, 0.68f, 0.82f), TextAnchor.MiddleLeft); line.horizontalOverflow = HorizontalWrapMode.Wrap; UiKit.SetPreferredHeight(line, 30f); } } private string Describe(EventView view) { if (view == null) return null; return view switch { UnitRodeView ride => "Ride: " + CardName(ride.PrintingId), UnitCalledView call => "Call: " + CardName(call.PrintingId) + " → " + SlotName(call.Slot), UnitMovedView move => "Move: " + SlotName(move.FromSlot) + " → " + SlotName(move.ToSlot), AttackDeclaredView attack => "Атака: " + SlotName(attack.AttackerSlot) + " → " + SlotName(attack.TargetSlot), GuardAddedView guard => "Guard: " + CardName(guard.PrintingId) + " (+" + guard.Shield + ")", PerfectGuardView perfect => "Perfect Guard: " + CardName(perfect.SentinelPrintingId), DriveCheckedView drive => "Drive: " + CardName(drive.PrintingId) + " · " + drive.Trigger, TriggerResolvedView trigger => "Триггер: " + CardName(trigger.PrintingId), BattleResolvedView battle => battle.Hit ? "Атака прошла." : "Атака отбита.", DamageTakenView damage => "Урон: " + PlayerName(damage.Player) + " +" + damage.Amount + " (всего " + damage.Total + ")", HealedView heal => "Heal: " + PlayerName(heal.Player), UnitRetiredView retire => "Retire: " + SlotName(retire.Slot), InterceptedView intercept => "Intercept: " + CardName(intercept.PrintingId), CardDrawnView draw => "Карта: " + PlayerName(draw.Player), PhaseChangedView phase => "Фаза: " + phase.Phase, GameFinishedView finish => "Партия завершена.", _ => null, }; } private string PlayerName(int player) => _view == null ? "P" + player : player == _view.You ? "Вы" : "Противник"; private void OnClock(ServerClock clock) { if (!_root.gameObject.activeSelf || clock?.Clock == null) return; _clockServerMs = clock.Clock.ServerTimeMs; _clockReceivedMs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); if (_view != null) _view.Clock = clock.Clock; UpdateClock(); } private void OnError(ServerError error) { SetStatus(error.Code + ": " + error.Message, new Color(1f, 0.55f, 0.45f)); } private void OnClosed(string reason) { if (!_root.gameObject.activeSelf || _finished) return; SetStatus("Соединение потеряно: " + reason, new Color(1f, 0.60f, 0.45f)); _reconnect.gameObject.SetActive(true); } private async Task RequestSnapshotAsync() { if (_snapshotPending || _connection == null || !_connection.IsConnected) return; _snapshotPending = true; try { await _connection.RequestSnapshotAsync(_cts != null ? _cts.Token : CancellationToken.None); } catch (OperationCanceledException) { // экран закрыли } catch (Exception exception) { Debug.LogException(exception); SetStatus("Не удалось обновить состояние.", new Color(1f, 0.60f, 0.45f)); } finally { _snapshotPending = false; } } private async void OnIntentClicked(IntentPayload intent) { if (_sending || _connection == null || _cts == null || _view == null) return; _pendingIntents.Clear(); _highlightKeys.Clear(); _sending = true; SetStatus("Отправляем: " + Label(intent), Muted); try { var result = await _connection.SubmitAsync(intent, _cts.Token); if (!result.Accepted) { SetStatus( "Отклонено (" + result.Code + "): " + (result.Reason ?? "без причины"), new Color(1f, 0.55f, 0.45f)); } else { SetStatus(result.Duplicate ? "Повтор уже применён." : "Принято.", Muted); await RequestSnapshotAsync(); } } catch (OperationCanceledException) { // экран закрыли } catch (Exception exception) { Debug.LogException(exception); SetStatus("Ошибка отправки интента: " + exception.Message, new Color(1f, 0.55f, 0.45f)); } finally { _sending = false; } } private void OnConcedeClicked() { if (_view == null || _finished) return; if (!_confirmConcede) { _confirmConcede = true; _confirmDeadline = Time.unscaledTime + 4f; _concedeLabel.text = "Подтвердить сдачу"; SetStatus("Нажмите «Подтвердить сдачу» ещё раз.", new Color(1f, 0.76f, 0.38f)); return; } _confirmConcede = false; _concedeLabel.text = "Сдаться"; OnIntentClicked(new ConcedeIntent()); } private async void OnReconnectClicked() { if (_info == null) return; _reconnect.interactable = false; SetStatus("Получаем новый тикет…", Muted); try { var ticket = await _meta.CreateTicketAsync(_info.MatchId); _info.Ticket = ticket.Ticket; _info.WsUrl = ticket.WsUrl; await ConnectAsync(); } catch (ApiException exception) { SetStatus(exception.Message, new Color(1f, 0.55f, 0.45f)); } catch (Exception exception) { Debug.LogException(exception); SetStatus("Переподключение не удалось.", new Color(1f, 0.55f, 0.45f)); } finally { _reconnect.interactable = true; } } private void OnExitClicked() { Hide(); _onExit(); } private void Render() { if (_view == null) return; ClearChildren(_board); var opponentIndex = _view.You == 0 ? 1 : 0; var opponent = _view.Players.FirstOrDefault(player => player.Index == opponentIndex) ?? (_view.Players.Count > opponentIndex ? _view.Players[opponentIndex] : null); var self = _view.Players.FirstOrDefault(player => player.Index == _view.You) ?? (_view.Players.Count > _view.You ? _view.Players[_view.You] : null); AddFieldBlock(opponent, false); AddCenterPanel(_view); AddFieldBlock(self, true); AddHand(self); RebuildIntents(_view); UpdateClock(); if (_view.IsFinished) ShowResult(_view); } private void AddFieldBlock(PlayerView player, bool self) { if (player == null) return; var block = UiKit.CreatePanel( _board, self ? "SelfField" : "OpponentField", new Color(0.05f, 0.07f, 0.11f, 0.96f)); var blockElement = block.gameObject.AddComponent(); blockElement.preferredHeight = self ? 214f : 204f; UiKit.AddVerticalLayout(block, 7, 3); var header = UiKit.CreateText( block, "Header", (self ? "ВЫ" : "ПРОТИВНИК") + " · " + player.Name + " рука " + player.HandCount + " · колода " + player.DeckCount + " · урон " + (player.FaceDownDamage + player.FaceUpDamage.Count) + " · soul " + player.Soul.Count + " · drop " + player.Drop.Count, 15, self ? Color.white : new Color(0.94f, 0.82f, 0.70f), TextAnchor.MiddleLeft); header.fontStyle = FontStyle.Bold; UiKit.SetPreferredHeight(header, 25f); var row = UiKit.CreatePanel(block, "Field", new Color(0f, 0f, 0f, 0f)); var rowElement = row.gameObject.AddComponent(); rowElement.flexibleHeight = 1f; rowElement.minHeight = 166f; UiKit.AddHorizontalLayout(row, 3, 7); AddCardBox(row, player.Vanguard, "V", compact: false, player.Index, -1); for (var i = 0; i < 5; i++) { var card = player.RearGuards != null && i < player.RearGuards.Length ? player.RearGuards[i] : null; AddCardBox(row, card, "R" + (i + 1), compact: false, player.Index, i); } } private void AddCenterPanel(MatchView view) { var panel = UiKit.CreatePanel(_board, "MatchInfo", new Color(0.06f, 0.09f, 0.15f, 0.98f)); var element = panel.gameObject.AddComponent(); element.preferredHeight = 76f; UiKit.AddVerticalLayout(panel, 8, 2); var active = view.ActivePlayer == view.You ? "решаете вы" : "решает противник"; var main = UiKit.CreateText( panel, "Main", "Ход " + view.TurnNumber + " · " + view.Phase + " · " + view.Step + " · " + active, 17, view.ActivePlayer == view.You ? new Color(0.55f, 0.86f, 1f) : new Color(1f, 0.78f, 0.52f), TextAnchor.MiddleLeft); main.fontStyle = FontStyle.Bold; UiKit.SetPreferredHeight(main, 26f); var details = new List(); if (view.Battle != null) details.Add("Бой: " + SlotName(view.Battle.AttackerSlot) + " → " + SlotName(view.Battle.TargetSlot) + " · щит " + view.Battle.GuardShield + " · проверок " + view.Battle.ChecksRemaining); if (view.Choice != null) details.Add(view.Choice.Prompt); if (view.Ability != null) details.Add("Способность: " + CardName(view.Ability.PrintingId)); if (view.Trigger != null) details.Add("Триггер: " + CardName(view.Trigger.PrintingId) + " · " + view.Trigger.Trigger); if (view.OpponentChoosing) details.Add("Противник выбирает действие…"); if (details.Count == 0) details.Add("Выберите действие в панели справа."); var detail = UiKit.CreateText( panel, "Detail", string.Join(" · ", details), 14, Muted, TextAnchor.MiddleLeft); detail.horizontalOverflow = HorizontalWrapMode.Wrap; UiKit.SetPreferredHeight(detail, 28f); } private void AddHand(PlayerView self) { var hand = UiKit.CreatePanel(_board, "HandBlock", new Color(0.05f, 0.07f, 0.11f, 0.96f)); var handElement = hand.gameObject.AddComponent(); handElement.preferredHeight = 188f; UiKit.AddVerticalLayout(hand, 6, 3); var header = UiKit.CreateText( hand, "Header", "РУКА · " + (self?.Hand?.Count ?? 0) + " карт", 16, Color.white, TextAnchor.MiddleLeft); header.fontStyle = FontStyle.Bold; UiKit.SetPreferredHeight(header, 22f); var scroll = UiKit.CreateHorizontalScrollView(hand, "HandScroll", out var content, 6f); var scrollElement = scroll.gameObject.AddComponent(); scrollElement.flexibleHeight = 1f; scrollElement.minHeight = 130f; if (self?.Hand == null || self.Hand.Count == 0) { var empty = UiKit.CreateText( content, "Empty", "Рука пуста", 17, Muted); UiKit.SetPreferredHeight(empty, 110f); return; } foreach (var card in self.Hand) AddCardBox(content, card, "Рука", compact: true, self.Index, -2); } private void AddInfoLine(Transform parent, string text) { var line = UiKit.CreateText( parent, "Info", text, 16, Muted, TextAnchor.MiddleLeft); UiKit.SetPreferredHeight(line, 22f); } private void AddCardBox( Transform parent, CardView card, string slot, bool compact, int playerIndex, int slotIndex) { var meta = card != null && _catalog.TryGetValue(card.PrintingId, out var found) ? found : null; var clanColor = CardArt.ClanColor(meta != null ? meta.Clan : "None"); var frameColor = card == null ? new Color(0.16f, 0.18f, 0.24f) : CardArt.ClanColor(meta != null ? meta.Clan : "None"); var panel = UiKit.CreatePanel( parent, "Card_" + slot, card == null ? new Color(0.06f, 0.08f, 0.12f, 0.9f) : card.FaceUp ? new Color(0.09f, 0.11f, 0.16f, 1f) : new Color(0.05f, 0.08f, 0.14f, 1f)); var element = panel.gameObject.AddComponent(); element.preferredWidth = compact ? 106f : 124f; element.preferredHeight = compact ? 142f : 162f; element.flexibleWidth = 0f; var highlighted = _highlightKeys.Contains( TargetKey(playerIndex, slotIndex, card != null ? card.PrintingId : null)); var button = panel.gameObject.AddComponent