Files
commander-ai-lab/unity-client/Assets/Scripts/Services/GameWebSocketClient.cs
T
KoalaTrapLord 3f5d6d12e8 feat: 4-player Commander Battleground UI (issues #138–#151)
* chore: add battleground UI task tracker (2026-03-28)

* feat(#142): add [NonSerialized] battleground runtime state to CardModel

* feat(#143): add LoadArtCrop and LoadCardRaw (RawImage) to ImageCache

* feat(#148): add GameStateManager singleton and GameState/SeatState POCOs

* feat(#138): add BattlegroundController scene orchestrator

* feat(#139): add LifeTrackerWidget, CommanderDamageRow, PoisonCounter

* feat(#140): add PhaseTrackerWidget and PhaseStepButton

* feat(#141): add TurnOrderBar and TurnOrderPill

* feat(#142): add CardZone and CardView battlefield zone components

* feat(#143): add CommanderZoneWidget with art crop, cast counter, and tax display

* feat(#144): add TokenModel POCO, TokenPanelController, and TokenRowView

* chore: mark issues 1-8 as complete in task tracker

* feat(#146): add StackZoneController, StackItemView, and ManaPoolDisplay

* feat(#147 #150 #151): add LobbySetupModal, ZoneViewerModal, EliminationHandler; add Play Live button to SimulationController

* feat(#151): add Play Live button to SimulationController

* feat(#149): add GameWebSocketClient with reconnect, ping, and main-thread dispatch

* fix: add PostGameAction to ApiClient + update TODO.md all issues complete

- ApiClient.cs: add PostGameAction() wrapper → POST /api/game/action
  (fixes compile error in HumanActionBar.cs)
- TODO.md: mark issues #145, #146, #147, #149, #150, #151 as ✅
  all 14 battleground issues now committed

* feat(game): add routes/game.py + wire lab_api + fix GameWebSocketClient game_id URL

- routes/game.py: POST /api/game/start, POST /api/game/action (new)
- lab_api.py: import + register game_router
- GameWebSocketClient.cs: read game_id from PlayerPrefs, build
  ws://{host}/ws/game/{game_id} — fixes URL mismatch with ws_game.py

* fix(lobby): wire OnConfirm to POST /api/game/start, save game_id to PlayerPrefs

- OnConfirm() now calls ApiClient.PostGameStart() with 4-seat config
- On success: saves BattleSeats + GameId + WsUrl to PlayerPrefs,
  loads Battleground scene
- On failure: shows inline error label (red), re-enables Confirm button
- Added StartGameRequest/Response POCOs matching routes/game.py schema
- Added _errorLabel [SerializeField] for user-facing error feedback
2026-03-29 05:35:29 -04:00

208 lines
8.0 KiB
C#

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using Newtonsoft.Json;
using CommanderAILab.UI;
namespace CommanderAILab.Services
{
/// <summary>
/// WebSocket client for the live game backend.
/// Connects to ws://{serverHost}/ws/game/{gameId}.
///
/// game_id is written to PlayerPrefs["GameId"] by LobbySetupModal
/// after a successful POST /api/game/start response.
///
/// ServerUrl PlayerPref should be the HTTP base URL, e.g.
/// "http://localhost:8080" — this client converts it to ws://.
/// </summary>
public class GameWebSocketClient : MonoBehaviour
{
[SerializeField] private string defaultServerUrl = "http://localhost:8080";
[SerializeField] private float reconnectDelay = 3f;
[SerializeField] private float pingIntervalSec = 15f;
private System.Net.WebSockets.ClientWebSocket _ws;
private CancellationTokenSource _cts;
private readonly ConcurrentQueue<(string type, string payload)> _mainThreadQueue = new();
private bool _running;
private float _pingTimer;
private string _wsUrl;
// ── Lifecycle ────────────────────────────────────────────────────────
private void Start()
{
_wsUrl = BuildWsUrl();
if (string.IsNullOrEmpty(_wsUrl))
{
Debug.LogError("[GameWebSocketClient] Could not build WS URL — PlayerPrefs 'GameId' is missing. " +
"LobbySetupModal must set it after /api/game/start.");
return;
}
_running = true;
StartCoroutine(ConnectLoop());
}
private void Update()
{
// Drain main-thread queue
while (_mainThreadQueue.TryDequeue(out var msg))
GameStateManager.Instance?.ApplyServerEvent(msg.type, msg.payload);
// Ping
_pingTimer += Time.deltaTime;
if (_pingTimer >= pingIntervalSec)
{
_pingTimer = 0f;
_ = SendRawAsync("{\"type\":\"ping\"}");
}
}
private void OnDestroy()
{
_running = false;
_cts?.Cancel();
_ws?.Dispose();
}
// ── URL construction ────────────────────────────────────────────────
/// <summary>
/// Builds ws://{host}/ws/game/{gameId} from PlayerPrefs.
/// ServerUrl pref stores the HTTP base URL (e.g. http://localhost:8080).
/// GameId pref stores the game_id returned by /api/game/start.
/// </summary>
private string BuildWsUrl()
{
string gameId = PlayerPrefs.GetString("GameId", "");
if (string.IsNullOrEmpty(gameId))
return string.Empty;
string httpBase = PlayerPrefs.GetString("ServerUrl", defaultServerUrl).TrimEnd('/');
// Convert http(s):// to ws(s)://
string wsBase = httpBase
.Replace("https://", "wss://")
.Replace("http://", "ws://");
return $"{wsBase}/ws/game/{gameId}";
}
// ── Connection loop ──────────────────────────────────────────────────
private IEnumerator ConnectLoop()
{
while (_running)
{
_cts = new CancellationTokenSource();
_ws = new System.Net.WebSockets.ClientWebSocket();
bool connected = false;
var connectTask = _ws.ConnectAsync(new Uri(_wsUrl), _cts.Token);
yield return new WaitUntil(() => connectTask.IsCompleted);
if (!connectTask.IsFaulted && !connectTask.IsCanceled)
{
connected = true;
Debug.Log("[GameWebSocketClient] Connected to " + _wsUrl);
_ = ReceiveLoop();
}
else
{
Debug.LogWarning($"[GameWebSocketClient] Connect failed ({_wsUrl}): {connectTask.Exception?.Message}");
}
if (!connected)
{
yield return new WaitForSeconds(reconnectDelay);
}
else
{
yield return new WaitUntil(() =>
_ws.State != System.Net.WebSockets.WebSocketState.Open);
Debug.Log("[GameWebSocketClient] Disconnected — reconnecting...");
yield return new WaitForSeconds(reconnectDelay);
}
}
}
// ── Receive loop (background thread) ────────────────────────────────
private async Task ReceiveLoop()
{
var buffer = new byte[8192];
try
{
while (_ws.State == System.Net.WebSockets.WebSocketState.Open)
{
var sb = new StringBuilder();
System.Net.WebSockets.WebSocketReceiveResult result;
do
{
result = await _ws.ReceiveAsync(
new ArraySegment<byte>(buffer), _cts.Token);
sb.Append(Encoding.UTF8.GetString(buffer, 0, result.Count));
} while (!result.EndOfMessage);
if (result.MessageType ==
System.Net.WebSockets.WebSocketMessageType.Close)
break;
ParseAndEnqueue(sb.ToString());
}
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
Debug.LogWarning($"[GameWebSocketClient] ReceiveLoop error: {ex.Message}");
}
}
// ── Parse incoming JSON envelope ─────────────────────────────────────
private void ParseAndEnqueue(string raw)
{
try
{
var env = JsonConvert.DeserializeObject<WsEnvelope>(raw);
if (env == null) return;
if (env.type == "pong") return;
_mainThreadQueue.Enqueue((env.type, env.payload ?? raw));
}
catch
{
Debug.LogWarning($"[GameWebSocketClient] Failed to parse: {raw}");
}
}
// ── Send (public for external callers) ───────────────────────────────
public async Task SendRawAsync(string json)
{
if (_ws == null ||
_ws.State != System.Net.WebSockets.WebSocketState.Open) return;
try
{
var bytes = Encoding.UTF8.GetBytes(json);
await _ws.SendAsync(new ArraySegment<byte>(bytes),
System.Net.WebSockets.WebSocketMessageType.Text,
true, _cts?.Token ?? CancellationToken.None);
}
catch (Exception ex)
{
Debug.LogWarning($"[GameWebSocketClient] Send error: {ex.Message}");
}
}
// ── POCO ────────────────────────────────────────────────────────────────
[Serializable]
private class WsEnvelope
{
[JsonProperty("type")] public string type;
[JsonProperty("payload")] public string payload;
}
}
}