init
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import 'auth_repository.dart';
|
||||
|
||||
enum AuthStatus { initial, loading, otpSent, authenticated, error }
|
||||
|
||||
class AuthState extends Equatable {
|
||||
final AuthStatus status;
|
||||
final String mobile;
|
||||
final String? error;
|
||||
|
||||
const AuthState({
|
||||
this.status = AuthStatus.initial,
|
||||
this.mobile = '',
|
||||
this.error,
|
||||
});
|
||||
|
||||
AuthState copyWith({AuthStatus? status, String? mobile, String? error}) =>
|
||||
AuthState(
|
||||
status: status ?? this.status,
|
||||
mobile: mobile ?? this.mobile,
|
||||
error: error,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, mobile, error];
|
||||
}
|
||||
|
||||
class AuthCubit extends Cubit<AuthState> {
|
||||
final AuthRepository _repo;
|
||||
AuthCubit(this._repo) : super(const AuthState());
|
||||
|
||||
Future<void> requestOtp(String mobile) async {
|
||||
emit(state.copyWith(status: AuthStatus.loading, mobile: mobile));
|
||||
try {
|
||||
await _repo.requestOtp(mobile);
|
||||
emit(state.copyWith(status: AuthStatus.otpSent, mobile: mobile));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(status: AuthStatus.error, error: _msg(e)));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> verifyOtp(String code) async {
|
||||
emit(state.copyWith(status: AuthStatus.loading));
|
||||
try {
|
||||
await _repo.verifyOtp(state.mobile, code);
|
||||
emit(state.copyWith(status: AuthStatus.authenticated));
|
||||
} catch (e) {
|
||||
emit(state.copyWith(status: AuthStatus.error, error: _msg(e)));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
await _repo.logout();
|
||||
emit(const AuthState());
|
||||
}
|
||||
|
||||
/// بازنشانی وضعیت خطا به حالت مناسب فرم.
|
||||
void resetError({required bool onOtpScreen}) {
|
||||
emit(state.copyWith(
|
||||
status: onOtpScreen ? AuthStatus.otpSent : AuthStatus.initial));
|
||||
}
|
||||
|
||||
String _msg(Object e) {
|
||||
if (e is DioException) {
|
||||
final data = e.response?.data;
|
||||
if (data is Map && data['message'] != null) {
|
||||
return data['message'].toString();
|
||||
}
|
||||
return 'خطا در ارتباط با سرور';
|
||||
}
|
||||
return 'خطای نامشخص';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import '../../core/network/api_client.dart';
|
||||
import '../../core/storage/token_storage.dart';
|
||||
|
||||
/// دسترسی به endpointهای احراز هویت (login-otp / check-otp).
|
||||
class AuthRepository {
|
||||
final ApiClient _api;
|
||||
final TokenStorage _storage;
|
||||
|
||||
AuthRepository(this._api, this._storage);
|
||||
|
||||
/// درخواست ارسال کد یکبارمصرف.
|
||||
Future<void> requestOtp(String mobile) async {
|
||||
await _api.dio.post('/auth/login-otp', data: {'mobile': mobile});
|
||||
}
|
||||
|
||||
/// اعتبارسنجی کد و ذخیرهی توکن JWT.
|
||||
Future<void> verifyOtp(String mobile, String code) async {
|
||||
final res = await _api.dio.post(
|
||||
'/auth/check-otp',
|
||||
data: {'mobile': mobile, 'token': code},
|
||||
);
|
||||
final token = res.data['token'] as String?;
|
||||
if (token == null || token.isEmpty) {
|
||||
throw Exception('no token in response');
|
||||
}
|
||||
await _storage.write(token);
|
||||
}
|
||||
|
||||
Future<bool> isLoggedIn() async {
|
||||
final t = await _storage.read();
|
||||
return t != null && t.isNotEmpty;
|
||||
}
|
||||
|
||||
Future<void> logout() => _storage.clear();
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import 'auth_cubit.dart';
|
||||
|
||||
/// صفحهی ورود شماره موبایل.
|
||||
class MobileScreen extends StatefulWidget {
|
||||
const MobileScreen({super.key});
|
||||
|
||||
@override
|
||||
State<MobileScreen> createState() => _MobileScreenState();
|
||||
}
|
||||
|
||||
class _MobileScreenState extends State<MobileScreen> {
|
||||
final _controller = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool get _valid => RegExp(r'^09\d{9}$').hasMatch(_controller.text.trim());
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: BlocConsumer<AuthCubit, AuthState>(
|
||||
listener: (context, state) {
|
||||
if (state.status == AuthStatus.otpSent) {
|
||||
context.push('/otp');
|
||||
} else if (state.status == AuthStatus.error) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(state.error ?? 'خطا')),
|
||||
);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final loading = state.status == AuthStatus.loading;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Text('سلطان حکم',
|
||||
style: TextStyle(
|
||||
fontSize: 36,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: AppColors.gold)),
|
||||
const SizedBox(height: 8),
|
||||
const Text('برای ورود شماره موبایلت رو وارد کن',
|
||||
style: TextStyle(color: Colors.white70)),
|
||||
const SizedBox(height: 32),
|
||||
TextField(
|
||||
controller: _controller,
|
||||
keyboardType: TextInputType.phone,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontSize: 20, letterSpacing: 2),
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.digitsOnly,
|
||||
LengthLimitingTextInputFormatter(11),
|
||||
],
|
||||
decoration: const InputDecoration(hintText: '09xxxxxxxxx'),
|
||||
onChanged: (_) => setState(() {}),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
ElevatedButton(
|
||||
onPressed: (!_valid || loading)
|
||||
? null
|
||||
: () => context
|
||||
.read<AuthCubit>()
|
||||
.requestOtp(_controller.text.trim()),
|
||||
child: loading
|
||||
? const SizedBox(
|
||||
height: 22,
|
||||
width: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Text('دریافت کد'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import 'auth_cubit.dart';
|
||||
|
||||
/// صفحهی ورود کد یکبارمصرف (۵ رقمی).
|
||||
class OtpScreen extends StatefulWidget {
|
||||
const OtpScreen({super.key});
|
||||
|
||||
@override
|
||||
State<OtpScreen> createState() => _OtpScreenState();
|
||||
}
|
||||
|
||||
class _OtpScreenState extends State<OtpScreen> {
|
||||
final _controller = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool get _valid => _controller.text.trim().length == 5;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('تأیید کد')),
|
||||
body: SafeArea(
|
||||
child: BlocConsumer<AuthCubit, AuthState>(
|
||||
listener: (context, state) {
|
||||
if (state.status == AuthStatus.authenticated) {
|
||||
context.go('/lobby');
|
||||
} else if (state.status == AuthStatus.error) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(state.error ?? 'خطا')),
|
||||
);
|
||||
context.read<AuthCubit>().resetError(onOtpScreen: true);
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final loading = state.status == AuthStatus.loading;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text('کد پیامکشده به ${state.mobile} را وارد کنید',
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: Colors.white70)),
|
||||
const SizedBox(height: 32),
|
||||
TextField(
|
||||
controller: _controller,
|
||||
keyboardType: TextInputType.number,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(fontSize: 28, letterSpacing: 12),
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.digitsOnly,
|
||||
LengthLimitingTextInputFormatter(5),
|
||||
],
|
||||
decoration: const InputDecoration(hintText: '- - - - -'),
|
||||
onChanged: (_) => setState(() {}),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
ElevatedButton(
|
||||
onPressed: (!_valid || loading)
|
||||
? null
|
||||
: () => context
|
||||
.read<AuthCubit>()
|
||||
.verifyOtp(_controller.text.trim()),
|
||||
child: loading
|
||||
? const SizedBox(
|
||||
height: 22,
|
||||
width: 22,
|
||||
child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Text('ورود'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: loading ? null : () => context.pop(),
|
||||
child: const Text('تغییر شماره',
|
||||
style: TextStyle(color: AppColors.gold)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import '../auth/auth_cubit.dart';
|
||||
import 'wallet.dart';
|
||||
import 'wallet_cubit.dart';
|
||||
|
||||
/// لابی اصلی: کیفپول، دکمه بازی، سکه روزانه.
|
||||
class LobbyScreen extends StatefulWidget {
|
||||
const LobbyScreen({super.key});
|
||||
|
||||
@override
|
||||
State<LobbyScreen> createState() => _LobbyScreenState();
|
||||
}
|
||||
|
||||
class _LobbyScreenState extends State<LobbyScreen> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
context.read<WalletCubit>().load();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: SafeArea(
|
||||
child: BlocBuilder<WalletCubit, WalletState>(
|
||||
builder: (context, state) {
|
||||
return Column(
|
||||
children: [
|
||||
_TopBar(wallet: state.wallet),
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text('سلطان حکم',
|
||||
style: TextStyle(
|
||||
fontSize: 40,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: AppColors.gold)),
|
||||
const SizedBox(height: 48),
|
||||
_MenuButton(
|
||||
label: 'بازی',
|
||||
icon: Icons.style,
|
||||
color: const Color(0xFF8E1B5B),
|
||||
onTap: () async {
|
||||
await context.push('/game/tiers');
|
||||
if (context.mounted) {
|
||||
context.read<WalletCubit>().load();
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_MenuButton(
|
||||
label: 'فروشگاه',
|
||||
icon: Icons.storefront,
|
||||
color: const Color(0xFF4A148C),
|
||||
onTap: () async {
|
||||
await context.push('/shop');
|
||||
if (context.mounted) {
|
||||
context.read<WalletCubit>().load();
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_MenuButton(
|
||||
label: 'سکه روزانه',
|
||||
icon: Icons.monetization_on,
|
||||
color: AppColors.green,
|
||||
onTap: () => _claimDaily(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: () async {
|
||||
await context.read<AuthCubit>().logout();
|
||||
if (context.mounted) context.go('/login');
|
||||
},
|
||||
icon: const Icon(Icons.logout, color: Colors.white54),
|
||||
label: const Text('خروج',
|
||||
style: TextStyle(color: Colors.white54)),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _claimDaily(BuildContext context) async {
|
||||
final amount = await context.read<WalletCubit>().claimDaily();
|
||||
if (!context.mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(amount != null
|
||||
? 'سکه روزانه دریافت شد: +$amount'
|
||||
: 'سکه روزانه را قبلاً امروز گرفتهاید'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TopBar extends StatelessWidget {
|
||||
final Wallet? wallet;
|
||||
const _TopBar({this.wallet});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final w = wallet;
|
||||
return Container(
|
||||
margin: const EdgeInsets.all(8),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.bgDark,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: AppColors.goldDark),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const CircleAvatar(
|
||||
backgroundColor: AppColors.panel,
|
||||
child: Icon(Icons.person, color: AppColors.gold),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('سطح ${w?.level ?? '-'}',
|
||||
style: const TextStyle(color: AppColors.gold)),
|
||||
if (w != null)
|
||||
SizedBox(
|
||||
width: 90,
|
||||
child: LinearProgressIndicator(
|
||||
value: w.xpForNext == 0 ? 0 : w.xpIntoLevel / w.xpForNext,
|
||||
backgroundColor: Colors.white12,
|
||||
color: AppColors.gold,
|
||||
minHeight: 5,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const Spacer(),
|
||||
_Chip(icon: Icons.confirmation_number, value: w?.tickets ?? 0),
|
||||
const SizedBox(width: 8),
|
||||
_Chip(icon: Icons.monetization_on, value: w?.coins ?? 0),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Chip extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final int value;
|
||||
const _Chip({required this.icon, required this.value});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.panel,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: AppColors.goldDark),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, color: AppColors.gold, size: 18),
|
||||
const SizedBox(width: 6),
|
||||
Text('$value', style: const TextStyle(color: AppColors.text)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MenuButton extends StatelessWidget {
|
||||
final String label;
|
||||
final IconData icon;
|
||||
final Color color;
|
||||
final VoidCallback onTap;
|
||||
const _MenuButton({
|
||||
required this.label,
|
||||
required this.icon,
|
||||
required this.color,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SizedBox(
|
||||
width: 280,
|
||||
child: ElevatedButton.icon(
|
||||
style: ElevatedButton.styleFrom(backgroundColor: color),
|
||||
onPressed: onTap,
|
||||
icon: Icon(icon, color: AppColors.gold),
|
||||
label: Text(label),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
/// وضعیت اقتصادی کاربر (پاسخ GET /api/wallet).
|
||||
class Wallet extends Equatable {
|
||||
final int coins;
|
||||
final int tickets;
|
||||
final int xp;
|
||||
final int trophies;
|
||||
final int level;
|
||||
final int xpIntoLevel;
|
||||
final int xpForNext;
|
||||
final bool vip;
|
||||
final String selectedCard;
|
||||
|
||||
const Wallet({
|
||||
required this.coins,
|
||||
required this.tickets,
|
||||
required this.xp,
|
||||
required this.trophies,
|
||||
required this.level,
|
||||
required this.xpIntoLevel,
|
||||
required this.xpForNext,
|
||||
required this.vip,
|
||||
required this.selectedCard,
|
||||
});
|
||||
|
||||
factory Wallet.fromJson(Map<String, dynamic> j) => Wallet(
|
||||
coins: (j['coins'] ?? 0) as int,
|
||||
tickets: (j['tickets'] ?? 0) as int,
|
||||
xp: (j['xp'] ?? 0) as int,
|
||||
trophies: (j['trophies'] ?? 0) as int,
|
||||
level: (j['level'] ?? 1) as int,
|
||||
xpIntoLevel: (j['xp_into_level'] ?? 0) as int,
|
||||
xpForNext: (j['xp_for_next'] ?? 1) as int,
|
||||
vip: (j['vip'] ?? false) as bool,
|
||||
selectedCard: (j['selected_card'] ?? 'simple') as String,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props =>
|
||||
[coins, tickets, xp, trophies, level, xpIntoLevel, xpForNext, vip, selectedCard];
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../core/network/api_client.dart';
|
||||
import 'wallet.dart';
|
||||
|
||||
enum WalletStatus { initial, loading, loaded, error }
|
||||
|
||||
class WalletState extends Equatable {
|
||||
final WalletStatus status;
|
||||
final Wallet? wallet;
|
||||
|
||||
const WalletState({this.status = WalletStatus.initial, this.wallet});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, wallet];
|
||||
}
|
||||
|
||||
class WalletCubit extends Cubit<WalletState> {
|
||||
final ApiClient _api;
|
||||
WalletCubit(this._api) : super(const WalletState());
|
||||
|
||||
Future<void> load() async {
|
||||
emit(const WalletState(status: WalletStatus.loading));
|
||||
try {
|
||||
final res = await _api.dio.get('/wallet');
|
||||
emit(WalletState(
|
||||
status: WalletStatus.loaded,
|
||||
wallet: Wallet.fromJson(Map<String, dynamic>.from(res.data)),
|
||||
));
|
||||
} catch (_) {
|
||||
emit(const WalletState(status: WalletStatus.error));
|
||||
}
|
||||
}
|
||||
|
||||
/// دریافت سکه روزانه و سپس بهروزرسانی کیفپول.
|
||||
Future<int?> claimDaily() async {
|
||||
try {
|
||||
final res = await _api.dio.post('/rewards/daily');
|
||||
await load();
|
||||
return (res.data['amount'] ?? 0) as int;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import 'shop_models.dart';
|
||||
import 'shop_repository.dart';
|
||||
|
||||
enum ShopStatus { initial, loading, loaded, error }
|
||||
|
||||
class ShopState extends Equatable {
|
||||
final ShopStatus status;
|
||||
final ShopData? data;
|
||||
final bool busy; // در حال انجام یک عملیات (خرید/انتخاب)
|
||||
|
||||
const ShopState({this.status = ShopStatus.initial, this.data, this.busy = false});
|
||||
|
||||
ShopState copyWith({ShopStatus? status, ShopData? data, bool? busy}) => ShopState(
|
||||
status: status ?? this.status,
|
||||
data: data ?? this.data,
|
||||
busy: busy ?? this.busy,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [status, data, busy];
|
||||
}
|
||||
|
||||
class ShopCubit extends Cubit<ShopState> {
|
||||
final ShopRepository _repo;
|
||||
ShopCubit(this._repo) : super(const ShopState());
|
||||
|
||||
Future<void> load() async {
|
||||
emit(state.copyWith(status: ShopStatus.loading));
|
||||
try {
|
||||
emit(state.copyWith(status: ShopStatus.loaded, data: await _repo.getShop()));
|
||||
} catch (_) {
|
||||
emit(state.copyWith(status: ShopStatus.error));
|
||||
}
|
||||
}
|
||||
|
||||
/// یک عملیات را اجرا، فروشگاه را بازخوانی و پیام نتیجه را برمیگرداند.
|
||||
Future<String> _run(Future<void> Function() action, String okMsg) async {
|
||||
if (state.busy) return '';
|
||||
emit(state.copyWith(busy: true));
|
||||
try {
|
||||
await action();
|
||||
final data = await _repo.getShop();
|
||||
emit(state.copyWith(status: ShopStatus.loaded, data: data, busy: false));
|
||||
return okMsg;
|
||||
} on DioException catch (e) {
|
||||
emit(state.copyWith(busy: false));
|
||||
final d = e.response?.data;
|
||||
if (d is Map && d['message'] != null) return d['message'].toString();
|
||||
return 'خطا در ارتباط با سرور';
|
||||
} catch (_) {
|
||||
emit(state.copyWith(busy: false));
|
||||
return 'خطای نامشخص';
|
||||
}
|
||||
}
|
||||
|
||||
Future<String> buyCard(String id) => _run(() => _repo.buyCard(id), 'کارت خریداری شد');
|
||||
|
||||
Future<String> selectCard(String id) =>
|
||||
_run(() => _repo.selectCard(id), 'کارت انتخاب شد');
|
||||
|
||||
Future<String> purchase(String kind, String id) => _run(
|
||||
() => _repo.purchase(
|
||||
store: 'bazaar',
|
||||
kind: kind,
|
||||
productId: id,
|
||||
token: 'dev-$kind-$id-${DateTime.now().millisecondsSinceEpoch}',
|
||||
),
|
||||
'خرید با موفقیت انجام شد',
|
||||
);
|
||||
|
||||
Future<String> claimAd() => _run(
|
||||
() => _repo.adReward('dev-ad-${DateTime.now().millisecondsSinceEpoch}'),
|
||||
'سکه رایگان دریافت شد',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
// مدلهای کاتالوگ فروشگاه (پاسخ GET /api/shop).
|
||||
|
||||
class CoinPackage {
|
||||
final String id;
|
||||
final String title;
|
||||
final int coins;
|
||||
final int vipDays;
|
||||
final int priceToman;
|
||||
final int bonusPct;
|
||||
|
||||
CoinPackage.fromJson(Map<String, dynamic> j)
|
||||
: id = j['id'] as String,
|
||||
title = j['title'] as String,
|
||||
coins = (j['coins'] ?? 0) as int,
|
||||
vipDays = (j['vip_days'] ?? 0) as int,
|
||||
priceToman = (j['price_toman'] ?? 0) as int,
|
||||
bonusPct = (j['bonus_pct'] ?? 0) as int;
|
||||
}
|
||||
|
||||
class TicketPackage {
|
||||
final String id;
|
||||
final String title;
|
||||
final int tickets;
|
||||
final int priceToman;
|
||||
|
||||
TicketPackage.fromJson(Map<String, dynamic> j)
|
||||
: id = j['id'] as String,
|
||||
title = j['title'] as String,
|
||||
tickets = (j['tickets'] ?? 0) as int,
|
||||
priceToman = (j['price_toman'] ?? 0) as int;
|
||||
}
|
||||
|
||||
class CardSkin {
|
||||
final String id;
|
||||
final String title;
|
||||
final int priceCoins;
|
||||
|
||||
CardSkin.fromJson(Map<String, dynamic> j)
|
||||
: id = j['id'] as String,
|
||||
title = j['title'] as String,
|
||||
priceCoins = (j['price_coins'] ?? 0) as int;
|
||||
}
|
||||
|
||||
class Booster {
|
||||
final String id;
|
||||
final String title;
|
||||
final int multiplier;
|
||||
final int hours;
|
||||
final int priceToman;
|
||||
|
||||
Booster.fromJson(Map<String, dynamic> j)
|
||||
: id = j['id'] as String,
|
||||
title = j['title'] as String,
|
||||
multiplier = (j['multiplier'] ?? 1) as int,
|
||||
hours = (j['hours'] ?? 0) as int,
|
||||
priceToman = (j['price_toman'] ?? 0) as int;
|
||||
}
|
||||
|
||||
/// دادهی کامل فروشگاه: کاتالوگ + کارتهای متعلق به کاربر + کارت انتخابی.
|
||||
class ShopData {
|
||||
final List<CoinPackage> coinPackages;
|
||||
final List<TicketPackage> ticketPackages;
|
||||
final List<CardSkin> cardSkins;
|
||||
final List<Booster> boosters;
|
||||
final List<String> ownedCards;
|
||||
final String selectedCard;
|
||||
|
||||
ShopData({
|
||||
required this.coinPackages,
|
||||
required this.ticketPackages,
|
||||
required this.cardSkins,
|
||||
required this.boosters,
|
||||
required this.ownedCards,
|
||||
required this.selectedCard,
|
||||
});
|
||||
|
||||
factory ShopData.fromJson(Map<String, dynamic> j) {
|
||||
final cat = Map<String, dynamic>.from(j['catalog'] as Map);
|
||||
List<T> parse<T>(String key, T Function(Map<String, dynamic>) f) =>
|
||||
((cat[key] as List?) ?? [])
|
||||
.map((e) => f(Map<String, dynamic>.from(e as Map)))
|
||||
.toList();
|
||||
return ShopData(
|
||||
coinPackages: parse('coin_packages', CoinPackage.fromJson),
|
||||
ticketPackages: parse('ticket_packages', TicketPackage.fromJson),
|
||||
cardSkins: parse('card_skins', CardSkin.fromJson),
|
||||
boosters: parse('boosters', Booster.fromJson),
|
||||
ownedCards: ((j['owned_cards'] as List?) ?? []).map((e) => e as String).toList(),
|
||||
selectedCard: (j['selected_card'] ?? 'simple') as String,
|
||||
);
|
||||
}
|
||||
|
||||
bool owns(String cardId) => cardId == 'simple' || ownedCards.contains(cardId);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import '../../core/network/api_client.dart';
|
||||
import 'shop_models.dart';
|
||||
|
||||
/// دسترسی به endpointهای فروشگاه و پاداشها.
|
||||
class ShopRepository {
|
||||
final ApiClient _api;
|
||||
ShopRepository(this._api);
|
||||
|
||||
Future<ShopData> getShop() async {
|
||||
final res = await _api.dio.get('/shop');
|
||||
return ShopData.fromJson(Map<String, dynamic>.from(res.data));
|
||||
}
|
||||
|
||||
Future<void> buyCard(String cardId) =>
|
||||
_api.dio.post('/shop/buy-card', data: {'card_id': cardId});
|
||||
|
||||
Future<void> selectCard(String cardId) =>
|
||||
_api.dio.post('/shop/select-card', data: {'card_id': cardId});
|
||||
|
||||
/// تأیید خرید IAP. در حالت واقعی token از SDK بازار/مایکت میآید؛
|
||||
/// فعلاً توکن توسعهای فرستاده میشود (بکاند در حالت dev هر توکن غیرخالی را میپذیرد).
|
||||
Future<void> purchase({
|
||||
required String store,
|
||||
required String kind,
|
||||
required String productId,
|
||||
required String token,
|
||||
}) =>
|
||||
_api.dio.post('/shop/purchase', data: {
|
||||
'store': store,
|
||||
'kind': kind,
|
||||
'product_id': productId,
|
||||
'token': token,
|
||||
});
|
||||
|
||||
/// سکه رایگان پس از تبلیغ rewarded. token از SDK تپسل میآید (فعلاً توسعهای).
|
||||
Future<int> adReward(String token) async {
|
||||
final res = await _api.dio.post('/rewards/ad', data: {'token': token});
|
||||
return (res.data['amount'] ?? 0) as int;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../core/theme/app_theme.dart';
|
||||
import '../lobby/wallet_cubit.dart';
|
||||
import 'shop_cubit.dart';
|
||||
import 'shop_models.dart';
|
||||
|
||||
/// صفحهی فروشگاه با تبهای سکه/بلیط/کارت/تجهیزات.
|
||||
class ShopScreen extends StatelessWidget {
|
||||
const ShopScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DefaultTabController(
|
||||
length: 4,
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('فروشگاه'),
|
||||
actions: [
|
||||
BlocBuilder<WalletCubit, WalletState>(
|
||||
builder: (context, s) => Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 12),
|
||||
child: Row(children: [
|
||||
const Icon(Icons.monetization_on,
|
||||
color: AppColors.gold, size: 18),
|
||||
const SizedBox(width: 4),
|
||||
Text('${s.wallet?.coins ?? 0}',
|
||||
style: const TextStyle(color: AppColors.text)),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
bottom: const TabBar(
|
||||
isScrollable: true,
|
||||
labelColor: AppColors.gold,
|
||||
indicatorColor: AppColors.gold,
|
||||
tabs: [
|
||||
Tab(text: 'سکه'),
|
||||
Tab(text: 'بلیط'),
|
||||
Tab(text: 'کارت'),
|
||||
Tab(text: 'تجهیزات'),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: BlocConsumer<ShopCubit, ShopState>(
|
||||
listener: (context, state) {},
|
||||
builder: (context, state) {
|
||||
if (state.status == ShopStatus.loading ||
|
||||
state.status == ShopStatus.initial) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (state.status == ShopStatus.error || state.data == null) {
|
||||
return Center(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
const Text('خطا در بارگذاری فروشگاه'),
|
||||
TextButton(
|
||||
onPressed: () => context.read<ShopCubit>().load(),
|
||||
child: const Text('تلاش مجدد'),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
final d = state.data!;
|
||||
return TabBarView(
|
||||
children: [
|
||||
_CoinsTab(packages: d.coinPackages),
|
||||
_TicketsTab(packages: d.ticketPackages),
|
||||
_CardsTab(data: d),
|
||||
_BoostersTab(boosters: d.boosters),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// اجرای یک عملیات فروشگاه و نمایش نتیجه + بازخوانی کیفپول.
|
||||
Future<void> _do(BuildContext context, Future<String> Function() action) async {
|
||||
final msg = await action();
|
||||
if (!context.mounted || msg.isEmpty) return;
|
||||
await context.read<WalletCubit>().load();
|
||||
if (!context.mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));
|
||||
}
|
||||
|
||||
class _CoinsTab extends StatelessWidget {
|
||||
final List<CoinPackage> packages;
|
||||
const _CoinsTab({required this.packages});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GridView.count(
|
||||
crossAxisCount: 2,
|
||||
padding: const EdgeInsets.all(12),
|
||||
childAspectRatio: 0.82,
|
||||
mainAxisSpacing: 12,
|
||||
crossAxisSpacing: 12,
|
||||
children: [
|
||||
_FreeCoinCard(
|
||||
onTap: () => _do(context, () => context.read<ShopCubit>().claimAd()),
|
||||
),
|
||||
for (final p in packages)
|
||||
_StoreCard(
|
||||
title: p.title,
|
||||
badge: p.bonusPct > 0 ? '+${p.bonusPct}%' : null,
|
||||
lines: [
|
||||
'${p.coins} سکه',
|
||||
if (p.vipDays > 0) '${p.vipDays} روز VIP',
|
||||
],
|
||||
priceLabel: '${p.priceToman} تومان',
|
||||
icon: Icons.savings,
|
||||
onTap: () =>
|
||||
_do(context, () => context.read<ShopCubit>().purchase('coin', p.id)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TicketsTab extends StatelessWidget {
|
||||
final List<TicketPackage> packages;
|
||||
const _TicketsTab({required this.packages});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GridView.count(
|
||||
crossAxisCount: 2,
|
||||
padding: const EdgeInsets.all(12),
|
||||
childAspectRatio: 0.82,
|
||||
mainAxisSpacing: 12,
|
||||
crossAxisSpacing: 12,
|
||||
children: [
|
||||
for (final p in packages)
|
||||
_StoreCard(
|
||||
title: p.title,
|
||||
lines: ['${p.tickets} بلیط'],
|
||||
priceLabel: '${p.priceToman} تومان',
|
||||
icon: Icons.confirmation_number,
|
||||
onTap: () =>
|
||||
_do(context, () => context.read<ShopCubit>().purchase('ticket', p.id)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BoostersTab extends StatelessWidget {
|
||||
final List<Booster> boosters;
|
||||
const _BoostersTab({required this.boosters});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GridView.count(
|
||||
crossAxisCount: 2,
|
||||
padding: const EdgeInsets.all(12),
|
||||
childAspectRatio: 0.82,
|
||||
mainAxisSpacing: 12,
|
||||
crossAxisSpacing: 12,
|
||||
children: [
|
||||
for (final b in boosters)
|
||||
_StoreCard(
|
||||
title: b.title,
|
||||
lines: ['تجربه ×${b.multiplier}', '${b.hours} ساعت'],
|
||||
priceLabel: '${b.priceToman} تومان',
|
||||
icon: Icons.bolt,
|
||||
onTap: () =>
|
||||
_do(context, () => context.read<ShopCubit>().purchase('booster', b.id)),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CardsTab extends StatelessWidget {
|
||||
final ShopData data;
|
||||
const _CardsTab({required this.data});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GridView.count(
|
||||
crossAxisCount: 2,
|
||||
padding: const EdgeInsets.all(12),
|
||||
childAspectRatio: 0.82,
|
||||
mainAxisSpacing: 12,
|
||||
crossAxisSpacing: 12,
|
||||
children: [
|
||||
for (final c in data.cardSkins)
|
||||
_CardSkinCard(
|
||||
skin: c,
|
||||
owned: data.owns(c.id),
|
||||
selected: data.selectedCard == c.id,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CardSkinCard extends StatelessWidget {
|
||||
final CardSkin skin;
|
||||
final bool owned;
|
||||
final bool selected;
|
||||
const _CardSkinCard(
|
||||
{required this.skin, required this.owned, required this.selected});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final Widget action;
|
||||
if (selected) {
|
||||
action = const _Pill(text: 'انتخاب شده', color: AppColors.goldDark);
|
||||
} else if (owned) {
|
||||
action = _ActionButton(
|
||||
label: 'انتخاب',
|
||||
color: AppColors.green,
|
||||
onTap: () =>
|
||||
_do(context, () => context.read<ShopCubit>().selectCard(skin.id)),
|
||||
);
|
||||
} else {
|
||||
action = _ActionButton(
|
||||
label: '${skin.priceCoins} سکه',
|
||||
color: AppColors.accent,
|
||||
onTap: () => _do(context, () => context.read<ShopCubit>().buyCard(skin.id)),
|
||||
);
|
||||
}
|
||||
return _Panel(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(skin.title,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: AppColors.gold)),
|
||||
const Icon(Icons.style, size: 48, color: AppColors.text),
|
||||
SizedBox(width: double.infinity, child: action),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FreeCoinCard extends StatelessWidget {
|
||||
final VoidCallback onTap;
|
||||
const _FreeCoinCard({required this.onTap});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _Panel(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
const Text('سکه رایگان',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: AppColors.gold)),
|
||||
const Icon(Icons.ondemand_video, size: 44, color: AppColors.green),
|
||||
const Text('با دیدن تبلیغ',
|
||||
style: TextStyle(color: Colors.white60, fontSize: 12)),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: _ActionButton(
|
||||
label: 'رایگان', color: AppColors.green, onTap: onTap),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StoreCard extends StatelessWidget {
|
||||
final String title;
|
||||
final List<String> lines;
|
||||
final String priceLabel;
|
||||
final IconData icon;
|
||||
final String? badge;
|
||||
final VoidCallback onTap;
|
||||
const _StoreCard({
|
||||
required this.title,
|
||||
required this.lines,
|
||||
required this.priceLabel,
|
||||
required this.icon,
|
||||
required this.onTap,
|
||||
this.badge,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Stack(
|
||||
children: [
|
||||
_Panel(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(title,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: AppColors.gold)),
|
||||
Icon(icon, size: 40, color: AppColors.gold),
|
||||
Column(
|
||||
children: [
|
||||
for (final l in lines)
|
||||
Text(l, style: const TextStyle(color: AppColors.text)),
|
||||
],
|
||||
),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: _ActionButton(
|
||||
label: priceLabel, color: AppColors.accent, onTap: onTap),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (badge != null)
|
||||
Positioned(
|
||||
top: 4,
|
||||
left: 4,
|
||||
child: _Pill(text: badge!, color: AppColors.green),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Panel extends StatelessWidget {
|
||||
final Widget child;
|
||||
const _Panel({required this.child});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(10),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.panel,
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: AppColors.goldDark),
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ActionButton extends StatelessWidget {
|
||||
final String label;
|
||||
final Color color;
|
||||
final VoidCallback onTap;
|
||||
const _ActionButton(
|
||||
{required this.label, required this.color, required this.onTap});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final busy = context.select((ShopCubit c) => c.state.busy);
|
||||
return ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: color,
|
||||
minimumSize: const Size.fromHeight(38),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6),
|
||||
),
|
||||
onPressed: busy ? null : onTap,
|
||||
child: Text(label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(fontSize: 13)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Pill extends StatelessWidget {
|
||||
final String text;
|
||||
final Color color;
|
||||
const _Pill({required this.text, required this.color});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(text,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 12)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user