feat(m5): client-server sync, offline queue and replay playback

This commit is contained in:
2026-10-24 23:37:13 +02:00
parent 4a9031b29c
commit 33bdc16fbd
22 changed files with 1419 additions and 184 deletions
+149 -162
View File
@@ -1,7 +1,13 @@
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'src/game/iron_arc_game.dart';
import 'src/native/native_match.dart';
import 'src/net/api_client.dart';
import 'src/net/match_session.dart';
import 'src/net/offline_queue.dart';
import 'src/ui/widgets.dart';
void main() => runApp(const IronArcApp());
@@ -19,7 +25,7 @@ class IronArcApp extends StatelessWidget {
}
}
/// One hotseat match; restart creates a new game with a new seed.
/// Hotseat match with optional server sync (`adb reverse tcp:8080 tcp:8080`).
class MatchScreen extends StatefulWidget {
const MatchScreen({super.key});
@@ -28,50 +34,166 @@ class MatchScreen extends StatefulWidget {
}
class _MatchScreenState extends State<MatchScreen> {
static const _baseUrl = 'http://127.0.0.1:8080';
int _seed = 42;
late IronArcGame _game = IronArcGame(seed: _seed);
late final ApiClient _api = ApiClient(baseUrl: _baseUrl);
late final OfflineQueue _queue = OfflineQueue();
late final MatchSession _session =
MatchSession(client: _api, queue: _queue, deviceId: 'pending');
late IronArcGame _game = _buildGame();
@override
void initState() {
super.initState();
_initSession();
}
@override
void dispose() {
_api.close();
_session.dispose();
super.dispose();
}
/// Loads or creates a stable device id, then refreshes the offline queue.
Future<void> _initSession() async {
final prefs = await SharedPreferences.getInstance();
var id = prefs.getString('iron_arc.device_id');
if (id == null || id.length < 4) {
id = 'dev-${DateTime.now().microsecondsSinceEpoch.toRadixString(16)}';
await prefs.setString('iron_arc.device_id', id);
}
_session.deviceId = id;
await _session.refreshQueueSize();
}
IronArcGame _buildGame({int? seed, String? replayJson}) {
final game = replayJson != null
? IronArcGame(matchFactory: () => NativeMatch.playback(replayJson))
: IronArcGame(seed: seed ?? _seed);
game.onShotResolved = (expect, command, localHashAfter) {
if (game.isPlayback) return;
if (_session.status == SyncStatus.online) {
_session.submitShot(
expectHash: expect,
command: command,
localHashAfter: localHashAfter,
replayJson: game.replayJson(),
);
} else if (game.hud.value.isFinished) {
_session.enqueueReplay(game.replayJson());
}
};
return game;
}
Future<void> _startOnline() async {
final seed = await _session.startOnlineMatch();
if (!mounted || seed == null) {
_toast('Server nicht erreichbar');
return;
}
setState(() {
_seed = seed;
_game = _buildGame(seed: seed);
});
_toast('Online-Match ${_session.matchId}');
}
void _playReplay() {
final json = _game.replayJson();
debugPrint('iron_arc: replay tapped, ${json.length} bytes');
if (json.isEmpty) {
_toast('Kein Replay vorhanden');
return;
}
setState(() => _game = _buildGame(replayJson: json));
_toast('Replay läuft');
}
Future<void> _flushQueue() async {
final validated = await _session.flushQueue();
if (mounted) _toast('$validated Replay(s) validiert');
}
void _restart() {
setState(() {
_seed += 1;
_game = IronArcGame(seed: _seed);
_game = _buildGame(seed: _seed);
});
}
void _toast(String message) {
ScaffoldMessenger.of(context)
..clearSnackBars()
..showSnackBar(SnackBar(
content: Text(message),
duration: const Duration(seconds: 2),
behavior: SnackBarBehavior.floating,
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFF05070A),
body: SafeArea(
child: Stack(
child: Column(
children: [
Positioned.fill(child: GameWidget(game: _game)),
Positioned.fill(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onPanStart: (d) => _game.beginAim(d.localPosition),
onPanUpdate: (d) => _game.updateAim(d.localPosition),
onPanEnd: (_) => _game.releaseAim(),
Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 0),
child: Column(
children: [
ValueListenableBuilder<HudState>(
valueListenable: _game.hud,
builder: (context, hud, _) => Hud(hud: hud),
),
const SizedBox(height: 6),
AnimatedBuilder(
animation: _session,
builder: (context, _) => StatusBar(session: _session),
),
],
),
),
Positioned(
top: 8,
left: 12,
right: 12,
child: ValueListenableBuilder<HudState>(
valueListenable: _game.hud,
builder: (context, hud, _) => _Hud(hud: hud),
// Play area: gestures only affect the game, never the controls.
Expanded(
child: Stack(
children: [
Positioned.fill(child: GameWidget(key: ValueKey(_game), game: _game)),
Positioned.fill(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onPanStart: (d) => _game.beginAim(d.localPosition),
onPanUpdate: (d) => _game.updateAim(d.localPosition),
onPanEnd: (_) => _game.releaseAim(),
),
),
Positioned(
left: 16,
right: 16,
bottom: 8,
child: ValueListenableBuilder<HudState>(
valueListenable: _game.hud,
builder: (context, hud, _) => hud.isFinished
? GameOver(hud: hud, onRestart: _restart)
: HintBubble(hud: hud),
),
),
],
),
),
Positioned(
bottom: 16,
left: 16,
right: 16,
child: ValueListenableBuilder<HudState>(
valueListenable: _game.hud,
builder: (context, hud, _) => hud.isFinished
? _GameOver(hud: hud, onRestart: _restart)
: _Hint(hud: hud),
Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
child: AnimatedBuilder(
animation: _session,
builder: (context, _) => Controls(
session: _session,
onOnline: _startOnline,
onReplay: _playReplay,
onFlush: _flushQueue,
),
),
),
],
@@ -80,138 +202,3 @@ class _MatchScreenState extends State<MatchScreen> {
);
}
}
class _Hud extends StatelessWidget {
const _Hud({required this.hud});
final HudState hud;
@override
Widget build(BuildContext context) {
return Row(
children: [
_Pill(
label: 'P1',
value: '${hud.hp0} HP',
color: const Color(0xFFFF8A3D),
active: hud.current == 0 && !hud.isFinished,
),
const SizedBox(width: 8),
Expanded(
child: Column(
children: [
Text('Zug ${hud.turn}',
style: const TextStyle(
fontSize: 13, fontWeight: FontWeight.w700)),
const SizedBox(height: 2),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.air, size: 14),
const SizedBox(width: 4),
Text('${hud.wind > 0 ? '+' : ''}${hud.wind}',
style: const TextStyle(fontSize: 13)),
],
),
],
),
),
const SizedBox(width: 8),
_Pill(
label: 'P2',
value: '${hud.hp1} HP',
color: const Color(0xFF4DD0E1),
active: hud.current == 1 && !hud.isFinished,
),
],
);
}
}
class _Pill extends StatelessWidget {
const _Pill({
required this.label,
required this.value,
required this.color,
required this.active,
});
final String label;
final String value;
final Color color;
final bool active;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: color.withValues(alpha: active ? 0.28 : 0.10),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: color.withValues(alpha: active ? 0.9 : 0.3),
width: active ? 2 : 1,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label,
style: TextStyle(
fontSize: 11,
color: color,
fontWeight: FontWeight.w800)),
Text(value, style: const TextStyle(fontSize: 15)),
],
),
);
}
}
class _Hint extends StatelessWidget {
const _Hint({required this.hud});
final HudState hud;
@override
Widget build(BuildContext context) {
final text = hud.phase == 1
? 'Projektil im Flug…'
: 'Ziehen zum Zielen · Loslassen zum Schießen';
return Center(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: const Color(0xCC0B1220),
borderRadius: BorderRadius.circular(20),
),
child: Text(text, style: const TextStyle(fontSize: 13)),
),
);
}
}
class _GameOver extends StatelessWidget {
const _GameOver({required this.hud, required this.onRestart});
final HudState hud;
final VoidCallback onRestart;
@override
Widget build(BuildContext context) {
final text = switch (hud.winner) {
0 => 'Spieler 1 gewinnt',
1 => 'Spieler 2 gewinnt',
_ => 'Unentschieden',
};
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(text,
style: const TextStyle(fontSize: 26, fontWeight: FontWeight.w800)),
const SizedBox(height: 12),
FilledButton.icon(
onPressed: onRestart,
icon: const Icon(Icons.refresh),
label: const Text('Neuer Match'),
),
],
);
}
}
+42 -2
View File
@@ -66,6 +66,14 @@ class IronArcGame extends FlameGame {
/// Optional override, used by golden tests to run without the native library.
final MatchSource Function()? matchFactory;
/// Called once a shot has been resolved locally.
void Function(int expectHash, Map<String, Object?> command,
int localHashAfter)? onShotResolved;
int? _shotExpectHash;
Map<String, Object?>? _shotCommand;
bool _wasFlying = false;
late final MatchSource _match;
final ValueNotifier<HudState> hud = ValueNotifier<HudState>(
const HudState(
@@ -108,7 +116,9 @@ class IronArcGame extends FlameGame {
@override
void update(double dt) {
super.update(dt);
if (_match.isFlying) {
// A playback handle must keep ticking even while aiming, otherwise the
// recorded commands (which are bound to ticks) never become due.
if (_match.isFlying || _match.isPlayback) {
_accumulator += dt;
const step = 1 / 60;
var steps = 0;
@@ -129,6 +139,19 @@ class IronArcGame extends FlameGame {
if (_impactFlash > 0) {
_impactFlash = math.max(0, _impactFlash - dt * 1.8);
}
// Shot resolved: hand the command and both hashes to the sync layer.
final flying = _match.isFlying;
if (_wasFlying && !flying) {
final expect = _shotExpectHash;
final command = _shotCommand;
if (expect != null && command != null) {
onShotResolved?.call(expect, command, _match.stateHash());
_shotExpectHash = null;
_shotCommand = null;
}
}
_wasFlying = flying;
_updateCamera(dt);
}
@@ -169,7 +192,16 @@ class IronArcGame extends FlameGame {
if (!_match.isAiming) return;
final angleMdeg = (aimAngle * 1000).round().clamp(1000, 89000);
final powerQ16 = (aimPower * 65536).round().clamp(3277, 65536);
_match.fire(angleMdeg: angleMdeg, powerQ16: powerQ16);
final before = _match.stateHash();
if (_match.fire(angleMdeg: angleMdeg, powerQ16: powerQ16) == 0) {
_shotExpectHash = before;
_shotCommand = {
'kind': 'fire',
'angle': angleMdeg,
'power': powerQ16,
'w': 1,
};
}
_pushHud();
}
@@ -410,6 +442,14 @@ class IronArcGame extends FlameGame {
);
}
/// Replay JSON of everything played so far.
String replayJson() => _match.replayJson();
/// Local state hash (compare with the server).
int stateHash() => _match.stateHash();
bool get isPlayback => _match.isPlayback;
@override
void onRemove() {
_match.dispose();
+10
View File
@@ -44,5 +44,15 @@ abstract class MatchSource {
int fire({required int angleMdeg, required int powerQ16, int weapon});
int endTurn();
int tick(int ticks);
/// Current state hash (FNV chain over the whole state).
int stateHash();
/// Replay JSON (ReplayV1) of the match played so far.
String replayJson();
/// True when the handle plays back a recording.
bool get isPlayback;
void dispose();
}
+62
View File
@@ -54,12 +54,44 @@ typedef _ProjectileDart = int Function(Pointer<Void>, Pointer<Int32>);
typedef _ImpactC = Uint32 Function(Pointer<Void>, Pointer<Int32>);
typedef _ImpactDart = int Function(Pointer<Void>, Pointer<Int32>);
typedef _StateHashC = Uint64 Function(Pointer<Void>);
typedef _StateHashDart = int Function(Pointer<Void>);
typedef _ReplayJsonC = Pointer<Utf8> Function(Pointer<Void>);
typedef _ReplayJsonDart = Pointer<Utf8> Function(Pointer<Void>);
typedef _StringFreeC = Void Function(Pointer<Utf8>);
typedef _StringFreeDart = void Function(Pointer<Utf8>);
typedef _PlaybackC = Pointer<Void> Function(Pointer<Utf8>);
typedef _PlaybackDart = Pointer<Void> Function(Pointer<Utf8>);
typedef _IsPlaybackC = Int32 Function(Pointer<Void>);
typedef _IsPlaybackDart = int Function(Pointer<Void>);
/// Thin typed wrapper around the Rust match handle.
///
/// The handle owns the simulation; Dart only pulls snapshots for rendering.
class NativeMatch extends MatchSource {
NativeMatch(int seed) : _handle = _newMatch(seed);
/// Creates a handle that replays a recorded match (see [replayJson]).
NativeMatch.playback(String replayJson)
: _handle = _createPlayback(replayJson) {
if (_handle.address == 0) {
throw StateError('replay rejected (content or sim version mismatch)');
}
}
static Pointer<Void> _createPlayback(String json) {
final encoded = json.toNativeUtf8();
try {
return _newPlayback(encoded);
} finally {
calloc.free(encoded);
}
}
final Pointer<Void> _handle;
bool _disposed = false;
@@ -102,6 +134,16 @@ class NativeMatch extends MatchSource {
_lib.lookupFunction<_ProjectileC, _ProjectileDart>('iron_arc_projectile');
static final _ImpactDart _lastImpact =
_lib.lookupFunction<_ImpactC, _ImpactDart>('iron_arc_last_impact');
static final _StateHashDart _stateHash =
_lib.lookupFunction<_StateHashC, _StateHashDart>('iron_arc_state_hash');
static final _ReplayJsonDart _replayJson =
_lib.lookupFunction<_ReplayJsonC, _ReplayJsonDart>('iron_arc_replay_json');
static final _StringFreeDart _stringFree =
_lib.lookupFunction<_StringFreeC, _StringFreeDart>('iron_arc_string_free');
static final _PlaybackDart _newPlayback = _lib
.lookupFunction<_PlaybackC, _PlaybackDart>('iron_arc_new_match_playback');
static final _IsPlaybackDart _isPlayback =
_lib.lookupFunction<_IsPlaybackC, _IsPlaybackDart>('iron_arc_is_playback');
/// Phase: 0 aiming, 1 flying, 2 finished.
@override
@@ -176,6 +218,26 @@ class NativeMatch extends MatchSource {
}
}
/// Current state hash (desync detection against the server).
@override
int stateHash() => BigInt.from(_stateHash(_handle)).toSigned(64).toInt();
/// Serialised replay (ReplayV1 JSON) of everything played so far.
@override
String replayJson() {
final ptr = _replayJson(_handle);
if (ptr.address == 0) return '';
try {
return ptr.toDartString();
} finally {
_stringFree(ptr);
}
}
/// True when this handle plays back a recorded match.
@override
bool get isPlayback => _isPlayback(_handle) == 1;
@override
void dispose() {
if (_disposed) return;
+195
View File
@@ -0,0 +1,195 @@
import 'dart:convert';
import 'package:http/http.dart' as http;
/// Error returned by the referee service.
class ApiException implements Exception {
ApiException(this.statusCode, this.code, this.message);
final int statusCode;
final String code;
final String message;
@override
String toString() => 'ApiException($statusCode, $code): $message';
}
/// Result of `POST /v1/matches`.
class MatchInfo {
const MatchInfo({
required this.matchId,
required this.seed,
required this.turn,
required this.stateHash,
});
final String matchId;
final int seed;
final int turn;
final int stateHash;
}
/// Result of `POST /v1/matches/{id}/turn`.
class TurnResult {
const TurnResult({
required this.turn,
required this.current,
required this.stateHash,
required this.impacts,
});
final int turn;
final int current;
final int stateHash;
final int impacts;
}
/// Result of `POST /v1/matches/{id}/validate`.
class ValidateResult {
const ValidateResult({
required this.finalHash,
required this.scrap,
required this.xp,
});
final int finalHash;
final int scrap;
final int xp;
}
/// Thin client for the replay referee (`crates/server`).
class ApiClient {
ApiClient({required this.baseUrl, http.Client? client})
: _http = client ?? http.Client();
final String baseUrl;
final http.Client _http;
Uri _uri(String path) => Uri.parse('$baseUrl$path');
Future<Map<String, dynamic>> _decode(http.Response response) async {
final body = response.body.isEmpty
? <String, dynamic>{}
: jsonDecode(response.body) as Map<String, dynamic>;
if (response.statusCode >= 400) {
final error = (body['error'] as Map<String, dynamic>?) ?? const {};
throw ApiException(
response.statusCode,
error['code'] as String? ?? 'unknown',
error['message'] as String? ?? response.body,
);
}
return body;
}
/// Public health probe.
Future<Map<String, dynamic>> health() async {
final response = await _http.get(_uri('/v1/health'));
return _decode(response);
}
/// Exchanges a device id for a bearer token.
Future<String> authenticate(String deviceId) async {
final response = await _http.post(
_uri('/v1/auth/device'),
headers: const {'content-type': 'application/json'},
body: jsonEncode({'device_id': deviceId}),
);
final body = await _decode(response);
return body['token'] as String;
}
/// Creates a server-authoritative match.
Future<MatchInfo> createMatch({
required String token,
required String mode,
required String contentHash,
required String simVersion,
required List<List<int>> loadouts,
}) async {
final response = await _http.post(
_uri('/v1/matches'),
headers: {
'content-type': 'application/json',
'authorization': 'Bearer $token',
},
body: jsonEncode({
'mode': mode,
'content_hash': contentHash,
'sim_version': simVersion,
'players': [
{'tank': 'vanguard', 'loadout': loadouts[0]},
{'tank': 'longshot', 'loadout': loadouts[1]},
],
}),
);
final body = await _decode(response);
return MatchInfo(
matchId: body['match_id'] as String,
seed: (body['seed'] as num).toInt(),
turn: (body['turn'] as num).toInt(),
stateHash: _u64(body['state_hash']),
);
}
/// Submits one shot and lets the server resolve it.
Future<TurnResult> submitTurn({
required String token,
required String matchId,
required int expectHash,
required Map<String, Object?> command,
}) async {
final response = await _http.post(
_uri('/v1/matches/$matchId/turn'),
headers: {
'content-type': 'application/json',
'authorization': 'Bearer $token',
},
body: jsonEncode({'expect_hash': _hex64(expectHash), 'command': command}),
);
final body = await _decode(response);
return TurnResult(
turn: (body['turn'] as num).toInt(),
current: (body['current'] as num).toInt(),
stateHash: _u64(body['state_hash']),
impacts: (body['impacts'] as num?)?.toInt() ?? 0,
);
}
/// Submits a replay for validation (offline play, anti-cheat).
Future<ValidateResult> validate({
required String token,
required String replayJson,
String? matchId,
}) async {
final response = await _http.post(
_uri('/v1/matches/${matchId ?? 'offline'}/validate'),
headers: {
'content-type': 'application/json',
'authorization': 'Bearer $token',
},
body: jsonEncode({'match_id': matchId, 'replay': jsonDecode(replayJson)}),
);
final body = await _decode(response);
final rewards = (body['rewards'] as Map<String, dynamic>?) ?? const {};
return ValidateResult(
finalHash: _u64(body['final_hash']),
scrap: (rewards['scrap'] as num?)?.toInt() ?? 0,
xp: (rewards['xp'] as num?)?.toInt() ?? 0,
);
}
void close() => _http.close();
}
/// Hashes travel as fixed-width hex strings: JSON numbers lose precision above
/// 2^53, and u64 hashes routinely exceed that.
int _u64(Object? value) {
if (value is String) return BigInt.parse(value, radix: 16).toSigned(64).toInt();
if (value is int) return value.toUnsigned(64);
if (value is num) return value.toInt().toUnsigned(64);
return 0;
}
String _hex64(int value) =>
BigInt.from(value).toUnsigned(64).toRadixString(16).padLeft(16, '0');
+141
View File
@@ -0,0 +1,141 @@
import 'package:flutter/foundation.dart';
import 'api_client.dart';
import 'offline_queue.dart';
/// Connection state shown in the HUD.
enum SyncStatus { offline, connecting, online, desync, error }
/// Keeps a match in sync with the referee service.
///
/// Online: every shot is submitted with the pre-shot state hash; the server
/// resolves it and returns its own hash. A mismatch means the client and server
/// disagree (desync) and ranked play stops immediately.
/// Offline: replays are queued and validated later, rewards only after a
/// `valid: true` verdict.
class MatchSession extends ChangeNotifier {
MatchSession({
required this.client,
required this.queue,
required this.deviceId,
});
final ApiClient client;
final OfflineQueue queue;
String deviceId;
SyncStatus status = SyncStatus.offline;
String? matchId;
int? seed;
String? lastError;
int queued = 0;
String? _token;
String get statusLabel => switch (status) {
SyncStatus.offline => 'Offline',
SyncStatus.connecting => 'Verbinde…',
SyncStatus.online => 'Online · ${matchId ?? '-'}',
SyncStatus.desync => 'DESYNC – Ranked gestoppt',
SyncStatus.error => 'Fehler: ${lastError ?? '?'}',
};
Future<void> _ensureToken() async {
_token ??= await client.authenticate(deviceId);
}
/// Creates a server-authoritative match and returns its seed.
Future<int?> startOnlineMatch() async {
status = SyncStatus.connecting;
notifyListeners();
try {
await _ensureToken();
final health = await client.health();
final info = await client.createMatch(
token: _token!,
mode: 'ranked',
contentHash: health['content_hash'] as String,
simVersion: health['sim_version'] as String,
loadouts: const [
[1, 2, 5],
[1, 3, 4],
],
);
matchId = info.matchId;
seed = info.seed;
status = SyncStatus.online;
lastError = null;
notifyListeners();
return info.seed;
} catch (e) {
status = SyncStatus.error;
lastError = e.toString();
debugPrint('iron_arc: online start failed: $e');
notifyListeners();
return null;
}
}
/// Submits one shot. Falls back to the offline queue on transport errors.
Future<void> submitShot({
required int expectHash,
required Map<String, Object?> command,
required int localHashAfter,
required String replayJson,
}) async {
if (status != SyncStatus.online || matchId == null) {
await queue.add(replayJson);
queued = await queue.size();
notifyListeners();
return;
}
try {
final result = await client.submitTurn(
token: _token!,
matchId: matchId!,
expectHash: expectHash,
command: command,
);
if (result.stateHash != localHashAfter) {
status = SyncStatus.desync;
lastError = 'server ${result.stateHash} != local $localHashAfter';
notifyListeners();
}
} on ApiException catch (e) {
if (e.statusCode == 409 && e.code == 'state_conflict') {
status = SyncStatus.desync;
lastError = e.message;
} else {
await queue.add(replayJson);
queued = await queue.size();
}
notifyListeners();
} catch (e) {
await queue.add(replayJson);
queued = await queue.size();
lastError = e.toString();
notifyListeners();
}
}
/// Validates everything that was played offline.
/// Queues a finished offline match for later validation.
Future<void> enqueueReplay(String replayJson) async {
await queue.add(replayJson);
queued = await queue.size();
notifyListeners();
}
Future<int> flushQueue() async {
await _ensureToken();
final validated = await queue.flush(client, _token!);
queued = await queue.size();
notifyListeners();
return validated;
}
Future<void> refreshQueueSize() async {
queued = await queue.size();
notifyListeners();
}
}
+50
View File
@@ -0,0 +1,50 @@
import 'package:shared_preferences/shared_preferences.dart';
import 'api_client.dart';
/// Durable queue of replays that still need server validation.
///
/// Rewards are only granted after `valid: true`, so offline matches are played
/// locally and submitted later ("pending" in the UI).
class OfflineQueue {
static const _key = 'iron_arc.pending_replays';
Future<List<String>> pending() async {
final prefs = await SharedPreferences.getInstance();
return prefs.getStringList(_key) ?? const [];
}
Future<int> size() async => (await pending()).length;
Future<void> add(String replayJson) async {
final prefs = await SharedPreferences.getInstance();
final items = prefs.getStringList(_key) ?? <String>[];
items.add(replayJson);
await prefs.setStringList(_key, items);
}
/// Tries to validate every queued replay.
///
/// Rejected replays are dropped (no rewards), transport failures are kept.
Future<int> flush(ApiClient client, String token) async {
final prefs = await SharedPreferences.getInstance();
final items = prefs.getStringList(_key) ?? <String>[];
if (items.isEmpty) return 0;
final remaining = <String>[];
var validated = 0;
for (final replay in items) {
try {
await client.validate(token: token, replayJson: replay);
validated++;
} on ApiException catch (e) {
if (e.statusCode >= 400 && e.statusCode < 500) continue;
remaining.add(replay);
} catch (_) {
remaining.add(replay);
}
}
await prefs.setStringList(_key, remaining);
return validated;
}
}
+244
View File
@@ -0,0 +1,244 @@
import 'package:flutter/material.dart';
import '../game/iron_arc_game.dart';
import '../net/match_session.dart';
/// Score pills, turn counter and wind indicator.
class Hud extends StatelessWidget {
const Hud({super.key, required this.hud});
final HudState hud;
@override
Widget build(BuildContext context) {
return Row(
children: [
_Pill(
label: 'P1',
value: '${hud.hp0} HP',
color: const Color(0xFFFF8A3D),
active: hud.current == 0 && !hud.isFinished,
),
const SizedBox(width: 8),
Expanded(
child: Column(
children: [
Text('Zug ${hud.turn}',
style: const TextStyle(
fontSize: 13, fontWeight: FontWeight.w700)),
const SizedBox(height: 2),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.air, size: 14),
const SizedBox(width: 4),
Text('${hud.wind > 0 ? '+' : ''}${hud.wind}',
style: const TextStyle(fontSize: 13)),
],
),
],
),
),
const SizedBox(width: 8),
_Pill(
label: 'P2',
value: '${hud.hp1} HP',
color: const Color(0xFF4DD0E1),
active: hud.current == 1 && !hud.isFinished,
),
],
);
}
}
/// Connection state and pending-replay counter.
class StatusBar extends StatelessWidget {
const StatusBar({super.key, required this.session});
final MatchSession session;
@override
Widget build(BuildContext context) {
final (color, icon) = switch (session.status) {
SyncStatus.online => (const Color(0xFF66BB6A), Icons.cloud_done),
SyncStatus.connecting => (const Color(0xFFFFC107), Icons.cloud_sync),
SyncStatus.desync => (const Color(0xFFE53935), Icons.warning_amber),
SyncStatus.error => (const Color(0xFFE53935), Icons.cloud_off),
SyncStatus.offline => (const Color(0xFF90A4AE), Icons.cloud_off),
};
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, size: 14, color: color),
const SizedBox(width: 6),
Flexible(
child: Text(
session.statusLabel,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 11, color: color),
),
),
if (session.queued > 0) ...[
const SizedBox(width: 8),
Text('· ${session.queued} pending',
style: const TextStyle(fontSize: 11, color: Color(0xFFFFC107))),
],
],
);
}
}
/// Online / Replay / Upload actions.
class Controls extends StatelessWidget {
const Controls({
super.key,
required this.session,
required this.onOnline,
required this.onReplay,
required this.onFlush,
});
final MatchSession session;
final VoidCallback onOnline;
final VoidCallback onReplay;
final VoidCallback onFlush;
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
_Action(icon: Icons.wifi_tethering, label: 'Online', onTap: onOnline),
_Action(icon: Icons.replay, label: 'Replay', onTap: onReplay),
_Action(
icon: Icons.cloud_upload,
label: session.queued > 0 ? 'Senden (${session.queued})' : 'Senden',
onTap: onFlush,
),
],
);
}
}
class _Action extends StatelessWidget {
const _Action({required this.icon, required this.label, required this.onTap});
final IconData icon;
final String label;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
return Material(
color: const Color(0xCC0B1220),
borderRadius: BorderRadius.circular(18),
child: InkWell(
borderRadius: BorderRadius.circular(18),
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 18),
const SizedBox(width: 6),
Text(label, style: const TextStyle(fontSize: 13)),
],
),
),
),
);
}
}
class _Pill extends StatelessWidget {
const _Pill({
required this.label,
required this.value,
required this.color,
required this.active,
});
final String label;
final String value;
final Color color;
final bool active;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: color.withValues(alpha: active ? 0.28 : 0.10),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: color.withValues(alpha: active ? 0.9 : 0.3),
width: active ? 2 : 1,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label,
style: TextStyle(
fontSize: 11, color: color, fontWeight: FontWeight.w800)),
Text(value, style: const TextStyle(fontSize: 15)),
],
),
);
}
}
/// Short instruction or flight indicator.
class HintBubble extends StatelessWidget {
const HintBubble({super.key, required this.hud});
final HudState hud;
@override
Widget build(BuildContext context) {
final text = hud.phase == 1
? 'Projektil im Flug…'
: 'Ziehen zum Zielen · Loslassen zum Schießen';
return Center(
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: const Color(0xCC0B1220),
borderRadius: BorderRadius.circular(20),
),
child: Text(text, style: const TextStyle(fontSize: 13)),
),
);
}
}
/// Winner banner plus rematch button.
class GameOver extends StatelessWidget {
const GameOver({super.key, required this.hud, required this.onRestart});
final HudState hud;
final VoidCallback onRestart;
@override
Widget build(BuildContext context) {
final text = switch (hud.winner) {
0 => 'Spieler 1 gewinnt',
1 => 'Spieler 2 gewinnt',
_ => 'Unentschieden',
};
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(text,
style: const TextStyle(fontSize: 26, fontWeight: FontWeight.w800)),
const SizedBox(height: 12),
FilledButton.icon(
onPressed: onRestart,
icon: const Icon(Icons.refresh),
label: const Text('Neuer Match'),
),
],
);
}
}