feat: refactor code
This commit is contained in:
@@ -0,0 +1,12 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../../core/locator/locator.dart';
|
||||
import '../../../../../core/network/api_provider_imp.dart';
|
||||
|
||||
/// تماسهای HTTP بازی: فهرست میزها و سهمیهی میز خصوصی.
|
||||
class GameApiProvider {
|
||||
ApiProviderImp get _api => locator<ApiProviderImp>();
|
||||
|
||||
Future<Response> getShop() => _api.get('/shop');
|
||||
Future<Response> getTablesInfo() => _api.get('/tables/info');
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import 'dart:async';
|
||||
|
||||
import '../../../../../core/network/ws_client.dart';
|
||||
import '../../../../auth/data/data_source/local/auth_local_data.dart';
|
||||
|
||||
/// منبعِ realtime بازی: یک اتصال WebSocket را مدیریت کرده و پیامها/وضعیت را
|
||||
/// بهصورت استریم در اختیار repository میگذارد. توکن از حافظهی محلی خوانده میشود.
|
||||
class GameWsProvider {
|
||||
final AuthLocalData local;
|
||||
GameWsProvider(this.local);
|
||||
|
||||
WsClient? _ws;
|
||||
StreamSubscription? _msgSub;
|
||||
StreamSubscription? _statusSub;
|
||||
|
||||
final _messages = StreamController<Map<String, dynamic>>.broadcast();
|
||||
final _status = StreamController<WsStatus>.broadcast();
|
||||
|
||||
Stream<Map<String, dynamic>> get messages => _messages.stream;
|
||||
Stream<WsStatus> get status => _status.stream;
|
||||
|
||||
Future<void> connect() async {
|
||||
await _teardown(); // اتصال قبلی (در صورت وجود) بسته شود
|
||||
final token = await local.readToken();
|
||||
if (token == null || token.isEmpty) return;
|
||||
final ws = WsClient(token);
|
||||
_ws = ws;
|
||||
_msgSub = ws.messages.listen(_messages.add);
|
||||
_statusSub = ws.status.listen(_status.add);
|
||||
ws.connect();
|
||||
}
|
||||
|
||||
void send(Map<String, dynamic> msg) => _ws?.send(msg);
|
||||
|
||||
Future<void> _teardown() async {
|
||||
await _msgSub?.cancel();
|
||||
await _statusSub?.cancel();
|
||||
_msgSub = null;
|
||||
_statusSub = null;
|
||||
_ws?.dispose();
|
||||
_ws = null;
|
||||
}
|
||||
|
||||
Future<void> disconnect() => _teardown();
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../core/error/custom_error.dart';
|
||||
import '../../../../core/network/ws_client.dart';
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../domain/entities/table_entities.dart';
|
||||
import '../../domain/repository/game_repository.dart';
|
||||
import '../data_source/remote/game_api_provider.dart';
|
||||
import '../data_source/remote/game_ws_provider.dart';
|
||||
|
||||
class GameRepositoryImpl extends GameRepository {
|
||||
final GameWsProvider ws;
|
||||
final GameApiProvider api;
|
||||
GameRepositoryImpl(this.ws, this.api);
|
||||
|
||||
@override
|
||||
Stream<Map<String, dynamic>> get messages => ws.messages;
|
||||
|
||||
@override
|
||||
Stream<WsStatus> get status => ws.status;
|
||||
|
||||
@override
|
||||
Future<void> connect() => ws.connect();
|
||||
|
||||
@override
|
||||
void send(Map<String, dynamic> msg) => ws.send(msg);
|
||||
|
||||
@override
|
||||
Future<void> disconnect() => ws.disconnect();
|
||||
|
||||
@override
|
||||
Future<DataState<List<TableTier>>> getTiers() async {
|
||||
final Response res = await api.getShop();
|
||||
if (res.statusCode == 200) {
|
||||
final cat = Map<String, dynamic>.from(res.data['catalog'] as Map);
|
||||
final list = ((cat['table_tiers'] as List?) ?? [])
|
||||
.map((e) => TableTier.fromJson(Map<String, dynamic>.from(e as Map)))
|
||||
.toList();
|
||||
return DataSuccess(list);
|
||||
}
|
||||
return DataError(errorConvertor(res.statusCode, null));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DataState<TablesInfo>> getTablesInfo() async {
|
||||
final Response res = await api.getTablesInfo();
|
||||
if (res.statusCode == 200) {
|
||||
return DataSuccess(
|
||||
TablesInfo.fromJson(Map<String, dynamic>.from(res.data as Map)));
|
||||
}
|
||||
return DataError(errorConvertor(res.statusCode, null));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// موجودیتهای وضعیت بازی (نگاشت از پیامهای 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 bool hakemKot;
|
||||
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,
|
||||
hakemKot = (j['hakem_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 FirstOrNullExt<E> on Iterable<E> {
|
||||
E? get firstOrNull {
|
||||
final it = iterator;
|
||||
return it.moveNext() ? it.current : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/// نوع میز (از 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;
|
||||
|
||||
const TableTier({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.hands,
|
||||
required this.entry,
|
||||
required this.prize,
|
||||
required this.xp,
|
||||
required this.trophy,
|
||||
});
|
||||
|
||||
factory TableTier.fromJson(Map<String, dynamic> j) => TableTier(
|
||||
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,
|
||||
);
|
||||
}
|
||||
|
||||
/// اطلاعات سهمیهی میزهای خصوصی (GET /api/tables/info).
|
||||
class TablesInfo {
|
||||
final int remaining;
|
||||
final bool unlimited;
|
||||
const TablesInfo(this.remaining, this.unlimited);
|
||||
|
||||
factory TablesInfo.fromJson(Map<String, dynamic> j) => TablesInfo(
|
||||
(j['remaining'] ?? 0) as int,
|
||||
(j['unlimited'] ?? false) as bool,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import '../../../../core/network/ws_client.dart';
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../entities/table_entities.dart';
|
||||
|
||||
/// قرارداد دادهٔ بازی: بخش realtime (سوکت) + بخش HTTP (میزها/سهمیه).
|
||||
abstract class GameRepository {
|
||||
// --- realtime ---
|
||||
Stream<Map<String, dynamic>> get messages;
|
||||
Stream<WsStatus> get status;
|
||||
Future<void> connect();
|
||||
void send(Map<String, dynamic> msg);
|
||||
Future<void> disconnect();
|
||||
|
||||
// --- HTTP ---
|
||||
Future<DataState<List<TableTier>>> getTiers();
|
||||
Future<DataState<TablesInfo>> getTablesInfo();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../entities/table_entities.dart';
|
||||
import '../repository/game_repository.dart';
|
||||
|
||||
class GetTablesInfoUseCase
|
||||
implements UseCase<DataState<TablesInfo>, NoParams> {
|
||||
final GameRepository repository;
|
||||
GetTablesInfoUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<TablesInfo>> call(NoParams params) =>
|
||||
repository.getTablesInfo();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../entities/table_entities.dart';
|
||||
import '../repository/game_repository.dart';
|
||||
|
||||
class GetTiersUseCase
|
||||
implements UseCase<DataState<List<TableTier>>, NoParams> {
|
||||
final GameRepository repository;
|
||||
GetTiersUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<List<TableTier>>> call(NoParams params) =>
|
||||
repository.getTiers();
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/network/ws_client.dart';
|
||||
import '../../domain/entities/game_entities.dart';
|
||||
import '../../domain/repository/game_repository.dart';
|
||||
import 'game_event.dart';
|
||||
import 'game_state.dart';
|
||||
|
||||
/// بلوکِ realtime بازی: به استریمِ پیامها/وضعیتِ repository گوش میدهد و
|
||||
/// اقدامهای بازیکن را به سرور میفرستد. متدهای کمکی برای موتور Flame هم دارد.
|
||||
class GameBloc extends Bloc<GameEvent, GameUiState> {
|
||||
final GameRepository repository;
|
||||
late final StreamSubscription _msgSub;
|
||||
late final StreamSubscription _statusSub;
|
||||
|
||||
Map<String, dynamic> _joinAction = const {};
|
||||
bool _joined = false;
|
||||
|
||||
GameBloc(this.repository) : super(const GameUiState()) {
|
||||
_msgSub =
|
||||
repository.messages.listen((m) => add(GameMessageReceived(m)));
|
||||
_statusSub =
|
||||
repository.status.listen((s) => add(GameStatusChanged(s)));
|
||||
|
||||
on<ConnectGameEvent>((event, emit) async {
|
||||
_joinAction = event.joinAction;
|
||||
_joined = false;
|
||||
await repository.connect();
|
||||
});
|
||||
|
||||
on<GameStatusChanged>((event, emit) {
|
||||
emit(state.copyWith(connection: event.status));
|
||||
if (event.status == WsStatus.connected && !_joined) {
|
||||
_joined = true;
|
||||
repository.send(_joinAction);
|
||||
}
|
||||
});
|
||||
|
||||
on<GameMessageReceived>((event, emit) => _onMessage(event.message, emit));
|
||||
|
||||
on<ChooseTrumpEvent>(
|
||||
(event, emit) => repository.send({'type': 'choose_trump', 'suit': event.suit}));
|
||||
on<PlayCardEvent>(
|
||||
(event, emit) => repository.send({'type': 'play_card', 'card': event.card}));
|
||||
on<LeaveGameEvent>((event, emit) => repository.send({'type': 'leave'}));
|
||||
on<StartTableEvent>((event, emit) => repository.send({'type': 'start_table'}));
|
||||
on<LeaveTableEvent>((event, emit) => repository.send({'type': 'leave_table'}));
|
||||
on<ClearNoticeEvent>((event, emit) => emit(state.copyWith(clearNotice: true)));
|
||||
}
|
||||
|
||||
void _onMessage(Map<String, dynamic> msg, Emitter<GameUiState> emit) {
|
||||
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 'table_lobby':
|
||||
emit(state.copyWith(lobby: TableLobby.fromJson(msg)));
|
||||
case 'countdown':
|
||||
emit(state.copyWith(countdown: (msg['seconds'] ?? 3) as int));
|
||||
case 'table_closed':
|
||||
emit(state.copyWith(
|
||||
tableClosed: true, notice: 'میز توسط میزبان بسته شد'));
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
// --- متدهای کمکی برای موتور Flame و صفحهها ---
|
||||
void chooseTrump(String suit) => add(ChooseTrumpEvent(suit));
|
||||
void playCard(String card) => add(PlayCardEvent(card));
|
||||
void leave() => add(LeaveGameEvent());
|
||||
void startTable() => add(StartTableEvent());
|
||||
void leaveTable() => add(LeaveTableEvent());
|
||||
void clearNotice() => add(ClearNoticeEvent());
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_msgSub.cancel();
|
||||
_statusSub.cancel();
|
||||
repository.disconnect();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import '../../../../core/network/ws_client.dart';
|
||||
|
||||
abstract class GameEvent {}
|
||||
|
||||
/// شروع اتصال با اقدامِ ورود (join_queue / create_table / join_table).
|
||||
class ConnectGameEvent extends GameEvent {
|
||||
final Map<String, dynamic> joinAction;
|
||||
ConnectGameEvent(this.joinAction);
|
||||
}
|
||||
|
||||
/// پیام دریافتی از سرور (داخلی).
|
||||
class GameMessageReceived extends GameEvent {
|
||||
final Map<String, dynamic> message;
|
||||
GameMessageReceived(this.message);
|
||||
}
|
||||
|
||||
/// تغییر وضعیت اتصال (داخلی).
|
||||
class GameStatusChanged extends GameEvent {
|
||||
final WsStatus status;
|
||||
GameStatusChanged(this.status);
|
||||
}
|
||||
|
||||
class ChooseTrumpEvent extends GameEvent {
|
||||
final String suit;
|
||||
ChooseTrumpEvent(this.suit);
|
||||
}
|
||||
|
||||
class PlayCardEvent extends GameEvent {
|
||||
final String card;
|
||||
PlayCardEvent(this.card);
|
||||
}
|
||||
|
||||
class LeaveGameEvent extends GameEvent {}
|
||||
|
||||
class StartTableEvent extends GameEvent {}
|
||||
|
||||
class LeaveTableEvent extends GameEvent {}
|
||||
|
||||
class ClearNoticeEvent extends GameEvent {}
|
||||
@@ -0,0 +1,98 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
|
||||
import '../../../../core/network/ws_client.dart';
|
||||
import '../../domain/entities/game_entities.dart';
|
||||
|
||||
/// یک بازیکن در اتاق انتظارِ میز خصوصی.
|
||||
class LobbyPlayer {
|
||||
final String name;
|
||||
final bool host;
|
||||
const LobbyPlayer(this.name, this.host);
|
||||
}
|
||||
|
||||
/// وضعیت اتاق انتظارِ میز خصوصی (دورهمی).
|
||||
class TableLobby {
|
||||
final String code;
|
||||
final List<LobbyPlayer> players;
|
||||
final bool isHost;
|
||||
final int remaining;
|
||||
final bool unlimited;
|
||||
const TableLobby({
|
||||
required this.code,
|
||||
required this.players,
|
||||
required this.isHost,
|
||||
required this.remaining,
|
||||
required this.unlimited,
|
||||
});
|
||||
|
||||
factory TableLobby.fromJson(Map<String, dynamic> j) => TableLobby(
|
||||
code: (j['code'] ?? '') as String,
|
||||
players: ((j['players'] as List?) ?? [])
|
||||
.map((e) => LobbyPlayer(
|
||||
(e['name'] ?? '') as String, (e['host'] ?? false) as bool))
|
||||
.toList(),
|
||||
isHost: (j['host'] ?? false) as bool,
|
||||
remaining: (j['remaining'] ?? 0) as int,
|
||||
unlimited: (j['unlimited'] ?? false) as bool,
|
||||
);
|
||||
|
||||
String get sig => '$code|$isHost|$remaining|$unlimited|'
|
||||
'${players.map((p) => '${p.name}${p.host ? '*' : ''}').join(',')}';
|
||||
}
|
||||
|
||||
class GameUiState extends Equatable {
|
||||
final WsStatus connection;
|
||||
final GameState? state;
|
||||
final HandResult? handResult;
|
||||
final GameOver? gameOver;
|
||||
final String? notice;
|
||||
final TableLobby? lobby;
|
||||
final int? countdown;
|
||||
final bool tableClosed;
|
||||
|
||||
const GameUiState({
|
||||
this.connection = WsStatus.connecting,
|
||||
this.state,
|
||||
this.handResult,
|
||||
this.gameOver,
|
||||
this.notice,
|
||||
this.lobby,
|
||||
this.countdown,
|
||||
this.tableClosed = false,
|
||||
});
|
||||
|
||||
GameUiState copyWith({
|
||||
WsStatus? connection,
|
||||
GameState? state,
|
||||
HandResult? handResult,
|
||||
GameOver? gameOver,
|
||||
String? notice,
|
||||
TableLobby? lobby,
|
||||
int? countdown,
|
||||
bool? tableClosed,
|
||||
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),
|
||||
lobby: lobby ?? this.lobby,
|
||||
countdown: countdown ?? this.countdown,
|
||||
tableClosed: tableClosed ?? this.tableClosed,
|
||||
);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
connection,
|
||||
state,
|
||||
handResult,
|
||||
gameOver,
|
||||
notice,
|
||||
lobby?.sig,
|
||||
countdown,
|
||||
tableClosed,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../../domain/entities/table_entities.dart';
|
||||
import '../../domain/use_cases/get_tables_info_usecase.dart';
|
||||
|
||||
abstract class PrivateInfoEvent {}
|
||||
|
||||
class LoadTablesInfoEvent extends PrivateInfoEvent {}
|
||||
|
||||
abstract class PrivateInfoState {}
|
||||
|
||||
class PrivateInfoInitial extends PrivateInfoState {}
|
||||
|
||||
class PrivateInfoLoading extends PrivateInfoState {}
|
||||
|
||||
class PrivateInfoLoaded extends PrivateInfoState {
|
||||
final TablesInfo info;
|
||||
PrivateInfoLoaded(this.info);
|
||||
}
|
||||
|
||||
class PrivateInfoError extends PrivateInfoState {
|
||||
final String message;
|
||||
PrivateInfoError(this.message);
|
||||
}
|
||||
|
||||
class PrivateInfoBloc extends Bloc<PrivateInfoEvent, PrivateInfoState> {
|
||||
final GetTablesInfoUseCase getTablesInfoUseCase;
|
||||
PrivateInfoBloc(this.getTablesInfoUseCase) : super(PrivateInfoInitial()) {
|
||||
on<LoadTablesInfoEvent>((event, emit) async {
|
||||
emit(PrivateInfoLoading());
|
||||
final res = await getTablesInfoUseCase(const NoParams());
|
||||
if (res is DataSuccess) {
|
||||
emit(PrivateInfoLoaded(res.data!));
|
||||
} else {
|
||||
emit(PrivateInfoError(res.error!));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../../domain/entities/table_entities.dart';
|
||||
import '../../domain/use_cases/get_tiers_usecase.dart';
|
||||
|
||||
abstract class TierEvent {}
|
||||
|
||||
class LoadTiersEvent extends TierEvent {}
|
||||
|
||||
abstract class TierState {}
|
||||
|
||||
class TierInitial extends TierState {}
|
||||
|
||||
class TierLoading extends TierState {}
|
||||
|
||||
class TierLoaded extends TierState {
|
||||
final List<TableTier> tiers;
|
||||
TierLoaded(this.tiers);
|
||||
}
|
||||
|
||||
class TierError extends TierState {
|
||||
final String message;
|
||||
TierError(this.message);
|
||||
}
|
||||
|
||||
class TierBloc extends Bloc<TierEvent, TierState> {
|
||||
final GetTiersUseCase getTiersUseCase;
|
||||
TierBloc(this.getTiersUseCase) : super(TierInitial()) {
|
||||
on<LoadTiersEvent>((event, emit) async {
|
||||
emit(TierLoading());
|
||||
final res = await getTiersUseCase(const NoParams());
|
||||
if (res is DataSuccess) {
|
||||
emit(TierLoaded(res.data!));
|
||||
} else {
|
||||
emit(TierError(res.error!));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,378 @@
|
||||
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 '../../../wallet/presentation/bloc/wallet_bloc.dart';
|
||||
import '../../../wallet/presentation/bloc/wallet_event.dart';
|
||||
import '../../domain/entities/game_entities.dart';
|
||||
import '../bloc/game_bloc.dart';
|
||||
import '../bloc/game_state.dart';
|
||||
import '../widgets/flame/hokm_game.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<GameBloc>());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_introTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool _showSearch(GameUiState s) => s.state == null || !_introHidden;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return PopScope(
|
||||
canPop: false,
|
||||
onPopInvokedWithResult: (didPop, _) {
|
||||
if (!didPop) _confirmLeave(context);
|
||||
},
|
||||
child: Scaffold(
|
||||
body: BlocConsumer<GameBloc, 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<GameBloc>().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<GameBloc>().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<GameBloc>().leave();
|
||||
_exitToLobby(context);
|
||||
}
|
||||
}
|
||||
|
||||
void _exitToLobby(BuildContext context) {
|
||||
context.read<WalletBloc>().add(LoadWalletEvent());
|
||||
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<GameBloc>().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)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 6),
|
||||
child: Text(
|
||||
r.hakemKot
|
||||
? 'حاکمکُت! (${r.points} امتیاز)'
|
||||
: 'کُت! (${r.points} امتیاز)',
|
||||
style: const 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,167 @@
|
||||
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 '../../../../core/widgets/game_ui.dart';
|
||||
import '../bloc/private_info_bloc.dart';
|
||||
|
||||
/// صفحهی دورهمی: پیوستن با شماره میز یا ساختِ میز جدید.
|
||||
class PrivateEntryScreen extends StatefulWidget {
|
||||
const PrivateEntryScreen({super.key});
|
||||
|
||||
@override
|
||||
State<PrivateEntryScreen> createState() => _PrivateEntryScreenState();
|
||||
}
|
||||
|
||||
class _PrivateEntryScreenState extends State<PrivateEntryScreen> {
|
||||
final _code = TextEditingController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
context.read<PrivateInfoBloc>().add(LoadTablesInfoEvent());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_code.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _join() {
|
||||
final code = _code.text.trim();
|
||||
if (code.length < 4) return;
|
||||
context.push('/private/room?join=$code');
|
||||
}
|
||||
|
||||
void _create(bool canCreate) {
|
||||
if (!canCreate) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
|
||||
content:
|
||||
Text('سهمیهی میزهای رایگان تمام شده؛ با VIP نامحدود بسازید')));
|
||||
return;
|
||||
}
|
||||
context.push('/private/room?create=1').then((_) {
|
||||
if (mounted) {
|
||||
context.read<PrivateInfoBloc>().add(LoadTablesInfoEvent());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: GameBackground(
|
||||
child: SafeArea(
|
||||
child: BlocBuilder<PrivateInfoBloc, PrivateInfoState>(
|
||||
builder: (context, state) {
|
||||
final loading = state is! PrivateInfoLoaded;
|
||||
final unlimited =
|
||||
state is PrivateInfoLoaded && state.info.unlimited;
|
||||
final remaining =
|
||||
state is PrivateInfoLoaded ? state.info.remaining : 0;
|
||||
final canCreate = unlimited || remaining > 0;
|
||||
return Column(
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: GestureDetector(
|
||||
onTap: () => context.pop(),
|
||||
child: Container(
|
||||
width: 46,
|
||||
height: 46,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.panel,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border:
|
||||
Border.all(color: AppColors.gold, width: 1.5),
|
||||
),
|
||||
child: const Icon(Icons.arrow_back,
|
||||
color: AppColors.gold),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 24),
|
||||
child: Column(
|
||||
children: [
|
||||
const SizedBox(height: 8),
|
||||
const Icon(Icons.person,
|
||||
color: AppColors.gold, size: 56),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _code,
|
||||
textAlign: TextAlign.center,
|
||||
keyboardType: TextInputType.number,
|
||||
style: const TextStyle(
|
||||
fontSize: 22, letterSpacing: 6),
|
||||
inputFormatters: [
|
||||
FilteringTextInputFormatter.digitsOnly,
|
||||
LengthLimitingTextInputFormatter(5),
|
||||
],
|
||||
decoration:
|
||||
const InputDecoration(hintText: 'شماره میز'),
|
||||
onChanged: (_) => setState(() {}),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
GameButton(
|
||||
label: 'پیوستن',
|
||||
width: double.infinity,
|
||||
colors: const [Color(0xFFC2185B), Color(0xFF6A0D38)],
|
||||
onTap: _code.text.trim().length >= 4 ? _join : null,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text('برای ورود، شماره میز را وارد کنید.',
|
||||
style: TextStyle(
|
||||
color: Colors.white60, fontSize: 13)),
|
||||
const SizedBox(height: 24),
|
||||
Divider(
|
||||
color: AppColors.goldDark.withValues(alpha: 0.5)),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
loading
|
||||
? '...'
|
||||
: unlimited
|
||||
? 'میزهای نامحدود (VIP)'
|
||||
: 'میزهای رایگان باقیمانده: $remaining',
|
||||
style: const TextStyle(
|
||||
color: AppColors.gold,
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
const Icon(Icons.groups,
|
||||
color: AppColors.gold, size: 56),
|
||||
const SizedBox(height: 12),
|
||||
GameButton(
|
||||
label: 'ساخت میز',
|
||||
width: double.infinity,
|
||||
colors: canCreate
|
||||
? const [Color(0xFFC2185B), Color(0xFF6A0D38)]
|
||||
: const [Color(0xFF555555), Color(0xFF333333)],
|
||||
onTap: loading ? null : () => _create(canCreate),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
const Text('میز جدید بساز و دوستانت را دعوت کن',
|
||||
style: TextStyle(
|
||||
color: Colors.white60, fontSize: 13)),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
import 'dart:async';
|
||||
|
||||
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/network/ws_client.dart';
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../../../core/widgets/game_ui.dart';
|
||||
import '../bloc/game_bloc.dart';
|
||||
import '../bloc/game_state.dart';
|
||||
import 'game_screen.dart';
|
||||
|
||||
/// میز خصوصی: اتاق انتظار (کد، بازیکنان، شروع) سپس صحنهی بازی (روی همان اتصال).
|
||||
class PrivateTableScreen extends StatelessWidget {
|
||||
const PrivateTableScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocConsumer<GameBloc, GameUiState>(
|
||||
listenWhen: (a, b) =>
|
||||
(a.notice != b.notice && b.notice != null) ||
|
||||
(!a.tableClosed && b.tableClosed),
|
||||
listener: (context, state) {
|
||||
if (state.tableClosed) {
|
||||
if (context.canPop()) context.pop();
|
||||
return;
|
||||
}
|
||||
if (state.notice != null) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text(state.notice!),
|
||||
duration: const Duration(seconds: 2)));
|
||||
context.read<GameBloc>().clearNotice();
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
if (state.state != null) {
|
||||
return const GameScreen(prize: 0);
|
||||
}
|
||||
return _LobbyView(state: state);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _LobbyView extends StatelessWidget {
|
||||
final GameUiState state;
|
||||
const _LobbyView({required this.state});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final lobby = state.lobby;
|
||||
final connecting = state.connection != WsStatus.connected || lobby == null;
|
||||
|
||||
return PopScope(
|
||||
canPop: false,
|
||||
onPopInvokedWithResult: (didPop, _) {
|
||||
if (didPop) return;
|
||||
context.read<GameBloc>().leaveTable();
|
||||
if (context.canPop()) context.pop();
|
||||
},
|
||||
child: Scaffold(
|
||||
body: GameBackground(
|
||||
child: SafeArea(
|
||||
child: Stack(
|
||||
children: [
|
||||
Column(
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(10),
|
||||
child: GestureDetector(
|
||||
onTap: () {
|
||||
context.read<GameBloc>().leaveTable();
|
||||
if (context.canPop()) context.pop();
|
||||
},
|
||||
child: Container(
|
||||
width: 46,
|
||||
height: 46,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.panel,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border:
|
||||
Border.all(color: AppColors.gold, width: 1.5),
|
||||
),
|
||||
child: const Icon(Icons.arrow_back,
|
||||
color: AppColors.gold),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: connecting
|
||||
? const Center(
|
||||
child: CircularProgressIndicator(
|
||||
color: AppColors.gold))
|
||||
: _content(context, lobby),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (state.countdown != null)
|
||||
_CountdownOverlay(seconds: state.countdown!),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _content(BuildContext context, TableLobby lobby) {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 20),
|
||||
child: Column(
|
||||
children: [
|
||||
const GlowText('میز دورهمی', size: 26),
|
||||
const SizedBox(height: 16),
|
||||
GamePanel(
|
||||
child: Column(children: [
|
||||
const Text('شماره میز', style: TextStyle(color: Colors.white70)),
|
||||
const SizedBox(height: 6),
|
||||
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
SelectableText(lobby.code,
|
||||
style: const TextStyle(
|
||||
color: AppColors.gold,
|
||||
fontSize: 40,
|
||||
fontWeight: FontWeight.bold,
|
||||
letterSpacing: 8)),
|
||||
IconButton(
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: lobby.code));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('کد کپی شد')));
|
||||
},
|
||||
icon: const Icon(Icons.copy, color: AppColors.gold),
|
||||
),
|
||||
]),
|
||||
const Text('این کد را برای دوستانت بفرست',
|
||||
style: TextStyle(color: Colors.white54, fontSize: 12)),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
GamePanel(
|
||||
child: Column(children: [
|
||||
for (var i = 0; i < 4; i++) _seatRow(i, lobby),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
if (lobby.isHost)
|
||||
GameButton(
|
||||
label: 'شروع بازی',
|
||||
icon: Icons.play_arrow,
|
||||
width: double.infinity,
|
||||
colors: const [Color(0xFF3FA34D), Color(0xFF1B5E20)],
|
||||
onTap: () => context.read<GameBloc>().startTable(),
|
||||
)
|
||||
else
|
||||
const Text('در انتظار شروع توسط میزبان…',
|
||||
style: TextStyle(color: AppColors.gold, fontSize: 15)),
|
||||
const SizedBox(height: 8),
|
||||
if (lobby.isHost)
|
||||
const Text('جایهای خالی با ربات پر میشوند',
|
||||
style: TextStyle(color: Colors.white54, fontSize: 12)),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _seatRow(int i, TableLobby lobby) {
|
||||
final filled = i < lobby.players.length;
|
||||
final p = filled ? lobby.players[i] : null;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 6),
|
||||
child: Row(children: [
|
||||
Icon(filled ? Icons.person : Icons.person_outline,
|
||||
color: filled ? AppColors.gold : Colors.white24, size: 24),
|
||||
const SizedBox(width: 10),
|
||||
Text(
|
||||
filled ? p!.name : 'در انتظار بازیکن…',
|
||||
style: TextStyle(
|
||||
color: filled ? Colors.white : Colors.white38,
|
||||
fontSize: 15,
|
||||
fontWeight: filled ? FontWeight.bold : FontWeight.normal),
|
||||
),
|
||||
const Spacer(),
|
||||
if (p?.host == true)
|
||||
const Icon(Icons.star, color: AppColors.gold, size: 18),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// اوورلی شمارش معکوس ۳، ۲، ۱ پیش از شروع بازی.
|
||||
class _CountdownOverlay extends StatefulWidget {
|
||||
final int seconds;
|
||||
const _CountdownOverlay({required this.seconds});
|
||||
|
||||
@override
|
||||
State<_CountdownOverlay> createState() => _CountdownOverlayState();
|
||||
}
|
||||
|
||||
class _CountdownOverlayState extends State<_CountdownOverlay> {
|
||||
late int _n;
|
||||
Timer? _timer;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_n = widget.seconds;
|
||||
_timer = Timer.periodic(const Duration(seconds: 1), (_) {
|
||||
if (!mounted) return;
|
||||
setState(() => _n--);
|
||||
if (_n <= 0) _timer?.cancel();
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
color: Colors.black.withValues(alpha: 0.7),
|
||||
alignment: Alignment.center,
|
||||
child: TweenAnimationBuilder<double>(
|
||||
key: ValueKey(_n),
|
||||
tween: Tween(begin: 0.4, end: 1.2),
|
||||
duration: const Duration(milliseconds: 700),
|
||||
curve: Curves.easeOut,
|
||||
builder: (context, scale, child) =>
|
||||
Transform.scale(scale: scale, child: child),
|
||||
child: GlowText(_n > 0 ? '$_n' : 'شروع!', size: 96),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
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 '../../../../core/widgets/game_ui.dart';
|
||||
import '../../domain/entities/table_entities.dart';
|
||||
import '../bloc/tier_bloc.dart';
|
||||
|
||||
/// لیست میزها (tierها) با ورودی/جایزه؛ انتخاب → ورود به میز.
|
||||
class TierListScreen extends StatelessWidget {
|
||||
const TierListScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: GameBackground(
|
||||
child: Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Row(children: [
|
||||
_BackButton(onTap: () => context.pop()),
|
||||
const Spacer(),
|
||||
const GlowText('انتخاب میز', size: 26),
|
||||
const Spacer(),
|
||||
const SizedBox(width: 48),
|
||||
]),
|
||||
),
|
||||
Expanded(
|
||||
child: BlocBuilder<TierBloc, TierState>(
|
||||
builder: (context, state) {
|
||||
if (state is TierError) {
|
||||
return Center(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text(state.message),
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
context.read<TierBloc>().add(LoadTiersEvent()),
|
||||
child: const Text('تلاش مجدد'),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (state is! TierLoaded) {
|
||||
return const Center(
|
||||
child:
|
||||
CircularProgressIndicator(color: AppColors.gold));
|
||||
}
|
||||
final tiers = state.tiers;
|
||||
return ListView.separated(
|
||||
padding: const EdgeInsets.fromLTRB(16, 4, 16, 20),
|
||||
itemCount: tiers.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 14),
|
||||
itemBuilder: (_, i) => _TierCard(tier: tiers[i], index: i),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BackButton extends StatelessWidget {
|
||||
final VoidCallback onTap;
|
||||
const _BackButton({required this.onTap});
|
||||
@override
|
||||
Widget build(BuildContext context) => GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.panel,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: AppColors.gold, width: 1.5),
|
||||
),
|
||||
child: const Icon(Icons.arrow_back, color: AppColors.gold),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _TierCard extends StatelessWidget {
|
||||
final TableTier tier;
|
||||
final int index;
|
||||
const _TierCard({required this.tier, required this.index});
|
||||
|
||||
static const _palettes = [
|
||||
[Color(0xFF43A047), Color(0xFF1B5E20)],
|
||||
[Color(0xFFE53935), Color(0xFF8E0E1B)],
|
||||
[Color(0xFF1E88E5), Color(0xFF0D3C73)],
|
||||
[Color(0xFF8E24AA), Color(0xFF4A0D5E)],
|
||||
];
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = _palettes[index % _palettes.length];
|
||||
return GestureDetector(
|
||||
onTap: () => context.push('/game/${tier.id}?prize=${tier.prize}'),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.fromLTRB(14, 12, 14, 12),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: colors,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: AppColors.gold, width: 2),
|
||||
boxShadow: const [
|
||||
BoxShadow(
|
||||
color: Colors.black54, blurRadius: 10, offset: Offset(0, 5)),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFFE9952F),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: AppColors.gold),
|
||||
),
|
||||
child: Column(children: [
|
||||
Text('${tier.hands}',
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold)),
|
||||
const Text('دست',
|
||||
style: TextStyle(color: Colors.white, fontSize: 11)),
|
||||
]),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(tier.title,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
shadows: [Shadow(color: Colors.black54, blurRadius: 3)],
|
||||
)),
|
||||
const SizedBox(height: 6),
|
||||
_stat(Icons.login, 'ورودی', tier.entry),
|
||||
_stat(Icons.monetization_on, 'جایزه', tier.prize),
|
||||
],
|
||||
),
|
||||
const Spacer(),
|
||||
Column(children: [
|
||||
_badge(Icons.star, 'XP ${tier.xp}'),
|
||||
const SizedBox(height: 6),
|
||||
_badge(Icons.emoji_events, '${tier.trophy}'),
|
||||
]),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _stat(IconData icon, String label, int value) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Icon(icon, size: 15, color: AppColors.gold),
|
||||
const SizedBox(width: 5),
|
||||
Text('$label: $value',
|
||||
style: const TextStyle(color: Colors.white, fontSize: 13)),
|
||||
]),
|
||||
);
|
||||
|
||||
Widget _badge(IconData icon, String text) => Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 16, color: AppColors.gold),
|
||||
const SizedBox(width: 4),
|
||||
Text(text, style: const TextStyle(color: Colors.white, fontSize: 12)),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// توابع کمکیِ خالصِ کدِ کوتاهِ کارتها (مثل "AS", "10H", "KD").
|
||||
// بدون وابستگی به Flame/Flutter تا قابلتست و بازاستفاده باشد.
|
||||
|
||||
/// نسبت ابعاد تصویرِ کارت (۵۰۰×۷۲۶ منبع).
|
||||
const double kCardRatio = 726 / 500;
|
||||
|
||||
/// نام کاملِ خال از روی آخرین حرفِ کد: S/H/D/C.
|
||||
String suitName(String code) {
|
||||
switch (code[code.length - 1]) {
|
||||
case 'H':
|
||||
return 'hearts';
|
||||
case 'D':
|
||||
return 'diamonds';
|
||||
case 'C':
|
||||
return 'clubs';
|
||||
default:
|
||||
return 'spades';
|
||||
}
|
||||
}
|
||||
|
||||
/// رتبهی عددی کارت (۲..۱۰ معمولی، J=11، Q=12، K=13، A=14).
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// ترتیب خالها برای چیدنِ دست (سیاه/قرمز متناوب تا تفکیک بصری راحتتر باشد).
|
||||
const _suitOrder = {'S': 0, 'H': 1, 'C': 2, 'D': 3};
|
||||
|
||||
/// مقایسه برای مرتبسازی کارتهای دست: ابتدا خال، سپس رتبه.
|
||||
int compareCards(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);
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
import 'package:flame/components.dart';
|
||||
import 'package:flame/effects.dart';
|
||||
import 'package:flame/events.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// یک کارت روی میز؛ اگر تصویر `assets/images/cards/<code>.png` موجود باشد از آن
|
||||
/// استفاده میکند، وگرنه نسخهی برداری میکشد. برای پشت کارت `back.jpg`.
|
||||
/// کارتهای قابلبازی فقط با **کشیدن (drag)** به سمت زمین بازی میشوند (نه tap).
|
||||
class CardComponent extends PositionComponent
|
||||
with DragCallbacks, HasGameReference {
|
||||
final String code; // مثل "AS"؛ برای پشت کارت خالی
|
||||
final bool faceUp;
|
||||
VoidCallback? onPlay; // در صورت مجاز بودن، بازیِ این کارت
|
||||
bool dimmed; // کارت غیرمجاز/غیرفعال
|
||||
Vector2? home; // موقعیت اصلی در دست (برای برگشت پس از کشیدنِ ناقص)
|
||||
int restPriority = 0; // ترتیب لایهی اصلی در دست (برای بازگردانی پس از کشیدن)
|
||||
Rect? dropZone; // ناحیهی وسط میز؛ رهاکردن کارت در آن یعنی بازی
|
||||
Sprite? _sprite;
|
||||
bool _dragging = false;
|
||||
bool _overZone = false; // کارت روی ناحیهی انداختن است (برای هایلایت)
|
||||
|
||||
CardComponent({
|
||||
required this.code,
|
||||
required this.faceUp,
|
||||
this.onPlay,
|
||||
this.dimmed = false,
|
||||
super.position,
|
||||
super.size,
|
||||
super.angle,
|
||||
super.priority,
|
||||
super.anchor = Anchor.center,
|
||||
});
|
||||
|
||||
bool get _playable => onPlay != null && !dimmed;
|
||||
|
||||
@override
|
||||
Future<void> onLoad() async {
|
||||
try {
|
||||
_sprite = await game.loadSprite(faceUp ? 'cards/$code.png' : 'cards/back.jpg');
|
||||
} catch (_) {
|
||||
_sprite = null; // fallback برداری
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void onDragStart(DragStartEvent event) {
|
||||
super.onDragStart(event);
|
||||
if (!_playable) return;
|
||||
_dragging = true;
|
||||
priority = 1000; // روی همهی کارتها
|
||||
scale = Vector2.all(1.12); // بزرگنمایی هنگام کشیدن (فیدبک)
|
||||
}
|
||||
|
||||
@override
|
||||
void onDragUpdate(DragUpdateEvent event) {
|
||||
if (!_dragging) return;
|
||||
position += event.localDelta;
|
||||
_overZone = _inDropZone();
|
||||
}
|
||||
|
||||
@override
|
||||
void onDragEnd(DragEndEvent event) {
|
||||
super.onDragEnd(event);
|
||||
if (!_dragging) return;
|
||||
_dragging = false;
|
||||
scale = Vector2.all(1);
|
||||
// فقط اگر داخل ناحیهی وسط میز رها شد ⇒ بازی؛ وگرنه برگشت به جای مرتبِ خود.
|
||||
if (_inDropZone()) {
|
||||
onPlay?.call();
|
||||
} else {
|
||||
_returnHome();
|
||||
}
|
||||
_overZone = false;
|
||||
}
|
||||
|
||||
@override
|
||||
void onDragCancel(DragCancelEvent event) {
|
||||
super.onDragCancel(event);
|
||||
if (!_dragging) return;
|
||||
_dragging = false;
|
||||
_overZone = false;
|
||||
scale = Vector2.all(1);
|
||||
_returnHome();
|
||||
}
|
||||
|
||||
bool _inDropZone() {
|
||||
final z = dropZone;
|
||||
if (z != null) return z.contains(position.toOffset());
|
||||
return position.y < game.size.y * 0.72; // fallback
|
||||
}
|
||||
|
||||
void _returnHome() {
|
||||
priority = restPriority; // بازگردانی ترتیب لایه تا روی کارتهای دیگر نیفتد
|
||||
if (home == null) return;
|
||||
add(MoveToEffect(home!, EffectController(duration: 0.2, curve: Curves.easeOut)));
|
||||
}
|
||||
|
||||
@override
|
||||
void render(Canvas canvas) {
|
||||
final rect = size.toRect();
|
||||
final radius = Radius.circular(size.x * 0.09);
|
||||
final rrect = RRect.fromRectAndRadius(rect, radius);
|
||||
|
||||
// سایهی سبک و ارزان (بدون blurِ هر-فریمی) فقط برای کارتهای رو ⇒ عمق بدون افت کارایی.
|
||||
// (drawShadow هر فریم برای دهها کارت بسیار سنگین بود و باعث لگ میشد.)
|
||||
if (faceUp) {
|
||||
final off = _dragging ? size.x * 0.10 : size.x * 0.03;
|
||||
canvas.drawRRect(rrect.shift(Offset(off * 0.4, off)),
|
||||
Paint()..color = Color(_dragging ? 0x66000000 : 0x44000000));
|
||||
}
|
||||
|
||||
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 (faceUp) {
|
||||
canvas.save();
|
||||
canvas.clipRRect(rrect);
|
||||
canvas.drawRect(
|
||||
Rect.fromLTWH(0, 0, size.x, size.y * 0.5),
|
||||
Paint()
|
||||
..shader = const LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Color(0x2BFFFFFF), Color(0x00FFFFFF)],
|
||||
).createShader(Rect.fromLTWH(0, 0, size.x, size.y * 0.5)),
|
||||
);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
if (dimmed) {
|
||||
canvas.drawRRect(rrect, Paint()..color = const Color(0x73000000));
|
||||
}
|
||||
canvas.drawRRect(
|
||||
rrect,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = 1.5
|
||||
..color = const Color(0xFF1A1A1A),
|
||||
);
|
||||
|
||||
// هایلایت طلایی وقتی کارت روی ناحیهی انداختن است (رهاکنی، بازی میشود).
|
||||
if (_dragging && _overZone) {
|
||||
canvas.drawRRect(
|
||||
rrect,
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = size.x * 0.06
|
||||
..color = const Color(0xFFE9B949)
|
||||
..maskFilter = const MaskFilter.blur(BlurStyle.normal, 6),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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,475 @@
|
||||
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:flame_audio/flame_audio.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../domain/entities/game_entities.dart';
|
||||
import '../../bloc/game_bloc.dart';
|
||||
import 'card_codes.dart';
|
||||
import 'card_component.dart';
|
||||
import 'table_pieces.dart';
|
||||
|
||||
/// صحنهی میز حکم با انیمیشن. شما همیشه پایین میز (rel=0) هستید.
|
||||
/// کامپوننتهای دست و trick ماندگارند و با افکت حرکت جابهجا میشوند.
|
||||
///
|
||||
/// این کلاس فقط «وضعیتِ سرور → چیدمانِ صحنه» را مدیریت میکند:
|
||||
/// - [_layoutHand] / [_layoutTrick] کارتهای دست و زمین (ماندگار، با انیمیشن).
|
||||
/// - [_rebuildBacksAndInfo] عناصرِ بازساختهشونده (پشتکارت، شمارندهها، برچسبها).
|
||||
/// - [_checkCut] + [update]/[render] افکتِ «بریدن با حکم» (تکان + رعد).
|
||||
class HokmGame extends FlameGame {
|
||||
final GameBloc cubit;
|
||||
|
||||
// وضعیت بازی و اشتراکِ stream.
|
||||
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;
|
||||
List<String> _prevTrick = const [];
|
||||
int _prevHandSize = 0; // برای تشخیصِ پخشِ کارت (دستِ جدید) جهت صدای بُر زدن
|
||||
|
||||
HokmGame(this.cubit);
|
||||
|
||||
@override
|
||||
Color backgroundColor() => const Color(0xFF2C0A10);
|
||||
|
||||
@override
|
||||
Future<void> onLoad() async {
|
||||
add(Felt());
|
||||
// پیشبارگذاریِ صدای بُر زدن (در صورت نبودِ فایل، بیصدا رد میشود).
|
||||
FlameAudio.audioCache.load('shuffle.mp3').catchError((_) => Uri());
|
||||
_sub = cubit.stream.listen((ui) {
|
||||
if (ui.state == null) return;
|
||||
final s = ui.state!;
|
||||
_checkCut(s);
|
||||
// شروعِ دستِ جدید (پخشِ کارت): صدای بُر زدن.
|
||||
if (_prevHandSize == 0 && s.yourHand.isNotEmpty) _playShuffle();
|
||||
_prevHandSize = s.yourHand.length;
|
||||
_s = s;
|
||||
_relayout();
|
||||
});
|
||||
if (cubit.state.state != null) {
|
||||
_prevTrick = cubit.state.state!.trick.map((t) => t.card).toList();
|
||||
_prevHandSize = cubit.state.state!.yourHand.length;
|
||||
_s = cubit.state.state;
|
||||
_relayout();
|
||||
}
|
||||
}
|
||||
|
||||
void _playShuffle() {
|
||||
// اگر فایل صدا نباشد، خطا نادیده گرفته میشود (بازی بیصدا).
|
||||
FlameAudio.play('shuffle.mp3', volume: 0.7).then((_) {}, onError: (_) {});
|
||||
}
|
||||
|
||||
@override
|
||||
void onGameResize(Vector2 size) {
|
||||
super.onGameResize(size);
|
||||
if (isLoaded) _relayout();
|
||||
}
|
||||
|
||||
@override
|
||||
void onRemove() {
|
||||
_sub?.cancel();
|
||||
super.onRemove();
|
||||
}
|
||||
|
||||
// ===== افکتِ بریدن با حکم (تکان + رعد) =====
|
||||
|
||||
// اگر دقیقاً یک کارتِ تازه به زمین اضافه شده و آن کارت «بُرِش با حکم» باشد
|
||||
// (خالِ زمینه آتو نیست ولی کارتِ تازه آتوست)، همان لحظه تکان + رعد.
|
||||
void _checkCut(GameState s) {
|
||||
final now = s.trick.map((t) => t.card).toList();
|
||||
final addedOne = now.length == _prevTrick.length + 1 && _isPrefix(_prevTrick, now);
|
||||
if (addedOne &&
|
||||
s.trump != null &&
|
||||
s.leadSuit != null &&
|
||||
s.leadSuit != s.trump &&
|
||||
suitName(now.last) == s.trump) {
|
||||
_shake = 1.0;
|
||||
add(Lightning());
|
||||
}
|
||||
_prevTrick = now;
|
||||
}
|
||||
|
||||
static bool _isPrefix(List<String> a, List<String> b) {
|
||||
for (var i = 0; i < a.length; i++) {
|
||||
if (a[i] != b[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@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) {
|
||||
super.render(canvas);
|
||||
return;
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
// ===== چیدمان =====
|
||||
|
||||
// جایگاهِ نسبیِ یک seat نسبت به شما: 0=پایین، 1=چپ، 2=بالا، 3=راست.
|
||||
int _rel(int seat) => (seat - _s!.yourSeat + 4) % 4;
|
||||
|
||||
void _relayout() {
|
||||
final s = _s;
|
||||
if (s == null) return;
|
||||
_cardW = size.x * 0.19;
|
||||
_cardH = _cardW * kCardRatio;
|
||||
|
||||
_rebuildBacksAndInfo(s);
|
||||
_layoutTrick(s);
|
||||
_layoutHand(s);
|
||||
}
|
||||
|
||||
// آیا این کارت در نوبتِ فعلی قابل بازی است (با رعایت follow-suit)؟
|
||||
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 _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)));
|
||||
}
|
||||
|
||||
// ناحیهی وسط میز که رهاکردنِ کارت در آن یعنی بازی (بالاتر از دستِ شما).
|
||||
Rect _dropZone() =>
|
||||
Rect.fromLTRB(size.x * 0.15, size.y * 0.22, size.x * 0.85, size.y * 0.66);
|
||||
|
||||
void _layoutHand(GameState s) {
|
||||
// مرتبسازی بر اساس خال و رتبه تا انتخاب برای بازیکن راحتتر باشد.
|
||||
final codes = List<String>.from(s.yourHand)..sort(compareCards);
|
||||
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 hw = size.x * 0.225, hh = hw * kCardRatio;
|
||||
final handW = size.x * 0.86;
|
||||
final stepX = n > 1 ? ((handW - hw) / (n - 1)).clamp(0.0, hw * 0.62) : 0.0;
|
||||
final cx = size.x / 2;
|
||||
final baseY = size.y * 0.86;
|
||||
final tMax = (n - 1) / 2;
|
||||
const edgeAngle = 0.34; // چرخشِ کارتهای کناری (رادیان)
|
||||
final dip = hh * 0.16; // افتِ عمودیِ کارتهای کناری برای قوس
|
||||
|
||||
for (var i = 0; i < n; i++) {
|
||||
final code = codes[i];
|
||||
final t = i - tMax;
|
||||
final norm = tMax > 0 ? t / tMax : 0.0;
|
||||
final target = Vector2(cx + t * stepX, baseY + norm * norm * dip);
|
||||
final legal = _legal(code);
|
||||
var c = _hand[code];
|
||||
if (c == null) {
|
||||
// کارت جدید ⇒ از مرکز میز پخش میشود.
|
||||
c = CardComponent(code: code, faceUp: true, size: Vector2(hw, hh), position: size / 2);
|
||||
_hand[code] = c;
|
||||
add(c);
|
||||
} else {
|
||||
c.size = Vector2(hw, hh);
|
||||
}
|
||||
c.angle = norm * edgeAngle; // چرخشِ بادبزنی
|
||||
c.onPlay = legal ? () => cubit.playCard(code) : null;
|
||||
c.dimmed = s.phase == 'playing' && s.isMyTurn && !legal;
|
||||
c.home = target;
|
||||
c.dropZone = _dropZone();
|
||||
c.restPriority = 10 + i;
|
||||
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)) continue;
|
||||
final c = _trick.remove(code)!;
|
||||
c.children.whereType<MoveToEffect>().toList().forEach((e) => e.removeFromParent());
|
||||
c.add(SequenceEffect([
|
||||
MoveToEffect(_seatOrigin(_rel(s.turn)),
|
||||
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.onPlay = null;
|
||||
c.dimmed = false;
|
||||
c.home = null;
|
||||
} 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.angle = 0; // کارتهای روی زمین صافاند (چرخشِ بادبزنیِ دست حذف میشود)
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
// جابهجاییِ کارتِ هر جایگاه از مرکز، در ناحیهی trick.
|
||||
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 count = seat < s.handCounts.length ? s.handCounts[seat] : 0;
|
||||
_addBacks(_rel(seat), count);
|
||||
}
|
||||
_addTricksWon(s);
|
||||
_addScorePucks(s);
|
||||
_addInfo(s);
|
||||
}
|
||||
|
||||
// شمارنده ۱: دستهای بردهی این هَند (tricks_won) — دستهکارتِ پشترو + عدد.
|
||||
// رسیدن به ۷ یعنی پایان هَند (سرور صفر میکند).
|
||||
void _addTricksWon(GameState s) {
|
||||
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.28, size.y * 0.72)
|
||||
: Vector2(size.x * 0.82, size.y * 0.24);
|
||||
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++) {
|
||||
_addBack(start + step * i.toDouble(), Vector2(w, h), priority: 2);
|
||||
}
|
||||
_addLabel('$won', base - Vector2(0, h * 0.7), _cardW * 0.34, bold: true);
|
||||
}
|
||||
}
|
||||
|
||||
// شمارنده ۲: امتیاز بازی (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 * 0.50, size.y * 0.74)
|
||||
: Vector2(size.x * 0.84, size.y * 0.44);
|
||||
final puck = ScorePuck(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++) {
|
||||
_addBack(start + stepV * i.toDouble(), Vector2(w, h), priority: 1);
|
||||
}
|
||||
}
|
||||
|
||||
void _addInfo(GameState s) {
|
||||
if (s.trump != null) {
|
||||
final (sym, col) = _trumpGlyph(s.trump!);
|
||||
_addLabel('حکم: $sym', Vector2(size.x * 0.04, size.y * 0.04), size.x * 0.05,
|
||||
color: col, anchor: Anchor.topLeft, bold: true);
|
||||
}
|
||||
final a = s.scores.isNotEmpty ? s.scores[0] : 0;
|
||||
final b = s.scores.length > 1 ? s.scores[1] : 0;
|
||||
_addLabel('$a - $b', Vector2(size.x / 2, size.y * 0.04), size.x * 0.05,
|
||||
anchor: Anchor.topCenter);
|
||||
|
||||
for (final p in s.players) {
|
||||
final pos = _seatLabelPos(_rel(p.seat));
|
||||
final isTurn = s.turn == p.seat;
|
||||
_addLabel(
|
||||
'${p.name}${p.bot ? ' (ربات)' : ''}${p.connected ? '' : ' …'}',
|
||||
pos,
|
||||
size.x * 0.035,
|
||||
color: 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ===== کمکیهای ساختِ عنصر (ثبت در فهرستِ بازساختهشونده) =====
|
||||
|
||||
void _addBack(Vector2 pos, Vector2 sz, {required int priority}) {
|
||||
final c = CardComponent(code: '', faceUp: false, size: sz, position: pos, priority: priority);
|
||||
_backs.add(c);
|
||||
add(c);
|
||||
}
|
||||
|
||||
void _addLabel(String text, Vector2 pos, double fontSize,
|
||||
{Color color = const Color(0xFFE9B949),
|
||||
Anchor anchor = Anchor.center,
|
||||
bool bold = false}) {
|
||||
final t = TextComponent(
|
||||
text: text,
|
||||
anchor: anchor,
|
||||
position: pos,
|
||||
priority: 21,
|
||||
textRenderer: TextPaint(
|
||||
style: TextStyle(
|
||||
fontFamily: 'Dana',
|
||||
color: color,
|
||||
fontSize: fontSize,
|
||||
fontWeight: bold ? FontWeight.bold : FontWeight.normal,
|
||||
shadows: const [Shadow(color: Colors.black, blurRadius: 4)],
|
||||
),
|
||||
),
|
||||
);
|
||||
_info.add(t);
|
||||
add(t);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flame/components.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
// رنگهای مشترکِ میز.
|
||||
const _gold = Color(0xFFE9B949);
|
||||
const _goldDark = Color(0xFFB8860B);
|
||||
|
||||
/// نمدِ سبزِ بیضیشکلِ میز با عمق: لبهی برجسته، گرادیانِ شعاعی و وینیت.
|
||||
class Felt extends PositionComponent with HasGameReference {
|
||||
@override
|
||||
void render(Canvas canvas) {
|
||||
final w = game.size.x, h = game.size.y;
|
||||
final center = Offset(w / 2, h / 2);
|
||||
final rect = Rect.fromCenter(center: center, width: w * 0.86, height: h * 0.62);
|
||||
final radius = Radius.circular(h * 0.3);
|
||||
final felt = RRect.fromRectAndRadius(rect, radius);
|
||||
|
||||
// ۱) لبهی چوبیِ بیرونی (ریل) با گرادیان — حسِ برجستگی بدون drawShadowِ هر-فریمی.
|
||||
final rail = RRect.fromRectAndRadius(
|
||||
rect.inflate(w * 0.03), Radius.circular(h * 0.33));
|
||||
canvas.drawRRect(
|
||||
rail,
|
||||
Paint()
|
||||
..shader = const LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Color(0xFF5A2E12), Color(0xFF2E1608)],
|
||||
).createShader(rail.outerRect),
|
||||
);
|
||||
|
||||
// ۲) حلقهی طلایی بین ریل و نمد.
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(rect.inflate(w * 0.008), radius),
|
||||
Paint()
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = w * 0.012
|
||||
..color = _gold,
|
||||
);
|
||||
|
||||
// ۳) نمدِ سبز با گرادیانِ شعاعی (مرکز روشن، لبهها تیره) — خودش حسِ وینیت/عمق میدهد.
|
||||
canvas.drawRRect(
|
||||
felt,
|
||||
Paint()
|
||||
..shader = RadialGradient(
|
||||
center: Alignment.center,
|
||||
radius: 0.95,
|
||||
colors: const [Color(0xFF34A03F), Color(0xFF0E3614)],
|
||||
stops: const [0.45, 1.0],
|
||||
).createShader(rect),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// دیسکِ فلزیِ شمارش (امتیاز تیم) با عددِ وسط؛ از ۰ تا ۷.
|
||||
class ScorePuck extends PositionComponent {
|
||||
final int count;
|
||||
ScorePuck(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 = _goldDark,
|
||||
);
|
||||
final tp = TextPainter(
|
||||
text: TextSpan(
|
||||
text: '$count',
|
||||
style: TextStyle(
|
||||
fontFamily: 'Dana',
|
||||
color: _gold,
|
||||
fontSize: r * 1.05,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout();
|
||||
tp.paint(canvas, c - Offset(tp.width / 2, tp.height / 2));
|
||||
}
|
||||
}
|
||||
|
||||
/// افکت رعد روی زمین هنگام «بریدن با حکم»؛ پس از مدت کوتاهی خودش حذف میشود.
|
||||
class Lightning extends PositionComponent with HasGameReference {
|
||||
static const _max = 0.55;
|
||||
double _life = _max;
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user