feat: refactor code
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
import '../../../../../core/storage/token_storage.dart';
|
||||
|
||||
/// ذخیرهی محلیِ توکن احراز هویت.
|
||||
class AuthLocalData {
|
||||
final TokenStorage _storage;
|
||||
AuthLocalData(this._storage);
|
||||
|
||||
Future<void> saveToken(String token) => _storage.write(token);
|
||||
Future<String?> readToken() => _storage.read();
|
||||
Future<void> clearToken() => _storage.clear();
|
||||
|
||||
Future<bool> hasToken() async {
|
||||
final t = await _storage.read();
|
||||
return t != null && t.isNotEmpty;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../../core/locator/locator.dart';
|
||||
import '../../../../../core/network/api_provider_imp.dart';
|
||||
|
||||
/// تماسهای خامِ HTTP مربوط به احراز هویت (خروجی Response).
|
||||
class AuthApiProvider {
|
||||
ApiProviderImp get _api => locator<ApiProviderImp>();
|
||||
|
||||
Future<Response> loginOtp(String mobile) =>
|
||||
_api.post('/auth/login-otp', body: {'mobile': mobile});
|
||||
|
||||
Future<Response> checkOtp(String mobile, String token) =>
|
||||
_api.post('/auth/check-otp', body: {'mobile': mobile, 'token': token});
|
||||
|
||||
Future<Response> updateProfile(String firstName, String avatar) =>
|
||||
_api.post('/profile', body: {'first_name': firstName, 'avatar': avatar});
|
||||
|
||||
Future<Response> me() => _api.get('/me');
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import '../../domain/entities/user_entity.dart';
|
||||
|
||||
/// مدلِ دادهی کاربر؛ از JSON ساخته شده و به UserEntity نگاشت میشود.
|
||||
class UserModel extends UserEntity {
|
||||
const UserModel({
|
||||
required super.id,
|
||||
required super.mobile,
|
||||
super.firstName,
|
||||
super.avatar,
|
||||
});
|
||||
|
||||
factory UserModel.fromJson(Map<String, dynamic> j) => UserModel(
|
||||
id: (j['id'] ?? 0) as int,
|
||||
mobile: (j['mobile'] ?? '') as String,
|
||||
firstName: j['first_name'] as String?,
|
||||
avatar: j['avatar'] as String?,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../core/error/custom_error.dart';
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../../domain/entities/user_entity.dart';
|
||||
import '../../domain/repository/auth_repository.dart';
|
||||
import '../data_source/local/auth_local_data.dart';
|
||||
import '../data_source/remote/auth_api_provider.dart';
|
||||
import '../model/user_model.dart';
|
||||
|
||||
class AuthRepositoryImpl extends AuthRepository {
|
||||
final AuthApiProvider api;
|
||||
final AuthLocalData local;
|
||||
AuthRepositoryImpl(this.api, this.local);
|
||||
|
||||
@override
|
||||
Future<DataState<String>> loginOtp(String mobile) async {
|
||||
final Response res = await api.loginOtp(mobile);
|
||||
if (res.statusCode == 200) {
|
||||
return const DataSuccess('ok');
|
||||
}
|
||||
return DataError(errorConvertor(res.statusCode, _msg(res)));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DataState<UserEntity>> checkOtp(OtpParams params) async {
|
||||
final Response res = await api.checkOtp(params.mobile, params.token);
|
||||
if (res.statusCode == 200) {
|
||||
final token = res.data['token'] as String?;
|
||||
if (token == null || token.isEmpty) {
|
||||
return const DataError('پاسخ نامعتبر از سرور');
|
||||
}
|
||||
await local.saveToken(token);
|
||||
return DataSuccess(UserModel.fromJson(
|
||||
Map<String, dynamic>.from(res.data['user'] as Map)));
|
||||
}
|
||||
return DataError(errorConvertor(res.statusCode, _msg(res)));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DataState<UserEntity>> updateProfile(ProfileParams params) async {
|
||||
final Response res = await api.updateProfile(params.firstName, params.avatar);
|
||||
if (res.statusCode == 200) {
|
||||
return DataSuccess(UserModel.fromJson(
|
||||
Map<String, dynamic>.from(res.data['user'] as Map)));
|
||||
}
|
||||
return DataError(errorConvertor(res.statusCode, _msg(res)));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DataState<String>> logout() async {
|
||||
await local.clearToken();
|
||||
return const DataSuccess('ok');
|
||||
}
|
||||
|
||||
@override
|
||||
Future<bool> isLoggedIn() => local.hasToken();
|
||||
|
||||
String? _msg(Response res) {
|
||||
final d = res.data;
|
||||
if (d is Map && d['message'] != null) return d['message'].toString();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
/// موجودیتِ کاربر (نام نمایشی و آواتار برای استفاده در UI).
|
||||
class UserEntity {
|
||||
final int id;
|
||||
final String mobile;
|
||||
final String? firstName;
|
||||
final String? avatar;
|
||||
|
||||
const UserEntity({
|
||||
required this.id,
|
||||
required this.mobile,
|
||||
this.firstName,
|
||||
this.avatar,
|
||||
});
|
||||
|
||||
bool get hasName => firstName != null && firstName!.trim().isNotEmpty;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../entities/user_entity.dart';
|
||||
|
||||
/// قرارداد لایهی دادهی احراز هویت (پیادهسازی در data/repository).
|
||||
abstract class AuthRepository {
|
||||
Future<DataState<String>> loginOtp(String mobile);
|
||||
|
||||
/// بررسی کد؛ توکن را ذخیره کرده و کاربرِ احرازشده را برمیگرداند.
|
||||
Future<DataState<UserEntity>> checkOtp(OtpParams params);
|
||||
|
||||
Future<DataState<UserEntity>> updateProfile(ProfileParams params);
|
||||
|
||||
Future<DataState<String>> logout();
|
||||
|
||||
Future<bool> isLoggedIn();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../entities/user_entity.dart';
|
||||
import '../repository/auth_repository.dart';
|
||||
|
||||
class CheckOtpUseCase implements UseCase<DataState<UserEntity>, OtpParams> {
|
||||
final AuthRepository repository;
|
||||
CheckOtpUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<UserEntity>> call(OtpParams params) =>
|
||||
repository.checkOtp(params);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../repository/auth_repository.dart';
|
||||
|
||||
class LoginUseCase implements UseCase<DataState<String>, String> {
|
||||
final AuthRepository repository;
|
||||
LoginUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<String>> call(String params) => repository.loginOtp(params);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../repository/auth_repository.dart';
|
||||
|
||||
class LogoutUseCase implements UseCase<DataState<String>, NoParams> {
|
||||
final AuthRepository repository;
|
||||
LogoutUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<String>> call(NoParams params) => repository.logout();
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../entities/user_entity.dart';
|
||||
import '../repository/auth_repository.dart';
|
||||
|
||||
class UpdateProfileUseCase
|
||||
implements UseCase<DataState<UserEntity>, ProfileParams> {
|
||||
final AuthRepository repository;
|
||||
UpdateProfileUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<UserEntity>> call(ProfileParams params) =>
|
||||
repository.updateProfile(params);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../../domain/use_cases/check_otp_usecase.dart';
|
||||
import '../../domain/use_cases/login_usecase.dart';
|
||||
import '../../domain/use_cases/logout_usecase.dart';
|
||||
import '../../domain/use_cases/update_profile_usecase.dart';
|
||||
import 'auth_event.dart';
|
||||
import 'auth_state.dart';
|
||||
import 'login_status.dart';
|
||||
import 'otp_status.dart';
|
||||
import 'profile_status.dart';
|
||||
|
||||
class AuthBloc extends Bloc<AuthEvent, AuthState> {
|
||||
final LoginUseCase loginUseCase;
|
||||
final CheckOtpUseCase checkOtpUseCase;
|
||||
final UpdateProfileUseCase updateProfileUseCase;
|
||||
final LogoutUseCase logoutUseCase;
|
||||
|
||||
AuthBloc(
|
||||
this.loginUseCase,
|
||||
this.checkOtpUseCase,
|
||||
this.updateProfileUseCase,
|
||||
this.logoutUseCase,
|
||||
) : super(AuthState.initial()) {
|
||||
on<LoginOtpEvent>((event, emit) async {
|
||||
emit(state.copyWith(mobile: event.mobile, loginStatus: LoginLoading()));
|
||||
final res = await loginUseCase(event.mobile);
|
||||
if (res is DataSuccess) {
|
||||
emit(state.copyWith(loginStatus: LoginSuccess()));
|
||||
} else {
|
||||
emit(state.copyWith(loginStatus: LoginError(res.error!)));
|
||||
}
|
||||
});
|
||||
|
||||
on<CheckOtpEvent>((event, emit) async {
|
||||
emit(state.copyWith(otpStatus: OtpLoading()));
|
||||
final res = await checkOtpUseCase(OtpParams(state.mobile, event.token));
|
||||
if (res is DataSuccess) {
|
||||
emit(state.copyWith(otpStatus: OtpSuccess(res.data!.hasName)));
|
||||
} else {
|
||||
emit(state.copyWith(otpStatus: OtpError(res.error!)));
|
||||
}
|
||||
});
|
||||
|
||||
on<UpdateProfileEvent>((event, emit) async {
|
||||
emit(state.copyWith(profileStatus: ProfileLoading()));
|
||||
final res = await updateProfileUseCase(
|
||||
ProfileParams(event.firstName, event.avatar));
|
||||
if (res is DataSuccess) {
|
||||
emit(state.copyWith(profileStatus: ProfileSuccess()));
|
||||
} else {
|
||||
emit(state.copyWith(profileStatus: ProfileError(res.error!)));
|
||||
}
|
||||
});
|
||||
|
||||
on<LogoutEvent>((event, emit) async {
|
||||
await logoutUseCase(const NoParams());
|
||||
emit(AuthState.initial());
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
abstract class AuthEvent {}
|
||||
|
||||
class LoginOtpEvent extends AuthEvent {
|
||||
final String mobile;
|
||||
LoginOtpEvent(this.mobile);
|
||||
}
|
||||
|
||||
class CheckOtpEvent extends AuthEvent {
|
||||
final String token;
|
||||
CheckOtpEvent(this.token);
|
||||
}
|
||||
|
||||
class UpdateProfileEvent extends AuthEvent {
|
||||
final String firstName;
|
||||
final String avatar;
|
||||
UpdateProfileEvent(this.firstName, this.avatar);
|
||||
}
|
||||
|
||||
class LogoutEvent extends AuthEvent {}
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'login_status.dart';
|
||||
import 'otp_status.dart';
|
||||
import 'profile_status.dart';
|
||||
|
||||
class AuthState {
|
||||
final String mobile; // شمارهی در حال احراز (برای صفحهی کد)
|
||||
final LoginStatus loginStatus;
|
||||
final OtpStatus otpStatus;
|
||||
final ProfileStatus profileStatus;
|
||||
|
||||
AuthState({
|
||||
required this.mobile,
|
||||
required this.loginStatus,
|
||||
required this.otpStatus,
|
||||
required this.profileStatus,
|
||||
});
|
||||
|
||||
factory AuthState.initial() => AuthState(
|
||||
mobile: '',
|
||||
loginStatus: LoginInitial(),
|
||||
otpStatus: OtpInitial(),
|
||||
profileStatus: ProfileInitial(),
|
||||
);
|
||||
|
||||
AuthState copyWith({
|
||||
String? mobile,
|
||||
LoginStatus? loginStatus,
|
||||
OtpStatus? otpStatus,
|
||||
ProfileStatus? profileStatus,
|
||||
}) =>
|
||||
AuthState(
|
||||
mobile: mobile ?? this.mobile,
|
||||
loginStatus: loginStatus ?? this.loginStatus,
|
||||
otpStatus: otpStatus ?? this.otpStatus,
|
||||
profileStatus: profileStatus ?? this.profileStatus,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
abstract class LoginStatus {}
|
||||
|
||||
class LoginInitial extends LoginStatus {}
|
||||
|
||||
class LoginLoading extends LoginStatus {}
|
||||
|
||||
class LoginSuccess extends LoginStatus {}
|
||||
|
||||
class LoginError extends LoginStatus {
|
||||
final String message;
|
||||
LoginError(this.message);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
abstract class OtpStatus {}
|
||||
|
||||
class OtpInitial extends OtpStatus {}
|
||||
|
||||
class OtpLoading extends OtpStatus {}
|
||||
|
||||
class OtpSuccess extends OtpStatus {
|
||||
final bool hasName; // اگر نام نداشته باشد، باید به صفحهی انتخاب نام برود
|
||||
OtpSuccess(this.hasName);
|
||||
}
|
||||
|
||||
class OtpError extends OtpStatus {
|
||||
final String message;
|
||||
OtpError(this.message);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
abstract class ProfileStatus {}
|
||||
|
||||
class ProfileInitial extends ProfileStatus {}
|
||||
|
||||
class ProfileLoading extends ProfileStatus {}
|
||||
|
||||
class ProfileSuccess extends ProfileStatus {}
|
||||
|
||||
class ProfileError extends ProfileStatus {
|
||||
final String message;
|
||||
ProfileError(this.message);
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
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/widgets/game_ui.dart';
|
||||
import '../bloc/auth_bloc.dart';
|
||||
import '../bloc/auth_event.dart';
|
||||
import '../bloc/auth_state.dart';
|
||||
import '../bloc/login_status.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: GameBackground(
|
||||
child: BlocConsumer<AuthBloc, AuthState>(
|
||||
listenWhen: (a, b) => a.loginStatus != b.loginStatus,
|
||||
listener: (context, state) {
|
||||
final s = state.loginStatus;
|
||||
if (s is LoginSuccess) {
|
||||
context.push('/otp');
|
||||
} else if (s is LoginError) {
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(s.message)));
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final loading = state.loginStatus is LoginLoading;
|
||||
return Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const GlowText('سلطان حکم', size: 40),
|
||||
const SizedBox(height: 28),
|
||||
GamePanel(
|
||||
padding: const EdgeInsets.all(22),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text('برای ورود شماره موبایلت رو وارد کن',
|
||||
style: TextStyle(color: Colors.white70)),
|
||||
const SizedBox(height: 20),
|
||||
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: 20),
|
||||
GameButton(
|
||||
label: 'دریافت کد',
|
||||
width: double.infinity,
|
||||
colors: const [Color(0xFF3FA34D), Color(0xFF1B5E20)],
|
||||
onTap: (!_valid || loading)
|
||||
? null
|
||||
: () => context
|
||||
.read<AuthBloc>()
|
||||
.add(LoginOtpEvent(_controller.text.trim())),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
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/auth_bloc.dart';
|
||||
import '../bloc/auth_event.dart';
|
||||
import '../bloc/auth_state.dart';
|
||||
import '../bloc/otp_status.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(
|
||||
body: GameBackground(
|
||||
child: BlocConsumer<AuthBloc, AuthState>(
|
||||
listenWhen: (a, b) => a.otpStatus != b.otpStatus,
|
||||
listener: (context, state) {
|
||||
final s = state.otpStatus;
|
||||
if (s is OtpSuccess) {
|
||||
context.go(s.hasName ? '/lobby' : '/setup');
|
||||
} else if (s is OtpError) {
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(s.message)));
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final loading = state.otpStatus is OtpLoading;
|
||||
return Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const GlowText('تأیید کد', size: 32),
|
||||
const SizedBox(height: 24),
|
||||
GamePanel(
|
||||
padding: const EdgeInsets.all(22),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text('کد پیامکشده به ${state.mobile} را وارد کنید',
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: Colors.white70)),
|
||||
const SizedBox(height: 20),
|
||||
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: 20),
|
||||
GameButton(
|
||||
label: 'ورود',
|
||||
width: double.infinity,
|
||||
colors: const [Color(0xFF3FA34D), Color(0xFF1B5E20)],
|
||||
onTap: (!_valid || loading)
|
||||
? null
|
||||
: () => context
|
||||
.read<AuthBloc>()
|
||||
.add(CheckOtpEvent(_controller.text.trim())),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: loading ? null : () => context.pop(),
|
||||
child: const Text('تغییر شماره',
|
||||
style: TextStyle(color: AppColors.gold)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
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 'package:random_avatar/random_avatar.dart';
|
||||
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../../../core/widgets/game_ui.dart';
|
||||
import '../bloc/auth_bloc.dart';
|
||||
import '../bloc/auth_event.dart';
|
||||
import '../bloc/auth_state.dart';
|
||||
import '../bloc/profile_status.dart';
|
||||
|
||||
/// صفحهی انتخاب نام و آواتار پس از اولین ورود.
|
||||
class ProfileSetupScreen extends StatefulWidget {
|
||||
const ProfileSetupScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ProfileSetupScreen> createState() => _ProfileSetupScreenState();
|
||||
}
|
||||
|
||||
class _ProfileSetupScreenState extends State<ProfileSetupScreen> {
|
||||
final _name = TextEditingController();
|
||||
late List<String> _seeds;
|
||||
int _selected = 0;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_seeds = List.generate(12, (i) => 'hakem-${i + 1}');
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_name.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool get _valid => _name.text.trim().length >= 2;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: GameBackground(
|
||||
child: BlocConsumer<AuthBloc, AuthState>(
|
||||
listenWhen: (a, b) => a.profileStatus != b.profileStatus,
|
||||
listener: (context, state) {
|
||||
final s = state.profileStatus;
|
||||
if (s is ProfileSuccess) {
|
||||
context.go('/lobby');
|
||||
} else if (s is ProfileError) {
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(s.message)));
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final saving = state.profileStatus is ProfileLoading;
|
||||
return Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const GlowText('انتخاب نام و آواتار', size: 26),
|
||||
const SizedBox(height: 20),
|
||||
GamePanel(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(6),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
border:
|
||||
Border.all(color: AppColors.gold, width: 2),
|
||||
),
|
||||
child: RandomAvatar(_seeds[_selected],
|
||||
height: 84, width: 84),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
TextField(
|
||||
controller: _name,
|
||||
textAlign: TextAlign.center,
|
||||
maxLength: 20,
|
||||
inputFormatters: [
|
||||
LengthLimitingTextInputFormatter(20),
|
||||
],
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'نام نمایشی (۲ تا ۲۰ حرف)',
|
||||
counterText: ''),
|
||||
onChanged: (_) => setState(() {}),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
const Text('یک آواتار انتخاب کن',
|
||||
style: TextStyle(color: AppColors.gold)),
|
||||
const SizedBox(height: 10),
|
||||
GridView.count(
|
||||
crossAxisCount: 4,
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
mainAxisSpacing: 10,
|
||||
crossAxisSpacing: 10,
|
||||
children: [
|
||||
for (var i = 0; i < _seeds.length; i++)
|
||||
GestureDetector(
|
||||
onTap: () => setState(() => _selected = i),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: AppColors.bgDark,
|
||||
border: Border.all(
|
||||
color: _selected == i
|
||||
? AppColors.gold
|
||||
: Colors.transparent,
|
||||
width: 2.5,
|
||||
),
|
||||
),
|
||||
child: RandomAvatar(_seeds[i]),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
GameButton(
|
||||
label: saving ? 'در حال ذخیره…' : 'تأیید و ورود',
|
||||
width: double.infinity,
|
||||
colors: const [Color(0xFF3FA34D), Color(0xFF1B5E20)],
|
||||
onTap: (!_valid || saving)
|
||||
? null
|
||||
: () => context.read<AuthBloc>().add(
|
||||
UpdateProfileEvent(
|
||||
_name.text.trim(), _seeds[_selected])),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../../core/locator/locator.dart';
|
||||
import '../../../../../core/network/api_provider_imp.dart';
|
||||
|
||||
class ProfileApiProvider {
|
||||
ApiProviderImp get _api => locator<ApiProviderImp>();
|
||||
|
||||
Future<Response> getMe() => _api.get('/me');
|
||||
Future<Response> getWallet() => _api.get('/wallet');
|
||||
Future<Response> getStats() => _api.get('/stats');
|
||||
|
||||
Future<Response> updateProfile(String firstName, String avatar) =>
|
||||
_api.post('/profile', body: {'first_name': firstName, 'avatar': avatar});
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import '../../domain/entities/profile_entity.dart';
|
||||
|
||||
/// نگاشتِ پاسخهای /me، /wallet و /stats به ProfileEntity.
|
||||
class ProfileModel {
|
||||
static ProfileEntity fromJson(
|
||||
Map<String, dynamic> user,
|
||||
Map<String, dynamic> wallet,
|
||||
Map<String, dynamic> stats,
|
||||
) {
|
||||
final name = (user['first_name'] as String?)?.trim();
|
||||
final avatar = (user['avatar'] as String?)?.trim();
|
||||
final s = stats['stats'] as Map?;
|
||||
return ProfileEntity(
|
||||
name: (name == null || name.isEmpty) ? 'بازیکن' : name,
|
||||
avatar: (avatar == null || avatar.isEmpty) ? 'hakem-1' : avatar,
|
||||
mobile: (user['mobile'] as String?) ?? '',
|
||||
level: (wallet['level'] ?? 1) as int,
|
||||
trophies: (wallet['trophies'] ?? 0) as int,
|
||||
xpInto: (wallet['xp_into_level'] ?? 0) as int,
|
||||
xpNext: (wallet['xp_for_next'] ?? 1) as int,
|
||||
vip: (stats['vip'] ?? false) as bool,
|
||||
stats: s == null
|
||||
? null
|
||||
: ProfileStats(
|
||||
games: (s['games'] ?? 0) as int,
|
||||
wins: (s['wins'] ?? 0) as int,
|
||||
losses: (s['losses'] ?? 0) as int,
|
||||
kotMade: (s['kot_made'] ?? 0) as int,
|
||||
kotReceived: (s['kot_received'] ?? 0) as int,
|
||||
cuts: (s['cuts'] ?? 0) as int,
|
||||
hakemCount: (s['hakem_count'] ?? 0) as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../core/error/custom_error.dart';
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../../domain/entities/profile_entity.dart';
|
||||
import '../../domain/repository/profile_repository.dart';
|
||||
import '../data_source/remote/profile_api_provider.dart';
|
||||
import '../model/profile_model.dart';
|
||||
|
||||
class ProfileRepositoryImpl extends ProfileRepository {
|
||||
final ProfileApiProvider api;
|
||||
ProfileRepositoryImpl(this.api);
|
||||
|
||||
@override
|
||||
Future<DataState<ProfileEntity>> getProfile() async {
|
||||
final results =
|
||||
await Future.wait([api.getMe(), api.getWallet(), api.getStats()]);
|
||||
final Response me = results[0];
|
||||
final Response wallet = results[1];
|
||||
final Response stats = results[2];
|
||||
if (me.statusCode == 200 &&
|
||||
wallet.statusCode == 200 &&
|
||||
stats.statusCode == 200) {
|
||||
return DataSuccess(ProfileModel.fromJson(
|
||||
Map<String, dynamic>.from((me.data['user'] ?? {}) as Map),
|
||||
Map<String, dynamic>.from(wallet.data as Map),
|
||||
Map<String, dynamic>.from(stats.data as Map),
|
||||
));
|
||||
}
|
||||
return DataError(errorConvertor(me.statusCode, null));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DataState<String>> updateProfile(ProfileParams params) async {
|
||||
final Response res = await api.updateProfile(params.firstName, params.avatar);
|
||||
if (res.statusCode == 200) return const DataSuccess('ok');
|
||||
final d = res.data;
|
||||
final msg = (d is Map && d['message'] != null) ? d['message'].toString() : null;
|
||||
return DataError(errorConvertor(res.statusCode, msg));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
/// آمار بازیِ کاربر (در صورت قفل بودن، null است).
|
||||
class ProfileStats {
|
||||
final int games;
|
||||
final int wins;
|
||||
final int losses;
|
||||
final int kotMade;
|
||||
final int kotReceived;
|
||||
final int cuts;
|
||||
final int hakemCount;
|
||||
const ProfileStats({
|
||||
required this.games,
|
||||
required this.wins,
|
||||
required this.losses,
|
||||
required this.kotMade,
|
||||
required this.kotReceived,
|
||||
required this.cuts,
|
||||
required this.hakemCount,
|
||||
});
|
||||
}
|
||||
|
||||
/// موجودیتِ کاملِ پروفایل (نام/آواتار + خلاصهی اقتصادی + آمار).
|
||||
class ProfileEntity {
|
||||
final String name;
|
||||
final String avatar;
|
||||
final String mobile;
|
||||
final int level;
|
||||
final int trophies;
|
||||
final int xpInto;
|
||||
final int xpNext;
|
||||
final bool vip;
|
||||
final ProfileStats? stats; // null یعنی قفل (غیر VIP)
|
||||
|
||||
const ProfileEntity({
|
||||
required this.name,
|
||||
required this.avatar,
|
||||
required this.mobile,
|
||||
required this.level,
|
||||
required this.trophies,
|
||||
required this.xpInto,
|
||||
required this.xpNext,
|
||||
required this.vip,
|
||||
required this.stats,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../entities/profile_entity.dart';
|
||||
|
||||
abstract class ProfileRepository {
|
||||
Future<DataState<ProfileEntity>> getProfile();
|
||||
Future<DataState<String>> updateProfile(ProfileParams params);
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../entities/profile_entity.dart';
|
||||
import '../repository/profile_repository.dart';
|
||||
|
||||
class GetProfileUseCase implements UseCase<DataState<ProfileEntity>, NoParams> {
|
||||
final ProfileRepository repository;
|
||||
GetProfileUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<ProfileEntity>> call(NoParams params) =>
|
||||
repository.getProfile();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../repository/profile_repository.dart';
|
||||
|
||||
class SaveProfileUseCase implements UseCase<DataState<String>, ProfileParams> {
|
||||
final ProfileRepository repository;
|
||||
SaveProfileUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<String>> call(ProfileParams params) =>
|
||||
repository.updateProfile(params);
|
||||
}
|
||||
@@ -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/use_cases/get_profile_usecase.dart';
|
||||
import '../../domain/use_cases/save_profile_usecase.dart';
|
||||
import 'profile_event.dart';
|
||||
import 'profile_state.dart';
|
||||
import 'profile_status.dart';
|
||||
|
||||
class ProfileBloc extends Bloc<ProfileEvent, ProfileBlocState> {
|
||||
final GetProfileUseCase getProfileUseCase;
|
||||
final SaveProfileUseCase saveProfileUseCase;
|
||||
|
||||
ProfileBloc(this.getProfileUseCase, this.saveProfileUseCase)
|
||||
: super(ProfileBlocState.initial()) {
|
||||
on<LoadProfileEvent>((event, emit) => _load(emit));
|
||||
|
||||
on<SaveProfileEvent>((event, emit) async {
|
||||
emit(state.copyWith(saveStatus: ProfileSaveLoading()));
|
||||
final res = await saveProfileUseCase(
|
||||
ProfileParams(event.firstName, event.avatar));
|
||||
if (res is DataSuccess) {
|
||||
emit(state.copyWith(saveStatus: ProfileSaveSuccess()));
|
||||
await _load(emit);
|
||||
} else {
|
||||
emit(state.copyWith(saveStatus: ProfileSaveError(res.error!)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _load(Emitter<ProfileBlocState> emit) async {
|
||||
emit(state.copyWith(loadStatus: ProfileLoadLoading()));
|
||||
final res = await getProfileUseCase(const NoParams());
|
||||
if (res is DataSuccess) {
|
||||
emit(state.copyWith(loadStatus: ProfileLoadLoaded(res.data!)));
|
||||
} else {
|
||||
emit(state.copyWith(loadStatus: ProfileLoadError(res.error!)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
abstract class ProfileEvent {}
|
||||
|
||||
class LoadProfileEvent extends ProfileEvent {}
|
||||
|
||||
class SaveProfileEvent extends ProfileEvent {
|
||||
final String firstName;
|
||||
final String avatar;
|
||||
SaveProfileEvent(this.firstName, this.avatar);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import 'profile_status.dart';
|
||||
|
||||
class ProfileBlocState {
|
||||
final ProfileLoadStatus loadStatus;
|
||||
final ProfileSaveStatus saveStatus;
|
||||
|
||||
ProfileBlocState({required this.loadStatus, required this.saveStatus});
|
||||
|
||||
factory ProfileBlocState.initial() => ProfileBlocState(
|
||||
loadStatus: ProfileLoadInitial(),
|
||||
saveStatus: ProfileSaveIdle(),
|
||||
);
|
||||
|
||||
ProfileBlocState copyWith({
|
||||
ProfileLoadStatus? loadStatus,
|
||||
ProfileSaveStatus? saveStatus,
|
||||
}) =>
|
||||
ProfileBlocState(
|
||||
loadStatus: loadStatus ?? this.loadStatus,
|
||||
saveStatus: saveStatus ?? this.saveStatus,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import '../../domain/entities/profile_entity.dart';
|
||||
|
||||
abstract class ProfileLoadStatus {}
|
||||
|
||||
class ProfileLoadInitial extends ProfileLoadStatus {}
|
||||
|
||||
class ProfileLoadLoading extends ProfileLoadStatus {}
|
||||
|
||||
class ProfileLoadLoaded extends ProfileLoadStatus {
|
||||
final ProfileEntity profile;
|
||||
ProfileLoadLoaded(this.profile);
|
||||
}
|
||||
|
||||
class ProfileLoadError extends ProfileLoadStatus {
|
||||
final String message;
|
||||
ProfileLoadError(this.message);
|
||||
}
|
||||
|
||||
/// وضعیتِ ذخیرهی ویرایش پروفایل.
|
||||
abstract class ProfileSaveStatus {}
|
||||
|
||||
class ProfileSaveIdle extends ProfileSaveStatus {}
|
||||
|
||||
class ProfileSaveLoading extends ProfileSaveStatus {}
|
||||
|
||||
class ProfileSaveSuccess extends ProfileSaveStatus {}
|
||||
|
||||
class ProfileSaveError extends ProfileSaveStatus {
|
||||
final String message;
|
||||
ProfileSaveError(this.message);
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart' show LengthLimitingTextInputFormatter;
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:random_avatar/random_avatar.dart';
|
||||
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../../../core/widgets/game_ui.dart';
|
||||
import '../../../wallet/presentation/bloc/wallet_bloc.dart';
|
||||
import '../../../wallet/presentation/bloc/wallet_event.dart';
|
||||
import '../../domain/entities/profile_entity.dart';
|
||||
import '../bloc/profile_bloc.dart';
|
||||
import '../bloc/profile_event.dart';
|
||||
import '../bloc/profile_state.dart';
|
||||
import '../bloc/profile_status.dart';
|
||||
|
||||
/// صفحهی پروفایل: نام، آواتار (قابل ویرایش)، سطح، جام و آمارِ بازی (ویژهی VIP).
|
||||
class ProfileScreen extends StatelessWidget {
|
||||
const ProfileScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: GameBackground(
|
||||
child: SafeArea(
|
||||
child: BlocConsumer<ProfileBloc, ProfileBlocState>(
|
||||
listenWhen: (a, b) => a.saveStatus != b.saveStatus,
|
||||
listener: (context, state) {
|
||||
final s = state.saveStatus;
|
||||
if (s is ProfileSaveSuccess) {
|
||||
context.read<WalletBloc>().add(LoadWalletEvent());
|
||||
} else if (s is ProfileSaveError) {
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(s.message)));
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final st = state.loadStatus;
|
||||
if (st is ProfileLoadError) {
|
||||
return Center(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text(st.message,
|
||||
style: const TextStyle(color: Colors.white70)),
|
||||
const SizedBox(height: 12),
|
||||
GameButton(
|
||||
label: 'تلاش دوباره',
|
||||
onTap: () =>
|
||||
context.read<ProfileBloc>().add(LoadProfileEvent())),
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (st is! ProfileLoadLoaded) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(color: AppColors.gold));
|
||||
}
|
||||
return _content(context, st.profile);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _editProfile(BuildContext context, ProfileEntity d) async {
|
||||
final result = await showModalBottomSheet<Map<String, String>>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (_) => _EditProfileSheet(name: d.name, avatar: d.avatar),
|
||||
);
|
||||
if (result == null || !context.mounted) return;
|
||||
context
|
||||
.read<ProfileBloc>()
|
||||
.add(SaveProfileEvent(result['name']!, result['avatar']!));
|
||||
}
|
||||
|
||||
Widget _content(BuildContext context, ProfileEntity d) {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: [
|
||||
Row(children: [
|
||||
IconButton(
|
||||
onPressed: () => context.pop(),
|
||||
icon: const Icon(Icons.arrow_back, color: AppColors.gold),
|
||||
),
|
||||
const Spacer(),
|
||||
const GlowText('پروفایل', size: 24),
|
||||
const Spacer(),
|
||||
const SizedBox(width: 48),
|
||||
]),
|
||||
const SizedBox(height: 8),
|
||||
GamePanel(
|
||||
child: Column(children: [
|
||||
Stack(children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(6),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: AppColors.gold, width: 2.5),
|
||||
),
|
||||
child: RandomAvatar(d.avatar, height: 92, width: 92),
|
||||
),
|
||||
Positioned(
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
child: GestureDetector(
|
||||
onTap: () => _editProfile(context, d),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(6),
|
||||
decoration: const BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
gradient: LinearGradient(
|
||||
colors: [Color(0xFFFFD54F), Color(0xFFB8860B)]),
|
||||
),
|
||||
child: const Icon(Icons.edit,
|
||||
color: Color(0xFF3A0A12), size: 18),
|
||||
),
|
||||
),
|
||||
),
|
||||
]),
|
||||
const SizedBox(height: 10),
|
||||
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
Flexible(child: GlowText(d.name, size: 22)),
|
||||
if (d.vip) ...[const SizedBox(width: 8), const _VipBadge()],
|
||||
]),
|
||||
if (d.mobile.isNotEmpty)
|
||||
Text(d.mobile,
|
||||
style:
|
||||
const TextStyle(color: Colors.white38, fontSize: 12)),
|
||||
const SizedBox(height: 14),
|
||||
Row(children: [
|
||||
Expanded(
|
||||
child: _MiniStat(
|
||||
icon: Icons.star, label: 'سطح', value: '${d.level}')),
|
||||
Expanded(
|
||||
child: _MiniStat(
|
||||
icon: Icons.emoji_events,
|
||||
label: 'جام',
|
||||
value: '${d.trophies}')),
|
||||
]),
|
||||
const SizedBox(height: 10),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(5),
|
||||
child: LinearProgressIndicator(
|
||||
value: d.xpNext == 0 ? 0 : d.xpInto / d.xpNext,
|
||||
minHeight: 8,
|
||||
backgroundColor: Colors.white10,
|
||||
valueColor: const AlwaysStoppedAnimation(AppColors.gold),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text('${d.xpInto} / ${d.xpNext} XP',
|
||||
style: const TextStyle(color: Colors.white38, fontSize: 11)),
|
||||
),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
const Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: GlowText('آمار بازی', size: 18)),
|
||||
const SizedBox(height: 8),
|
||||
_statsSection(context, d),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _statsSection(BuildContext context, ProfileEntity d) {
|
||||
final s = d.stats;
|
||||
final rows = <Widget>[
|
||||
_StatRow('بازی کل', s?.games, Icons.casino),
|
||||
_StatRow('برد کل', s?.wins, Icons.thumb_up),
|
||||
_StatRow('باخت کل', s?.losses, Icons.thumb_down),
|
||||
_StatRow('کُت کردن', s?.kotMade, Icons.flash_on),
|
||||
_StatRow('کُت شدن', s?.kotReceived, Icons.flash_off),
|
||||
_StatRow('بریدن', s?.cuts, Icons.bolt),
|
||||
_StatRow('دست حاکم', s?.hakemCount, Icons.workspace_premium),
|
||||
];
|
||||
final panel = GamePanel(child: Column(children: rows));
|
||||
if (d.vip) return panel;
|
||||
|
||||
return Stack(children: [
|
||||
Opacity(opacity: 0.35, child: IgnorePointer(child: panel)),
|
||||
Positioned.fill(
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: 0.45),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: AppColors.goldDark),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.lock, color: AppColors.gold, size: 36),
|
||||
const SizedBox(height: 8),
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 24),
|
||||
child: Text('مشاهدهی آمار ویژهی کاربران VIP است',
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: Colors.white, fontSize: 14)),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
GameButton(
|
||||
label: 'تهیه اشتراک VIP',
|
||||
icon: Icons.workspace_premium,
|
||||
colors: const [Color(0xFFFFC107), Color(0xFFB8860B)],
|
||||
onTap: () async {
|
||||
await context.push('/vip');
|
||||
if (context.mounted) {
|
||||
context.read<ProfileBloc>().add(LoadProfileEvent());
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
class _StatRow extends StatelessWidget {
|
||||
final String label;
|
||||
final Object? value;
|
||||
final IconData icon;
|
||||
const _StatRow(this.label, this.value, this.icon);
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 7),
|
||||
child: Row(children: [
|
||||
Icon(icon, color: AppColors.gold, size: 20),
|
||||
const SizedBox(width: 10),
|
||||
Text(label, style: const TextStyle(color: Colors.white, fontSize: 15)),
|
||||
const Spacer(),
|
||||
Text('${value ?? '—'}',
|
||||
style: const TextStyle(
|
||||
color: AppColors.gold,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold)),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _MiniStat extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final String value;
|
||||
const _MiniStat(
|
||||
{required this.icon, required this.label, required this.value});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(children: [
|
||||
Icon(icon, color: AppColors.gold, size: 22),
|
||||
const SizedBox(height: 2),
|
||||
Text(value,
|
||||
style: const TextStyle(
|
||||
color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold)),
|
||||
Text(label, style: const TextStyle(color: Colors.white54, fontSize: 12)),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
class _VipBadge extends StatelessWidget {
|
||||
const _VipBadge();
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
gradient:
|
||||
const LinearGradient(colors: [Color(0xFFFFD54F), Color(0xFFB8860B)]),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: const Text('VIP',
|
||||
style: TextStyle(
|
||||
color: Color(0xFF3A0A12),
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 12)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// شیتِ ویرایش نام و آواتار (با تأیید، مقدار جدید را برمیگرداند).
|
||||
class _EditProfileSheet extends StatefulWidget {
|
||||
final String name;
|
||||
final String avatar;
|
||||
const _EditProfileSheet({required this.name, required this.avatar});
|
||||
|
||||
@override
|
||||
State<_EditProfileSheet> createState() => _EditProfileSheetState();
|
||||
}
|
||||
|
||||
class _EditProfileSheetState extends State<_EditProfileSheet> {
|
||||
late final TextEditingController _name;
|
||||
late final List<String> _seeds;
|
||||
late String _selected;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_name = TextEditingController(text: widget.name);
|
||||
_seeds = List.generate(12, (i) => 'hakem-${i + 1}');
|
||||
if (!_seeds.contains(widget.avatar)) _seeds.insert(0, widget.avatar);
|
||||
_selected = widget.avatar;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_name.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool get _valid => _name.text.trim().length >= 2;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom),
|
||||
child: Container(
|
||||
decoration: const BoxDecoration(
|
||||
color: AppColors.bgDark,
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
|
||||
border: Border(top: BorderSide(color: AppColors.gold, width: 2)),
|
||||
),
|
||||
padding: const EdgeInsets.all(18),
|
||||
child: SingleChildScrollView(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
const GlowText('ویرایش پروفایل', size: 20),
|
||||
const SizedBox(height: 14),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(4),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
border: Border.all(color: AppColors.gold, width: 2),
|
||||
),
|
||||
child: RandomAvatar(_selected, height: 72, width: 72),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextField(
|
||||
controller: _name,
|
||||
textAlign: TextAlign.center,
|
||||
maxLength: 20,
|
||||
inputFormatters: [LengthLimitingTextInputFormatter(20)],
|
||||
decoration: const InputDecoration(
|
||||
hintText: 'نام نمایشی (۲ تا ۲۰ حرف)', counterText: ''),
|
||||
onChanged: (_) => setState(() {}),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
const Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child:
|
||||
Text('انتخاب آواتار', style: TextStyle(color: AppColors.gold)),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
GridView.count(
|
||||
crossAxisCount: 4,
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
mainAxisSpacing: 10,
|
||||
crossAxisSpacing: 10,
|
||||
children: [
|
||||
for (final s in _seeds)
|
||||
GestureDetector(
|
||||
onTap: () => setState(() => _selected = s),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: AppColors.panel,
|
||||
border: Border.all(
|
||||
color: _selected == s
|
||||
? AppColors.gold
|
||||
: Colors.transparent,
|
||||
width: 2.5,
|
||||
),
|
||||
),
|
||||
child: RandomAvatar(s),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
GameButton(
|
||||
label: 'تأیید',
|
||||
width: double.infinity,
|
||||
colors: const [Color(0xFF3FA34D), Color(0xFF1B5E20)],
|
||||
onTap: _valid
|
||||
? () => Navigator.pop(
|
||||
context, {'name': _name.text.trim(), 'avatar': _selected})
|
||||
: null,
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../../core/locator/locator.dart';
|
||||
import '../../../../../core/network/api_provider_imp.dart';
|
||||
|
||||
class ShopApiProvider {
|
||||
ApiProviderImp get _api => locator<ApiProviderImp>();
|
||||
|
||||
Future<Response> getShop() => _api.get('/shop');
|
||||
|
||||
Future<Response> buyCard(String cardId) =>
|
||||
_api.post('/shop/buy-card', body: {'card_id': cardId});
|
||||
|
||||
Future<Response> selectCard(String cardId) =>
|
||||
_api.post('/shop/select-card', body: {'card_id': cardId});
|
||||
|
||||
Future<Response> purchase({
|
||||
required String store,
|
||||
required String kind,
|
||||
required String productId,
|
||||
required String token,
|
||||
}) =>
|
||||
_api.post('/shop/purchase', body: {
|
||||
'store': store,
|
||||
'kind': kind,
|
||||
'product_id': productId,
|
||||
'token': token,
|
||||
});
|
||||
|
||||
Future<Response> adReward(String token) =>
|
||||
_api.post('/rewards/ad', body: {'token': token});
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import '../../domain/entities/shop_entities.dart';
|
||||
|
||||
/// نگاشتِ JSON کاتالوگ فروشگاه به موجودیتها.
|
||||
class ShopMapper {
|
||||
static CoinPackage coin(Map<String, dynamic> j) => CoinPackage(
|
||||
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,
|
||||
);
|
||||
|
||||
static TicketPackage ticket(Map<String, dynamic> j) => TicketPackage(
|
||||
id: j['id'] as String,
|
||||
title: j['title'] as String,
|
||||
tickets: (j['tickets'] ?? 0) as int,
|
||||
priceToman: (j['price_toman'] ?? 0) as int,
|
||||
);
|
||||
|
||||
static CardSkin card(Map<String, dynamic> j) => CardSkin(
|
||||
id: j['id'] as String,
|
||||
title: j['title'] as String,
|
||||
priceCoins: (j['price_coins'] ?? 0) as int,
|
||||
);
|
||||
|
||||
static Booster booster(Map<String, dynamic> j) => Booster(
|
||||
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,
|
||||
);
|
||||
|
||||
static VipPackage vip(Map<String, dynamic> j) => VipPackage(
|
||||
id: j['id'] as String,
|
||||
title: j['title'] as String,
|
||||
months: (j['months'] ?? 1) as int,
|
||||
priceToman: (j['price_toman'] ?? 0) as int,
|
||||
);
|
||||
|
||||
static ShopData shopData(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', coin),
|
||||
ticketPackages: parse('ticket_packages', ticket),
|
||||
cardSkins: parse('card_skins', card),
|
||||
boosters: parse('boosters', booster),
|
||||
vipPackages: parse('vip_packages', vip),
|
||||
ownedCards:
|
||||
((j['owned_cards'] as List?) ?? []).map((e) => e as String).toList(),
|
||||
selectedCard: (j['selected_card'] ?? 'simple') as String,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../core/error/custom_error.dart';
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../../domain/entities/shop_entities.dart';
|
||||
import '../../domain/repository/shop_repository.dart';
|
||||
import '../data_source/remote/shop_api_provider.dart';
|
||||
import '../model/shop_models.dart';
|
||||
|
||||
class ShopRepositoryImpl extends ShopRepository {
|
||||
final ShopApiProvider api;
|
||||
ShopRepositoryImpl(this.api);
|
||||
|
||||
@override
|
||||
Future<DataState<ShopData>> getShop() async {
|
||||
final Response res = await api.getShop();
|
||||
if (res.statusCode == 200) {
|
||||
return DataSuccess(
|
||||
ShopMapper.shopData(Map<String, dynamic>.from(res.data as Map)));
|
||||
}
|
||||
return DataError(errorConvertor(res.statusCode, _msg(res)));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DataState<String>> buyCard(String cardId) async {
|
||||
final Response res = await api.buyCard(cardId);
|
||||
if (res.statusCode == 200) return const DataSuccess('کارت خریداری شد');
|
||||
return DataError(errorConvertor(res.statusCode, _msg(res)));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DataState<String>> selectCard(String cardId) async {
|
||||
final Response res = await api.selectCard(cardId);
|
||||
if (res.statusCode == 200) return const DataSuccess('کارت انتخاب شد');
|
||||
return DataError(errorConvertor(res.statusCode, _msg(res)));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DataState<String>> purchase(PurchaseParams params) async {
|
||||
final Response res = await api.purchase(
|
||||
store: params.store,
|
||||
kind: params.kind,
|
||||
productId: params.productId,
|
||||
token: params.token,
|
||||
);
|
||||
if (res.statusCode == 200) return const DataSuccess('خرید با موفقیت انجام شد');
|
||||
return DataError(errorConvertor(res.statusCode, _msg(res)));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DataState<int>> adReward(String token) async {
|
||||
final Response res = await api.adReward(token);
|
||||
if (res.statusCode == 200) {
|
||||
return DataSuccess((res.data['amount'] ?? 0) as int);
|
||||
}
|
||||
return DataError(errorConvertor(res.statusCode, _msg(res)));
|
||||
}
|
||||
|
||||
String? _msg(Response res) {
|
||||
final d = res.data;
|
||||
if (d is Map && d['message'] != null) return d['message'].toString();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
/// موجودیتهای کاتالوگ فروشگاه (مستقل از JSON).
|
||||
class CoinPackage {
|
||||
final String id;
|
||||
final String title;
|
||||
final int coins;
|
||||
final int vipDays;
|
||||
final int priceToman;
|
||||
final int bonusPct;
|
||||
const CoinPackage({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.coins,
|
||||
required this.vipDays,
|
||||
required this.priceToman,
|
||||
required this.bonusPct,
|
||||
});
|
||||
}
|
||||
|
||||
class TicketPackage {
|
||||
final String id;
|
||||
final String title;
|
||||
final int tickets;
|
||||
final int priceToman;
|
||||
const TicketPackage({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.tickets,
|
||||
required this.priceToman,
|
||||
});
|
||||
}
|
||||
|
||||
class CardSkin {
|
||||
final String id;
|
||||
final String title;
|
||||
final int priceCoins;
|
||||
const CardSkin(
|
||||
{required this.id, required this.title, required this.priceCoins});
|
||||
}
|
||||
|
||||
class Booster {
|
||||
final String id;
|
||||
final String title;
|
||||
final int multiplier;
|
||||
final int hours;
|
||||
final int priceToman;
|
||||
const Booster({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.multiplier,
|
||||
required this.hours,
|
||||
required this.priceToman,
|
||||
});
|
||||
}
|
||||
|
||||
class VipPackage {
|
||||
final String id;
|
||||
final String title;
|
||||
final int months;
|
||||
final int priceToman;
|
||||
const VipPackage({
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.months,
|
||||
required this.priceToman,
|
||||
});
|
||||
}
|
||||
|
||||
/// کلِ دادهی فروشگاه: کاتالوگ + کارتهای متعلق به کاربر + کارت انتخابی.
|
||||
class ShopData {
|
||||
final List<CoinPackage> coinPackages;
|
||||
final List<TicketPackage> ticketPackages;
|
||||
final List<CardSkin> cardSkins;
|
||||
final List<Booster> boosters;
|
||||
final List<VipPackage> vipPackages;
|
||||
final List<String> ownedCards;
|
||||
final String selectedCard;
|
||||
|
||||
const ShopData({
|
||||
required this.coinPackages,
|
||||
required this.ticketPackages,
|
||||
required this.cardSkins,
|
||||
required this.boosters,
|
||||
required this.vipPackages,
|
||||
required this.ownedCards,
|
||||
required this.selectedCard,
|
||||
});
|
||||
|
||||
bool owns(String cardId) => cardId == 'simple' || ownedCards.contains(cardId);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../entities/shop_entities.dart';
|
||||
|
||||
abstract class ShopRepository {
|
||||
Future<DataState<ShopData>> getShop();
|
||||
Future<DataState<String>> buyCard(String cardId);
|
||||
Future<DataState<String>> selectCard(String cardId);
|
||||
Future<DataState<String>> purchase(PurchaseParams params);
|
||||
Future<DataState<int>> adReward(String token);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../repository/shop_repository.dart';
|
||||
|
||||
class AdRewardUseCase implements UseCase<DataState<int>, String> {
|
||||
final ShopRepository repository;
|
||||
AdRewardUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<int>> call(String params) => repository.adReward(params);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../repository/shop_repository.dart';
|
||||
|
||||
class BuyCardUseCase implements UseCase<DataState<String>, String> {
|
||||
final ShopRepository repository;
|
||||
BuyCardUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<String>> call(String params) => repository.buyCard(params);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../entities/shop_entities.dart';
|
||||
import '../repository/shop_repository.dart';
|
||||
|
||||
class GetShopUseCase implements UseCase<DataState<ShopData>, NoParams> {
|
||||
final ShopRepository repository;
|
||||
GetShopUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<ShopData>> call(NoParams params) => repository.getShop();
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../repository/shop_repository.dart';
|
||||
|
||||
class PurchaseUseCase implements UseCase<DataState<String>, PurchaseParams> {
|
||||
final ShopRepository repository;
|
||||
PurchaseUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<String>> call(PurchaseParams params) =>
|
||||
repository.purchase(params);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../repository/shop_repository.dart';
|
||||
|
||||
class SelectCardUseCase implements UseCase<DataState<String>, String> {
|
||||
final ShopRepository repository;
|
||||
SelectCardUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<String>> call(String params) =>
|
||||
repository.selectCard(params);
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../../domain/use_cases/ad_reward_usecase.dart';
|
||||
import '../../domain/use_cases/buy_card_usecase.dart';
|
||||
import '../../domain/use_cases/get_shop_usecase.dart';
|
||||
import '../../domain/use_cases/purchase_usecase.dart';
|
||||
import '../../domain/use_cases/select_card_usecase.dart';
|
||||
import 'shop_event.dart';
|
||||
import 'shop_state.dart';
|
||||
import 'shop_status.dart';
|
||||
|
||||
class ShopBloc extends Bloc<ShopEvent, ShopBlocState> {
|
||||
final GetShopUseCase getShopUseCase;
|
||||
final BuyCardUseCase buyCardUseCase;
|
||||
final SelectCardUseCase selectCardUseCase;
|
||||
final PurchaseUseCase purchaseUseCase;
|
||||
final AdRewardUseCase adRewardUseCase;
|
||||
|
||||
ShopBloc(
|
||||
this.getShopUseCase,
|
||||
this.buyCardUseCase,
|
||||
this.selectCardUseCase,
|
||||
this.purchaseUseCase,
|
||||
this.adRewardUseCase,
|
||||
) : super(ShopBlocState.initial()) {
|
||||
on<LoadShopEvent>((event, emit) => _load(emit));
|
||||
|
||||
on<BuyCardEvent>((event, emit) =>
|
||||
_action(emit, () => buyCardUseCase(event.cardId)));
|
||||
|
||||
on<SelectCardEvent>((event, emit) =>
|
||||
_action(emit, () => selectCardUseCase(event.cardId)));
|
||||
|
||||
on<PurchaseEvent>((event, emit) => _action(
|
||||
emit,
|
||||
() => purchaseUseCase(PurchaseParams(
|
||||
store: 'bazaar',
|
||||
kind: event.kind,
|
||||
productId: event.productId,
|
||||
token:
|
||||
'dev-${event.kind}-${event.productId}-${DateTime.now().millisecondsSinceEpoch}',
|
||||
))));
|
||||
|
||||
on<AdRewardEvent>((event, emit) => _action(
|
||||
emit,
|
||||
() async {
|
||||
final res = await adRewardUseCase(
|
||||
'dev-ad-${DateTime.now().millisecondsSinceEpoch}');
|
||||
if (res is DataSuccess) {
|
||||
return const DataSuccess('سکه رایگان دریافت شد');
|
||||
}
|
||||
return DataError<String>(res.error!);
|
||||
},
|
||||
));
|
||||
}
|
||||
|
||||
Future<void> _load(Emitter<ShopBlocState> emit) async {
|
||||
emit(state.copyWith(loadStatus: ShopLoading()));
|
||||
final res = await getShopUseCase(const NoParams());
|
||||
if (res is DataSuccess) {
|
||||
emit(state.copyWith(loadStatus: ShopLoaded(res.data!)));
|
||||
} else {
|
||||
emit(state.copyWith(loadStatus: ShopLoadError(res.error!)));
|
||||
}
|
||||
}
|
||||
|
||||
/// اجرای یک عملیات، نمایش وضعیت و سپس بازخوانی کاتالوگ.
|
||||
Future<void> _action(
|
||||
Emitter<ShopBlocState> emit,
|
||||
Future<DataState<String>> Function() action,
|
||||
) async {
|
||||
if (state.busy) return;
|
||||
emit(state.copyWith(actionStatus: ActionLoading()));
|
||||
final res = await action();
|
||||
if (res is DataSuccess) {
|
||||
emit(state.copyWith(actionStatus: ActionSuccess(res.data!)));
|
||||
await _load(emit);
|
||||
} else {
|
||||
emit(state.copyWith(actionStatus: ActionError(res.error!)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
abstract class ShopEvent {}
|
||||
|
||||
class LoadShopEvent extends ShopEvent {}
|
||||
|
||||
class BuyCardEvent extends ShopEvent {
|
||||
final String cardId;
|
||||
BuyCardEvent(this.cardId);
|
||||
}
|
||||
|
||||
class SelectCardEvent extends ShopEvent {
|
||||
final String cardId;
|
||||
SelectCardEvent(this.cardId);
|
||||
}
|
||||
|
||||
class PurchaseEvent extends ShopEvent {
|
||||
final String kind;
|
||||
final String productId;
|
||||
PurchaseEvent(this.kind, this.productId);
|
||||
}
|
||||
|
||||
class AdRewardEvent extends ShopEvent {}
|
||||
@@ -0,0 +1,22 @@
|
||||
import 'shop_status.dart';
|
||||
|
||||
class ShopBlocState {
|
||||
final ShopLoadStatus loadStatus;
|
||||
final ShopActionStatus actionStatus;
|
||||
|
||||
ShopBlocState({required this.loadStatus, required this.actionStatus});
|
||||
|
||||
factory ShopBlocState.initial() =>
|
||||
ShopBlocState(loadStatus: ShopInitial(), actionStatus: ActionIdle());
|
||||
|
||||
bool get busy => actionStatus is ActionLoading;
|
||||
|
||||
ShopBlocState copyWith({
|
||||
ShopLoadStatus? loadStatus,
|
||||
ShopActionStatus? actionStatus,
|
||||
}) =>
|
||||
ShopBlocState(
|
||||
loadStatus: loadStatus ?? this.loadStatus,
|
||||
actionStatus: actionStatus ?? this.actionStatus,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import '../../domain/entities/shop_entities.dart';
|
||||
|
||||
abstract class ShopLoadStatus {}
|
||||
|
||||
class ShopInitial extends ShopLoadStatus {}
|
||||
|
||||
class ShopLoading extends ShopLoadStatus {}
|
||||
|
||||
class ShopLoaded extends ShopLoadStatus {
|
||||
final ShopData data;
|
||||
ShopLoaded(this.data);
|
||||
}
|
||||
|
||||
class ShopLoadError extends ShopLoadStatus {
|
||||
final String message;
|
||||
ShopLoadError(this.message);
|
||||
}
|
||||
|
||||
/// وضعیتِ یک عملیات (خرید/انتخاب/تبلیغ).
|
||||
abstract class ShopActionStatus {}
|
||||
|
||||
class ActionIdle extends ShopActionStatus {}
|
||||
|
||||
class ActionLoading extends ShopActionStatus {}
|
||||
|
||||
class ActionSuccess extends ShopActionStatus {
|
||||
final String message;
|
||||
ActionSuccess(this.message);
|
||||
}
|
||||
|
||||
class ActionError extends ShopActionStatus {
|
||||
final String message;
|
||||
ActionError(this.message);
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
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 '../../../wallet/presentation/bloc/wallet_bloc.dart';
|
||||
import '../../../wallet/presentation/bloc/wallet_event.dart';
|
||||
import '../../../wallet/presentation/bloc/wallet_state.dart';
|
||||
import '../../../wallet/presentation/bloc/wallet_status.dart';
|
||||
import '../../domain/entities/shop_entities.dart';
|
||||
import '../bloc/shop_bloc.dart';
|
||||
import '../bloc/shop_event.dart';
|
||||
import '../bloc/shop_state.dart';
|
||||
import '../bloc/shop_status.dart';
|
||||
|
||||
/// فروشگاه با تبهای سکه/بلیط/کارت/تجهیزات/VIP.
|
||||
class ShopScreen extends StatelessWidget {
|
||||
const ShopScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return DefaultTabController(
|
||||
length: 5,
|
||||
child: Scaffold(
|
||||
backgroundColor: Colors.transparent,
|
||||
body: GameBackground(
|
||||
child: BlocConsumer<ShopBloc, ShopBlocState>(
|
||||
listenWhen: (a, b) => a.actionStatus != b.actionStatus,
|
||||
listener: (context, state) {
|
||||
final s = state.actionStatus;
|
||||
if (s is ActionSuccess) {
|
||||
context.read<WalletBloc>().add(LoadWalletEvent());
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(s.message)));
|
||||
} else if (s is ActionError) {
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(s.message)));
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
return Column(
|
||||
children: [
|
||||
_header(context),
|
||||
Expanded(
|
||||
child: Container(
|
||||
margin: const EdgeInsets.fromLTRB(8, 0, 8, 8),
|
||||
decoration: BoxDecoration(
|
||||
gradient: const LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Color(0xFF4A0C16), Color(0xFF2A0710)],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border:
|
||||
Border.all(color: AppColors.goldDark, width: 1.5),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
const _ShopTabs(),
|
||||
Expanded(child: _body(context, state.loadStatus)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(BuildContext context, ShopLoadStatus status) {
|
||||
if (status is ShopLoaded) {
|
||||
final d = status.data;
|
||||
return TabBarView(
|
||||
children: [
|
||||
_CoinsTab(packages: d.coinPackages),
|
||||
_TicketsTab(packages: d.ticketPackages),
|
||||
_CardsTab(data: d),
|
||||
_BoostersTab(boosters: d.boosters),
|
||||
_VipTab(packages: d.vipPackages),
|
||||
],
|
||||
);
|
||||
}
|
||||
if (status is ShopLoadError) {
|
||||
return Center(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text(status.message),
|
||||
TextButton(
|
||||
onPressed: () => context.read<ShopBloc>().add(LoadShopEvent()),
|
||||
child: const Text('تلاش مجدد'),
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
return const Center(child: CircularProgressIndicator(color: AppColors.gold));
|
||||
}
|
||||
|
||||
Widget _header(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Row(children: [
|
||||
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),
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
BlocBuilder<WalletBloc, WalletBlocState>(
|
||||
builder: (context, s) {
|
||||
final w = s.walletStatus is WalletLoaded
|
||||
? (s.walletStatus as WalletLoaded).wallet
|
||||
: null;
|
||||
return Row(children: [
|
||||
StatChip(
|
||||
icon: Icons.confirmation_number,
|
||||
value: '${w?.tickets ?? 0}'),
|
||||
const SizedBox(width: 8),
|
||||
StatChip(icon: Icons.monetization_on, value: '${w?.coins ?? 0}'),
|
||||
]);
|
||||
},
|
||||
),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ShopTabs extends StatelessWidget {
|
||||
const _ShopTabs();
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return const TabBar(
|
||||
indicator: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Color(0xFFC62828), Color(0xFF7B0E14)],
|
||||
),
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(12)),
|
||||
),
|
||||
indicatorSize: TabBarIndicatorSize.tab,
|
||||
labelColor: AppColors.gold,
|
||||
unselectedLabelColor: Colors.white60,
|
||||
labelStyle: TextStyle(fontWeight: FontWeight.bold),
|
||||
dividerColor: Colors.transparent,
|
||||
isScrollable: true,
|
||||
tabAlignment: TabAlignment.center,
|
||||
tabs: [
|
||||
Tab(text: 'سکه'),
|
||||
Tab(text: 'بلیط'),
|
||||
Tab(text: 'کارت'),
|
||||
Tab(text: 'تجهیزات'),
|
||||
Tab(text: 'VIP'),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ===== تبها =====
|
||||
|
||||
class _CoinsTab extends StatelessWidget {
|
||||
final List<CoinPackage> packages;
|
||||
const _CoinsTab({required this.packages});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _grid(
|
||||
note: 'با داشتن اشتراک VIP در هر خرید ۱۰٪ سکه اضافه هدیه میگیرید.',
|
||||
children: [
|
||||
_ItemCard(
|
||||
title: 'سکه رایگان',
|
||||
glowColor: const Color(0xFF1B5E20),
|
||||
icon: Icons.card_giftcard,
|
||||
subtitle: 'با دیدن تبلیغ',
|
||||
action: _PriceButton(
|
||||
label: 'رایگان',
|
||||
green: true,
|
||||
onTap: () => context.read<ShopBloc>().add(AdRewardEvent()),
|
||||
),
|
||||
),
|
||||
for (final p in packages)
|
||||
_ItemCard(
|
||||
title: p.title,
|
||||
glowColor: const Color(0xFF1B5E20),
|
||||
icon: Icons.savings,
|
||||
ribbon: p.bonusPct > 0 ? '+${p.bonusPct}٪' : null,
|
||||
subtitle:
|
||||
'${p.coins} سکه${p.vipDays > 0 ? ' + ${p.vipDays} روز VIP' : ''}',
|
||||
action: _PriceButton(
|
||||
label: '${p.priceToman} تومان',
|
||||
onTap: () =>
|
||||
context.read<ShopBloc>().add(PurchaseEvent('coin', p.id)),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TicketsTab extends StatelessWidget {
|
||||
final List<TicketPackage> packages;
|
||||
const _TicketsTab({required this.packages});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _grid(
|
||||
note: 'با خرید بلیط میتوانید درخواست بر زدن مجدد در بازیها انجام دهید.',
|
||||
children: [
|
||||
for (final p in packages)
|
||||
_ItemCard(
|
||||
title: p.title,
|
||||
glowColor: const Color(0xFF8E1B7A),
|
||||
icon: Icons.confirmation_number,
|
||||
subtitle: '${p.tickets} بلیط',
|
||||
action: _PriceButton(
|
||||
label: '${p.priceToman} تومان',
|
||||
onTap: () =>
|
||||
context.read<ShopBloc>().add(PurchaseEvent('ticket', p.id)),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BoostersTab extends StatelessWidget {
|
||||
final List<Booster> boosters;
|
||||
const _BoostersTab({required this.boosters});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _grid(
|
||||
note: 'با بستههای تجربه، چند برابر XP بگیرید و سریعتر بالا بروید.',
|
||||
children: [
|
||||
for (final b in boosters)
|
||||
_ItemCard(
|
||||
title: b.title,
|
||||
glowColor: const Color(0xFF1E3A8A),
|
||||
icon: Icons.bolt,
|
||||
subtitle: 'تجربه ×${b.multiplier} — ${b.hours} ساعت',
|
||||
action: _PriceButton(
|
||||
label: '${b.priceToman} تومان',
|
||||
onTap: () =>
|
||||
context.read<ShopBloc>().add(PurchaseEvent('booster', b.id)),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _VipTab extends StatelessWidget {
|
||||
final List<VipPackage> packages;
|
||||
const _VipTab({required this.packages});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _grid(
|
||||
note: 'با VIP: میز خصوصی نامحدود، آمار کامل و ۱۰٪ سکهی هدیه.',
|
||||
children: [
|
||||
for (final p in packages)
|
||||
_ItemCard(
|
||||
title: p.title,
|
||||
glowColor: const Color(0xFF8A6D00),
|
||||
icon: Icons.workspace_premium,
|
||||
ribbon: p.months >= 6 ? 'بهترین' : null,
|
||||
subtitle: '${p.months} ماه اشتراک',
|
||||
action: _PriceButton(
|
||||
label: '${p.priceToman} تومان',
|
||||
onTap: () =>
|
||||
context.read<ShopBloc>().add(PurchaseEvent('vip', p.id)),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CardsTab extends StatelessWidget {
|
||||
final ShopData data;
|
||||
const _CardsTab({required this.data});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return _grid(
|
||||
note: 'با اسکین کارتهای متنوع حالوهوای بازی را عوض کن.',
|
||||
children: [
|
||||
for (final c in data.cardSkins)
|
||||
_ItemCard(
|
||||
title: c.title,
|
||||
glowColor: const Color(0xFF0E3C73),
|
||||
icon: Icons.style,
|
||||
subtitle: c.priceCoins > 0 ? '${c.priceCoins} سکه' : 'پیشفرض',
|
||||
action: _cardAction(context, c, data),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cardAction(BuildContext context, CardSkin c, ShopData d) {
|
||||
if (d.selectedCard == c.id) {
|
||||
return const _PriceButton(label: 'انتخاب شده', disabled: true);
|
||||
}
|
||||
if (d.owns(c.id)) {
|
||||
return _PriceButton(
|
||||
label: 'انتخاب',
|
||||
green: true,
|
||||
onTap: () => context.read<ShopBloc>().add(SelectCardEvent(c.id)),
|
||||
);
|
||||
}
|
||||
return _PriceButton(
|
||||
label: '${c.priceCoins} سکه',
|
||||
green: true,
|
||||
coin: true,
|
||||
onTap: () => context.read<ShopBloc>().add(BuyCardEvent(c.id)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Widget _grid({required String note, required List<Widget> children}) {
|
||||
return Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 6),
|
||||
child: Text(note,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: AppColors.gold, fontSize: 13)),
|
||||
),
|
||||
Expanded(
|
||||
child: GridView.count(
|
||||
crossAxisCount: 2,
|
||||
padding: const EdgeInsets.all(12),
|
||||
childAspectRatio: 0.74,
|
||||
mainAxisSpacing: 12,
|
||||
crossAxisSpacing: 12,
|
||||
children: children,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// ===== ویجتهای کارت آیتم =====
|
||||
|
||||
class _ItemCard extends StatelessWidget {
|
||||
final String title;
|
||||
final IconData icon;
|
||||
final Color glowColor;
|
||||
final String subtitle;
|
||||
final String? ribbon;
|
||||
final Widget action;
|
||||
const _ItemCard({
|
||||
required this.title,
|
||||
required this.icon,
|
||||
required this.glowColor,
|
||||
required this.subtitle,
|
||||
required this.action,
|
||||
this.ribbon,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final card = Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
gradient: const LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Color(0xFF6E1322), Color(0xFF3A0A12)],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: AppColors.gold, width: 1.6),
|
||||
boxShadow: const [
|
||||
BoxShadow(color: Colors.black54, blurRadius: 8, offset: Offset(0, 4)),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: AppColors.gold, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 6),
|
||||
Expanded(child: _GlowArt(color: glowColor, icon: icon)),
|
||||
const SizedBox(height: 4),
|
||||
Text(subtitle,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 11)),
|
||||
const SizedBox(height: 6),
|
||||
SizedBox(width: double.infinity, child: action),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ribbon == null) return card;
|
||||
return Stack(clipBehavior: Clip.none, children: [
|
||||
card,
|
||||
Positioned(
|
||||
top: 8,
|
||||
left: -22,
|
||||
child: Transform.rotate(
|
||||
angle: -0.7,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 26, vertical: 3),
|
||||
color: const Color(0xFF2E7D32),
|
||||
child: Text(ribbon!,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.bold)),
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
class _GlowArt extends StatelessWidget {
|
||||
final Color color;
|
||||
final IconData icon;
|
||||
const _GlowArt({required this.color, required this.icon});
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
gradient: RadialGradient(
|
||||
colors: [color, Colors.black.withValues(alpha: 0.85)],
|
||||
radius: 0.9,
|
||||
),
|
||||
border: Border.all(color: Colors.black26),
|
||||
),
|
||||
child: Center(child: Icon(icon, size: 44, color: AppColors.gold)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PriceButton extends StatelessWidget {
|
||||
final String label;
|
||||
final VoidCallback? onTap;
|
||||
final bool green;
|
||||
final bool coin;
|
||||
final bool disabled;
|
||||
const _PriceButton({
|
||||
required this.label,
|
||||
this.onTap,
|
||||
this.green = false,
|
||||
this.coin = false,
|
||||
this.disabled = false,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final busy = context.select((ShopBloc c) => c.state.busy);
|
||||
final colors = disabled
|
||||
? const [Color(0xFF555555), Color(0xFF333333)]
|
||||
: green
|
||||
? const [Color(0xFF3FA34D), Color(0xFF1B5E20)]
|
||||
: const [Color(0xFFD83A4A), Color(0xFF8E0E1B)];
|
||||
return Opacity(
|
||||
opacity: disabled ? 0.85 : 1,
|
||||
child: GestureDetector(
|
||||
onTap: (disabled || busy) ? null : onTap,
|
||||
child: Container(
|
||||
height: 36,
|
||||
alignment: Alignment.center,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: colors,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(color: AppColors.gold, width: 1.2),
|
||||
),
|
||||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
if (coin) ...[
|
||||
const Icon(Icons.monetization_on, color: AppColors.gold, size: 16),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
Flexible(
|
||||
child: Text(label,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 13,
|
||||
fontWeight: FontWeight.bold)),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
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 '../../../wallet/presentation/bloc/wallet_bloc.dart';
|
||||
import '../../../wallet/presentation/bloc/wallet_event.dart';
|
||||
import '../../../wallet/presentation/bloc/wallet_status.dart';
|
||||
import '../bloc/shop_bloc.dart';
|
||||
import '../bloc/shop_event.dart';
|
||||
import '../bloc/shop_state.dart';
|
||||
import '../bloc/shop_status.dart';
|
||||
|
||||
/// صفحهی اشتراک VIP: نمایش بستهها و خرید.
|
||||
class VipScreen extends StatelessWidget {
|
||||
const VipScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: GameBackground(
|
||||
child: SafeArea(
|
||||
child: BlocConsumer<ShopBloc, ShopBlocState>(
|
||||
listenWhen: (a, b) => a.actionStatus != b.actionStatus,
|
||||
listener: (context, state) {
|
||||
final s = state.actionStatus;
|
||||
if (s is ActionSuccess) {
|
||||
context.read<WalletBloc>().add(LoadWalletEvent());
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(s.message)));
|
||||
} else if (s is ActionError) {
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(s.message)));
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final st = state.loadStatus;
|
||||
if (st is ShopLoadError) {
|
||||
return Center(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
Text(st.message,
|
||||
style: const TextStyle(color: Colors.white70)),
|
||||
TextButton(
|
||||
onPressed: () =>
|
||||
context.read<ShopBloc>().add(LoadShopEvent()),
|
||||
child: const Text('تلاش مجدد')),
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (st is! ShopLoaded) {
|
||||
return const Center(
|
||||
child: CircularProgressIndicator(color: AppColors.gold));
|
||||
}
|
||||
final packages = st.data.vipPackages;
|
||||
final isVip = context.select((WalletBloc c) {
|
||||
final ws = c.state.walletStatus;
|
||||
return ws is WalletLoaded ? ws.wallet.vip : false;
|
||||
});
|
||||
return Column(
|
||||
children: [
|
||||
Row(children: [
|
||||
IconButton(
|
||||
onPressed: () => context.pop(),
|
||||
icon: const Icon(Icons.arrow_back, color: AppColors.gold),
|
||||
),
|
||||
const Spacer(),
|
||||
const GlowText('اشتراک VIP', size: 24),
|
||||
const Spacer(),
|
||||
const SizedBox(width: 48),
|
||||
]),
|
||||
Expanded(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
gradient: const LinearGradient(colors: [
|
||||
Color(0xFF5A3A00),
|
||||
Color(0xFF2A1A00)
|
||||
]),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border:
|
||||
Border.all(color: AppColors.gold, width: 1.3),
|
||||
),
|
||||
child: Column(children: [
|
||||
const Icon(Icons.workspace_premium,
|
||||
color: AppColors.gold, size: 40),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
isVip
|
||||
? 'شما کاربر VIP هستید'
|
||||
: 'با VIP بازی حرفهایتری داشته باش',
|
||||
style: const TextStyle(
|
||||
color: AppColors.gold,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16)),
|
||||
const SizedBox(height: 10),
|
||||
const _Benefit('میزهای خصوصی نامحدود'),
|
||||
const _Benefit('مشاهدهی کامل آمار بازی'),
|
||||
const _Benefit('۱۰٪ سکهی هدیه در هر خرید'),
|
||||
]),
|
||||
),
|
||||
const SizedBox(height: 18),
|
||||
for (final p in packages)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: _VipPackageTile(
|
||||
title: p.title,
|
||||
months: p.months,
|
||||
price: p.priceToman,
|
||||
busy: state.busy,
|
||||
onBuy: () => context
|
||||
.read<ShopBloc>()
|
||||
.add(PurchaseEvent('vip', p.id)),
|
||||
),
|
||||
),
|
||||
if (packages.isEmpty)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(top: 30),
|
||||
child: Text('فعلاً بستهای موجود نیست',
|
||||
style: TextStyle(color: Colors.white54)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _VipPackageTile extends StatelessWidget {
|
||||
final String title;
|
||||
final int months;
|
||||
final int price;
|
||||
final bool busy;
|
||||
final VoidCallback onBuy;
|
||||
const _VipPackageTile({
|
||||
required this.title,
|
||||
required this.months,
|
||||
required this.price,
|
||||
required this.busy,
|
||||
required this.onBuy,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
gradient: const LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Color(0xFF6E1322), Color(0xFF3A0A12)],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(14),
|
||||
border: Border.all(color: AppColors.gold, width: 1.4),
|
||||
),
|
||||
child: Row(children: [
|
||||
const Icon(Icons.workspace_premium, color: AppColors.gold, size: 34),
|
||||
const SizedBox(width: 12),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(title,
|
||||
style: const TextStyle(
|
||||
color: AppColors.gold,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16)),
|
||||
Text('$months ماه اشتراک',
|
||||
style: const TextStyle(color: Colors.white70, fontSize: 12)),
|
||||
],
|
||||
),
|
||||
const Spacer(),
|
||||
GameButton(label: '$price تومان', onTap: busy ? null : onBuy),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Benefit extends StatelessWidget {
|
||||
final String text;
|
||||
const _Benefit(this.text);
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 2),
|
||||
child: Row(children: [
|
||||
const Icon(Icons.check_circle, color: Color(0xFF6FCF7A), size: 16),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(text,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 13))),
|
||||
]),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../../core/locator/locator.dart';
|
||||
import '../../../../../core/network/api_provider_imp.dart';
|
||||
|
||||
/// تماسهای خامِ HTTP مربوط به کیفپول و پاداش روزانه.
|
||||
class WalletApiProvider {
|
||||
ApiProviderImp get _api => locator<ApiProviderImp>();
|
||||
|
||||
Future<Response> getWallet() => _api.get('/wallet');
|
||||
Future<Response> getMe() => _api.get('/me');
|
||||
Future<Response> claimDaily() => _api.post('/rewards/daily');
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import '../../domain/entities/wallet_entity.dart';
|
||||
|
||||
/// مدلِ کیفپول؛ از پاسخِ /wallet و /me ساخته میشود.
|
||||
class WalletModel extends WalletEntity {
|
||||
const WalletModel({
|
||||
required super.coins,
|
||||
required super.tickets,
|
||||
required super.xp,
|
||||
required super.trophies,
|
||||
required super.level,
|
||||
required super.xpIntoLevel,
|
||||
required super.xpForNext,
|
||||
required super.vip,
|
||||
required super.selectedCard,
|
||||
required super.name,
|
||||
required super.avatar,
|
||||
});
|
||||
|
||||
factory WalletModel.fromJson(
|
||||
Map<String, dynamic> wallet,
|
||||
Map<String, dynamic> user,
|
||||
) {
|
||||
final name = (user['first_name'] as String?)?.trim();
|
||||
final avatar = (user['avatar'] as String?)?.trim();
|
||||
return WalletModel(
|
||||
coins: (wallet['coins'] ?? 0) as int,
|
||||
tickets: (wallet['tickets'] ?? 0) as int,
|
||||
xp: (wallet['xp'] ?? 0) as int,
|
||||
trophies: (wallet['trophies'] ?? 0) as int,
|
||||
level: (wallet['level'] ?? 1) as int,
|
||||
xpIntoLevel: (wallet['xp_into_level'] ?? 0) as int,
|
||||
xpForNext: (wallet['xp_for_next'] ?? 1) as int,
|
||||
vip: (wallet['vip'] ?? false) as bool,
|
||||
selectedCard: (wallet['selected_card'] ?? 'simple') as String,
|
||||
name: (name == null || name.isEmpty) ? 'بازیکن' : name,
|
||||
avatar: (avatar == null || avatar.isEmpty) ? 'hakem-1' : avatar,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
import '../../../../core/error/custom_error.dart';
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../domain/entities/wallet_entity.dart';
|
||||
import '../../domain/repository/wallet_repository.dart';
|
||||
import '../data_source/remote/wallet_api_provider.dart';
|
||||
import '../model/wallet_model.dart';
|
||||
|
||||
class WalletRepositoryImpl extends WalletRepository {
|
||||
final WalletApiProvider api;
|
||||
WalletRepositoryImpl(this.api);
|
||||
|
||||
@override
|
||||
Future<DataState<WalletEntity>> getWallet() async {
|
||||
final results = await Future.wait([api.getWallet(), api.getMe()]);
|
||||
final Response wallet = results[0];
|
||||
final Response me = results[1];
|
||||
if (wallet.statusCode == 200 && me.statusCode == 200) {
|
||||
return DataSuccess(WalletModel.fromJson(
|
||||
Map<String, dynamic>.from(wallet.data as Map),
|
||||
Map<String, dynamic>.from((me.data['user'] ?? {}) as Map),
|
||||
));
|
||||
}
|
||||
return DataError(errorConvertor(wallet.statusCode, null));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<DataState<int>> claimDaily() async {
|
||||
final Response res = await api.claimDaily();
|
||||
if (res.statusCode == 200) {
|
||||
return DataSuccess((res.data['amount'] ?? 0) as int);
|
||||
}
|
||||
final d = res.data;
|
||||
final msg = (d is Map && d['message'] != null) ? d['message'].toString() : null;
|
||||
return DataError(errorConvertor(res.statusCode, msg));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/// موجودیتِ کیفپول و وضعیت اقتصادیِ کاربر (بههمراه نام و آواتار برای نوار لابی).
|
||||
class WalletEntity {
|
||||
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;
|
||||
final String name;
|
||||
final String avatar;
|
||||
|
||||
const WalletEntity({
|
||||
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,
|
||||
required this.name,
|
||||
required this.avatar,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../entities/wallet_entity.dart';
|
||||
|
||||
abstract class WalletRepository {
|
||||
Future<DataState<WalletEntity>> getWallet();
|
||||
|
||||
/// دریافت سکه روزانه؛ مقدار دریافتی را برمیگرداند.
|
||||
Future<DataState<int>> claimDaily();
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../repository/wallet_repository.dart';
|
||||
|
||||
class ClaimDailyUseCase implements UseCase<DataState<int>, NoParams> {
|
||||
final WalletRepository repository;
|
||||
ClaimDailyUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<int>> call(NoParams params) => repository.claimDaily();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../entities/wallet_entity.dart';
|
||||
import '../repository/wallet_repository.dart';
|
||||
|
||||
class GetWalletUseCase implements UseCase<DataState<WalletEntity>, NoParams> {
|
||||
final WalletRepository repository;
|
||||
GetWalletUseCase(this.repository);
|
||||
|
||||
@override
|
||||
Future<DataState<WalletEntity>> call(NoParams params) =>
|
||||
repository.getWallet();
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
abstract class DailyStatus {}
|
||||
|
||||
class DailyInitial extends DailyStatus {}
|
||||
|
||||
class DailyLoading extends DailyStatus {}
|
||||
|
||||
class DailySuccess extends DailyStatus {
|
||||
final int amount;
|
||||
DailySuccess(this.amount);
|
||||
}
|
||||
|
||||
class DailyError extends DailyStatus {
|
||||
final String message;
|
||||
DailyError(this.message);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
|
||||
import '../../../../core/resources/data_state.dart';
|
||||
import '../../../../core/usecase/use_case.dart';
|
||||
import '../../domain/use_cases/claim_daily_usecase.dart';
|
||||
import '../../domain/use_cases/get_wallet_usecase.dart';
|
||||
import 'daily_status.dart';
|
||||
import 'wallet_event.dart';
|
||||
import 'wallet_state.dart';
|
||||
import 'wallet_status.dart';
|
||||
|
||||
class WalletBloc extends Bloc<WalletEvent, WalletBlocState> {
|
||||
final GetWalletUseCase getWalletUseCase;
|
||||
final ClaimDailyUseCase claimDailyUseCase;
|
||||
|
||||
WalletBloc(this.getWalletUseCase, this.claimDailyUseCase)
|
||||
: super(WalletBlocState.initial()) {
|
||||
on<LoadWalletEvent>((event, emit) async {
|
||||
emit(state.copyWith(walletStatus: WalletLoading()));
|
||||
final res = await getWalletUseCase(const NoParams());
|
||||
if (res is DataSuccess) {
|
||||
emit(state.copyWith(walletStatus: WalletLoaded(res.data!)));
|
||||
} else {
|
||||
emit(state.copyWith(walletStatus: WalletError(res.error!)));
|
||||
}
|
||||
});
|
||||
|
||||
on<ClaimDailyEvent>((event, emit) async {
|
||||
emit(state.copyWith(dailyStatus: DailyLoading()));
|
||||
final res = await claimDailyUseCase(const NoParams());
|
||||
if (res is DataSuccess) {
|
||||
emit(state.copyWith(dailyStatus: DailySuccess(res.data!)));
|
||||
// پس از دریافت، کیفپول بهروزرسانی شود.
|
||||
final w = await getWalletUseCase(const NoParams());
|
||||
if (w is DataSuccess) {
|
||||
emit(state.copyWith(walletStatus: WalletLoaded(w.data!)));
|
||||
}
|
||||
} else {
|
||||
emit(state.copyWith(dailyStatus: DailyError(res.error!)));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
abstract class WalletEvent {}
|
||||
|
||||
class LoadWalletEvent extends WalletEvent {}
|
||||
|
||||
class ClaimDailyEvent extends WalletEvent {}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'daily_status.dart';
|
||||
import 'wallet_status.dart';
|
||||
|
||||
class WalletBlocState {
|
||||
final WalletStatus walletStatus;
|
||||
final DailyStatus dailyStatus;
|
||||
|
||||
WalletBlocState({required this.walletStatus, required this.dailyStatus});
|
||||
|
||||
factory WalletBlocState.initial() => WalletBlocState(
|
||||
walletStatus: WalletInitial(),
|
||||
dailyStatus: DailyInitial(),
|
||||
);
|
||||
|
||||
WalletBlocState copyWith({
|
||||
WalletStatus? walletStatus,
|
||||
DailyStatus? dailyStatus,
|
||||
}) =>
|
||||
WalletBlocState(
|
||||
walletStatus: walletStatus ?? this.walletStatus,
|
||||
dailyStatus: dailyStatus ?? this.dailyStatus,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import '../../domain/entities/wallet_entity.dart';
|
||||
|
||||
abstract class WalletStatus {}
|
||||
|
||||
class WalletInitial extends WalletStatus {}
|
||||
|
||||
class WalletLoading extends WalletStatus {}
|
||||
|
||||
class WalletLoaded extends WalletStatus {
|
||||
final WalletEntity wallet;
|
||||
WalletLoaded(this.wallet);
|
||||
}
|
||||
|
||||
class WalletError extends WalletStatus {
|
||||
final String message;
|
||||
WalletError(this.message);
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:random_avatar/random_avatar.dart';
|
||||
|
||||
import '../../../../core/theme/app_theme.dart';
|
||||
import '../../../../core/widgets/game_ui.dart';
|
||||
import '../../../auth/presentation/bloc/auth_bloc.dart';
|
||||
import '../../../auth/presentation/bloc/auth_event.dart';
|
||||
import '../../domain/entities/wallet_entity.dart';
|
||||
import '../bloc/daily_status.dart';
|
||||
import '../bloc/wallet_bloc.dart';
|
||||
import '../bloc/wallet_event.dart';
|
||||
import '../bloc/wallet_state.dart';
|
||||
import '../bloc/wallet_status.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<WalletBloc>().add(LoadWalletEvent());
|
||||
}
|
||||
|
||||
void _reload() => context.read<WalletBloc>().add(LoadWalletEvent());
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: GameBackground(
|
||||
child: BlocConsumer<WalletBloc, WalletBlocState>(
|
||||
listenWhen: (a, b) => a.dailyStatus != b.dailyStatus,
|
||||
listener: (context, state) {
|
||||
final d = state.dailyStatus;
|
||||
if (d is DailySuccess) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('سکه روزانه دریافت شد: +${d.amount}')));
|
||||
} else if (d is DailyError) {
|
||||
ScaffoldMessenger.of(context)
|
||||
.showSnackBar(SnackBar(content: Text(d.message)));
|
||||
}
|
||||
},
|
||||
builder: (context, state) {
|
||||
final st = state.walletStatus;
|
||||
final wallet = st is WalletLoaded ? st.wallet : null;
|
||||
return Column(
|
||||
children: [
|
||||
_TopBar(wallet: wallet, onCoinTap: () => _openShop(context)),
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 28),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const GlowText('سلطان حکم', size: 44),
|
||||
const SizedBox(height: 44),
|
||||
GameButton(
|
||||
label: 'بازی',
|
||||
icon: Icons.style,
|
||||
width: double.infinity,
|
||||
colors: const [Color(0xFFC2185B), Color(0xFF6A0D38)],
|
||||
onTap: () async {
|
||||
await context.push('/game/tiers');
|
||||
if (context.mounted) _reload();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
GameButton(
|
||||
label: 'دورهمی',
|
||||
icon: Icons.group_add,
|
||||
width: double.infinity,
|
||||
colors: const [Color(0xFF1565C0), Color(0xFF0A2E57)],
|
||||
onTap: () async {
|
||||
await context.push('/private');
|
||||
if (context.mounted) _reload();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
GameButton(
|
||||
label: 'فروشگاه',
|
||||
icon: Icons.storefront,
|
||||
width: double.infinity,
|
||||
colors: const [Color(0xFF7B1FA2), Color(0xFF3E0A57)],
|
||||
onTap: () => _openShop(context),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
GameButton(
|
||||
label: 'سکه روزانه',
|
||||
icon: Icons.monetization_on,
|
||||
width: double.infinity,
|
||||
colors: const [Color(0xFF3FA34D), Color(0xFF1B5E20)],
|
||||
onTap: () =>
|
||||
context.read<WalletBloc>().add(ClaimDailyEvent()),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: () {
|
||||
context.read<AuthBloc>().add(LogoutEvent());
|
||||
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> _openShop(BuildContext context) async {
|
||||
await context.push('/shop');
|
||||
if (context.mounted) _reload();
|
||||
}
|
||||
}
|
||||
|
||||
class _TopBar extends StatelessWidget {
|
||||
final WalletEntity? wallet;
|
||||
final VoidCallback onCoinTap;
|
||||
const _TopBar({required this.wallet, required this.onCoinTap});
|
||||
|
||||
@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(
|
||||
gradient: const LinearGradient(
|
||||
begin: Alignment.topCenter,
|
||||
end: Alignment.bottomCenter,
|
||||
colors: [Color(0xFF3A0A12), Color(0xFF1A0106)],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: AppColors.goldDark),
|
||||
boxShadow: const [BoxShadow(color: Colors.black54, blurRadius: 8)],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
GestureDetector(
|
||||
onTap: () async {
|
||||
await context.push('/profile');
|
||||
if (context.mounted) {
|
||||
context.read<WalletBloc>().add(LoadWalletEvent());
|
||||
}
|
||||
},
|
||||
child: Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
padding: const EdgeInsets.all(2),
|
||||
decoration: BoxDecoration(
|
||||
shape: BoxShape.circle,
|
||||
color: AppColors.panel,
|
||||
border: Border.all(color: AppColors.gold, width: 2),
|
||||
),
|
||||
child: (w == null || w.avatar.isEmpty)
|
||||
? const Icon(Icons.person, color: AppColors.gold)
|
||||
: ClipOval(child: RandomAvatar(w.avatar)),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 10),
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(children: [
|
||||
if (w != null && w.name.isNotEmpty) ...[
|
||||
Text(w.name,
|
||||
style: const TextStyle(
|
||||
color: Colors.white, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(width: 6),
|
||||
],
|
||||
if (w?.vip == true) const _VipTag(),
|
||||
]),
|
||||
const SizedBox(height: 2),
|
||||
Row(children: [
|
||||
const Icon(Icons.star, color: AppColors.gold, size: 16),
|
||||
const SizedBox(width: 4),
|
||||
Text('سطح ${w?.level ?? '-'}',
|
||||
style: const TextStyle(
|
||||
color: AppColors.gold, fontWeight: FontWeight.bold)),
|
||||
]),
|
||||
const SizedBox(height: 4),
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
child: SizedBox(
|
||||
width: 96,
|
||||
height: 7,
|
||||
child: LinearProgressIndicator(
|
||||
value: (w == null || w.xpForNext == 0)
|
||||
? 0
|
||||
: w.xpIntoLevel / w.xpForNext,
|
||||
backgroundColor: Colors.white10,
|
||||
valueColor: const AlwaysStoppedAnimation(AppColors.gold),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const Spacer(),
|
||||
GestureDetector(
|
||||
onTap: onCoinTap,
|
||||
child: StatChip(
|
||||
icon: Icons.confirmation_number, value: '${w?.tickets ?? 0}'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
GestureDetector(
|
||||
onTap: onCoinTap,
|
||||
child: StatChip(
|
||||
icon: Icons.monetization_on, value: '${w?.coins ?? 0}'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _VipTag extends StatelessWidget {
|
||||
const _VipTag();
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),
|
||||
decoration: BoxDecoration(
|
||||
gradient: const LinearGradient(
|
||||
colors: [Color(0xFFFFD54F), Color(0xFFB8860B)]),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: const Text('VIP',
|
||||
style: TextStyle(
|
||||
color: Color(0xFF3A0A12),
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 10)),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user