init
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
import 'package:flame/components.dart';
|
||||
import 'package:flame/events.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// نسبت ابعاد کارت (۵۰۰×۷۲۶ منبع).
|
||||
const double kCardRatio = 726 / 500;
|
||||
|
||||
/// یک کارت روی میز؛ اگر تصویر `assets/images/cards/<code>.png` موجود باشد از آن
|
||||
/// استفاده میکند، وگرنه نسخهی برداری میکشد. برای پشت کارت `back.jpg`.
|
||||
class CardComponent extends PositionComponent with TapCallbacks, HasGameReference {
|
||||
final String code; // مثل "AS"؛ برای پشت کارت خالی
|
||||
final bool faceUp;
|
||||
VoidCallback? onTap; // با تغییر نوبت/مجازبودن بهروز میشود
|
||||
bool dimmed; // کارت غیرمجاز/غیرفعال
|
||||
Sprite? _sprite;
|
||||
|
||||
CardComponent({
|
||||
required this.code,
|
||||
required this.faceUp,
|
||||
this.onTap,
|
||||
this.dimmed = false,
|
||||
super.position,
|
||||
super.size,
|
||||
super.angle,
|
||||
super.priority,
|
||||
super.anchor = Anchor.center,
|
||||
});
|
||||
|
||||
@override
|
||||
Future<void> onLoad() async {
|
||||
try {
|
||||
_sprite = await game.loadSprite(faceUp ? 'cards/$code.png' : 'cards/back.jpg');
|
||||
} catch (_) {
|
||||
_sprite = null; // fallback برداری
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onTapDown(TapDownEvent event) {
|
||||
if (onTap != null && !dimmed) onTap!.call();
|
||||
}
|
||||
|
||||
@override
|
||||
void render(Canvas canvas) {
|
||||
final rect = size.toRect();
|
||||
final radius = Radius.circular(size.x * 0.09);
|
||||
final rrect = RRect.fromRectAndRadius(rect, radius);
|
||||
|
||||
if (_sprite != null) {
|
||||
canvas.save();
|
||||
canvas.clipRRect(rrect);
|
||||
_sprite!.render(canvas, size: size);
|
||||
canvas.restore();
|
||||
} else if (faceUp) {
|
||||
_drawVectorFace(canvas, rrect);
|
||||
} else {
|
||||
_drawVectorBack(canvas, rrect);
|
||||
}
|
||||
|
||||
if (dimmed) {
|
||||
canvas.drawRRect(rrect, Paint()..color = const Color(0x73000000));
|
||||
}
|
||||
canvas.drawRRect(
|
||||
rrect,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.5
|
||||
..color = const Color(0xFF1A1A1A),
|
||||
);
|
||||
}
|
||||
|
||||
void _drawVectorBack(Canvas canvas, RRect rrect) {
|
||||
canvas.drawRRect(rrect, Paint()..color = const Color(0xFF1C3A66));
|
||||
final inner = rrect.deflate(size.x * 0.08);
|
||||
canvas.drawRRect(
|
||||
inner,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 2
|
||||
..color = const Color(0xFFE9B949),
|
||||
);
|
||||
}
|
||||
|
||||
void _drawVectorFace(Canvas canvas, RRect rrect) {
|
||||
canvas.drawRRect(rrect, Paint()..color = Colors.white);
|
||||
final rank = code.substring(0, code.length - 1);
|
||||
final suit = code.substring(code.length - 1);
|
||||
final (symbol, color) = _suit(suit);
|
||||
|
||||
_text(canvas, '$rank$symbol', size.x * 0.26, color,
|
||||
Offset(size.x * 0.08, size.y * 0.05));
|
||||
// نماد بزرگ وسط
|
||||
_text(canvas, symbol, size.x * 0.5, color,
|
||||
Offset(size.x * 0.5, size.y * 0.5), center: true);
|
||||
}
|
||||
|
||||
(String, Color) _suit(String s) {
|
||||
switch (s) {
|
||||
case 'H':
|
||||
return ('♥', const Color(0xFFD32F2F));
|
||||
case 'D':
|
||||
return ('♦', const Color(0xFFD32F2F));
|
||||
case 'C':
|
||||
return ('♣', const Color(0xFF1A1A1A));
|
||||
default:
|
||||
return ('♠', const Color(0xFF1A1A1A));
|
||||
}
|
||||
}
|
||||
|
||||
void _text(Canvas canvas, String s, double fontSize, Color color, Offset at,
|
||||
{bool center = false}) {
|
||||
final tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: s, style: TextStyle(color: color, fontSize: fontSize)),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout();
|
||||
final offset = center ? at - Offset(tp.width / 2, tp.height / 2) : at;
|
||||
tp.paint(canvas, offset);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,615 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flame/components.dart';
|
||||
import 'package:flame/effects.dart';
|
||||
import 'package:flame/game.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../game_cubit.dart';
|
||||
import '../game_models.dart';
|
||||
import 'card_component.dart';
|
||||
|
||||
/// صحنهی میز حکم با انیمیشن. شما همیشه پایین میز (rel=0) هستید.
|
||||
/// کامپوننتهای دست و trick ماندگارند و با افکت حرکت جابهجا میشوند.
|
||||
class HokmGame extends FlameGame {
|
||||
final GameCubit cubit;
|
||||
GameState? _s;
|
||||
StreamSubscription? _sub;
|
||||
|
||||
final Map<String, CardComponent> _hand = {}; // کارتهای دستِ شما (با کد)
|
||||
final Map<String, CardComponent> _trick = {}; // کارتهای روی زمین (با کد)
|
||||
final List<Component> _backs = []; // پشتکارت حریفان
|
||||
final List<Component> _info = []; // نام/امتیاز/حکم/نوبت
|
||||
|
||||
double _cardW = 60;
|
||||
double _cardH = 87;
|
||||
|
||||
double _shake = 0; // شدت تکانِ صفحه (افکت برد با حکم)
|
||||
double _t = 0; // زمان برای نوسان تکان
|
||||
bool _prevTrickDone = false;
|
||||
|
||||
HokmGame(this.cubit);
|
||||
|
||||
@override
|
||||
Color backgroundColor() => const Color(0xFF2C0A10);
|
||||
|
||||
@override
|
||||
Future<void> onLoad() async {
|
||||
add(_Felt());
|
||||
_sub = cubit.stream.listen((ui) {
|
||||
if (ui.state != null) {
|
||||
final s = ui.state!;
|
||||
if (s.trickDone && !_prevTrickDone) _onTrickComplete(s);
|
||||
_prevTrickDone = s.trickDone;
|
||||
_s = s;
|
||||
_relayout();
|
||||
}
|
||||
});
|
||||
if (cubit.state.state != null) {
|
||||
_s = cubit.state.state;
|
||||
_relayout();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void update(double dt) {
|
||||
super.update(dt);
|
||||
_t += dt;
|
||||
if (_shake > 0) _shake = math.max(0, _shake - dt * 2.2);
|
||||
}
|
||||
|
||||
@override
|
||||
void render(Canvas canvas) {
|
||||
if (_shake > 0) {
|
||||
final dx = math.sin(_t * 55) * _shake * size.x * 0.018;
|
||||
final dy = math.cos(_t * 70) * _shake * size.y * 0.010;
|
||||
canvas.save();
|
||||
canvas.translate(dx, dy);
|
||||
super.render(canvas);
|
||||
canvas.restore();
|
||||
} else {
|
||||
super.render(canvas);
|
||||
}
|
||||
}
|
||||
|
||||
// هنگام کاملشدن یک دست: اگر برنده «بریده» باشد (خالِ زمینه آتو نبوده ولی
|
||||
// کارتِ برنده آتوست — یعنی بازیکن چون خال زمینه را نداشت آتو زد) تکان + رعد.
|
||||
void _onTrickComplete(GameState s) {
|
||||
if (s.trick.length < 4) return;
|
||||
final winner = _winnerCard(s);
|
||||
final cutWithTrump = s.trump != null &&
|
||||
s.leadSuit != s.trump &&
|
||||
_suitName(winner.card) == s.trump;
|
||||
_shake = cutWithTrump ? 1.0 : 0.3;
|
||||
if (cutWithTrump) add(_Lightning());
|
||||
}
|
||||
|
||||
TrickCard _winnerCard(GameState s) {
|
||||
var best = s.trick.first;
|
||||
for (final tc in s.trick.skip(1)) {
|
||||
if (_beats(tc.card, best.card, s.trump, s.leadSuit)) best = tc;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// آیا کارت a کارت b را میبرد (با توجه به حکم و خال زمینه)؟ مطابق منطق سرور.
|
||||
bool _beats(String a, String b, String? trump, String? lead) {
|
||||
final aT = _suitName(a) == trump, bT = _suitName(b) == trump;
|
||||
if (aT && !bT) return true;
|
||||
if (!aT && bT) return false;
|
||||
if (aT && bT) return _rankValue(a) > _rankValue(b);
|
||||
if (_suitName(a) != lead) return false;
|
||||
if (_suitName(b) != lead) return true;
|
||||
return _rankValue(a) > _rankValue(b);
|
||||
}
|
||||
|
||||
@override
|
||||
void onGameResize(Vector2 size) {
|
||||
super.onGameResize(size);
|
||||
if (isLoaded) _relayout();
|
||||
}
|
||||
|
||||
@override
|
||||
void onRemove() {
|
||||
_sub?.cancel();
|
||||
super.onRemove();
|
||||
}
|
||||
|
||||
int _rel(int seat) => (seat - _s!.yourSeat + 4) % 4;
|
||||
|
||||
static String _suitName(String code) {
|
||||
switch (code[code.length - 1]) {
|
||||
case 'H':
|
||||
return 'hearts';
|
||||
case 'D':
|
||||
return 'diamonds';
|
||||
case 'C':
|
||||
return 'clubs';
|
||||
default:
|
||||
return 'spades';
|
||||
}
|
||||
}
|
||||
|
||||
bool _legal(String code) {
|
||||
final s = _s!;
|
||||
if (s.phase != 'playing' || s.trickDone || !s.isMyTurn) return false;
|
||||
final lead = s.leadSuit;
|
||||
if (lead == null || lead.isEmpty) return true;
|
||||
final hasLead = s.yourHand.any((c) => _suitName(c) == lead);
|
||||
return !hasLead || _suitName(code) == lead;
|
||||
}
|
||||
|
||||
void _relayout() {
|
||||
final s = _s;
|
||||
if (s == null) return;
|
||||
_cardW = size.x * 0.19; // کارتهای بزرگتر (مطابق تصویر مرجع)
|
||||
_cardH = _cardW * kCardRatio;
|
||||
|
||||
_rebuildBacksAndInfo(s);
|
||||
_layoutTrick(s);
|
||||
_layoutHand(s);
|
||||
}
|
||||
|
||||
// افکت حرکت بدون انباشتهشدن.
|
||||
void _moveTo(CardComponent c, Vector2 target, {double dur = 0.38}) {
|
||||
c.children.whereType<MoveToEffect>().toList().forEach((e) => e.removeFromParent());
|
||||
if ((c.position - target).length < 0.5) {
|
||||
c.position = target;
|
||||
return;
|
||||
}
|
||||
c.add(MoveToEffect(
|
||||
target, EffectController(duration: dur, curve: Curves.easeOutCubic)));
|
||||
}
|
||||
|
||||
// ترتیب خالها برای چیدنِ دست (سیاه/قرمز متناوب تا تفکیک بصری راحتتر باشد).
|
||||
static const _suitOrder = {'S': 0, 'H': 1, 'C': 2, 'D': 3};
|
||||
|
||||
static int _rankValue(String code) {
|
||||
switch (code.substring(0, code.length - 1)) {
|
||||
case 'A':
|
||||
return 14;
|
||||
case 'K':
|
||||
return 13;
|
||||
case 'Q':
|
||||
return 12;
|
||||
case 'J':
|
||||
return 11;
|
||||
default:
|
||||
return int.tryParse(code.substring(0, code.length - 1)) ?? 0;
|
||||
}
|
||||
}
|
||||
|
||||
static int _cardCompare(String a, String b) {
|
||||
final sa = _suitOrder[a[a.length - 1]] ?? 0;
|
||||
final sb = _suitOrder[b[b.length - 1]] ?? 0;
|
||||
if (sa != sb) return sa - sb;
|
||||
return _rankValue(a) - _rankValue(b);
|
||||
}
|
||||
|
||||
void _layoutHand(GameState s) {
|
||||
// کارتهای دست بر اساس خال و سپس رتبه مرتب میشوند تا کار بازیکن راحتتر باشد.
|
||||
final codes = List<String>.from(s.yourHand)..sort(_cardCompare);
|
||||
final n = codes.length;
|
||||
|
||||
// کارتهایی که دیگر در دست نیستند و به trick هم نرفتهاند ⇒ حذف.
|
||||
for (final code in _hand.keys.toList()) {
|
||||
if (!codes.contains(code)) {
|
||||
final c = _hand.remove(code)!;
|
||||
if (!_trick.containsKey(code)) c.removeFromParent();
|
||||
}
|
||||
}
|
||||
|
||||
final handW = size.x * 0.72;
|
||||
final step = n > 1 ? (handW - _cardW) / (n - 1) : 0.0;
|
||||
final startX = size.x / 2 - (step * (n - 1)) / 2;
|
||||
final y = size.y * 0.84;
|
||||
|
||||
for (var i = 0; i < n; i++) {
|
||||
final code = codes[i];
|
||||
final target = Vector2(startX + i * step, y);
|
||||
final legal = _legal(code);
|
||||
final dim = s.phase == 'playing' && s.isMyTurn && !legal;
|
||||
var c = _hand[code];
|
||||
if (c == null) {
|
||||
// کارت جدید ⇒ از مرکز میز پخش میشود.
|
||||
c = CardComponent(
|
||||
code: code,
|
||||
faceUp: true,
|
||||
size: Vector2(_cardW, _cardH),
|
||||
position: size / 2,
|
||||
);
|
||||
_hand[code] = c;
|
||||
add(c);
|
||||
} else {
|
||||
c.size = Vector2(_cardW, _cardH);
|
||||
}
|
||||
c.onTap = legal ? () => cubit.playCard(code) : null;
|
||||
c.dimmed = dim;
|
||||
c.priority = 10 + i;
|
||||
_moveTo(c, target);
|
||||
}
|
||||
}
|
||||
|
||||
void _layoutTrick(GameState s) {
|
||||
final present = s.trick.map((t) => t.card).toSet();
|
||||
|
||||
// کارتهای trick که دیگر نیستند (دست جمع شد) ⇒ به سمت برنده (نوبت بعدی) برو و حذف شو.
|
||||
for (final code in _trick.keys.toList()) {
|
||||
if (!present.contains(code)) {
|
||||
final c = _trick.remove(code)!;
|
||||
final winnerOrigin = _seatOrigin(_rel(s.turn));
|
||||
c.children.whereType<MoveToEffect>().toList().forEach((e) => e.removeFromParent());
|
||||
c.add(SequenceEffect([
|
||||
MoveToEffect(winnerOrigin,
|
||||
EffectController(duration: 0.25, curve: Curves.easeIn)),
|
||||
RemoveEffect(),
|
||||
]));
|
||||
}
|
||||
}
|
||||
|
||||
for (final tc in s.trick) {
|
||||
final slot = size / 2 + _trickOffset(_rel(tc.seat));
|
||||
var c = _trick[tc.card];
|
||||
if (c == null) {
|
||||
// اگر خودِ شما بازی کردید، همان کارتِ دست را منتقل کن (پرواز به وسط).
|
||||
c = _hand.remove(tc.card);
|
||||
if (c != null) {
|
||||
c.onTap = null;
|
||||
c.dimmed = false;
|
||||
} else {
|
||||
c = CardComponent(
|
||||
code: tc.card,
|
||||
faceUp: true,
|
||||
size: Vector2(_cardW, _cardH),
|
||||
position: _seatOrigin(_rel(tc.seat)),
|
||||
);
|
||||
add(c);
|
||||
}
|
||||
_trick[tc.card] = c;
|
||||
}
|
||||
c.size = Vector2(_cardW, _cardH);
|
||||
c.priority = 5;
|
||||
_moveTo(c, slot);
|
||||
}
|
||||
}
|
||||
|
||||
Vector2 _seatOrigin(int rel) {
|
||||
final c = size / 2;
|
||||
switch (rel) {
|
||||
case 1:
|
||||
return Vector2(size.x * 0.10, c.y);
|
||||
case 2:
|
||||
return Vector2(c.x, size.y * 0.14);
|
||||
case 3:
|
||||
return Vector2(size.x * 0.90, c.y);
|
||||
default:
|
||||
return Vector2(c.x, size.y * 0.82);
|
||||
}
|
||||
}
|
||||
|
||||
Vector2 _trickOffset(int rel) {
|
||||
final d = _cardW * 0.62;
|
||||
switch (rel) {
|
||||
case 1:
|
||||
return Vector2(-d, 0);
|
||||
case 2:
|
||||
return Vector2(0, -d);
|
||||
case 3:
|
||||
return Vector2(d, 0);
|
||||
default:
|
||||
return Vector2(0, d);
|
||||
}
|
||||
}
|
||||
|
||||
void _rebuildBacksAndInfo(GameState s) {
|
||||
for (final c in _backs) {
|
||||
c.removeFromParent();
|
||||
}
|
||||
for (final c in _info) {
|
||||
c.removeFromParent();
|
||||
}
|
||||
_backs.clear();
|
||||
_info.clear();
|
||||
|
||||
// پشتکارت حریفان
|
||||
for (var seat = 0; seat < 4; seat++) {
|
||||
if (seat == s.yourSeat) continue;
|
||||
final rel = _rel(seat);
|
||||
final count = seat < s.handCounts.length ? s.handCounts[seat] : 0;
|
||||
_addBacks(rel, count);
|
||||
}
|
||||
_addTricksWon(s);
|
||||
_addScorePucks(s);
|
||||
_addInfo(s);
|
||||
}
|
||||
|
||||
// شمارنده ۱: دستهای بردهی این هَند (tricks_won) — دستهکارتِ پشترو + عدد.
|
||||
// با هر دست یکی اضافه میشود؛ رسیدن به ۷ یعنی پایان هَند (سرور صفر میکند).
|
||||
void _addTricksWon(GameState s) {
|
||||
const gold = Color(0xFFE9B949);
|
||||
for (var team = 0; team < 2; team++) {
|
||||
final won = team < s.tricksWon.length ? s.tricksWon[team] : 0;
|
||||
if (won <= 0) continue;
|
||||
final mine = team == s.yourSeat % 2;
|
||||
final w = _cardW * 0.40, h = w * kCardRatio;
|
||||
final base = mine
|
||||
? Vector2(size.x * 0.30, size.y * 0.60)
|
||||
: Vector2(size.x * 0.70, size.y * 0.40);
|
||||
final step = Vector2(w * 0.40, 0);
|
||||
final n = won.clamp(1, 7);
|
||||
final start = base - step * ((n - 1) / 2);
|
||||
for (var i = 0; i < n; i++) {
|
||||
final c = CardComponent(
|
||||
code: '',
|
||||
faceUp: false,
|
||||
size: Vector2(w, h),
|
||||
position: start + step * i.toDouble(),
|
||||
priority: 2,
|
||||
);
|
||||
_backs.add(c);
|
||||
add(c);
|
||||
}
|
||||
final badge = TextComponent(
|
||||
text: '$won',
|
||||
anchor: Anchor.center,
|
||||
position: base - Vector2(0, h * 0.7),
|
||||
priority: 21,
|
||||
textRenderer: TextPaint(
|
||||
style: TextStyle(
|
||||
fontFamily: 'Dana',
|
||||
color: gold,
|
||||
fontSize: _cardW * 0.34,
|
||||
fontWeight: FontWeight.bold,
|
||||
shadows: const [Shadow(color: Colors.black, blurRadius: 4)],
|
||||
),
|
||||
),
|
||||
);
|
||||
_info.add(badge);
|
||||
add(badge);
|
||||
}
|
||||
}
|
||||
|
||||
// شمارنده ۲: امتیاز بازی (scores = هندهای برده) — دیسک مرکزیِ هر تیم، ۰ تا ۷.
|
||||
// رسیدن به ۷ یعنی پایان کل بازی.
|
||||
void _addScorePucks(GameState s) {
|
||||
final radius = size.x * 0.05;
|
||||
for (var team = 0; team < 2; team++) {
|
||||
final score = team < s.scores.length ? s.scores[team] : 0;
|
||||
final mine = team == s.yourSeat % 2;
|
||||
final pos = mine
|
||||
? Vector2(size.x / 2, size.y * 0.72) // تیم شما: پایینِ مرکز
|
||||
: Vector2(size.x / 2, size.y * 0.28); // تیم حریف: بالای مرکز
|
||||
final puck = _Puck(score, radius: radius, position: pos)..priority = 22;
|
||||
_info.add(puck);
|
||||
add(puck);
|
||||
}
|
||||
}
|
||||
|
||||
void _addBacks(int rel, int count) {
|
||||
if (count <= 0) return;
|
||||
final n = count.clamp(1, 13);
|
||||
final w = _cardW * 0.7, h = _cardH * 0.7;
|
||||
final c = size / 2;
|
||||
Vector2 base, stepV;
|
||||
switch (rel) {
|
||||
case 2:
|
||||
base = Vector2(c.x, size.y * 0.12);
|
||||
stepV = Vector2(size.x * 0.45 / 13, 0);
|
||||
break;
|
||||
case 1:
|
||||
base = Vector2(size.x * 0.07, c.y);
|
||||
stepV = Vector2(0, size.y * 0.4 / 13);
|
||||
break;
|
||||
default:
|
||||
base = Vector2(size.x * 0.93, c.y);
|
||||
stepV = Vector2(0, size.y * 0.4 / 13);
|
||||
}
|
||||
final start = base - stepV * ((n - 1) / 2);
|
||||
for (var i = 0; i < n; i++) {
|
||||
final comp = CardComponent(
|
||||
code: '',
|
||||
faceUp: false,
|
||||
size: Vector2(w, h),
|
||||
position: start + stepV * i.toDouble(),
|
||||
priority: 1,
|
||||
);
|
||||
_backs.add(comp);
|
||||
add(comp);
|
||||
}
|
||||
}
|
||||
|
||||
void _addInfo(GameState s) {
|
||||
void addText(String text, Vector2 pos, double fs, Color color,
|
||||
{Anchor anchor = Anchor.center, bool bold = false}) {
|
||||
final t = TextComponent(
|
||||
text: text,
|
||||
anchor: anchor,
|
||||
position: pos,
|
||||
priority: 20,
|
||||
textRenderer: TextPaint(
|
||||
style: TextStyle(
|
||||
fontFamily: 'Dana',
|
||||
color: color,
|
||||
fontSize: fs,
|
||||
fontWeight: bold ? FontWeight.bold : FontWeight.normal)),
|
||||
);
|
||||
_info.add(t);
|
||||
add(t);
|
||||
}
|
||||
|
||||
if (s.trump != null) {
|
||||
final (sym, col) = _trumpGlyph(s.trump!);
|
||||
addText('حکم: $sym', Vector2(size.x * 0.04, size.y * 0.04), size.x * 0.05,
|
||||
col, anchor: Anchor.topLeft, bold: true);
|
||||
}
|
||||
addText(
|
||||
'${s.scores.isNotEmpty ? s.scores[0] : 0} - ${s.scores.length > 1 ? s.scores[1] : 0}',
|
||||
Vector2(size.x / 2, size.y * 0.04),
|
||||
size.x * 0.05,
|
||||
const Color(0xFFE9B949),
|
||||
anchor: Anchor.topCenter);
|
||||
|
||||
for (final p in s.players) {
|
||||
final rel = _rel(p.seat);
|
||||
final pos = _seatLabelPos(rel);
|
||||
final isTurn = s.turn == p.seat;
|
||||
addText(
|
||||
'${p.name}${p.bot ? ' (ربات)' : ''}${p.connected ? '' : ' …'}',
|
||||
pos,
|
||||
size.x * 0.035,
|
||||
isTurn ? const Color(0xFFE9B949) : Colors.white70,
|
||||
bold: isTurn,
|
||||
);
|
||||
if (isTurn) {
|
||||
final dot = CircleComponent(
|
||||
radius: size.x * 0.012,
|
||||
anchor: Anchor.center,
|
||||
position: pos - Vector2(0, size.y * 0.03),
|
||||
paint: Paint()..color = const Color(0xFFE9B949),
|
||||
)..priority = 20;
|
||||
_info.add(dot);
|
||||
add(dot);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Vector2 _seatLabelPos(int rel) {
|
||||
switch (rel) {
|
||||
case 1:
|
||||
return Vector2(size.x * 0.07, size.y * 0.30);
|
||||
case 2:
|
||||
return Vector2(size.x / 2, size.y * 0.07);
|
||||
case 3:
|
||||
return Vector2(size.x * 0.93, size.y * 0.30);
|
||||
default:
|
||||
return Vector2(size.x / 2, size.y * 0.975);
|
||||
}
|
||||
}
|
||||
|
||||
(String, Color) _trumpGlyph(String suit) {
|
||||
switch (suit) {
|
||||
case 'hearts':
|
||||
return ('♥', const Color(0xFFD32F2F));
|
||||
case 'diamonds':
|
||||
return ('♦', const Color(0xFFD32F2F));
|
||||
case 'clubs':
|
||||
return ('♣', Colors.white);
|
||||
default:
|
||||
return ('♠', Colors.white);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// افکت رعد روی زمین هنگام برد با حکم؛ پس از مدت کوتاهی خودش حذف میشود.
|
||||
class _Lightning extends PositionComponent with HasGameReference {
|
||||
double _life = 0.55;
|
||||
static const _max = 0.55;
|
||||
final _rng = math.Random();
|
||||
final List<List<Offset>> _bolts = [];
|
||||
|
||||
@override
|
||||
Future<void> onLoad() async {
|
||||
size = game.size;
|
||||
final center = Offset(size.x / 2, size.y / 2);
|
||||
for (var i = 0; i < 3; i++) {
|
||||
// هر رعد یک خط شکسته از یک نقطهی تصادفیِ کناری به سمت مرکز.
|
||||
final start = Offset(_rng.nextDouble() * size.x, _rng.nextDouble() * size.y * 0.4);
|
||||
final pts = <Offset>[start];
|
||||
const segs = 6;
|
||||
for (var s = 1; s <= segs; s++) {
|
||||
final t = s / segs;
|
||||
final base = Offset.lerp(start, center, t)!;
|
||||
final jitter = (1 - t) * size.x * 0.06;
|
||||
pts.add(base + Offset((_rng.nextDouble() - 0.5) * jitter, (_rng.nextDouble() - 0.5) * jitter));
|
||||
}
|
||||
_bolts.add(pts);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void update(double dt) {
|
||||
_life -= dt;
|
||||
if (_life <= 0) removeFromParent();
|
||||
}
|
||||
|
||||
@override
|
||||
void render(Canvas canvas) {
|
||||
final op = (_life / _max).clamp(0.0, 1.0);
|
||||
final glow = Paint()
|
||||
..color = const Color(0xFFFFE082).withValues(alpha: op * 0.5)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = size.x * 0.02
|
||||
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 6);
|
||||
final core = Paint()
|
||||
..color = const Color(0xFFFFFDE7).withValues(alpha: op)
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = size.x * 0.006
|
||||
..strokeCap = StrokeCap.round;
|
||||
for (final bolt in _bolts) {
|
||||
final path = Path()..moveTo(bolt.first.dx, bolt.first.dy);
|
||||
for (final p in bolt.skip(1)) {
|
||||
path.lineTo(p.dx, p.dy);
|
||||
}
|
||||
canvas.drawPath(path, glow);
|
||||
canvas.drawPath(path, core);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// دیسکِ فلزیِ شمارش دستهای بردهی یک تیم (۰ تا ۷).
|
||||
class _Puck extends PositionComponent {
|
||||
final int count;
|
||||
_Puck(this.count, {required double radius, super.position})
|
||||
: super(size: Vector2.all(radius * 2), anchor: Anchor.center);
|
||||
|
||||
@override
|
||||
void render(Canvas canvas) {
|
||||
final r = size.x / 2;
|
||||
final c = Offset(r, r);
|
||||
canvas.drawCircle(c, r, Paint()..color = const Color(0xFF14110F));
|
||||
canvas.drawCircle(
|
||||
c,
|
||||
r * 0.92,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = r * 0.22
|
||||
..color = const Color(0xFFB8860B),
|
||||
);
|
||||
final tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: '$count',
|
||||
style: TextStyle(
|
||||
fontFamily: 'Dana',
|
||||
color: const Color(0xFFE9B949),
|
||||
fontSize: r * 1.05,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout();
|
||||
tp.paint(canvas, c - Offset(tp.width / 2, tp.height / 2));
|
||||
}
|
||||
}
|
||||
|
||||
/// نمدِ سبز میز.
|
||||
class _Felt extends PositionComponent with HasGameReference {
|
||||
@override
|
||||
void render(Canvas canvas) {
|
||||
final w = game.size.x, h = game.size.y;
|
||||
final rect = Rect.fromCenter(
|
||||
center: Offset(w / 2, h / 2),
|
||||
width: w * 0.86,
|
||||
height: h * 0.62,
|
||||
);
|
||||
final rrect = RRect.fromRectAndRadius(rect, Radius.circular(h * 0.3));
|
||||
canvas.drawRRect(rrect, Paint()..color = const Color(0xFF1B5E20));
|
||||
canvas.drawRRect(
|
||||
rrect,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 6
|
||||
..color = const Color(0xFFB8860B),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../core/network/ws_client.dart';
|
||||
import 'game_models.dart';
|
||||
|
||||
class GameUiState extends Equatable {
|
||||
final WsStatus connection;
|
||||
final GameState? state;
|
||||
final HandResult? handResult; // اوورلی نتیجهی هَند (گذرا)
|
||||
final GameOver? gameOver; // اوورلی پایان بازی
|
||||
final String? notice; // پیام گذرا (خطا/خروج بازیکن)
|
||||
|
||||
const GameUiState({
|
||||
this.connection = WsStatus.connecting,
|
||||
this.state,
|
||||
this.handResult,
|
||||
this.gameOver,
|
||||
this.notice,
|
||||
});
|
||||
|
||||
GameUiState copyWith({
|
||||
WsStatus? connection,
|
||||
GameState? state,
|
||||
HandResult? handResult,
|
||||
GameOver? gameOver,
|
||||
String? notice,
|
||||
bool clearHandResult = false,
|
||||
bool clearNotice = false,
|
||||
}) =>
|
||||
GameUiState(
|
||||
connection: connection ?? this.connection,
|
||||
state: state ?? this.state,
|
||||
handResult: clearHandResult ? null : (handResult ?? this.handResult),
|
||||
gameOver: gameOver ?? this.gameOver,
|
||||
notice: clearNotice ? null : (notice ?? this.notice),
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [connection, state, handResult, gameOver, notice];
|
||||
}
|
||||
|
||||
class GameCubit extends Cubit<GameUiState> {
|
||||
final WsClient _ws;
|
||||
final String tier;
|
||||
late final StreamSubscription _msgSub;
|
||||
late final StreamSubscription _statusSub;
|
||||
|
||||
GameCubit(this._ws, this.tier) : super(const GameUiState()) {
|
||||
_msgSub = _ws.messages.listen(_onMessage);
|
||||
_statusSub = _ws.status.listen(_onStatus);
|
||||
_ws.connect();
|
||||
}
|
||||
|
||||
void _onStatus(WsStatus s) {
|
||||
emit(state.copyWith(connection: s));
|
||||
// پس از برقراری اتصال، درخواست ورود به صف؛ در صورت reconnect سرور خودش
|
||||
// بازیکن را به میز برمیگرداند (این پیام را نادیده میگیرد).
|
||||
if (s == WsStatus.connected) {
|
||||
_ws.send({'type': 'join_queue', 'tier': tier});
|
||||
}
|
||||
}
|
||||
|
||||
void _onMessage(Map<String, dynamic> msg) {
|
||||
switch (msg['type']) {
|
||||
case 'state':
|
||||
final gs = GameState.fromJson(msg);
|
||||
// با شروع دست/هَند جدید، اوورلی نتیجه پاک میشود.
|
||||
final clear = gs.phase == 'choose_trump' || gs.phase == 'playing';
|
||||
emit(state.copyWith(state: gs, clearHandResult: clear));
|
||||
case 'hand_over':
|
||||
emit(state.copyWith(handResult: HandResult.fromJson(msg)));
|
||||
case 'game_over':
|
||||
emit(state.copyWith(gameOver: GameOver.fromJson(msg)));
|
||||
case 'player_disconnected':
|
||||
emit(state.copyWith(notice: 'یک بازیکن قطع شد'));
|
||||
case 'player_reconnected':
|
||||
emit(state.copyWith(notice: 'بازیکن بازگشت'));
|
||||
case 'player_left':
|
||||
emit(state.copyWith(notice: 'یک بازیکن میز را ترک کرد'));
|
||||
case 'error':
|
||||
emit(state.copyWith(notice: (msg['message'] ?? 'خطا').toString()));
|
||||
}
|
||||
}
|
||||
|
||||
void chooseTrump(String suit) => _ws.send({'type': 'choose_trump', 'suit': suit});
|
||||
|
||||
void playCard(String card) => _ws.send({'type': 'play_card', 'card': card});
|
||||
|
||||
void leave() => _ws.send({'type': 'leave'});
|
||||
|
||||
void clearNotice() => emit(state.copyWith(clearNotice: true));
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_msgSub.cancel();
|
||||
_statusSub.cancel();
|
||||
_ws.dispose();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// مدلهای وضعیت بازی (پیامهای WebSocket سرور).
|
||||
|
||||
class GamePlayer {
|
||||
final int seat;
|
||||
final String name;
|
||||
final bool bot;
|
||||
final bool connected;
|
||||
|
||||
GamePlayer.fromJson(Map<String, dynamic> j)
|
||||
: seat = (j['seat'] ?? 0) as int,
|
||||
name = (j['name'] ?? '') as String,
|
||||
bot = (j['bot'] ?? false) as bool,
|
||||
connected = (j['connected'] ?? false) as bool;
|
||||
}
|
||||
|
||||
class TrickCard {
|
||||
final int seat;
|
||||
final String card;
|
||||
TrickCard(this.seat, this.card);
|
||||
factory TrickCard.fromJson(Map<String, dynamic> j) =>
|
||||
TrickCard((j['seat'] ?? 0) as int, (j['card'] ?? '') as String);
|
||||
}
|
||||
|
||||
/// نمای وضعیت بازی برای بازیکن جاری (پیام type=state).
|
||||
class GameState {
|
||||
final String room;
|
||||
final String phase; // choose_trump | playing | hand_over | game_over
|
||||
final int yourSeat;
|
||||
final int hakem;
|
||||
final int turn;
|
||||
final String? trump; // پس از انتخاب حکم
|
||||
final bool trickDone; // دستِ کامل در حال نمایش (بازی ممنوع)
|
||||
final List<String> yourHand;
|
||||
final List<int> handCounts;
|
||||
final List<TrickCard> trick;
|
||||
final String? leadSuit;
|
||||
final List<int> tricksWon;
|
||||
final List<int> scores;
|
||||
final int targetScore;
|
||||
final List<GamePlayer> players;
|
||||
|
||||
GameState({
|
||||
required this.room,
|
||||
required this.phase,
|
||||
required this.yourSeat,
|
||||
required this.hakem,
|
||||
required this.turn,
|
||||
required this.trump,
|
||||
required this.trickDone,
|
||||
required this.yourHand,
|
||||
required this.handCounts,
|
||||
required this.trick,
|
||||
required this.leadSuit,
|
||||
required this.tricksWon,
|
||||
required this.scores,
|
||||
required this.targetScore,
|
||||
required this.players,
|
||||
});
|
||||
|
||||
factory GameState.fromJson(Map<String, dynamic> j) {
|
||||
List<int> ints(dynamic v) =>
|
||||
((v as List?) ?? []).map((e) => (e as num).toInt()).toList();
|
||||
return GameState(
|
||||
room: (j['room'] ?? '') as String,
|
||||
phase: (j['phase'] ?? '') as String,
|
||||
yourSeat: (j['your_seat'] ?? 0) as int,
|
||||
hakem: (j['hakem'] ?? 0) as int,
|
||||
turn: (j['turn'] ?? 0) as int,
|
||||
trump: j['trump'] as String?,
|
||||
trickDone: (j['trick_done'] ?? false) as bool,
|
||||
yourHand: ((j['your_hand'] as List?) ?? []).map((e) => e as String).toList(),
|
||||
handCounts: ints(j['hand_counts']),
|
||||
trick: ((j['trick'] as List?) ?? [])
|
||||
.map((e) => TrickCard.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
leadSuit: j['lead_suit'] as String?,
|
||||
tricksWon: ints(j['tricks_won']),
|
||||
scores: ints(j['scores']),
|
||||
targetScore: (j['target_score'] ?? 7) as int,
|
||||
players: ((j['players'] as List?) ?? [])
|
||||
.map((e) => GamePlayer.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
bool get isMyTurn => turn == yourSeat;
|
||||
bool get amHakem => hakem == yourSeat;
|
||||
GamePlayer? playerAt(int seat) =>
|
||||
players.where((p) => p.seat == seat).cast<GamePlayer?>().firstOrNull;
|
||||
}
|
||||
|
||||
/// نتیجهی یک هَند (پیام type=hand_over).
|
||||
class HandResult {
|
||||
final int winnerTeam;
|
||||
final bool kot;
|
||||
final int points;
|
||||
final List<int> scores;
|
||||
HandResult.fromJson(Map<String, dynamic> j)
|
||||
: winnerTeam = (j['winner_team'] ?? 0) as int,
|
||||
kot = (j['kot'] ?? false) as bool,
|
||||
points = (j['points'] ?? 0) as int,
|
||||
scores = ((j['scores'] as List?) ?? [])
|
||||
.map((e) => (e as num).toInt())
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// نتیجهی پایان بازی (پیام type=game_over).
|
||||
class GameOver {
|
||||
final int winnerTeam;
|
||||
final List<int> scores;
|
||||
GameOver.fromJson(Map<String, dynamic> j)
|
||||
: winnerTeam = (j['winner_team'] ?? 0) as int,
|
||||
scores = ((j['scores'] as List?) ?? [])
|
||||
.map((e) => (e as num).toInt())
|
||||
.toList();
|
||||
}
|
||||
|
||||
extension _FirstOrNull<E> on Iterable<E> {
|
||||
E? get firstOrNull {
|
||||
final it = iterator;
|
||||
return it.moveNext() ? it.current : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import '../../core/network/api_client.dart';
|
||||
import 'tier.dart';
|
||||
|
||||
/// واکشی انواع میز برای صفحهی لیست میزها.
|
||||
class GameRepository {
|
||||
final ApiClient _api;
|
||||
GameRepository(this._api);
|
||||
|
||||
Future<List<TableTier>> getTiers() async {
|
||||
final res = await _api.dio.get('/shop');
|
||||
final cat = Map<String, dynamic>.from(res.data['catalog'] as Map);
|
||||
final list = (cat['table_tiers'] as List?) ?? [];
|
||||
return list
|
||||
.map((e) => TableTier.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flame/game.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/network/ws_client.dart';
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import '../lobby/wallet_cubit.dart';
|
||||
import 'flame/hokm_game.dart';
|
||||
import 'game_cubit.dart';
|
||||
import 'game_models.dart';
|
||||
|
||||
/// صفحهی میز بازی: صحنهی Flame + اوورلیهای وضعیت (انتخاب حکم، نتیجه، پایان، اتصال).
|
||||
class GameScreen extends StatefulWidget {
|
||||
final int prize; // جایزهی میز برای نمایش در دیالوگ جستجو
|
||||
const GameScreen({super.key, this.prize = 0});
|
||||
|
||||
@override
|
||||
State<GameScreen> createState() => _GameScreenState();
|
||||
}
|
||||
|
||||
class _GameScreenState extends State<GameScreen> {
|
||||
late final HokmGame _game;
|
||||
Timer? _introTimer;
|
||||
bool _introHidden = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_game = HokmGame(context.read<GameCubit>());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_introTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// دیالوگ جستجو تا یافتن حریفان و کمی پس از آن نمایش داده میشود.
|
||||
bool _showSearch(GameUiState s) => s.state == null || !_introHidden;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return PopScope(
|
||||
// خروج با دکمهی back سیستم هم باید با تأیید باشد.
|
||||
canPop: false,
|
||||
onPopInvokedWithResult: (didPop, _) {
|
||||
if (!didPop) _confirmLeave(context);
|
||||
},
|
||||
child: Scaffold(
|
||||
body: BlocConsumer<GameCubit, GameUiState>(
|
||||
listenWhen: (a, b) => a.notice != b.notice && b.notice != null,
|
||||
listener: (context, state) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(state.notice!), duration: const Duration(seconds: 2)),
|
||||
);
|
||||
context.read<GameCubit>().clearNotice();
|
||||
},
|
||||
builder: (context, state) {
|
||||
// پس از یافتن حریفان، دیالوگ جستجو را کمی نگه میداریم بعد مخفی میکنیم.
|
||||
if (state.state != null && _introTimer == null) {
|
||||
_introTimer = Timer(const Duration(milliseconds: 1600), () {
|
||||
if (mounted) setState(() => _introHidden = true);
|
||||
});
|
||||
}
|
||||
return Stack(
|
||||
children: [
|
||||
GameWidget(game: _game),
|
||||
_backButton(context),
|
||||
if (state.connection == WsStatus.disconnected) _connBanner(),
|
||||
if (_showSearch(state)) _searchPanel(state),
|
||||
if (!_showSearch(state) && _showTrumpPicker(state))
|
||||
_trumpPicker(context),
|
||||
if (state.handResult != null && state.gameOver == null)
|
||||
_handResult(state),
|
||||
if (state.gameOver != null) _gameOver(context, state),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
bool _showTrumpPicker(GameUiState s) =>
|
||||
s.state != null &&
|
||||
s.state!.phase == 'choose_trump' &&
|
||||
s.state!.amHakem &&
|
||||
s.gameOver == null;
|
||||
|
||||
Widget _backButton(BuildContext context) => Positioned(
|
||||
top: 8,
|
||||
right: 8,
|
||||
child: SafeArea(
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.arrow_back, color: AppColors.gold),
|
||||
onPressed: () => _confirmLeave(context),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Future<void> _confirmLeave(BuildContext context) async {
|
||||
// اگر بازی تمام شده، بدون تأیید خارج شو.
|
||||
if (context.read<GameCubit>().state.gameOver != null) {
|
||||
_exitToLobby(context);
|
||||
return;
|
||||
}
|
||||
final yes = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
backgroundColor: AppColors.panel,
|
||||
title: const Text('خروج از میز'),
|
||||
content: const Text('از میز خارج میشوید؟ ورودی بازگردانده نمیشود.'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('ماندن')),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: const Text('خروج')),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (yes == true && context.mounted) {
|
||||
context.read<GameCubit>().leave();
|
||||
_exitToLobby(context);
|
||||
}
|
||||
}
|
||||
|
||||
void _exitToLobby(BuildContext context) {
|
||||
context.read<WalletCubit>().load();
|
||||
context.go('/lobby');
|
||||
}
|
||||
|
||||
Widget _connBanner() => Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: Material(
|
||||
color: Colors.orange.shade900,
|
||||
child: const SafeArea(
|
||||
bottom: false,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(8),
|
||||
child: Text('ارتباط با سرور قطع شد، در حال تلاش برای اتصال مجدد…',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: Colors.white)),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// دیالوگ «جستجوی حریف» مطابق اپ مرجع: ۴ جایگاه بازیکن + جایزه.
|
||||
Widget _searchPanel(GameUiState state) {
|
||||
final players = state.state?.players ?? const <GamePlayer>[];
|
||||
final mySeat = state.state?.yourSeat ?? -1;
|
||||
final searching = state.state == null;
|
||||
GamePlayer? at(int seat) {
|
||||
for (final p in players) {
|
||||
if (p.seat == seat) return p;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return Container(
|
||||
color: Colors.black.withValues(alpha: 0.78),
|
||||
alignment: Alignment.center,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 20),
|
||||
padding: const EdgeInsets.fromLTRB(16, 14, 16, 18),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.panel,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: AppColors.gold, width: 2.5),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text('جستجوی حریف',
|
||||
style: TextStyle(
|
||||
color: AppColors.gold,
|
||||
fontSize: 22,
|
||||
fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 18),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
for (var seat = 0; seat < 4; seat++)
|
||||
_searchSlot(at(seat), seat == mySeat),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 18, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.bgDark,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
border: Border.all(color: AppColors.goldDark),
|
||||
),
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
const Icon(Icons.monetization_on, color: AppColors.gold),
|
||||
const SizedBox(width: 8),
|
||||
Text('${widget.prize}',
|
||||
style: const TextStyle(
|
||||
color: AppColors.gold,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold)),
|
||||
]),
|
||||
),
|
||||
if (searching) ...[
|
||||
const SizedBox(height: 16),
|
||||
const SizedBox(
|
||||
height: 22,
|
||||
width: 22,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2, color: AppColors.gold),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _searchSlot(GamePlayer? p, bool isYou) {
|
||||
final found = p != null;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text(found ? p.name : '...',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
color: isYou ? AppColors.gold : Colors.white70, fontSize: 12)),
|
||||
const SizedBox(height: 4),
|
||||
Container(
|
||||
width: 58,
|
||||
height: 58,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.bgDark,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: isYou ? AppColors.gold : AppColors.goldDark, width: 1.5),
|
||||
),
|
||||
child: Icon(
|
||||
found ? (p.bot ? Icons.smart_toy : Icons.person) : Icons.help_outline,
|
||||
color: found ? AppColors.gold : Colors.white24,
|
||||
size: 30,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(found ? (p.bot ? 'ربات' : (isYou ? 'شما' : 'حریف')) : '',
|
||||
style: const TextStyle(color: Colors.white38, fontSize: 10)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _trumpPicker(BuildContext context) {
|
||||
const suits = [
|
||||
('spades', '♠', 'پیک', Colors.white),
|
||||
('hearts', '♥', 'دل', Color(0xFFD32F2F)),
|
||||
('diamonds', '♦', 'خشت', Color(0xFFD32F2F)),
|
||||
('clubs', '♣', 'گشنیز', Colors.white),
|
||||
];
|
||||
return Container(
|
||||
color: Colors.black54,
|
||||
alignment: Alignment.center,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.all(24),
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.panel,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: AppColors.gold, width: 2),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text('حکم را انتخاب کن',
|
||||
style: TextStyle(color: AppColors.gold, fontSize: 20)),
|
||||
const SizedBox(height: 16),
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
alignment: WrapAlignment.center,
|
||||
children: [
|
||||
for (final (id, sym, name, color) in suits)
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.bgDark,
|
||||
minimumSize: const Size(120, 64),
|
||||
),
|
||||
onPressed: () =>
|
||||
context.read<GameCubit>().chooseTrump(id),
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text(sym, style: TextStyle(fontSize: 26, color: color)),
|
||||
const SizedBox(width: 8),
|
||||
Text(name, style: const TextStyle(color: AppColors.text)),
|
||||
]),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _handResult(GameUiState s) {
|
||||
final r = s.handResult!;
|
||||
final mySeat = s.state?.yourSeat ?? 0;
|
||||
final myTeam = mySeat % 2;
|
||||
final won = r.winnerTeam == myTeam;
|
||||
return IgnorePointer(
|
||||
child: Center(
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 18),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black87,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: AppColors.gold),
|
||||
),
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text(won ? 'این دست را بردید!' : 'این دست را باختید',
|
||||
style: TextStyle(
|
||||
color: won ? AppColors.green : Colors.redAccent,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold)),
|
||||
if (r.kot)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(top: 6),
|
||||
child: Text('کُت! (دو امتیاز)',
|
||||
style: TextStyle(color: AppColors.gold)),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text('امتیاز: ${r.scores.isNotEmpty ? r.scores[0] : 0} - ${r.scores.length > 1 ? r.scores[1] : 0}',
|
||||
style: const TextStyle(color: Colors.white70)),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _gameOver(BuildContext context, GameUiState s) {
|
||||
final g = s.gameOver!;
|
||||
final mySeat = s.state?.yourSeat ?? 0;
|
||||
final won = g.winnerTeam == mySeat % 2;
|
||||
return Container(
|
||||
color: Colors.black87,
|
||||
alignment: Alignment.center,
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text(won ? 'بردید! 🎉' : 'باختید',
|
||||
style: TextStyle(
|
||||
color: won ? AppColors.gold : Colors.redAccent,
|
||||
fontSize: 32,
|
||||
fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 12),
|
||||
Text('نتیجه نهایی: ${g.scores.isNotEmpty ? g.scores[0] : 0} - ${g.scores.length > 1 ? g.scores[1] : 0}',
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 18)),
|
||||
const SizedBox(height: 28),
|
||||
SizedBox(
|
||||
width: 220,
|
||||
child: ElevatedButton(
|
||||
onPressed: () => _exitToLobby(context),
|
||||
child: const Text('بازگشت به لابی'),
|
||||
),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// نوع میز (از catalog.table_tiers در GET /api/shop).
|
||||
class TableTier {
|
||||
final String id;
|
||||
final String title;
|
||||
final int hands;
|
||||
final int entry;
|
||||
final int prize;
|
||||
final int xp;
|
||||
final int trophy;
|
||||
|
||||
TableTier.fromJson(Map<String, dynamic> j)
|
||||
: id = j['id'] as String,
|
||||
title = j['title'] as String,
|
||||
hands = (j['hands'] ?? 0) as int,
|
||||
entry = (j['entry'] ?? 0) as int,
|
||||
prize = (j['prize'] ?? 0) as int,
|
||||
xp = (j['xp'] ?? 0) as int,
|
||||
trophy = (j['trophy'] ?? 0) as int;
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import 'game_repository.dart';
|
||||
import 'tier.dart';
|
||||
|
||||
/// لیست میزها (tierها) با ورودی/جایزه؛ انتخاب → ورود به میز.
|
||||
class TierListScreen extends StatefulWidget {
|
||||
final GameRepository repo;
|
||||
const TierListScreen({super.key, required this.repo});
|
||||
|
||||
@override
|
||||
State<TierListScreen> createState() => _TierListScreenState();
|
||||
}
|
||||
|
||||
class _TierListScreenState extends State<TierListScreen> {
|
||||
late Future<List<TableTier>> _future;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_future = widget.repo.getTiers();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('انتخاب میز')),
|
||||
body: FutureBuilder<List<TableTier>>(
|
||||
future: _future,
|
||||
builder: (context, snap) {
|
||||
if (snap.connectionState != ConnectionState.done) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (snap.hasError || snap.data == null) {
|
||||
return Center(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
const Text('خطا در بارگذاری میزها'),
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
setState(() => _future = widget.repo.getTiers()),
|
||||
child: const Text('تلاش مجدد'),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
final tiers = snap.data!;
|
||||
return ListView.separated(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: tiers.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 12),
|
||||
itemBuilder: (_, i) => _TierCard(tier: tiers[i]),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TierCard extends StatelessWidget {
|
||||
final TableTier tier;
|
||||
const _TierCard({required this.tier});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return InkWell(
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
onTap: () => context.push('/game/${tier.id}?prize=${tier.prize}'),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.panel,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: AppColors.goldDark),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(tier.title,
|
||||
style: const TextStyle(
|
||||
color: AppColors.gold,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 4),
|
||||
Text('${tier.hands} دست',
|
||||
style: const TextStyle(color: Colors.white60)),
|
||||
],
|
||||
),
|
||||
const Spacer(),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
_row(Icons.login, 'ورودی', tier.entry),
|
||||
_row(Icons.emoji_events, 'جایزه', tier.prize),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _row(IconData icon, String label, int value) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text('$label: $value',
|
||||
style: const TextStyle(color: AppColors.text, fontSize: 13)),
|
||||
const SizedBox(width: 4),
|
||||
Icon(icon, size: 16, color: AppColors.gold),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user