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'),
),
],
);
}
}