Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
59fea64df5 | ||
|
|
a09639abcf | ||
|
|
2d2d0149d8 | ||
|
|
894a38bb27 | ||
|
|
432d3c0b88 | ||
|
|
1a7916a836 | ||
|
|
030b00059e | ||
|
|
a804f41956 | ||
|
|
25d21f7cf8 | ||
|
|
c3f8c3fff0 | ||
|
|
1dc2d25a41 | ||
|
|
7c8fdd6ea2 | ||
|
|
5e90de812b | ||
|
|
ee28333da8 | ||
|
|
e89b60c844 | ||
|
|
b9df0a4d4a | ||
|
|
3a7b1b9794 | ||
|
|
5880960c42 | ||
|
|
ef277a3cfd | ||
|
|
e23ca3d1ff | ||
|
|
e84dd993af | ||
|
|
bcdf542606 | ||
|
|
16f8d3bdfc | ||
|
|
45d8aa0035 | ||
|
|
c0af76abd3 | ||
|
|
ff16a57a97 |
@@ -15,7 +15,7 @@ class CoinPurchaseController extends Controller
|
|||||||
{
|
{
|
||||||
$validated = $request->validate([
|
$validated = $request->validate([
|
||||||
'euros' => 'required|numeric|min:1|max:100',
|
'euros' => 'required|numeric|min:1|max:100',
|
||||||
'payment_type' => 'required|in:MBWAY,IBAN,MB,VISA,PAYPAL',
|
'payment_type' => 'required|in:MBWAY,MB,VISA,PAYPAL',
|
||||||
'payment_reference' => [
|
'payment_reference' => [
|
||||||
'required',
|
'required',
|
||||||
function ($attribute, $value, $fail) use ($request) {
|
function ($attribute, $value, $fail) use ($request) {
|
||||||
@@ -24,7 +24,6 @@ class CoinPurchaseController extends Controller
|
|||||||
|
|
||||||
switch ($type) {
|
switch ($type) {
|
||||||
case 'MBWAY': $regex = '/^9[0-9]{8}$/'; break;
|
case 'MBWAY': $regex = '/^9[0-9]{8}$/'; break;
|
||||||
case 'IBAN': $regex = '/^[A-Z]{2}[0-9]{23}$/'; break;
|
|
||||||
case 'MB': $regex = '/^[0-9]{5}-[0-9]{9}$/'; break;
|
case 'MB': $regex = '/^[0-9]{5}-[0-9]{9}$/'; break;
|
||||||
case 'VISA': $regex = '/^4[0-9]{15}$/'; break;
|
case 'VISA': $regex = '/^4[0-9]{15}$/'; break;
|
||||||
case 'PAYPAL':
|
case 'PAYPAL':
|
||||||
|
|||||||
@@ -13,19 +13,17 @@ class GameController extends Controller
|
|||||||
public function index(Request $request)
|
public function index(Request $request)
|
||||||
{
|
{
|
||||||
$this->authorize('viewAny', Game::class);
|
$this->authorize('viewAny', Game::class);
|
||||||
|
|
||||||
$user = Auth::user();
|
$user = Auth::user();
|
||||||
$query = Game::query()->with(["winner", "player1", "player2"]);
|
$query = Game::query()->with(["winner", "player1", "player2"]);
|
||||||
|
|
||||||
// Filter games based on user type
|
// Se não for Admin, mostra apenas os jogos do utilizador
|
||||||
if ($user->type !== 'A') {
|
if ($user->type !== 'A') {
|
||||||
// Players can only see games they participate in
|
|
||||||
$query->where(function ($q) use ($user) {
|
$query->where(function ($q) use ($user) {
|
||||||
$q->where('player1_user_id', $user->id)
|
$q->where('player1_user_id', $user->id)
|
||||||
->orWhere('player2_user_id', $user->id);
|
->orWhere('player2_user_id', $user->id);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
// Admins see all games (no filter needed)
|
|
||||||
|
|
||||||
if ($request->has("type") && in_array($request->type, ["3", "9"])) {
|
if ($request->has("type") && in_array($request->type, ["3", "9"])) {
|
||||||
$query->where("type", $request->type);
|
$query->where("type", $request->type);
|
||||||
@@ -43,87 +41,158 @@ class GameController extends Controller
|
|||||||
$query->where("status", $request->status);
|
$query->where("status", $request->status);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($request->has("sort_direction") && in_array($request->sort_direction, ["asc", "desc"])) {
|
if ($request->has("sort_direction") && in_array($request->sort_direction, ["asc", "desc"])) {
|
||||||
$query->orderBy("began_at", $request->sort_direction);
|
$query->orderBy("began_at", $request->sort_direction);
|
||||||
}else{
|
} else {
|
||||||
$query->orderBy("began_at", "desc");
|
$query->orderBy("began_at", "desc");
|
||||||
}
|
}
|
||||||
|
|
||||||
return response()->json($query->paginate(15));
|
return response()->json($query->paginate(15));
|
||||||
}
|
}
|
||||||
|
|
||||||
public function store(Request $request)
|
// --- MÉTODOS ADICIONADOS ---
|
||||||
|
|
||||||
|
// Host a new multiplayer Game
|
||||||
|
public function host(Request $request)
|
||||||
{
|
{
|
||||||
$this->authorize('create', Game::class);
|
$request->validate([
|
||||||
|
'type' => 'required|in:3,9'
|
||||||
$validated = $request->validate([
|
|
||||||
"type" => "required|in:3,9",
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
$user = Auth::user();
|
$user = $request->user();
|
||||||
|
|
||||||
|
// Check for active game
|
||||||
$activeGame = Game::where(function ($q) use ($user) {
|
$activeGame = Game::where(function ($q) use ($user) {
|
||||||
$q->where("player1_user_id", $user->id)
|
$q->where("player1_user_id", $user->id)
|
||||||
->orWhere("player2_user_id", $user->id);
|
->orWhere("player2_user_id", $user->id);
|
||||||
})
|
})
|
||||||
->whereIn("status", ["Pending", "Playing"])
|
->whereIn("status", ["Pending", "Playing"])
|
||||||
->exists();
|
->exists();
|
||||||
|
|
||||||
if ($activeGame) {
|
if ($activeGame) {
|
||||||
return response()->json(["message" => "You already have an active game."], 400);
|
return response()->json(["message" => "You already have an active game."], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$game = Game::create([
|
||||||
|
'type' => $request->type,
|
||||||
|
'status' => 'Pending',
|
||||||
|
'player1_user_id' => $user->id,
|
||||||
|
'player2_user_id' => self::GHOST_ID, // Ghost ID = 1 (Waiting for player)
|
||||||
|
'began_at' => now(),
|
||||||
|
'player1_points' => 0,
|
||||||
|
'player2_points' => 0,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json($game, 201);
|
||||||
|
}
|
||||||
|
|
||||||
|
// List open games (Available to join)
|
||||||
|
public function open(Request $request)
|
||||||
|
{
|
||||||
|
$type = $request->query('type', '9');
|
||||||
|
$GHOST_ID = 1;
|
||||||
|
|
||||||
|
$games = Game::where('status', 'Pending')
|
||||||
|
->where('player2_user_id', $GHOST_ID) // Games waiting for P2
|
||||||
|
->where('type', $type)
|
||||||
|
->with('player1')
|
||||||
|
->orderBy('began_at', 'asc')
|
||||||
|
->paginate(10);
|
||||||
|
|
||||||
|
return response()->json($games);
|
||||||
|
}
|
||||||
|
// ---------------------------
|
||||||
|
|
||||||
|
public function store(Request $request)
|
||||||
|
{
|
||||||
|
$this->authorize('create', Game::class);
|
||||||
|
|
||||||
|
$validated = $request->validate([
|
||||||
|
"type" => "required|in:3,9",
|
||||||
|
"player2_user_id" => "nullable|integer|exists:users,id",
|
||||||
|
"match_id" => "nullable|integer|exists:matches,id",
|
||||||
|
"status" => "nullable|in:Pending,Playing",
|
||||||
|
"began_at" => "nullable|date"
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user = Auth::user();
|
||||||
|
|
||||||
|
$activeGame = Game::where(function ($q) use ($user) {
|
||||||
|
$q->where("player1_user_id", $user->id)
|
||||||
|
->orWhere("player2_user_id", $user->id);
|
||||||
|
})
|
||||||
|
->whereIn("status", ["Pending", "Playing"])
|
||||||
|
->exists();
|
||||||
|
|
||||||
|
if ($activeGame) {
|
||||||
|
return response()->json(["message" => "You already have an active game."], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$player2Id = $request->input('player2_user_id', self::GHOST_ID);
|
||||||
|
|
||||||
|
$initialStatus = $request->input('status', 'Pending');
|
||||||
|
|
||||||
|
// If specific player 2 is provided, auto-start game
|
||||||
|
if ($player2Id !== self::GHOST_ID && !$request->has('status')) {
|
||||||
|
$initialStatus = 'Playing';
|
||||||
}
|
}
|
||||||
|
|
||||||
$game = Game::create([
|
$game = Game::create([
|
||||||
"type" => $validated["type"],
|
"type" => $validated["type"],
|
||||||
"status" => "Pending",
|
"status" => $initialStatus,
|
||||||
"player1_user_id" => $user->id,
|
"player1_user_id" => $user->id,
|
||||||
"player2_user_id" => self::GHOST_ID,
|
"player2_user_id" => $player2Id,
|
||||||
"winner_user_id" => self::GHOST_ID,
|
"winner_user_id" => null,
|
||||||
"loser_user_id" => self::GHOST_ID,
|
"loser_user_id" => null,
|
||||||
"began_at" => now(),
|
"match_id" => $request->input('match_id', null),
|
||||||
|
"began_at" => $request->input('began_at', now()),
|
||||||
"player1_points" => 0,
|
"player1_points" => 0,
|
||||||
"player2_points" => 0,
|
"player2_points" => 0,
|
||||||
"custom" => null,
|
"custom" => null,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return response()->json([
|
return response()->json([
|
||||||
"message" => "Multiplayer game room created",
|
"message" => "Game created",
|
||||||
"game" => $game,
|
"game" => $game,
|
||||||
], 201);
|
], 201);
|
||||||
}
|
}
|
||||||
|
|
||||||
public function join(Game $game)
|
public function join(Request $request, Game $game)
|
||||||
{
|
{
|
||||||
$this->authorize('join', $game);
|
// Prevent joining if already full or started
|
||||||
|
if ($game->status !== 'Pending' || $game->player2_user_id !== self::GHOST_ID) {
|
||||||
$user = Auth::user();
|
return response()->json(['message' => 'Game is not available'], 400);
|
||||||
|
|
||||||
if ($game->player1_user_id == $user->id) {
|
|
||||||
return response()->json([
|
|
||||||
"message" => "You are the host. Waiting for opponent...",
|
|
||||||
"game" => $game
|
|
||||||
], 200);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($game->player2_user_id !== self::GHOST_ID) {
|
// Prevent joining your own game
|
||||||
return response()->json(["message" => "Game is full"], 400);
|
if ($game->player1_user_id === $request->user()->id) {
|
||||||
|
return response()->json(['message' => 'Cannot join your own game'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if joining user has another active game
|
||||||
|
$activeGame = Game::where(function ($q) use ($request) {
|
||||||
|
$q->where("player1_user_id", $request->user()->id)
|
||||||
|
->orWhere("player2_user_id", $request->user()->id);
|
||||||
|
})
|
||||||
|
->whereIn("status", ["Pending", "Playing"])
|
||||||
|
->exists();
|
||||||
|
|
||||||
|
if ($activeGame) {
|
||||||
|
return response()->json(["message" => "You already have an active game."], 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
$game->update([
|
$game->update([
|
||||||
"status" => "Playing",
|
'player2_user_id' => $request->user()->id,
|
||||||
"player2_user_id" => $user->id,
|
'status' => 'Playing',
|
||||||
]);
|
]);
|
||||||
|
|
||||||
return response()->json([
|
return response()->json($game);
|
||||||
"message" => "Joined successfully!",
|
|
||||||
"game" => $game,
|
|
||||||
], 200);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public function show(Game $game)
|
public function show(Game $game)
|
||||||
{
|
{
|
||||||
$this->authorize('view', $game);
|
$this->authorize('view', $game);
|
||||||
|
|
||||||
$game->load(["player1", "player2", "winner"]);
|
$game->load(["player1", "player2", "winner"]);
|
||||||
return response()->json($game);
|
return response()->json($game);
|
||||||
}
|
}
|
||||||
@@ -131,7 +200,7 @@ class GameController extends Controller
|
|||||||
public function update(Request $request, Game $game)
|
public function update(Request $request, Game $game)
|
||||||
{
|
{
|
||||||
$this->authorize('update', $game);
|
$this->authorize('update', $game);
|
||||||
|
|
||||||
if ($game->status == "Ended") {
|
if ($game->status == "Ended") {
|
||||||
return response()->json(["message" => "Game already ended"], 400);
|
return response()->json(["message" => "Game already ended"], 400);
|
||||||
}
|
}
|
||||||
@@ -158,13 +227,13 @@ class GameController extends Controller
|
|||||||
public function resign(Game $game)
|
public function resign(Game $game)
|
||||||
{
|
{
|
||||||
$this->authorize('resign', $game);
|
$this->authorize('resign', $game);
|
||||||
|
|
||||||
$user = Auth::user();
|
$user = Auth::user();
|
||||||
|
|
||||||
$game->update([
|
$game->update([
|
||||||
'status' => 'Ended',
|
'status' => 'Ended',
|
||||||
'winner_user_id' => $game->player1_user_id === $user->id
|
'winner_user_id' => $game->player1_user_id === $user->id
|
||||||
? $game->player2_user_id
|
? $game->player2_user_id
|
||||||
: $game->player1_user_id,
|
: $game->player1_user_id,
|
||||||
'loser_user_id' => $user->id,
|
'loser_user_id' => $user->id,
|
||||||
'ended_at' => now(),
|
'ended_at' => now(),
|
||||||
@@ -175,4 +244,4 @@ class GameController extends Controller
|
|||||||
'game' => $game->fresh(),
|
'game' => $game->fresh(),
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -3,12 +3,10 @@
|
|||||||
namespace App\Http\Controllers;
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
use App\Models\MatchGame;
|
use App\Models\MatchGame;
|
||||||
use App\Models\Game;
|
|
||||||
use App\Models\CoinTransaction;
|
use App\Models\CoinTransaction;
|
||||||
use App\Models\CoinTransactionType;
|
use App\Models\CoinTransactionType;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use App\Http\Requests\StoreMatchRequest;
|
use App\Http\Requests\StoreMatchRequest;
|
||||||
use Illuminate\Support\Facades\Auth;
|
|
||||||
use Illuminate\Support\Facades\DB;
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
class MatchController extends Controller
|
class MatchController extends Controller
|
||||||
@@ -196,4 +194,77 @@ class MatchController extends Controller
|
|||||||
return response()->json($match);
|
return response()->json($match);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function host(Request $request)
|
||||||
|
{
|
||||||
|
$request->validate([
|
||||||
|
'type' => 'required|in:3,9',
|
||||||
|
'stake' => 'required|integer|min:0'
|
||||||
|
]);
|
||||||
|
|
||||||
|
$user = $request->user();
|
||||||
|
$stake = $request->stake;
|
||||||
|
|
||||||
|
if ($user->coins_balance < $stake) {
|
||||||
|
return response()->json(['message' => 'Insufficient coin balance'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
$activeMatch = MatchGame::where(function ($q) use ($user) {
|
||||||
|
$q->where('player1_user_id', $user->id)
|
||||||
|
->orWhere('player2_user_id', $user->id);
|
||||||
|
})->whereIn('status', ['Pending', 'Playing'])->exists();
|
||||||
|
|
||||||
|
if ($activeMatch) {
|
||||||
|
return response()->json(['message' => 'You already have an active match.'], 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
return DB::transaction(function () use ($request, $user, $stake) {
|
||||||
|
$GHOST_ID = 1;
|
||||||
|
|
||||||
|
$user->decrement('coins_balance', $stake);
|
||||||
|
|
||||||
|
$stakeType = CoinTransactionType::firstOrCreate(
|
||||||
|
['name' => 'Match stake'],
|
||||||
|
['type' => 'D'] // Debit
|
||||||
|
);
|
||||||
|
|
||||||
|
$match = MatchGame::create([
|
||||||
|
'type' => $request->type,
|
||||||
|
'status' => 'Pending',
|
||||||
|
'player1_user_id' => $user->id,
|
||||||
|
'player2_user_id' => $GHOST_ID,
|
||||||
|
'winner_user_id' => null,
|
||||||
|
'loser_user_id' => null,
|
||||||
|
'stake' => $stake,
|
||||||
|
'began_at' => now(),
|
||||||
|
'player1_marks' => 0, 'player2_marks' => 0,
|
||||||
|
'player1_points' => 0, 'player2_points' => 0,
|
||||||
|
]);
|
||||||
|
|
||||||
|
CoinTransaction::create([
|
||||||
|
'user_id' => $user->id,
|
||||||
|
'match_id' => $match->id,
|
||||||
|
'coin_transaction_type_id' => $stakeType->id,
|
||||||
|
'transaction_datetime' => now(),
|
||||||
|
'coins' => -$stake,
|
||||||
|
]);
|
||||||
|
|
||||||
|
return response()->json($match, 201);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public function open(Request $request)
|
||||||
|
{
|
||||||
|
$type = $request->query('type', '9');
|
||||||
|
$GHOST_ID = 1;
|
||||||
|
|
||||||
|
$matches = MatchGame::where('status', 'Pending')
|
||||||
|
->where('player2_user_id', $GHOST_ID)
|
||||||
|
->where('type', $type)
|
||||||
|
->with('player1')
|
||||||
|
->orderBy('began_at', 'asc')
|
||||||
|
->paginate(10);
|
||||||
|
|
||||||
|
return response()->json($matches);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -29,16 +29,23 @@ class StatisticsController extends Controller
|
|||||||
{
|
{
|
||||||
$type = $request->query('type');
|
$type = $request->query('type');
|
||||||
|
|
||||||
$query = User::where('type', 'P')
|
$leaderboard = User::where('type', 'P')
|
||||||
->withCount(['wonGames' => function ($query) use ($type) {
|
->withCount(['wonGames' => function ($query) use ($type) {
|
||||||
if ($type) {
|
if ($type) {
|
||||||
$query->where('type', $type);
|
$query->where('type', $type);
|
||||||
}
|
}
|
||||||
}])
|
}])
|
||||||
->orderBy('won_games_count', 'desc')
|
->orderBy('won_games_count', 'desc')
|
||||||
->take(10);
|
->paginate(10);
|
||||||
|
|
||||||
$leaderboard = $query->get(['id', 'nickname', 'photo_avatar_filename']);
|
$leaderboard->through(function ($user) {
|
||||||
|
return [
|
||||||
|
'id' => $user->id,
|
||||||
|
'nickname' => $user->nickname,
|
||||||
|
'photo_avatar_filename' => $user->photo_avatar_filename,
|
||||||
|
'won_games_count' => $user->won_games_count,
|
||||||
|
];
|
||||||
|
});
|
||||||
|
|
||||||
return response()->json($leaderboard);
|
return response()->json($leaderboard);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Http\Controllers;
|
||||||
|
|
||||||
|
use App\Models\CoinTransaction;
|
||||||
|
use Illuminate\Http\Request;
|
||||||
|
|
||||||
|
class TransactionController extends Controller
|
||||||
|
{
|
||||||
|
|
||||||
|
public function index(Request $request)
|
||||||
|
{
|
||||||
|
|
||||||
|
$this->authorize('viewAny', CoinTransaction::class);
|
||||||
|
|
||||||
|
$query = CoinTransaction::with('user:id,nickname,email', 'type:id,name');
|
||||||
|
|
||||||
|
if ($request->has('sort_coins')) {
|
||||||
|
$direction = $request->get('sort_coins') === 'asc' ? 'asc' : 'desc';
|
||||||
|
$query->orderBy('coins', $direction);
|
||||||
|
}
|
||||||
|
|
||||||
|
$dateDirection = $request->get('sort_datetime') === 'asc' ? 'asc' : 'desc';
|
||||||
|
$query->orderBy('transaction_datetime', $dateDirection);
|
||||||
|
|
||||||
|
|
||||||
|
$transactions = $query->paginate(15);
|
||||||
|
|
||||||
|
return response()->json($transactions);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
|
|||||||
|
|
||||||
use App\Models\Game;
|
use App\Models\Game;
|
||||||
use App\Models\User;
|
use App\Models\User;
|
||||||
|
use App\Models\MatchGame;
|
||||||
use Illuminate\Http\Request;
|
use Illuminate\Http\Request;
|
||||||
use Illuminate\Support\Facades\Auth;
|
use Illuminate\Support\Facades\Auth;
|
||||||
use Illuminate\Support\Facades\Hash;
|
use Illuminate\Support\Facades\Hash;
|
||||||
@@ -21,11 +22,14 @@ class UserController extends Controller
|
|||||||
|
|
||||||
$query = User::query();
|
$query = User::query();
|
||||||
|
|
||||||
// Filtros úteis para o Backoffice
|
|
||||||
if ($request->has('type')) {
|
if ($request->has('type')) {
|
||||||
$query->where('type', $request->type);
|
$query->where('type', $request->type);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($request->has('blocked')) {
|
||||||
|
$query->where('blocked', $request->type);
|
||||||
|
}
|
||||||
|
|
||||||
if ($request->has('search')) {
|
if ($request->has('search')) {
|
||||||
$query->where(function ($q) use ($request) {
|
$query->where(function ($q) use ($request) {
|
||||||
$q->where('name', 'like', '%'.$request->search.'%')
|
$q->where('name', 'like', '%'.$request->search.'%')
|
||||||
@@ -47,7 +51,6 @@ class UserController extends Controller
|
|||||||
|
|
||||||
$validated = $request->validate([
|
$validated = $request->validate([
|
||||||
'name' => 'required|string|max:255',
|
'name' => 'required|string|max:255',
|
||||||
'nickname' => 'required|string|max:20|unique:users,nickname',
|
|
||||||
'email' => 'required|email|unique:users,email',
|
'email' => 'required|email|unique:users,email',
|
||||||
'password' => 'required|string|min:3',
|
'password' => 'required|string|min:3',
|
||||||
'type' => 'required|in:A,U',
|
'type' => 'required|in:A,U',
|
||||||
@@ -176,72 +179,87 @@ class UserController extends Controller
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GET /api/users/{user}/matches
|
* GET /api/users/{user}/games
|
||||||
* Histórico de Jogos Multiplayer do Utilizador
|
* Histórico de Partidas Individuais (Cartas)
|
||||||
*/
|
*/
|
||||||
public function getMatches(Request $request, User $user)
|
public function getGames(Request $request, User $user)
|
||||||
{
|
{
|
||||||
$this->authorize('view', $user);
|
$this->authorize('view', $user);
|
||||||
|
|
||||||
$outcomeSql = "CASE
|
// Define a query base para GAMES
|
||||||
WHEN is_draw = 1 THEN 'DRAW'
|
$query = \App\Models\Game::query()
|
||||||
WHEN winner_user_id = {$user->id} THEN 'WIN'
|
->where(function ($q) use ($user) {
|
||||||
ELSE 'LOSS'
|
$q->where('player1_user_id', $user->id)
|
||||||
END";
|
->orWhere('player2_user_id', $user->id);
|
||||||
|
})
|
||||||
$query = Game::query()
|
->with(['winner', 'player1', 'player2']);
|
||||||
->select('*')
|
|
||||||
->selectRaw("($outcomeSql) as outcome_text")
|
|
||||||
->where(function ($q) use ($user) {
|
|
||||||
$q->where('player1_user_id', $user->id)
|
|
||||||
->orWhere('player2_user_id', $user->id);
|
|
||||||
})
|
|
||||||
->with(['winner', 'player1', 'player2']);
|
|
||||||
|
|
||||||
if ($request->has('type')) {
|
if ($request->has('type')) {
|
||||||
$query->where('type', $request->type);
|
$query->where('type', $request->type);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($request->has('status')) {
|
if ($request->has('status')) {
|
||||||
$query->where('status', $request->status);
|
$query->where('status', $request->status);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($request->filled('outcome')) {
|
$sortDirection = $request->get('sort_direction', 'desc');
|
||||||
switch ($request->outcome) {
|
$query->orderBy('began_at', $sortDirection);
|
||||||
case 'win':
|
|
||||||
$query->where('winner_user_id', $user->id)
|
|
||||||
->where('is_draw', 0);
|
$games = $query->paginate(10);
|
||||||
break;
|
|
||||||
case 'loss':
|
$games->getCollection()->transform(function ($game) use ($user) {
|
||||||
case 'forfeit': // Forfeit treated as loss for now
|
if ($game->winner_user_id == $user->id) {
|
||||||
$query->where('loser_user_id', $user->id)
|
$game->outcome = 'win';
|
||||||
->where('is_draw', 0);
|
} elseif ($game->is_draw) {
|
||||||
break;
|
$game->outcome = 'draw';
|
||||||
case 'draw':
|
} else {
|
||||||
$query->where('is_draw', 1);
|
$game->outcome = 'loss';
|
||||||
break;
|
}
|
||||||
}
|
return $game;
|
||||||
|
});
|
||||||
|
|
||||||
|
return response()->json($games);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($request->has('date_from')) {
|
/**
|
||||||
$query->whereDate('began_at', '>=', $request->date_from);
|
* GET /api/users/{user}/matches
|
||||||
|
* Histórico de Matches (Apostas / Marcas)
|
||||||
|
*/
|
||||||
|
public function getMatches(Request $request, User $user)
|
||||||
|
{
|
||||||
|
$this->authorize('view', $user);
|
||||||
|
|
||||||
|
$query = MatchGame::query()
|
||||||
|
->where(function ($q) use ($user) {
|
||||||
|
$q->where('player1_user_id', $user->id)
|
||||||
|
->orWhere('player2_user_id', $user->id);
|
||||||
|
})
|
||||||
|
->with(['winner', 'player1', 'player2']);
|
||||||
|
|
||||||
|
if ($request->has('type')) {
|
||||||
|
$query->where('type', $request->type);
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($request->has('status')) {
|
||||||
|
$query->where('status', $request->status);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ($request->has('date_to')) {
|
$sortDirection = $request->get('sort_direction', 'desc');
|
||||||
$query->whereDate('ended_at', '<=', $request->date_to);
|
$query->orderBy('began_at', $sortDirection);
|
||||||
}
|
|
||||||
|
|
||||||
$order = $request->get('sort_by', 'began_at');
|
$matches = $query->paginate(10);
|
||||||
$direction = $request->get('sort_direction', 'desc');
|
|
||||||
|
|
||||||
if ($order === 'outcome') {
|
$matches->getCollection()->transform(function ($match) use ($user) {
|
||||||
$query->orderBy('outcome_text', $direction);
|
if ($match->winner_user_id == $user->id) {
|
||||||
} else {
|
$match->outcome = 'win';
|
||||||
$query->orderBy($order, $direction);
|
} elseif ($match->winner_user_id && $match->winner_user_id != $user->id) {
|
||||||
}
|
$match->outcome = 'loss';
|
||||||
|
} else {
|
||||||
$matches = $query->orderBy($order, $direction)
|
$match->outcome = 'interrupted'; // Matches geralmente não empatam (alguém chega a 4 marcas)
|
||||||
->paginate(10);
|
}
|
||||||
|
return $match;
|
||||||
|
});
|
||||||
|
|
||||||
return response()->json($matches);
|
return response()->json($matches);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,11 +29,22 @@ class Game extends Model
|
|||||||
'match_id'
|
'match_id'
|
||||||
];
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'began_at' => 'datetime',
|
||||||
|
'ended_at' => 'datetime',
|
||||||
|
'is_draw' => 'boolean',
|
||||||
|
];
|
||||||
|
|
||||||
public function winner()
|
public function winner()
|
||||||
{
|
{
|
||||||
return $this->belongsTo(User::class, "winner_user_id");
|
return $this->belongsTo(User::class, "winner_user_id");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function loser()
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class, "loser_user_id");
|
||||||
|
}
|
||||||
|
|
||||||
public function player1()
|
public function player1()
|
||||||
{
|
{
|
||||||
return $this->belongsTo(User::class, 'player1_user_id');
|
return $this->belongsTo(User::class, 'player1_user_id');
|
||||||
|
|||||||
@@ -0,0 +1,18 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Policies;
|
||||||
|
|
||||||
|
use App\Models\CoinTransaction;
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Auth\Access\Response;
|
||||||
|
|
||||||
|
class CoinTransactionPolicy
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Determine whether the user can view any models.
|
||||||
|
*/
|
||||||
|
public function viewAny(User $user): bool
|
||||||
|
{
|
||||||
|
return $user->type === 'A' ? true : false;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -20,7 +20,7 @@ class GamePolicy
|
|||||||
*/
|
*/
|
||||||
public function view(User $user, Game $game): bool
|
public function view(User $user, Game $game): bool
|
||||||
{
|
{
|
||||||
if ($user->type === 'A') {
|
if ($user->type === "A") {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -31,6 +31,10 @@ class GamePolicy
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($game->status === "Pending") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -39,7 +43,7 @@ class GamePolicy
|
|||||||
*/
|
*/
|
||||||
public function create(User $user): bool
|
public function create(User $user): bool
|
||||||
{
|
{
|
||||||
if ($user->type === 'A') {
|
if ($user->type === "A") {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,28 +52,32 @@ class GamePolicy
|
|||||||
|
|
||||||
public function join(User $user, Game $game): bool
|
public function join(User $user, Game $game): bool
|
||||||
{
|
{
|
||||||
if ($user->type === 'A') {
|
if ($user->type === "A") {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
$game->status !== 'waiting' ||
|
$game->status !== "Pending" ||
|
||||||
$game->player1_user_id === $user->id
|
$game->player1_user_id === $user->id
|
||||||
) {
|
) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($game->player2_user_id !== null && $game->player2_user_id !== 1) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
public function resign(User $user, Game $game): bool
|
public function resign(User $user, Game $game): bool
|
||||||
{
|
{
|
||||||
if ($user->type === 'A') {
|
if ($user->type === "A") {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
$game->status !== 'ongoing' ||
|
$game->status !== "Playing" ||
|
||||||
($game->player1_user_id !== $user->id &&
|
($game->player1_user_id !== $user->id &&
|
||||||
$game->player2_user_id !== $user->id)
|
$game->player2_user_id !== $user->id)
|
||||||
) {
|
) {
|
||||||
@@ -78,34 +86,32 @@ class GamePolicy
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine whether the user can update the model.
|
* Determine whether the user can update the model.
|
||||||
*/
|
*/
|
||||||
public function update(User $user, Game $game): bool
|
public function update(User $user, Game $game): bool
|
||||||
{
|
{
|
||||||
if ($user->type === 'A') {
|
if ($user->type === "A") {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (!in_array($game->status, ['Playing', 'Pending'])) {
|
||||||
$game->status !== 'ongoing' ||
|
return false;
|
||||||
($game->player1_user_id !== $user->id &&
|
}
|
||||||
$game->player2_user_id !== $user->id)
|
|
||||||
) {
|
if ($game->player1_user_id !== $user->id && $game->player2_user_id !== $user->id) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Determine whether the user can delete the model.
|
* Determine whether the user can delete the model.
|
||||||
*/
|
*/
|
||||||
public function delete(User $user, Game $game): bool
|
public function delete(User $user, Game $game): bool
|
||||||
{
|
{
|
||||||
// Only admins can delete games
|
// Only admins can delete games
|
||||||
return $user->type === 'A';
|
return $user->type === "A";
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
+18
-17
@@ -7,6 +7,7 @@ use App\Http\Controllers\ProfileController;
|
|||||||
use App\Http\Controllers\StatisticsController;
|
use App\Http\Controllers\StatisticsController;
|
||||||
use App\Http\Controllers\UserController;
|
use App\Http\Controllers\UserController;
|
||||||
use App\Http\Controllers\CoinPurchaseController;
|
use App\Http\Controllers\CoinPurchaseController;
|
||||||
|
use App\Http\Controllers\TransactionController;
|
||||||
use Illuminate\Support\Facades\Route;
|
use Illuminate\Support\Facades\Route;
|
||||||
|
|
||||||
Route::prefix('v1')->group(function () {
|
Route::prefix('v1')->group(function () {
|
||||||
@@ -39,31 +40,28 @@ Route::prefix('v1')->group(function () {
|
|||||||
// User Resources
|
// User Resources
|
||||||
Route::prefix('/users')->group(function () {
|
Route::prefix('/users')->group(function () {
|
||||||
Route::get('/{user}', [UserController::class, 'show']);
|
Route::get('/{user}', [UserController::class, 'show']);
|
||||||
Route::get('/{user}/matches', [
|
|
||||||
UserController::class,
|
|
||||||
'getMatches',
|
|
||||||
]);
|
|
||||||
Route::get('/{user}/transactions', [UserController::class, 'getTransactions']);
|
Route::get('/{user}/transactions', [UserController::class, 'getTransactions']);
|
||||||
|
Route::get('/{user}/games', [UserController::class, 'getGames']);
|
||||||
|
Route::get('/{user}/matches', [UserController::class, 'getMatches']);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Game Resources
|
|
||||||
Route::prefix('games')->group(function () {
|
Route::prefix('games')->group(function () {
|
||||||
Route::apiResource('/', GameController::class)->parameters([
|
Route::post('host', [GameController::class, 'host']);
|
||||||
'' => 'game',
|
Route::get('open', [GameController::class, 'open']);
|
||||||
]);
|
Route::get('/', [GameController::class, 'index']);
|
||||||
Route::post('/{game}/join', [GameController::class, 'join']);
|
Route::get('/{game}', [GameController::class, 'show']);
|
||||||
|
Route::post('/', [GameController::class, 'store']);
|
||||||
|
Route::put('/{game}', [GameController::class, 'update']);
|
||||||
|
Route::delete('/{game}', [GameController::class, 'destroy']);
|
||||||
Route::post('/{game}/resign', [GameController::class, 'resign']);
|
Route::post('/{game}/resign', [GameController::class, 'resign']);
|
||||||
|
Route::post('/{game}/join', [GameController::class, 'join']);
|
||||||
});
|
});
|
||||||
|
|
||||||
// Match Resources
|
|
||||||
Route::prefix('matches')->group(function () {
|
Route::prefix('matches')->group(function () {
|
||||||
Route::apiResource('/', MatchController::class)->parameters([
|
Route::apiResource('/', MatchController::class)->parameters(['' => 'match']);
|
||||||
'' => 'match',
|
Route::post('/{match}/join', [MatchController::class, 'join']);
|
||||||
]);
|
Route::post('host', [MatchController::class, 'host']); // <--- NOVA
|
||||||
Route::post('/{match}/join', [
|
Route::get('open', [MatchController::class, 'open']);
|
||||||
MatchController::class,
|
|
||||||
'join',
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Admin Routes
|
// Admin Routes
|
||||||
@@ -71,6 +69,9 @@ Route::prefix('v1')->group(function () {
|
|||||||
->prefix('admin')
|
->prefix('admin')
|
||||||
->group(function () {
|
->group(function () {
|
||||||
Route::get('/statistics', [StatisticsController::class, 'getAdminStats']);
|
Route::get('/statistics', [StatisticsController::class, 'getAdminStats']);
|
||||||
|
Route::get('/transactions', [TransactionController::class, 'index']);
|
||||||
|
Route::get('/games', [GameController::class, 'index']);
|
||||||
|
Route::get('/matches', [MatchController::class, 'index']);
|
||||||
Route::prefix('users')->group(function () {
|
Route::prefix('users')->group(function () {
|
||||||
Route::get('/', [UserController::class, 'index']);
|
Route::get('/', [UserController::class, 'index']);
|
||||||
Route::post('/', [UserController::class, 'store']);
|
Route::post('/', [UserController::class, 'store']);
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ Content-Type: application/json
|
|||||||
Accept: application/json
|
Accept: application/json
|
||||||
|
|
||||||
{
|
{
|
||||||
"email": "p[email protected]",
|
"email": "a1@mail.pt",
|
||||||
"password": "123"
|
"password": "123"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -14,7 +14,7 @@ Accept: application/json
|
|||||||
@id = {{login.response.body.user.id}}
|
@id = {{login.response.body.user.id}}
|
||||||
|
|
||||||
### Get All matches
|
### Get All matches
|
||||||
GET http://localhost:8000/api/v1/matches
|
GET http://localhost:8000/api/v1/games
|
||||||
Content-Type: application/json
|
Content-Type: application/json
|
||||||
Accept: application/json
|
Accept: application/json
|
||||||
Authorization: Bearer {{token}}
|
Authorization: Bearer {{token}}
|
||||||
@@ -25,6 +25,12 @@ Content-Type: application/json
|
|||||||
Accept: application/json
|
Accept: application/json
|
||||||
Authorization: Bearer {{token}}
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
|
### Get me coins
|
||||||
|
GET http://localhost:8000/api/v1/users/me/coins
|
||||||
|
Content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
### Get me matches
|
### Get me matches
|
||||||
GET http://localhost:8000/api/v1/users/{{id}}/matches
|
GET http://localhost:8000/api/v1/users/{{id}}/matches
|
||||||
Content-Type: application/json
|
Content-Type: application/json
|
||||||
@@ -35,4 +41,44 @@ Authorization: Bearer {{token}}
|
|||||||
GET http://localhost:8000/api/v1/users/{{id}}/transactions?type=C
|
GET http://localhost:8000/api/v1/users/{{id}}/transactions?type=C
|
||||||
Content-Type: application/json
|
Content-Type: application/json
|
||||||
Accept: application/json
|
Accept: application/json
|
||||||
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
|
### post coin-purchases
|
||||||
|
POST http://localhost:8000/api/v1/coin-purchases
|
||||||
|
Content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
|
{
|
||||||
|
"euros": 1,
|
||||||
|
"payment_type": "MBWAY",
|
||||||
|
"payment_reference": "912345678"
|
||||||
|
}
|
||||||
|
|
||||||
|
### Get leaderboard
|
||||||
|
GET http://localhost:8000/api/v1/leaderboard
|
||||||
|
Content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
|
|
||||||
|
### Get me stats
|
||||||
|
GET http://localhost:8000/api/v1/statistics/me
|
||||||
|
Content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
|
### Get public stats
|
||||||
|
GET http://localhost:8000/api/v1/statistics/public
|
||||||
|
Content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
|
|
||||||
|
### Get admin stats
|
||||||
|
GET http://localhost:8000/api/v1/admin/statistics
|
||||||
|
Content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
|
Authorization: Bearer {{token}}
|
||||||
|
|
||||||
|
### Get admin stats
|
||||||
|
GET http://localhost:8000/api/v1/admin/users
|
||||||
|
Content-Type: application/json
|
||||||
|
Accept: application/json
|
||||||
Authorization: Bearer {{token}}
|
Authorization: Bearer {{token}}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
meta {
|
||||||
|
name: Create Game
|
||||||
|
type: http
|
||||||
|
seq: 3
|
||||||
|
}
|
||||||
|
|
||||||
|
post {
|
||||||
|
url: {{api_url}}/games
|
||||||
|
body: none
|
||||||
|
auth: inherit
|
||||||
|
}
|
||||||
|
|
||||||
|
settings {
|
||||||
|
encodeUrl: true
|
||||||
|
}
|
||||||
@@ -3,8 +3,7 @@
|
|||||||
<nav class="max-w-full p-5 flex flex-row justify-between align-middle">
|
<nav class="max-w-full p-5 flex flex-row justify-between align-middle">
|
||||||
<div class="align-middle text-xl">
|
<div class="align-middle text-xl">
|
||||||
<RouterLink to="/"> {{ pageTitle }} </RouterLink>
|
<RouterLink to="/"> {{ pageTitle }} </RouterLink>
|
||||||
<span class="text-xs" v-if="authStore.currentUser"
|
<span class="text-xs" v-if="authStore.currentUser"> ({{ authStore.currentUser?.name }})
|
||||||
> ({{ authStore.currentUser?.name }})
|
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<NavBar @logout="logout" :userLoggedIn="authStore.isLoggedIn" />
|
<NavBar @logout="logout" :userLoggedIn="authStore.isLoggedIn" />
|
||||||
@@ -29,8 +28,7 @@ import { useSocketStore } from './stores/socket'
|
|||||||
const authStore = useAuthStore()
|
const authStore = useAuthStore()
|
||||||
const socketStore = useSocketStore()
|
const socketStore = useSocketStore()
|
||||||
|
|
||||||
const year = new Date().getFullYear()
|
const pageTitle = ref(`DAD 2025/26`)
|
||||||
const pageTitle = ref(`DAD ${year}/${String(year + 1).slice(-2)}`)
|
|
||||||
|
|
||||||
const logout = () => {
|
const logout = () => {
|
||||||
toast.promise(authStore.logout(), {
|
toast.promise(authStore.logout(), {
|
||||||
@@ -44,7 +42,8 @@ const logout = () => {
|
|||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await authStore.restoreSession()
|
await authStore.restoreSession()
|
||||||
socketStore.handleConnection()
|
// REMOVED - The WebSocket for multiplayer is handled separately in the WebSocketStore
|
||||||
|
// socketStore.handleConnection()
|
||||||
})
|
})
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,8 @@
|
|||||||
:player-score="playerScore"
|
:player-score="playerScore"
|
||||||
:opponent-score="opponentScore"
|
:opponent-score="opponentScore"
|
||||||
:current-turn="currentTurn"
|
:current-turn="currentTurn"
|
||||||
|
:player-name="playerName"
|
||||||
|
:opponent-name="opponentName"
|
||||||
:round-number="1"
|
:round-number="1"
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
@@ -62,16 +64,20 @@ const props = defineProps({
|
|||||||
// REMOVIDO: playableCardIndices (já não precisamos dele)
|
// REMOVIDO: playableCardIndices (já não precisamos dele)
|
||||||
playerScore: { type: Number, default: 0 },
|
playerScore: { type: Number, default: 0 },
|
||||||
opponentScore: { type: Number, default: 0 },
|
opponentScore: { type: Number, default: 0 },
|
||||||
|
playerName: { type: String, default: 'You' },
|
||||||
|
opponentName: { type: String, default: 'Bot' },
|
||||||
currentTurn: {
|
currentTurn: {
|
||||||
type: String,
|
type: String,
|
||||||
default: 'player',
|
default: 'player',
|
||||||
validator: (value) => ['player', 'opponent'].includes(value),
|
validator: (value) => ['player', 'opponent'].includes(value),
|
||||||
},
|
},
|
||||||
|
isMyTurn: { type: Boolean, default: false },
|
||||||
})
|
})
|
||||||
|
|
||||||
const emit = defineEmits(['play-card'])
|
const emit = defineEmits(['play-card'])
|
||||||
|
|
||||||
const handleCardClick = (payload) => {
|
const handleCardClick = (payload) => {
|
||||||
|
if (!props.isMyTurn) return
|
||||||
emit('play-card', payload.card)
|
emit('play-card', payload.card)
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -51,6 +51,10 @@ const props = defineProps({
|
|||||||
default: 3,
|
default: 3,
|
||||||
validator: (value) => [3, 9].includes(value),
|
validator: (value) => [3, 9].includes(value),
|
||||||
},
|
},
|
||||||
|
isDisabled: {
|
||||||
|
type: Boolean,
|
||||||
|
default: false,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
const emit = defineEmits(['card-clicked'])
|
const emit = defineEmits(['card-clicked'])
|
||||||
@@ -81,7 +85,7 @@ const overlapPercentage = computed(() => {
|
|||||||
return props.maxCards === 3 ? 0.7 : 0.85
|
return props.maxCards === 3 ? 0.7 : 0.85
|
||||||
})
|
})
|
||||||
|
|
||||||
const cardWidth = 128
|
const cardWidth = 128
|
||||||
const getCardStyle = (index) => {
|
const getCardStyle = (index) => {
|
||||||
const totalCards = props.cards.length
|
const totalCards = props.cards.length
|
||||||
const overlapOffset = cardWidth * (1 - overlapPercentage.value)
|
const overlapOffset = cardWidth * (1 - overlapPercentage.value)
|
||||||
@@ -105,4 +109,4 @@ const getCardStyle = (index) => {
|
|||||||
zIndex: hoveredIndex.value === index ? 50 : index + 1,
|
zIndex: hoveredIndex.value === index ? 50 : index + 1,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|||||||
@@ -33,7 +33,8 @@
|
|||||||
turnChanged && 'animate-pulse',
|
turnChanged && 'animate-pulse',
|
||||||
]"
|
]"
|
||||||
>
|
>
|
||||||
{{ currentTurn === 'player' ? 'Your Turn' : "Bot's Turn" }}
|
<!-- You can replace the above line with the following if you want to show names instead -->
|
||||||
|
{{ currentTurn === 'player' ? playerName + "'s Turn" : opponentName + "'s Turn" }}
|
||||||
</div>
|
</div>
|
||||||
<span v-if="roundNumber" class="text-gray-500 text-[10px] font-medium">
|
<span v-if="roundNumber" class="text-gray-500 text-[10px] font-medium">
|
||||||
Round {{ roundNumber }}
|
Round {{ roundNumber }}
|
||||||
|
|||||||
@@ -23,14 +23,14 @@
|
|||||||
</NavigationMenuItem>
|
</NavigationMenuItem>
|
||||||
|
|
||||||
<NavigationMenuItem v-else class="flex flex-row gap-4">
|
<NavigationMenuItem v-else class="flex flex-row gap-4">
|
||||||
<NavigationMenuLink v-if="coins > 0" href="/user?tab=transaction-history"
|
<NavigationMenuLink v-if="userStore.coins > 0" href="/coins-purchase"
|
||||||
class="flex flex-row items-center gap-1">
|
class="flex flex-row items-center gap-1">
|
||||||
<div class="flex items-center justify-center w-5 h-5 bg-purple-400 rounded-full shadow-sm">
|
<div class="flex items-center justify-center w-5 h-5 bg-purple-400 rounded-full shadow-sm">
|
||||||
<span class="text-[10px] font-bold text-purple-900">$</span>
|
<span class="text-[10px] font-bold text-purple-900">$</span>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<span class="text-sm font-medium tabular-nums">
|
<span class="text-sm font-medium tabular-nums">
|
||||||
{{ coins }} <span class="text-muted-foreground text-xs">Coins</span>
|
{{ userStore.coins }} <span class="text-muted-foreground text-xs">Coins</span>
|
||||||
</span>
|
</span>
|
||||||
</NavigationMenuLink>
|
</NavigationMenuLink>
|
||||||
<NavigationMenuLink>
|
<NavigationMenuLink>
|
||||||
@@ -56,13 +56,12 @@ import {
|
|||||||
NavigationMenuTrigger,
|
NavigationMenuTrigger,
|
||||||
} from '@/components/ui/navigation-menu'
|
} from '@/components/ui/navigation-menu'
|
||||||
import router from '@/router';
|
import router from '@/router';
|
||||||
import { ref, watch } from 'vue';
|
import { watch } from 'vue';
|
||||||
import { useUserStore } from '@/stores/user';
|
import { useUserStore } from '@/stores/user';
|
||||||
|
|
||||||
|
|
||||||
const emits = defineEmits(['logout'])
|
const emits = defineEmits(['logout'])
|
||||||
const { userLoggedIn } = defineProps(['userLoggedIn'])
|
const { userLoggedIn } = defineProps(['userLoggedIn'])
|
||||||
const coins = ref(0);
|
|
||||||
|
|
||||||
const biscaStore = useBiscaStore()
|
const biscaStore = useBiscaStore()
|
||||||
|
|
||||||
@@ -84,22 +83,13 @@ const logoutClickHandler = () => {
|
|||||||
router.push('/login')
|
router.push('/login')
|
||||||
}
|
}
|
||||||
|
|
||||||
const fetchUserCoins = async () => {
|
const userStore = useUserStore()
|
||||||
if (userLoggedIn) {
|
|
||||||
try {
|
|
||||||
const response = await useUserStore().getCoins()
|
|
||||||
coins.value = response.data?.coins || 0
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error fetching user coins', error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
watch(() => userLoggedIn, async (isLoggedIn) => {
|
watch(() => userLoggedIn, async (isLoggedIn) => {
|
||||||
if (isLoggedIn) {
|
if (isLoggedIn) {
|
||||||
await fetchUserCoins()
|
await userStore.fetchCoins()
|
||||||
} else {
|
} else {
|
||||||
coins.value = 0
|
userStore.coins = 0
|
||||||
}
|
}
|
||||||
}, { immediate: true })
|
}, { immediate: true })
|
||||||
</script>
|
</script>
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,323 @@
|
|||||||
|
<template>
|
||||||
|
<div class="relative min-h-screen overflow-hidden bg-green-900">
|
||||||
|
<div v-if="shouldShowBoard && !gameOver" class="absolute top-4 right-4 z-50">
|
||||||
|
<button
|
||||||
|
@click="handleSurrender"
|
||||||
|
class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all transform hover:scale-105 flex items-center gap-2"
|
||||||
|
>
|
||||||
|
<span>🏳️</span> Surrender
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="!wsStore.connected && hasConnectedOnce" class="absolute top-4 left-4 z-50 flex items-center gap-2 bg-gray-800 px-4 py-2 rounded-lg border border-gray-700 shadow-xl">
|
||||||
|
<div class="w-3 h-3 rounded-full bg-red-500 animate-pulse"></div>
|
||||||
|
<span class="text-white text-sm">Reconnecting...</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="shouldShowBoard && !gameOver && isMyTurn" class="absolute top-4 left-1/2 -translate-x-1/2 z-50">
|
||||||
|
<div class="bg-gray-800 px-6 py-3 rounded-lg border-2 shadow-xl transition-colors duration-300"
|
||||||
|
:class="timeLeft <= 5 ? 'border-red-500 bg-red-900/20' : 'border-gray-700'">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<svg class="w-6 h-6" :class="timeLeft <= 5 ? 'text-red-500 animate-bounce' : 'text-white'" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
||||||
|
<circle cx="12" cy="12" r="10" stroke-width="2"/>
|
||||||
|
<polyline points="12 6 12 12 16 14" stroke-width="2"/>
|
||||||
|
</svg>
|
||||||
|
<span :class="['text-3xl font-mono font-bold', timeLeft <= 5 ? 'text-red-500' : 'text-white']">
|
||||||
|
{{ timeLeft }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="shouldShowBoard">
|
||||||
|
<GameBoard
|
||||||
|
:trump-card="trumpCard"
|
||||||
|
:cards-remaining="deckCount + (trumpCard ? 1 : 0)"
|
||||||
|
|
||||||
|
:player-hand="visibleHand"
|
||||||
|
:opponent-hand="opponentHand"
|
||||||
|
|
||||||
|
:player-score="playerScore"
|
||||||
|
:opponent-score="opponentScore"
|
||||||
|
|
||||||
|
:player-name="myDisplayName"
|
||||||
|
:opponent-name="opponentDisplayName"
|
||||||
|
:current-turn="currentTurnLabel"
|
||||||
|
|
||||||
|
:current-trick="displayedTrick"
|
||||||
|
:is-my-turn="isMyTurn"
|
||||||
|
@play-card="handlePlayCard"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="!gameOver" class="flex h-screen items-center justify-center bg-green-900 text-white">
|
||||||
|
<div class="text-center p-8 bg-green-800/50 rounded-2xl border border-green-700 shadow-2xl backdrop-blur-sm">
|
||||||
|
<div class="relative mx-auto mb-6 h-16 w-16">
|
||||||
|
<div class="absolute inset-0 rounded-full border-4 border-green-600"></div>
|
||||||
|
<div class="absolute inset-0 rounded-full border-4 border-t-white border-r-transparent border-b-transparent border-l-transparent animate-spin"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<h2 class="text-2xl font-bold mb-2">
|
||||||
|
Waiting for Opponent...
|
||||||
|
</h2>
|
||||||
|
|
||||||
|
<p class="text-green-100 mb-8 max-w-sm">
|
||||||
|
Share the game code or wait for a player to join your lobby.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<button
|
||||||
|
@click="handleCloseModal"
|
||||||
|
class="px-6 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-all shadow-lg hover:shadow-red-500/20"
|
||||||
|
>
|
||||||
|
Cancel & Return Home
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<GameOver
|
||||||
|
:is-visible="gameOver"
|
||||||
|
:winner="winnerResult"
|
||||||
|
:player-score="playerScore"
|
||||||
|
:opponent-score="opponentScore"
|
||||||
|
:player-name="myDisplayName"
|
||||||
|
:opponent-name="opponentDisplayName"
|
||||||
|
:stats="{ playerTricks: 0, opponentTricks: 0 }"
|
||||||
|
:is-logging-out="false"
|
||||||
|
@play-again="handleCloseModal"
|
||||||
|
@close="handleCloseModal"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, computed, onMounted, onUnmounted, watch, inject } from 'vue'
|
||||||
|
import { useRoute, useRouter } from 'vue-router'
|
||||||
|
import { useSocketStore } from '@/stores/socket'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import axios from 'axios'
|
||||||
|
import GameBoard from '@/components/game/GameBoard.vue'
|
||||||
|
import GameOver from '@/components/game/GameOver.vue'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const router = useRouter()
|
||||||
|
const wsStore = useSocketStore()
|
||||||
|
const authStore = useAuthStore()
|
||||||
|
const API_BASE_URL = inject('apiBaseURL')
|
||||||
|
|
||||||
|
const gameId = ref(route.params.id)
|
||||||
|
const visibleHand = ref([])
|
||||||
|
const gameOver = ref(false)
|
||||||
|
const isDealing = ref(false)
|
||||||
|
const hasInitialDealHappened = ref(false)
|
||||||
|
const winnerResult = ref('draw')
|
||||||
|
const timeLeft = ref(20)
|
||||||
|
const timerInterval = ref(null)
|
||||||
|
const hasConnectedOnce = ref(false)
|
||||||
|
|
||||||
|
const gameMetadata = ref({
|
||||||
|
p1_id: null,
|
||||||
|
p1_name: 'Player 1',
|
||||||
|
p2_id: null,
|
||||||
|
p2_name: 'Opponent'
|
||||||
|
})
|
||||||
|
|
||||||
|
const displayedTrick = ref({ playerCard: null, opponentCard: null })
|
||||||
|
const trickClearTimer = ref(null)
|
||||||
|
|
||||||
|
// --- COMPUTED ---
|
||||||
|
|
||||||
|
const myUserId = computed(() => authStore.currentUser?.id)
|
||||||
|
|
||||||
|
const shouldShowBoard = computed(() => {
|
||||||
|
const s = wsStore.gameState;
|
||||||
|
if (s && s.player2 && s.player2.id > 1) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
})
|
||||||
|
|
||||||
|
const amIHost = computed(() => {
|
||||||
|
if (gameMetadata.value.p1_id) {
|
||||||
|
return String(gameMetadata.value.p1_id) === String(myUserId.value)
|
||||||
|
}
|
||||||
|
const p1Id = wsStore.gameState?.player1_user_id || wsStore.gameState?.player1?.id
|
||||||
|
return String(p1Id) === String(myUserId.value)
|
||||||
|
})
|
||||||
|
|
||||||
|
const myDisplayName = computed(() => amIHost.value ? gameMetadata.value.p1_name : gameMetadata.value.p2_name)
|
||||||
|
const opponentDisplayName = computed(() => amIHost.value ? gameMetadata.value.p2_name : gameMetadata.value.p1_name)
|
||||||
|
|
||||||
|
const mappedTrick = computed(() => {
|
||||||
|
const table = wsStore.gameState?.table
|
||||||
|
if (!table) return { playerCard: null, opponentCard: null }
|
||||||
|
if (amIHost.value) {
|
||||||
|
return { playerCard: table.playerCard, opponentCard: table.opponentCard }
|
||||||
|
} else {
|
||||||
|
return { playerCard: table.opponentCard, opponentCard: table.playerCard }
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const currentTurnLabel = computed(() => {
|
||||||
|
const turnId = wsStore.gameState?.currentTurn
|
||||||
|
if (!turnId) return 'player'
|
||||||
|
return String(turnId) === String(myUserId.value) ? 'player' : 'opponent'
|
||||||
|
})
|
||||||
|
|
||||||
|
const trumpCard = computed(() => wsStore.gameState?.trumpCard || null)
|
||||||
|
const deckCount = computed(() => wsStore.gameState?.deckCount || 0)
|
||||||
|
const playerScore = computed(() => wsStore.gameState?.points || 0)
|
||||||
|
const opponentScore = computed(() => wsStore.gameState?.opponent?.points || 0)
|
||||||
|
const serverHand = computed(() => wsStore.gameState?.hand || [])
|
||||||
|
const isMyTurn = computed(() => String(wsStore.gameState?.currentTurn) === String(myUserId.value))
|
||||||
|
const opponentHand = computed(() => {
|
||||||
|
const count = wsStore.gameState?.opponent?.cardCount || 0
|
||||||
|
return Array.from({ length: count }, (_, i) => ({ id: `opp-${i}`, suit: 'back', rank: 0 }))
|
||||||
|
})
|
||||||
|
|
||||||
|
// --- WATCHERS ---
|
||||||
|
|
||||||
|
watch(() => wsStore.connected, (isConnected) => {
|
||||||
|
if (isConnected) {
|
||||||
|
hasConnectedOnce.value = true
|
||||||
|
wsStore.joinGame(gameId.value)
|
||||||
|
}
|
||||||
|
}, { immediate: true })
|
||||||
|
|
||||||
|
watch(() => wsStore.gameState, async (newState, oldState) => {
|
||||||
|
const oldP2 = oldState?.player2?.id;
|
||||||
|
const newP2 = newState?.player2?.id;
|
||||||
|
if (newP2 && newP2 > 1 && newP2 !== oldP2) {
|
||||||
|
await fetchGameMetadata();
|
||||||
|
}
|
||||||
|
}, { deep: true })
|
||||||
|
|
||||||
|
watch(mappedTrick, (newVal) => {
|
||||||
|
if (newVal.playerCard || newVal.opponentCard) {
|
||||||
|
if (trickClearTimer.value) clearTimeout(trickClearTimer.value)
|
||||||
|
displayedTrick.value = { ...newVal }
|
||||||
|
} else {
|
||||||
|
const currentlyShowing = displayedTrick.value.playerCard || displayedTrick.value.opponentCard
|
||||||
|
if (currentlyShowing) {
|
||||||
|
trickClearTimer.value = setTimeout(() => {
|
||||||
|
displayedTrick.value = { playerCard: null, opponentCard: null }
|
||||||
|
}, 1500)
|
||||||
|
} else {
|
||||||
|
displayedTrick.value = { playerCard: null, opponentCard: null }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, { deep: true })
|
||||||
|
|
||||||
|
// --- FIX: TIMER GHOSTING ---
|
||||||
|
const startTimer = () => {
|
||||||
|
if (timerInterval.value) clearInterval(timerInterval.value)
|
||||||
|
|
||||||
|
if (!shouldShowBoard.value && wsStore.gameState?.status !== 'playing') {
|
||||||
|
timeLeft.value = 20;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// FORCE RESET to avoid showing old time for 1 frame
|
||||||
|
timeLeft.value = 20;
|
||||||
|
|
||||||
|
const startAt = wsStore.gameState?.turnStartedAt ? new Date(wsStore.gameState.turnStartedAt).getTime() : Date.now()
|
||||||
|
|
||||||
|
// Define update function
|
||||||
|
const update = () => {
|
||||||
|
const now = Date.now()
|
||||||
|
const elapsed = Math.floor((now - startAt) / 1000)
|
||||||
|
timeLeft.value = Math.max(0, 20 - elapsed)
|
||||||
|
if (timeLeft.value <= 0) clearInterval(timerInterval.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// EXECUTE IMMEDIATELY
|
||||||
|
update();
|
||||||
|
|
||||||
|
// Then set interval
|
||||||
|
timerInterval.value = setInterval(update, 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => wsStore.gameState?.currentTurn, (newTurn) => {
|
||||||
|
if (newTurn) startTimer()
|
||||||
|
}, { immediate: true })
|
||||||
|
|
||||||
|
const animateDeal = async (cards) => {
|
||||||
|
if (isDealing.value) return
|
||||||
|
isDealing.value = true
|
||||||
|
visibleHand.value = []
|
||||||
|
for (const card of cards) {
|
||||||
|
visibleHand.value.push(card)
|
||||||
|
await new Promise(r => setTimeout(r, 150))
|
||||||
|
}
|
||||||
|
isDealing.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(serverHand, (newHand) => {
|
||||||
|
if (visibleHand.value.length === 0 && newHand.length > 0 && !hasInitialDealHappened.value) {
|
||||||
|
animateDeal(newHand)
|
||||||
|
hasInitialDealHappened.value = true
|
||||||
|
} else if (!isDealing.value) {
|
||||||
|
visibleHand.value = [...newHand]
|
||||||
|
}
|
||||||
|
}, { deep: true })
|
||||||
|
|
||||||
|
// --- METHODS ---
|
||||||
|
|
||||||
|
const fetchGameMetadata = async () => {
|
||||||
|
try {
|
||||||
|
const response = await axios.get(`${API_BASE_URL}/games/${gameId.value}`)
|
||||||
|
const game = response.data.data || response.data
|
||||||
|
gameMetadata.value = {
|
||||||
|
p1_id: game.player1_user_id,
|
||||||
|
p1_name: game.player1?.nickname || 'Host',
|
||||||
|
p2_id: game.player2_user_id,
|
||||||
|
p2_name: game.player2?.nickname || 'Opponent'
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Failed to load metadata", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePlayCard = (card) => {
|
||||||
|
if (!isMyTurn.value || gameOver.value) return
|
||||||
|
visibleHand.value = visibleHand.value.filter(c => c.id !== card.id)
|
||||||
|
wsStore.playCard(gameId.value, card.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- FIX: SURRENDER LOGIC ---
|
||||||
|
const handleSurrender = () => {
|
||||||
|
if(confirm('Are you sure you want to surrender? You will lose.')) {
|
||||||
|
// Send event to server. Do NOT disconnect locally yet.
|
||||||
|
// Wait for the server to send "Game Over" event back.
|
||||||
|
wsStore.surrender(gameId.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCloseModal = () => {
|
||||||
|
wsStore.disconnect()
|
||||||
|
router.push({ name: 'home' })
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- LIFECYCLE ---
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await fetchGameMetadata()
|
||||||
|
wsStore.connect()
|
||||||
|
|
||||||
|
wsStore.onTrickEnd((result) => {
|
||||||
|
const winnerName = result.winnerId == authStore.currentUser?.id ? "You" : "Opponent"
|
||||||
|
toast.success(`${winnerName} won the trick!`, { position: 'top-center', duration: 1500 })
|
||||||
|
})
|
||||||
|
|
||||||
|
wsStore.onGameOver((result) => {
|
||||||
|
gameOver.value = true
|
||||||
|
if (result.isDraw) winnerResult.value = 'draw'
|
||||||
|
else winnerResult.value = result.winnerId == authStore.currentUser?.id ? 'player' : 'opponent'
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
if (timerInterval.value) clearInterval(timerInterval.value)
|
||||||
|
wsStore.disconnect()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
<script setup>
|
<script setup>
|
||||||
import { ref, onMounted, nextTick } from 'vue'
|
import { User, Trophy } from 'lucide-vue-next'
|
||||||
|
import { ref, onMounted, nextTick, inject } from 'vue'
|
||||||
import { Button } from '@/components/ui/button'
|
import { Button } from '@/components/ui/button'
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
@@ -10,90 +11,276 @@ import {
|
|||||||
} from '@/components/ui/card'
|
} from '@/components/ui/card'
|
||||||
import { useAPIStore } from '@/stores/api'
|
import { useAPIStore } from '@/stores/api'
|
||||||
import { useRouter } from 'vue-router'
|
import { useRouter } from 'vue-router'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import axios from 'axios'
|
||||||
|
|
||||||
|
const API_BASE_URL = inject('apiBaseURL')
|
||||||
const apiStore = useAPIStore()
|
const apiStore = useAPIStore()
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const openGames = ref([])
|
const openGames = ref([])
|
||||||
const selectedMode = ref('9')
|
const selectedMode = ref('9')
|
||||||
const observerTarget = ref(null);
|
const gObserverTarget = ref(null);
|
||||||
const observer = ref(null);
|
const gObserver = ref(null);
|
||||||
const isLoading = ref(false);
|
const gLoading = ref(false);
|
||||||
const pageCounter = ref(1);
|
const gPage = ref(1);
|
||||||
|
const openMatches = ref([])
|
||||||
|
const mObserverTarget = ref(null);
|
||||||
|
const mObserver = ref(null);
|
||||||
|
const mLoading = ref(false);
|
||||||
|
const mPage = ref(1);
|
||||||
const showHostModal = ref(false)
|
const showHostModal = ref(false)
|
||||||
const showJoinModal = ref(false)
|
const showJoinModal = ref(false)
|
||||||
const selectedGame = ref(null)
|
const selectedGame = ref(null)
|
||||||
const isReady = ref(false)
|
const isReady = ref(false)
|
||||||
|
const showLeaderboardModal = ref(false)
|
||||||
|
const showStatsModal = ref(false)
|
||||||
|
const userStats = ref(null)
|
||||||
|
const statsLoading = ref(false)
|
||||||
|
const leaderboardEntries = ref([])
|
||||||
|
const lbLoading = ref(false)
|
||||||
|
const lbPage = ref(1)
|
||||||
|
const lbObserverTarget = ref(null)
|
||||||
|
const lbObserver = ref(null)
|
||||||
|
const lbMorePages = ref(true)
|
||||||
|
const publicStats = ref(null)
|
||||||
|
const isLoggedIn = useAuthStore().isLoggedIn
|
||||||
|
|
||||||
const setupObserver = () => {
|
const setupMatchesObserver = () => {
|
||||||
if (observer.value) observer.value.disconnect();
|
if (mObserver.value) mObserver.value.disconnect();
|
||||||
|
|
||||||
observer.value = new IntersectionObserver((entries) => {
|
mObserver.value = new IntersectionObserver((entries) => {
|
||||||
if (entries[0].isIntersecting && !isLoading.value && openGames.value.length > 0) {
|
if (entries[0].isIntersecting && !mLoading.value && openMatches.value.length > 0) {
|
||||||
|
getPendingMatches();
|
||||||
|
}
|
||||||
|
}, { threshold: 0.1 });
|
||||||
|
|
||||||
|
if (mObserverTarget.value) {
|
||||||
|
mObserver.value.observe(mObserverTarget.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const setupGamesObserver = () => {
|
||||||
|
if (gObserver.value) gObserver.value.disconnect();
|
||||||
|
|
||||||
|
gObserver.value = new IntersectionObserver((entries) => {
|
||||||
|
if (entries[0].isIntersecting && !gLoading.value && openGames.value.length > 0) {
|
||||||
getPendingGames();
|
getPendingGames();
|
||||||
}
|
}
|
||||||
}, { threshold: 0.1 });
|
}, { threshold: 0.1 });
|
||||||
|
|
||||||
if (observerTarget.value) {
|
if (gObserverTarget.value) {
|
||||||
observer.value.observe(observerTarget.value);
|
gObserver.value.observe(gObserverTarget.value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const getPendingGames = async (mode = selectedMode.value) => {
|
const getPendingGames = async (mode = selectedMode.value) => {
|
||||||
if (isLoading.value) return;
|
if (gLoading.value) return;
|
||||||
isLoading.value = true;
|
gLoading.value = true;
|
||||||
|
|
||||||
|
|
||||||
apiStore.gameQueryParameters.page = pageCounter.value++;
|
|
||||||
apiStore.gameQueryParameters.filters.sort_direction = "asc"
|
|
||||||
apiStore.gameQueryParameters.filters.type = mode
|
|
||||||
apiStore.gameQueryParameters.filters.status = 'Pending'
|
|
||||||
try {
|
try {
|
||||||
const response = await apiStore.getGames();
|
const response = await axios.get(`${API_BASE_URL}/games/open`, {
|
||||||
|
params: {
|
||||||
|
type: mode,
|
||||||
|
page: gPage.value
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
const newGames = response.data.data;
|
const newGames = response.data.data;
|
||||||
openGames.value = [...openGames.value, ...newGames];
|
openGames.value = [...openGames.value, ...newGames];
|
||||||
} finally {
|
} finally {
|
||||||
isLoading.value = false;
|
gLoading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getPendingMatches = async (mode = selectedMode.value) => {
|
||||||
|
if (mLoading.value) return;
|
||||||
|
mLoading.value = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await axios.get(`${API_BASE_URL}/matches/open`, {
|
||||||
|
params: {
|
||||||
|
type: mode,
|
||||||
|
page: mPage.value
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const newMatches = response.data.data;
|
||||||
|
openMatches.value = [...openMatches.value, ...newMatches];
|
||||||
|
} finally {
|
||||||
|
mLoading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchPublicStats = async () => {
|
||||||
|
try {
|
||||||
|
const response = await apiStore.getPublicStats()
|
||||||
|
publicStats.value = response.data
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to fetch public stats", error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const openStats = async () => {
|
||||||
|
showStatsModal.value = true
|
||||||
|
statsLoading.value = true
|
||||||
|
try {
|
||||||
|
const response = await apiStore.getCurrentUserStats()
|
||||||
|
userStats.value = response.data
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Failed to fetch stats", error)
|
||||||
|
} finally {
|
||||||
|
statsLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getAvatarUrl = (filename) => {
|
||||||
|
return filename
|
||||||
|
? `${API_BASE_URL.replace('/api/v1', '').replace('v1/')}/storage/photos_avatars/${filename}`
|
||||||
|
: `${API_BASE_URL.replace('/api/v1', '').replace('v1/')}/storage/photos_avatars/anonymous.png`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fetchLeaderboard = async () => {
|
||||||
|
if (lbLoading.value || !lbMorePages.value) return;
|
||||||
|
lbLoading.value = true;
|
||||||
|
try {
|
||||||
|
const response = await apiStore.getLeaderboard({ page: lbPage.value });
|
||||||
|
const newEntries = response.data.data;
|
||||||
|
|
||||||
|
if (newEntries.length < 10) {
|
||||||
|
lbMorePages.value = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
leaderboardEntries.value = [...leaderboardEntries.value, ...newEntries];
|
||||||
|
lbPage.value++;
|
||||||
|
} finally {
|
||||||
|
lbLoading.value = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const openLeaderboard = async () => {
|
||||||
|
leaderboardEntries.value = [];
|
||||||
|
lbPage.value = 1;
|
||||||
|
showLeaderboardModal.value = true;
|
||||||
|
await nextTick();
|
||||||
|
setupLeaderboardObserver();
|
||||||
|
await fetchLeaderboard();
|
||||||
|
}
|
||||||
|
|
||||||
|
const setupLeaderboardObserver = () => {
|
||||||
|
if (lbObserver.value) lbObserver.value.disconnect();
|
||||||
|
lbObserver.value = new IntersectionObserver((entries) => {
|
||||||
|
if (entries[0].isIntersecting && !lbLoading.value && leaderboardEntries.value.length > 0) {
|
||||||
|
fetchLeaderboard();
|
||||||
|
}
|
||||||
|
}, { threshold: 0.1 });
|
||||||
|
|
||||||
|
if (lbObserverTarget.value) {
|
||||||
|
lbObserver.value.observe(lbObserverTarget.value);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const clickMode = async (mode) => {
|
const clickMode = async (mode) => {
|
||||||
if (selectedMode.value === mode) return;
|
if (selectedMode.value === mode) return;
|
||||||
openGames.value = [];
|
|
||||||
selectedMode.value = mode;
|
selectedMode.value = mode;
|
||||||
pageCounter.value = 1;
|
openGames.value = [];
|
||||||
await getPendingGames();
|
gPage.value = 1;
|
||||||
setupObserver();
|
openMatches.value = [];
|
||||||
|
mPage.value = 1;
|
||||||
|
await Promise.all([getPendingGames(), getPendingMatches()]);
|
||||||
|
setupGamesObserver();
|
||||||
|
setupMatchesObserver();
|
||||||
}
|
}
|
||||||
|
|
||||||
const startSingle = () => {
|
const startSingle = () => {
|
||||||
router.push({ name: 'bisca' + selectedMode.value });
|
router.push({ name: 'bisca' + selectedMode.value });
|
||||||
}
|
}
|
||||||
|
|
||||||
const JoinGameModal = (game) => {
|
|
||||||
selectedGame.value = game
|
|
||||||
isReady.value = false
|
|
||||||
showJoinModal.value = true
|
|
||||||
}
|
|
||||||
|
|
||||||
const hostGameModal = () => {
|
|
||||||
showHostModal.value = true
|
|
||||||
}
|
|
||||||
|
|
||||||
const toggleReady = () => {
|
const toggleReady = () => {
|
||||||
isReady.value = !isReady.value
|
isReady.value = !isReady.value
|
||||||
}
|
}
|
||||||
|
|
||||||
onMounted(async () => {
|
onMounted(async () => {
|
||||||
await getPendingGames();
|
await fetchPublicStats();
|
||||||
await nextTick();
|
if (isLoggedIn) {
|
||||||
setupObserver();
|
await Promise.all([getPendingGames(), getPendingMatches()]);
|
||||||
|
await nextTick();
|
||||||
|
setupGamesObserver();
|
||||||
|
setupMatchesObserver();
|
||||||
|
}
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const hostGame = async () => {
|
||||||
|
showHostModal.value = true
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await axios.post(`${API_BASE_URL}/games/host`, {
|
||||||
|
type: selectedMode.value
|
||||||
|
})
|
||||||
|
|
||||||
|
const gameId = response.data.id
|
||||||
|
|
||||||
|
console.log('Game hosted:', gameId)
|
||||||
|
|
||||||
|
router.push({
|
||||||
|
name: 'multiplayer-game',
|
||||||
|
params: { id: gameId },
|
||||||
|
query: { type: selectedMode.value }
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to host game:', error)
|
||||||
|
console.error('Error details:', error.response?.data)
|
||||||
|
showHostModal.value = false
|
||||||
|
alert('Failed to host game: ' + (error.response?.data?.message || error.message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const joinGame = async (game) => {
|
||||||
|
selectedGame.value = game
|
||||||
|
|
||||||
|
try {
|
||||||
|
await axios.post(`${API_BASE_URL}/games/${game.id}/join`)
|
||||||
|
|
||||||
|
console.log('Joined game:', game.id)
|
||||||
|
|
||||||
|
router.push({
|
||||||
|
name: 'multiplayer-game',
|
||||||
|
params: { id: game.id },
|
||||||
|
query: { type: selectedMode.value }
|
||||||
|
})
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Failed to join game:', error)
|
||||||
|
console.error('Error details:', error.response?.data)
|
||||||
|
alert('Failed to join game: ' + (error.response?.data?.message || error.message))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="min-h-screen bg-cover bg-center transition-all duration-700">
|
<div class="min-h-screen bg-cover bg-center transition-all duration-700">
|
||||||
|
|
||||||
<div class="flex flex-col justify-center items-center gap-5 pt-10 px-4">
|
<div class="flex flex-col justify-center items-center gap-5 pt-10 pb-10 px-4">
|
||||||
|
|
||||||
|
<Card v-if="publicStats" class="w-full max-w-2xl border-[#a855f7] bg-[#f8f0ff] shadow-sm">
|
||||||
|
<CardContent class="p-4">
|
||||||
|
<div class="flex justify-around items-center">
|
||||||
|
<div class="text-center">
|
||||||
|
<p class="text-xs uppercase font-bold opacity-70">Players</p>
|
||||||
|
<p class="text-xl font-black">{{ publicStats.total_players }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="h-8 w-[1px] bg-[#a855f7]/20"></div>
|
||||||
|
<div class="text-center">
|
||||||
|
<p class="text-xs uppercase font-bold opacity-70">Total Games</p>
|
||||||
|
<p class="text-xl font-black">{{ publicStats.total_games }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="h-8 w-[1px] bg-[#a855f7]/20"></div>
|
||||||
|
<div class="text-center">
|
||||||
|
<p class="text-xs uppercase font-bold opacity-70">Active</p>
|
||||||
|
<p class="text-xl font-black">{{ publicStats.active_games }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
|
||||||
<div class="relative w-full max-w-md bg-card rounded-lg border shadow-sm overflow-hidden">
|
<div class="relative w-full max-w-md bg-card rounded-lg border shadow-sm overflow-hidden">
|
||||||
<div class="relative h-14 flex items-center">
|
<div class="relative h-14 flex items-center">
|
||||||
@@ -138,50 +325,95 @@ onMounted(async () => {
|
|||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
<Card class="w-full max-w-2xl">
|
<Card class="w-full max-w-2xl flex flex-col">
|
||||||
<CardHeader>
|
<CardHeader>
|
||||||
<CardTitle class="text-3xl font-bold text-center">
|
<CardTitle class="text-3xl font-bold text-center">Multi Player</CardTitle>
|
||||||
MultiPlayer
|
<CardDescription class="text-center">Go one on one with another player!</CardDescription>
|
||||||
</CardTitle>
|
|
||||||
<CardDescription class="text-center">
|
|
||||||
Go one on one with another player!
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent class="space-y-6">
|
|
||||||
<label class="text-sm font-medium">Open games (oldest first)</label>
|
<CardContent class="flex-1 flex flex-col space-y-6">
|
||||||
<div class="rounded-lg border bg-card text-card-foreground shadow-sm">
|
<div class="flex flex-col flex-1">
|
||||||
<div v-if="openGames.length === 0" class="p-6 text-center text-sm text-muted-foreground">
|
<div class="flex justify-between items-end mb-2">
|
||||||
No open games yet. Try hosting one!
|
<label class="text-sm font-bold uppercase tracking-wider text-muted-foreground">Open
|
||||||
|
Matches</label>
|
||||||
|
<Button v-if="isLoggedIn" @click="showHostModal()" size="sm" variant="outline"
|
||||||
|
class="border-purple-500 text-purple-500 hover:bg-purple-500 hover:text-white transition-all duration-300 font-bold">
|
||||||
|
Host
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div v-else class="max-h-[350px] overflow-y-auto custom-scrollbar p-1">
|
|
||||||
|
|
||||||
<div v-for="(game, index) in openGames" :key="game.id" @click="JoinGameModal(game)"
|
<div class="rounded-lg border bg-card text-card-foreground shadow-sm">
|
||||||
class="flex items-center justify-between p-3 mb-2 border border-transparent rounded-lg transition-all hover:bg-muted/50 hover:border-purple-500">
|
<div v-if="openGames.length === 0"
|
||||||
|
class="p-6 text-center text-sm text-muted-foreground">
|
||||||
<div class="flex items-center gap-3">
|
No open macthes yet. Try hosting one!
|
||||||
<div
|
</div>
|
||||||
class="flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold bg-green-100 text-green-700">
|
<div v-else class="max-h-[350px] overflow-y-auto custom-scrollbar p-1">
|
||||||
{{ index + 1 }}
|
<div v-for="(match, index) in openMatches" :key="match.id"
|
||||||
</div>
|
class="flex items-center justify-between p-3 mb-2 border border-transparent rounded-lg cursor-pointer transition-all hover:bg-muted/50 hover:border-purple-500">
|
||||||
<div>
|
<div class="flex items-center gap-3">
|
||||||
<div class="font-medium text-sm">Started: {{ game.began_at }}</div>
|
<div
|
||||||
<div class="text-xs text-muted-foreground">host: {{
|
class="flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold bg-red-100 text-red-700">
|
||||||
game.player1?.nickname || 'Anonymous' }}</div>
|
{{ index + 1 }}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="font-medium text-sm">Match ID: {{ match.id }}</div>
|
||||||
|
<div class="text-[10px] text-muted-foreground">{{ new
|
||||||
|
Date(game.began_at).toLocaleDateString() }} • {{ new
|
||||||
|
Date(game.began_at).toLocaleTimeString([], {
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit' }) }}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
<div ref="mObserverTarget" class="h-10 flex items-center justify-center">
|
||||||
|
<span v-if="mLoading" class="text-xs text-purple-500 animate-pulse">Loading
|
||||||
<div ref="observerTarget" class="h-10 flex items-center justify-center">
|
matches...</span>
|
||||||
<span v-if="isLoading" class="text-xs text-purple-500 animate-pulse">Loading
|
</div>
|
||||||
more...</span>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="flex justify-center">
|
|
||||||
<Button @click="hostGameModal()" size="lg" variant="secondary"
|
<div class="flex flex-col flex-1">
|
||||||
class="hover:bg-purple-500 hover:text-slate-200">
|
<div class="flex justify-between items-end mb-2">
|
||||||
Host Game
|
<label class="text-sm font-medium uppercase tracking-wider text-muted-foreground">Open
|
||||||
</Button>
|
Games</label>
|
||||||
|
<Button v-if="isLoggedIn" @click="hostGame()" size="sm" variant="outline"
|
||||||
|
class="border-purple-500 text-purple-500 hover:bg-purple-500 hover:text-white transition-all duration-300 font-bold">
|
||||||
|
Host
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rounded-lg border bg-card text-card-foreground shadow-sm">
|
||||||
|
<div v-if="openGames.length === 0"
|
||||||
|
class="p-6 text-center text-sm text-muted-foreground">
|
||||||
|
No open games yet. Try hosting one!
|
||||||
|
</div>
|
||||||
|
<div v-else class="max-h-[350px] overflow-y-auto custom-scrollbar p-1">
|
||||||
|
<div v-for="(game, index) in openGames" :key="game.id" @click="joinGame(game)"
|
||||||
|
class="flex items-center justify-between p-3 mb-2 border border-transparent rounded-lg cursor-pointer transition-all hover:bg-muted/50 hover:border-purple-500">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<div
|
||||||
|
class="flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold bg-green-100 text-green-700">
|
||||||
|
{{ index + 1 }}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div class="font-medium text-sm">Host: {{ game.player1?.nickname ||
|
||||||
|
'Anonymous' }}</div>
|
||||||
|
<div class="text-[10px] text-muted-foreground">{{ new
|
||||||
|
Date(game.began_at).toLocaleDateString() }} • {{ new
|
||||||
|
Date(game.began_at).toLocaleTimeString([], {
|
||||||
|
hour: '2-digit',
|
||||||
|
minute: '2-digit' }) }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div ref="gObserverTarget" class="h-10 flex items-center justify-center">
|
||||||
|
<span v-if="gLoading" class="text-xs text-purple-500 animate-pulse">Loading
|
||||||
|
games...</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
@@ -238,5 +470,117 @@ onMounted(async () => {
|
|||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div v-if="showStatsModal"
|
||||||
|
class="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||||
|
<Card class="w-full max-w-sm max-h-2/3 border-purple-500 shadow-2xl">
|
||||||
|
<CardHeader class="border-b bg-muted/20">
|
||||||
|
<div class="flex justify-between items-center">
|
||||||
|
<CardTitle class="flex items-center gap-2">
|
||||||
|
<User class="text-yellow-500" /> My Statistics
|
||||||
|
</CardTitle>
|
||||||
|
<Button variant="ghost" size="sm" @click="showStatsModal = false">X</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent class="py-6">
|
||||||
|
<div v-if="statsLoading" class="flex flex-col items-center py-10 gap-4">
|
||||||
|
<div class="h-8 w-8 animate-spin rounded-full border-4 border-purple-500 border-t-transparent">
|
||||||
|
</div>
|
||||||
|
<p class="text-sm text-muted-foreground">Calculating your glory...</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="userStats" class="space-y-6">
|
||||||
|
<div class="text-center">
|
||||||
|
<h3 class="text-2xl font-bold text-purple-600">{{ userStats.nickname }}</h3>
|
||||||
|
<p class="text-sm text-muted-foreground">Performance Overview</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="grid grid-cols-2 gap-4">
|
||||||
|
<div
|
||||||
|
class="rounded-lg bg-muted/50 p-4 text-center border border-transparent hover:border-purple-500/30 transition-all">
|
||||||
|
<p class="text-xs uppercase text-muted-foreground font-semibold">Total Games</p>
|
||||||
|
<p class="text-2xl font-bold">{{ userStats.total_games }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="rounded-lg bg-purple-500/10 p-4 text-center border border-purple-500/20">
|
||||||
|
<p class="text-xs uppercase text-purple-600 font-semibold">Win Rate</p>
|
||||||
|
<p class="text-2xl font-bold text-purple-600">{{ userStats.win_rate }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="rounded-lg bg-green-500/10 p-4 text-center border border-green-500/20">
|
||||||
|
<p class="text-xs uppercase text-green-600 font-semibold">Wins</p>
|
||||||
|
<p class="text-2xl font-bold text-green-600">{{ userStats.total_wins }}</p>
|
||||||
|
</div>
|
||||||
|
<div class="rounded-lg bg-red-500/10 p-4 text-center border border-red-500/20">
|
||||||
|
<p class="text-xs uppercase text-red-600 font-semibold">Losses</p>
|
||||||
|
<p class="text-2xl font-bold text-red-600">{{ userStats.total_losses }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-2">
|
||||||
|
<div class="flex justify-between text-xs font-medium">
|
||||||
|
<span>Win/Loss Ratio</span>
|
||||||
|
<span>{{ userStats.total_wins }}W - {{ userStats.total_losses }}L</span>
|
||||||
|
</div>
|
||||||
|
<div class="h-2 w-full bg-red-500/20 rounded-full overflow-hidden flex">
|
||||||
|
<div class="bg-green-500 h-full" :style="{ width: userStats.win_rate }"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="showLeaderboardModal"
|
||||||
|
class="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
|
||||||
|
<Card class="w-full max-w-lg max-h-1/2 h-[80vh] flex flex-col border-purple-500 shadow-2xl">
|
||||||
|
<CardHeader class="border-b">
|
||||||
|
<div class="flex justify-between items-center">
|
||||||
|
<CardTitle class="flex items-center gap-2">
|
||||||
|
<Trophy class="text-purple-500" /> Leaderboard
|
||||||
|
</CardTitle>
|
||||||
|
<Button variant="ghost" size="sm" @click="showLeaderboardModal = false">X</Button>
|
||||||
|
</div>
|
||||||
|
</CardHeader>
|
||||||
|
|
||||||
|
<CardContent class="flex-1 overflow-y-auto custom-scrollbar p-0">
|
||||||
|
<div v-for="(user, index) in leaderboardEntries" :key="user.id"
|
||||||
|
class="flex items-center justify-between p-4 border-b last:border-0 hover:bg-muted/30 transition-colors">
|
||||||
|
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
<span class="font-bold text-muted-foreground w-6 text-center"
|
||||||
|
:class="{ 'text-yellow-500': index === 0, 'text-slate-400': index === 1, 'text-orange-400': index === 2 }">
|
||||||
|
#{{ index + 1 }}
|
||||||
|
</span>
|
||||||
|
<img :src="getAvatarUrl(user.photo_avatar_filename)"
|
||||||
|
class="h-10 w-10 rounded-full border border-purple-200 object-cover" alt="Avatar" />
|
||||||
|
<div>
|
||||||
|
<p class="font-semibold text-sm">{{ user.nickname }}</p>
|
||||||
|
<p class="text-[10px] text-muted-foreground uppercase tracking-wider">Player</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="text-right">
|
||||||
|
<p class="text-lg font-bold text-purple-600">{{ user.won_games_count }}</p>
|
||||||
|
<p class="text-[10px] text-muted-foreground uppercase">Wins</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div ref="lbObserverTarget" class="h-20 flex items-center justify-center">
|
||||||
|
<span v-if="lbLoading" class="text-purple-500 animate-bounce">Loading rankings...</span>
|
||||||
|
</div>
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="fixed right-4 top-1/2 -translate-y-1/2 flex flex-col gap-4 z-40">
|
||||||
|
<Button @click="openLeaderboard" variant="outline" size="icon"
|
||||||
|
class="h-12 w-12 rounded-full shadow-lg border-purple-500 bg-card hover:bg-purple-500 hover:text-white transition-all">
|
||||||
|
<Trophy class="h-6 w-6" />
|
||||||
|
</Button>
|
||||||
|
<Button v-if="useAuthStore().isLoggedIn" @click="openStats" variant="outline" size="icon"
|
||||||
|
class="h-12 w-12 rounded-full shadow-lg border-purple-500 bg-card hover:bg-purple-500 hover:text-white transition-all">
|
||||||
|
<User class="h-6 w-6" />
|
||||||
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -0,0 +1,139 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex min-h-screen items-center justify-center px-4 py-12 sm:px-6 lg:px-8">
|
||||||
|
<div class="w-full max-w-md space-y-8">
|
||||||
|
<div>
|
||||||
|
<h2 class="mt-6 text-center text-3xl font-bold tracking-tight text-gray-900">Buy Coins</h2>
|
||||||
|
<p class="mt-2 text-center text-sm text-gray-600">€1.00 = 10 Coins</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form class="mt-8 space-y-4" @submit.prevent="handleSubmit">
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1">Amount (Euros)</label>
|
||||||
|
<Input v-model.number="formData.euros" type="number" min="1" max="100" placeholder="Ex: 10"
|
||||||
|
required />
|
||||||
|
<p class="mt-1 text-xs text-blue-600 font-medium">
|
||||||
|
You will receive: {{ formData.euros * 10 }} coins
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1">Payment Method</label>
|
||||||
|
<select v-model="formData.payment_type"
|
||||||
|
class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2">
|
||||||
|
<option value="MBWAY">MB WAY</option>
|
||||||
|
<option value="MB">Multibanco (MB)</option>
|
||||||
|
<option value="VISA">VISA</option>
|
||||||
|
<option value="PAYPAL">PayPal</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label class="block text-sm font-medium text-gray-700 mb-1">
|
||||||
|
{{ referenceLabel }}
|
||||||
|
</label>
|
||||||
|
<Input v-model="formData.payment_reference" type="text" :placeholder="referencePlaceholder"
|
||||||
|
required />
|
||||||
|
<p v-if="errors.payment_reference" class="mt-1 text-xs text-red-500">
|
||||||
|
{{ errors.payment_reference }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pt-4">
|
||||||
|
<Button type="submit" class="w-full">
|
||||||
|
Confirm Purchase (€{{ formData.euros }})
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { ref, computed } from 'vue'
|
||||||
|
import { Input } from '@/components/ui/input'
|
||||||
|
import { Button } from '@/components/ui/button'
|
||||||
|
import { usePurchaseStore } from '@/stores/purchase'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { toast } from 'vue-sonner'
|
||||||
|
import { useUserStore } from '@/stores/user'
|
||||||
|
|
||||||
|
const purchaseStore = usePurchaseStore()
|
||||||
|
const router = useRouter()
|
||||||
|
|
||||||
|
const formData = ref({
|
||||||
|
euros: 1,
|
||||||
|
payment_type: 'MBWAY',
|
||||||
|
payment_reference: ''
|
||||||
|
})
|
||||||
|
|
||||||
|
const errors = ref({})
|
||||||
|
|
||||||
|
const referenceLabel = computed(() => {
|
||||||
|
const labels = {
|
||||||
|
MBWAY: 'Phone Number',
|
||||||
|
MB: 'Entity-Reference',
|
||||||
|
VISA: 'Card Number',
|
||||||
|
PAYPAL: 'PayPal Email'
|
||||||
|
}
|
||||||
|
return labels[formData.value.payment_type]
|
||||||
|
})
|
||||||
|
|
||||||
|
const referencePlaceholder = computed(() => {
|
||||||
|
const placeholders = {
|
||||||
|
MBWAY: '912345678',
|
||||||
|
MB: '12345-123456789',
|
||||||
|
VISA: '1234 5678 9012 3456',
|
||||||
|
PAYPAL: '[email protected]'
|
||||||
|
}
|
||||||
|
return placeholders[formData.value.payment_type]
|
||||||
|
})
|
||||||
|
|
||||||
|
const validateForm = () => {
|
||||||
|
errors.value = {}
|
||||||
|
const type = formData.value.payment_type
|
||||||
|
const refValue = formData.value.payment_reference
|
||||||
|
|
||||||
|
const patterns = {
|
||||||
|
MBWAY: /^9[0-9]{8}$/,
|
||||||
|
MB: /^[0-9]{5}-[0-9]{9}$/,
|
||||||
|
VISA: /^4[0-9]{15}$/,
|
||||||
|
PAYPAL: /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!patterns[type].test(refValue)) {
|
||||||
|
errors.value.payment_reference = `Invalid format for ${type}`
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
if (formData.value.euros < 1 || formData.value.euros > 100) {
|
||||||
|
toast.error("Amount must be between 1 and 100")
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
const userStore = useUserStore()
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!validateForm()) return
|
||||||
|
|
||||||
|
const promise = purchaseStore.purchase(formData.value)
|
||||||
|
|
||||||
|
toast.promise(promise, {
|
||||||
|
loading: 'Processing transaction...',
|
||||||
|
success: (res) => {
|
||||||
|
userStore.fetchCoins()
|
||||||
|
router.push('/')
|
||||||
|
return `Purchase successful! New balance: ${res.data.balance} coins`
|
||||||
|
},
|
||||||
|
error: (error) => {
|
||||||
|
if (error.response?.status === 422) {
|
||||||
|
errors.value = error.response.data.errors
|
||||||
|
return "Please check the highlighted fields"
|
||||||
|
}
|
||||||
|
return error.response?.data?.message || "Transaction failed"
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
</script>
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -9,7 +9,11 @@ import TestDealing from '@/pages/TestDealing.vue'
|
|||||||
import TestAllAnimations from '@/pages/TestAllAnimations.vue'
|
import TestAllAnimations from '@/pages/TestAllAnimations.vue'
|
||||||
import TestGameBoard from '@/pages/TestGameBoard.vue'
|
import TestGameBoard from '@/pages/TestGameBoard.vue'
|
||||||
import SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue'
|
import SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue'
|
||||||
|
import MultiplayerGamePage from '@/pages/game/MultiplayerGamePage.vue'
|
||||||
import RegisterPage from '@/pages/register/RegisterPage.vue'
|
import RegisterPage from '@/pages/register/RegisterPage.vue'
|
||||||
|
import CoinsPurchasePage from '@/pages/purchase/CoinPurchasePage.vue'
|
||||||
|
import { useAuthStore } from '@/stores/auth'
|
||||||
|
import AdminPage from '@/pages/admin/AdminPage.vue'
|
||||||
|
|
||||||
const router = createRouter({
|
const router = createRouter({
|
||||||
history: createWebHistory(import.meta.env.BASE_URL),
|
history: createWebHistory(import.meta.env.BASE_URL),
|
||||||
@@ -18,6 +22,7 @@ const router = createRouter({
|
|||||||
path: '/',
|
path: '/',
|
||||||
name: 'home',
|
name: 'home',
|
||||||
component: HomePage,
|
component: HomePage,
|
||||||
|
meta: { requiresAdmin: false }
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/login',
|
path: '/login',
|
||||||
@@ -34,7 +39,7 @@ const router = createRouter({
|
|||||||
name: 'bisca3',
|
name: 'bisca3',
|
||||||
component: SinglePlayerGamePage,
|
component: SinglePlayerGamePage,
|
||||||
props: { gameType: 3 },
|
props: { gameType: 3 },
|
||||||
meta: { requiresAuth: true },
|
meta: { requiresAuth: true, requiresAdmin: false },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/game/9',
|
path: '/game/9',
|
||||||
@@ -43,9 +48,27 @@ const router = createRouter({
|
|||||||
props: { gameType: 9 },
|
props: { gameType: 9 },
|
||||||
meta: { requiresAuth: true },
|
meta: { requiresAuth: true },
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/game/multiplayer/:id',
|
||||||
|
name: 'multiplayer-game',
|
||||||
|
component: MultiplayerGamePage,
|
||||||
|
meta: { requiresAuth: true }
|
||||||
|
},
|
||||||
{
|
{
|
||||||
path: '/user',
|
path: '/user',
|
||||||
component: UserPage,
|
component: UserPage,
|
||||||
|
meta: { requiresAuth: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/coins-purchase',
|
||||||
|
component: CoinsPurchasePage,
|
||||||
|
meta: { requiresAuth: true },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: '/admin',
|
||||||
|
name: 'admin',
|
||||||
|
component: AdminPage,
|
||||||
|
meta: { requiresAuth: true, requiresAdmin: true },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
path: '/testing',
|
path: '/testing',
|
||||||
@@ -81,6 +104,7 @@ const router = createRouter({
|
|||||||
|
|
||||||
router.beforeEach((to, from, next) => {
|
router.beforeEach((to, from, next) => {
|
||||||
const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)
|
const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)
|
||||||
|
const requiresAdmin = to.matched.some((record) => record.meta.requiresAdmin)
|
||||||
|
|
||||||
if (requiresAuth) {
|
if (requiresAuth) {
|
||||||
const token = localStorage.getItem('token')
|
const token = localStorage.getItem('token')
|
||||||
@@ -89,6 +113,10 @@ router.beforeEach((to, from, next) => {
|
|||||||
return next({ name: 'login' })
|
return next({ name: 'login' })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (useAuthStore().isAdmin && to.name === 'home') return next({ name: 'admin' })
|
||||||
|
if (requiresAdmin && !useAuthStore().isAdmin) return next({ name: 'home' })
|
||||||
|
|
||||||
next()
|
next()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
+109
-2
@@ -76,6 +76,23 @@ export const useAPIStore = defineStore('api', () => {
|
|||||||
return axios.get(`${API_BASE_URL}/games?${queryParams}`)
|
return axios.get(`${API_BASE_URL}/games?${queryParams}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- ADICIONADO: Função que faltava ---
|
||||||
|
const getCurrentUserGames = (params = {}) => {
|
||||||
|
const queryParams = new URLSearchParams({
|
||||||
|
page: params.page || 1,
|
||||||
|
...(params.type && { type: params.type }),
|
||||||
|
...(params.outcome && { outcome: params.outcome }),
|
||||||
|
...(params.status && { status: params.status }),
|
||||||
|
...(params.date_from && { date_from: params.date_from }),
|
||||||
|
...(params.date_to && { date_to: params.date_to }),
|
||||||
|
sort_by: params.sort_by || 'began_at',
|
||||||
|
sort_direction: params.sort_direction || 'desc',
|
||||||
|
}).toString()
|
||||||
|
|
||||||
|
return axios.get(`${API_BASE_URL}/users/${authStore.currentUserID}/games?${queryParams}`)
|
||||||
|
}
|
||||||
|
// --------------------------------------
|
||||||
|
|
||||||
const getCurrentUserMatches = (params = {}) => {
|
const getCurrentUserMatches = (params = {}) => {
|
||||||
const queryParams = new URLSearchParams({
|
const queryParams = new URLSearchParams({
|
||||||
page: params.page || 1,
|
page: params.page || 1,
|
||||||
@@ -95,20 +112,110 @@ export const useAPIStore = defineStore('api', () => {
|
|||||||
const queryParams = new URLSearchParams({
|
const queryParams = new URLSearchParams({
|
||||||
page: params.page || 1,
|
page: params.page || 1,
|
||||||
...(params.type && { type: params.type }),
|
...(params.type && { type: params.type }),
|
||||||
...(params.date_from && { date_from: params.date_from }),
|
...(params.blocked && { blocked: params.blocked }),
|
||||||
...(params.date_to && { date_to: params.date_to }),
|
|
||||||
}).toString()
|
}).toString()
|
||||||
|
|
||||||
return axios.get(`${API_BASE_URL}/users/${authStore.currentUserID}/transactions?${queryParams}`)
|
return axios.get(`${API_BASE_URL}/users/${authStore.currentUserID}/transactions?${queryParams}`)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getLeaderboard = (params = {}) => {
|
||||||
|
const queryParams = new URLSearchParams({
|
||||||
|
page: params.page || 1,
|
||||||
|
}).toString()
|
||||||
|
|
||||||
|
return axios.get(`${API_BASE_URL}/leaderboard?${queryParams}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getCurrentUserStats = () => {
|
||||||
|
return axios.get(`${API_BASE_URL}/statistics/me`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getPublicStats = () => {
|
||||||
|
return axios.get(`${API_BASE_URL}/statistics/public`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getAdminStats = () => {
|
||||||
|
return axios.get(`${API_BASE_URL}/admin/statistics`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getAdminUsers = (params) => {
|
||||||
|
const queryParams = new URLSearchParams({
|
||||||
|
page: params.page || 1,
|
||||||
|
...(params.type && { type: params.type }),
|
||||||
|
...(params.blocked && { blocked: params.blocked }),
|
||||||
|
}).toString()
|
||||||
|
return axios.get(`${API_BASE_URL}/admin/users?${queryParams}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const blockUser = (user) => {
|
||||||
|
return axios.post(`${API_BASE_URL}/admin/users/${user.id}/block`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const unblockUser = (user) => {
|
||||||
|
return axios.post(`${API_BASE_URL}/admin/users/${user.id}/unblock`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleteUser = (user) => {
|
||||||
|
return axios.delete(`${API_BASE_URL}/admin/users/${user.id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getAdminTransactions = (params) => {
|
||||||
|
const queryParams = new URLSearchParams({
|
||||||
|
page: params.page || 1,
|
||||||
|
...(params.sort_datetime == 'asc' && { sort_datetime: 'asc' }),
|
||||||
|
...(params.sort_coins && { sort_coins: params.sort_coins }),
|
||||||
|
}).toString()
|
||||||
|
return axios.get(`${API_BASE_URL}/admin/transactions?${queryParams}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getAdminGames = (params) => {
|
||||||
|
const queryParams = new URLSearchParams({
|
||||||
|
page: params.page || 1,
|
||||||
|
...(params.sort_direction == 'asc' && { sort_direction: 'asc' }),
|
||||||
|
...(params.type && { type: params.type }),
|
||||||
|
}).toString()
|
||||||
|
|
||||||
|
return axios.get(`${API_BASE_URL}/games?${queryParams}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const getAdminMatches = (params = {}) => {
|
||||||
|
const queryParams = new URLSearchParams({
|
||||||
|
page: params.page || 1,
|
||||||
|
...(params.type && { type: params.type }),
|
||||||
|
...(params.outcome && { outcome: params.outcome }),
|
||||||
|
...(params.date_from && { date_from: params.date_from }),
|
||||||
|
...(params.date_to && { date_to: params.date_to }),
|
||||||
|
sort_by: params.sort_by || 'began_at',
|
||||||
|
sort_direction: params.sort_direction || 'desc',
|
||||||
|
}).toString()
|
||||||
|
|
||||||
|
return axios.get(`${API_BASE_URL}/matches?${queryParams}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const postAdmin = async (credentials) => {
|
||||||
|
return axios.post(`${API_BASE_URL}/admin/users`, credentials)
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
postLogin,
|
postLogin,
|
||||||
postLogout,
|
postLogout,
|
||||||
getAuthUser,
|
getAuthUser,
|
||||||
getGames,
|
getGames,
|
||||||
|
getCurrentUserGames,
|
||||||
getCurrentUserMatches,
|
getCurrentUserMatches,
|
||||||
getCurrentUserTransactions,
|
getCurrentUserTransactions,
|
||||||
|
getCurrentUserStats,
|
||||||
|
getLeaderboard,
|
||||||
|
getPublicStats,
|
||||||
|
getAdminStats,
|
||||||
|
getAdminUsers,
|
||||||
|
blockUser,
|
||||||
|
unblockUser,
|
||||||
|
deleteUser,
|
||||||
|
getAdminTransactions,
|
||||||
|
getAdminGames,
|
||||||
|
getAdminMatches,
|
||||||
|
postAdmin,
|
||||||
gameQueryParameters,
|
gameQueryParameters,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { useAPIStore } from './api'
|
|||||||
|
|
||||||
export const useAuthStore = defineStore('auth', () => {
|
export const useAuthStore = defineStore('auth', () => {
|
||||||
|
|
||||||
const DEFAULT_TIMEOUT = 5 * 60 * 1000
|
const DEFAULT_TIMEOUT = 30 * 60 * 1000
|
||||||
const REMEMBER_ME_TIMEOUT = 365 * 24 * 60 * 60 * 1000
|
const REMEMBER_ME_TIMEOUT = 365 * 24 * 60 * 60 * 1000
|
||||||
|
|
||||||
const currentUser = ref(undefined)
|
const currentUser = ref(undefined)
|
||||||
@@ -20,6 +20,10 @@ export const useAuthStore = defineStore('auth', () => {
|
|||||||
return currentUser.value?.id
|
return currentUser.value?.id
|
||||||
})
|
})
|
||||||
|
|
||||||
|
const isAdmin = computed(() => {
|
||||||
|
return currentUser.value?.type === 'A'
|
||||||
|
})
|
||||||
|
|
||||||
const isTokenAlmostExpired = () => {
|
const isTokenAlmostExpired = () => {
|
||||||
if (!tokenExpiry.value) return false;
|
if (!tokenExpiry.value) return false;
|
||||||
return Date.now() > (tokenExpiry.value - 60 * 1000);
|
return Date.now() > (tokenExpiry.value - 60 * 1000);
|
||||||
@@ -112,10 +116,16 @@ export const useAuthStore = defineStore('auth', () => {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const updateCurrentUserCoins = (coins) => {
|
||||||
|
if (!currentUser.value) return;
|
||||||
|
currentUser.value.coins_balance = coins
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
currentUser,
|
currentUser,
|
||||||
isLoggedIn,
|
isLoggedIn,
|
||||||
currentUserID,
|
currentUserID,
|
||||||
|
isAdmin,
|
||||||
token,
|
token,
|
||||||
rememberMe,
|
rememberMe,
|
||||||
getToken,
|
getToken,
|
||||||
@@ -124,5 +134,6 @@ export const useAuthStore = defineStore('auth', () => {
|
|||||||
resetTokenExpiry,
|
resetTokenExpiry,
|
||||||
isTokenAlmostExpired,
|
isTokenAlmostExpired,
|
||||||
restoreSession,
|
restoreSession,
|
||||||
|
updateCurrentUserCoins,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import axios from 'axios'
|
||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { inject } from 'vue'
|
||||||
|
|
||||||
|
export const usePurchaseStore = defineStore('purchase', () => {
|
||||||
|
|
||||||
|
const API_BASE_URL = inject('apiBaseURL')
|
||||||
|
|
||||||
|
const purchase = async (data) => {
|
||||||
|
return await axios.post(`${API_BASE_URL}/coin-purchases`, data)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
purchase,
|
||||||
|
}
|
||||||
|
})
|
||||||
+121
-15
@@ -1,24 +1,130 @@
|
|||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import { inject } from 'vue'
|
import { ref } from 'vue'
|
||||||
|
import { io } from 'socket.io-client'
|
||||||
|
import { useAuthStore } from './auth'
|
||||||
|
|
||||||
export const useSocketStore = defineStore('socket', () => {
|
export const useSocketStore = defineStore('websocket', () => {
|
||||||
const socket = inject('socket')
|
const authStore = useAuthStore()
|
||||||
|
|
||||||
const handleConnection = () => {
|
const socket = ref(null)
|
||||||
try {
|
const connected = ref(false)
|
||||||
socket.on('connect', () => {
|
const gameState = ref(null)
|
||||||
console.log(`[Socket] Connected -- ${socket.id}`)
|
const lastError = ref(null)
|
||||||
})
|
const currentGameId = ref(null)
|
||||||
socket.on('disconnect', () => {
|
|
||||||
console.log(`[Socket] Disconnected -- ${socket.id}`)
|
const WS_URL = 'http://localhost:3000'
|
||||||
})
|
|
||||||
} catch (error) {
|
const connect = () => {
|
||||||
console.error('[Socket] Connection error:', error)
|
if (socket.value?.connected) return
|
||||||
|
|
||||||
|
const token = authStore.getToken()
|
||||||
|
if (!token) {
|
||||||
|
console.error('No token available for WebSocket connection')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
socket.value = io(WS_URL, {
|
||||||
|
auth: { token: `Bearer ${token}` },
|
||||||
|
reconnection: true,
|
||||||
|
reconnectionAttempts: 5,
|
||||||
|
reconnectionDelay: 1000
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.value.on('connect', () => {
|
||||||
|
if (currentGameId.value) {
|
||||||
|
console.log("Reconnected to socket. Rejoining game...");
|
||||||
|
socket.emit("join-game", { gameId: currentGameId.value });
|
||||||
|
}
|
||||||
|
|
||||||
|
connected.value = true
|
||||||
|
console.log('[WebSocket] Connected:', socket.value.id)
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.value.on('disconnect', (reason) => {
|
||||||
|
connected.value = false
|
||||||
|
console.log('[WebSocket] Disconnected:', reason)
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.value.on('connect_error', (error) => {
|
||||||
|
console.error('[WebSocket] Connection error:', error.message)
|
||||||
|
lastError.value = error.message
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.value.on('heartbeat', () => {
|
||||||
|
socket.value.emit('heartbeat_ack')
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.value.on('game-state', (state) => {
|
||||||
|
gameState.value = state
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.value.on('game-error', (data) => {
|
||||||
|
lastError.value = data.message
|
||||||
|
console.error('[Game] Error:', data.message)
|
||||||
|
})
|
||||||
|
|
||||||
|
socket.value.on('error', (data) => {
|
||||||
|
lastError.value = data.message
|
||||||
|
console.error('[Socket] Error:', data.message)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const disconnect = () => {
|
||||||
|
if (socket.value) {
|
||||||
|
socket.value.disconnect()
|
||||||
|
socket.value = null
|
||||||
|
connected.value = false
|
||||||
|
gameState.value = null
|
||||||
|
lastError.value = null
|
||||||
|
currentGameId.value = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const joinGame = (gameId) => {
|
||||||
|
currentGameId.value = gameId
|
||||||
|
if (!socket.value?.connected) return
|
||||||
|
console.log('[Game] Joining game:', gameId)
|
||||||
|
socket.value.emit('join-game', { gameId })
|
||||||
|
}
|
||||||
|
|
||||||
|
const playCard = (gameId, cardId) => {
|
||||||
|
if (!socket.value?.connected) return
|
||||||
|
socket.value.emit('play-card', { gameId, cardId })
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- NEW: Surrender Action ---
|
||||||
|
const surrender = (gameId) => {
|
||||||
|
if (!socket.value?.connected) return
|
||||||
|
console.log('[Game] Surrendering:', gameId)
|
||||||
|
socket.value.emit('surrender', { gameId })
|
||||||
|
}
|
||||||
|
|
||||||
|
const onTrickEnd = (callback) => {
|
||||||
|
if (socket.value) {
|
||||||
|
socket.value.off('trick-end')
|
||||||
|
socket.value.on('trick-end', callback)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onGameOver = (callback) => {
|
||||||
|
if (socket.value) {
|
||||||
|
socket.value.off('game-over')
|
||||||
|
socket.value.on('game-over', callback)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
handleConnection,
|
socket,
|
||||||
|
connected,
|
||||||
|
gameState,
|
||||||
|
lastError,
|
||||||
|
currentGameId,
|
||||||
|
connect,
|
||||||
|
disconnect,
|
||||||
|
joinGame,
|
||||||
|
playCard,
|
||||||
|
surrender, // Exported
|
||||||
|
onTrickEnd,
|
||||||
|
onGameOver
|
||||||
}
|
}
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,16 +1,26 @@
|
|||||||
import { defineStore } from 'pinia'
|
import { defineStore } from 'pinia'
|
||||||
import axios from 'axios'
|
import axios from 'axios'
|
||||||
import { inject } from 'vue'
|
import { inject, ref } from 'vue'
|
||||||
|
import { useAuthStore } from './auth'
|
||||||
|
|
||||||
export const useUserStore = defineStore('user', () => {
|
export const useUserStore = defineStore('user', () => {
|
||||||
|
|
||||||
const API_BASE_URL = inject('apiBaseURL')
|
const API_BASE_URL = inject('apiBaseURL')
|
||||||
|
const coins = ref(0)
|
||||||
|
|
||||||
const getCoins = async () => {
|
const fetchCoins = async () => {
|
||||||
return await axios.get(`${API_BASE_URL}/users/me/coins`)
|
try {
|
||||||
|
const response = await axios.get(`${API_BASE_URL}/users/me/coins`)
|
||||||
|
coins.value = response.data?.coins || 0
|
||||||
|
useAuthStore().updateCurrentUserCoins(coins.value)
|
||||||
|
return response
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching coins', error)
|
||||||
|
throw error
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
getCoins,
|
coins,
|
||||||
|
fetchCoins,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -1,11 +1,16 @@
|
|||||||
class BiscaGame {
|
class BiscaGame {
|
||||||
constructor(id, type, player1, player2) {
|
constructor(id, type, player1, player2, dbId = null, onGameEnd = null) {
|
||||||
this.id = id;
|
this.id = id;
|
||||||
|
this.dbId = dbId;
|
||||||
this.type = type;
|
this.type = type;
|
||||||
|
this.onGameEnd = onGameEnd;
|
||||||
|
|
||||||
this.deck = [];
|
this.deck = [];
|
||||||
this.trumpCard = null;
|
this.trumpCard = null;
|
||||||
this.trumpSuit = null;
|
this.trumpSuit = null;
|
||||||
|
this.timer = null;
|
||||||
|
this.turnDeadline = null;
|
||||||
|
this.timeoutCallback = null;
|
||||||
|
|
||||||
this.table = {
|
this.table = {
|
||||||
playerCard: null,
|
playerCard: null,
|
||||||
@@ -50,6 +55,46 @@ class BiscaGame {
|
|||||||
this.status = "playing";
|
this.status = "playing";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
startTurnTimer(callback) {
|
||||||
|
if (this.timer) clearTimeout(this.timer);
|
||||||
|
|
||||||
|
this.timeoutCallback = callback;
|
||||||
|
const DURATION_MS = 20000;
|
||||||
|
this.turnDeadline = Date.now() + DURATION_MS;
|
||||||
|
|
||||||
|
console.log(`[Game ${this.id}] Timer started for User ${this.currentTurn}`);
|
||||||
|
|
||||||
|
this.timer = setTimeout(() => {
|
||||||
|
this.handleTimeout();
|
||||||
|
}, DURATION_MS);
|
||||||
|
}
|
||||||
|
|
||||||
|
stopTimer() {
|
||||||
|
if (this.timer) clearTimeout(this.timer);
|
||||||
|
this.timer = null;
|
||||||
|
this.turnDeadline = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
handleTimeout() {
|
||||||
|
console.log(
|
||||||
|
`[Game ${this.id}] Timeout! Auto-playing for ${this.currentTurn}`
|
||||||
|
);
|
||||||
|
|
||||||
|
const lowestCard = this.getLowestCard(this.currentTurn);
|
||||||
|
|
||||||
|
if (lowestCard && this.timeoutCallback) {
|
||||||
|
this.timeoutCallback(this.currentTurn, lowestCard.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
getLowestCard(userId) {
|
||||||
|
const hand = this.players[userId].hand;
|
||||||
|
if (!hand || hand.length === 0) return null;
|
||||||
|
|
||||||
|
const sortedHand = [...hand].sort((a, b) => a.strength - b.strength);
|
||||||
|
return sortedHand[0];
|
||||||
|
}
|
||||||
|
|
||||||
createDeck() {
|
createDeck() {
|
||||||
const suits = ["c", "e", "o", "p"];
|
const suits = ["c", "e", "o", "p"];
|
||||||
const ranks = [1, 2, 3, 4, 5, 6, 7, 11, 12, 13];
|
const ranks = [1, 2, 3, 4, 5, 6, 7, 11, 12, 13];
|
||||||
@@ -105,6 +150,8 @@ class BiscaGame {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
this.stopTimer();
|
||||||
|
|
||||||
player.hand.splice(cardIndex, 1);
|
player.hand.splice(cardIndex, 1);
|
||||||
|
|
||||||
if (!this.table.playerCard) {
|
if (!this.table.playerCard) {
|
||||||
@@ -152,6 +199,7 @@ class BiscaGame {
|
|||||||
|
|
||||||
if (this.players[winnerId].hand.length === 0) {
|
if (this.players[winnerId].hand.length === 0) {
|
||||||
this.status = "finished";
|
this.status = "finished";
|
||||||
|
this.stopTimer();
|
||||||
|
|
||||||
const pIds = Object.keys(this.players);
|
const pIds = Object.keys(this.players);
|
||||||
const p1Obj = this.players[pIds[0]];
|
const p1Obj = this.players[pIds[0]];
|
||||||
@@ -185,6 +233,10 @@ class BiscaGame {
|
|||||||
player2_points: p2Obj.points,
|
player2_points: p2Obj.points,
|
||||||
totalTime: totalTime,
|
totalTime: totalTime,
|
||||||
};
|
};
|
||||||
|
if (this.onGameEnd) {
|
||||||
|
this.onGameEnd(result);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
return { action: "trick_resolved", trickResult };
|
return { action: "trick_resolved", trickResult };
|
||||||
@@ -194,6 +246,7 @@ class BiscaGame {
|
|||||||
const oppId = this.getOpponentId(userId);
|
const oppId = this.getOpponentId(userId);
|
||||||
return {
|
return {
|
||||||
id: this.id,
|
id: this.id,
|
||||||
|
dbId: this.dbId,
|
||||||
trumpCard: this.trumpCard,
|
trumpCard: this.trumpCard,
|
||||||
trumpSuit: this.trumpSuit,
|
trumpSuit: this.trumpSuit,
|
||||||
deckCount: this.deck.length + (this.trumpCard ? 1 : 0),
|
deckCount: this.deck.length + (this.trumpCard ? 1 : 0),
|
||||||
@@ -205,6 +258,7 @@ class BiscaGame {
|
|||||||
points: this.players[oppId].points,
|
points: this.players[oppId].points,
|
||||||
cardCount: this.players[oppId].hand.length,
|
cardCount: this.players[oppId].hand.length,
|
||||||
},
|
},
|
||||||
|
turnDeadline: this.turnDeadline,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,4 +286,4 @@ class BiscaGame {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = BiscaGame;
|
export default BiscaGame;
|
||||||
|
|||||||
@@ -0,0 +1,275 @@
|
|||||||
|
import BiscaGame from "../classes/BiscaGame.js";
|
||||||
|
import axios from "axios";
|
||||||
|
|
||||||
|
const API_URL = "http://localhost:8000/api/v1";
|
||||||
|
|
||||||
|
class BiscaMatch {
|
||||||
|
constructor(apiData, emitStateCallback, token) {
|
||||||
|
this.id = apiData.id;
|
||||||
|
this.emitStateCallback = emitStateCallback;
|
||||||
|
this.token = token;
|
||||||
|
this.stake = apiData.stake;
|
||||||
|
this.type = apiData.type;
|
||||||
|
this.status = apiData.status;
|
||||||
|
|
||||||
|
this.player1Id = apiData.player1_user_id;
|
||||||
|
this.player2Id = apiData.player2_user_id;
|
||||||
|
|
||||||
|
this.marks = {
|
||||||
|
[this.player1Id]: apiData.player1_marks || 0,
|
||||||
|
[this.player2Id]: apiData.player2_marks || 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.points = {
|
||||||
|
[this.player1Id]: apiData.player1_points || 0,
|
||||||
|
[this.player2Id]: apiData.player2_points || 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
this.currentGame = null;
|
||||||
|
this.GHOST_ID = 1;
|
||||||
|
|
||||||
|
if (this.status === "Playing" && this.player2Id !== this.GHOST_ID) {
|
||||||
|
this.startNewGame();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async joinPlayer(userId) {
|
||||||
|
if (this.player2Id !== this.GHOST_ID) return false;
|
||||||
|
if (userId === this.player1Id) return false;
|
||||||
|
|
||||||
|
this.player2Id = userId;
|
||||||
|
this.marks[userId] = 0;
|
||||||
|
this.points[userId] = 0;
|
||||||
|
this.status = "Playing";
|
||||||
|
|
||||||
|
await this.startNewGame();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
getAuthHeaders() {
|
||||||
|
return {
|
||||||
|
headers: { Authorization: this.token },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async startNewGame() {
|
||||||
|
console.log(`[Match ${this.id}] A iniciar nova mão (Game DB)...`);
|
||||||
|
|
||||||
|
let newGameDbId = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
let payloadP1 = this.player1Id;
|
||||||
|
let payloadP2 = this.player2Id;
|
||||||
|
|
||||||
|
if (this.player2Id !== this.GHOST_ID) {
|
||||||
|
console.log(
|
||||||
|
"🔄 Multiplayer detetado: Trocando ordem para satisfazer a API..."
|
||||||
|
);
|
||||||
|
payloadP1 = this.player2Id;
|
||||||
|
payloadP2 = this.player1Id;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
type: this.type,
|
||||||
|
player1_user_id: payloadP1,
|
||||||
|
player2_user_id: payloadP2,
|
||||||
|
match_id: this.id,
|
||||||
|
status: "Playing",
|
||||||
|
began_at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log("📤 [Payload Adaptado]:", JSON.stringify(payload, null, 2));
|
||||||
|
|
||||||
|
const res = await axios.post(
|
||||||
|
`${API_URL}/games`,
|
||||||
|
payload,
|
||||||
|
this.getAuthHeaders()
|
||||||
|
);
|
||||||
|
|
||||||
|
const gameData = res.data.game || res.data.data || res.data;
|
||||||
|
newGameDbId = gameData.id;
|
||||||
|
|
||||||
|
console.log(`[Match ${this.id}] Game DB criado: #${newGameDbId}`);
|
||||||
|
|
||||||
|
const apiP1 = gameData.player1_user_id;
|
||||||
|
const apiP2 = gameData.player2_user_id;
|
||||||
|
|
||||||
|
const p1 = { id: apiP1, name: `User ${apiP1}` };
|
||||||
|
const p2 = { id: apiP2, name: `User ${apiP2}` };
|
||||||
|
|
||||||
|
this.currentGame = new BiscaGame(
|
||||||
|
this.id,
|
||||||
|
this.type,
|
||||||
|
p1,
|
||||||
|
p2,
|
||||||
|
newGameDbId,
|
||||||
|
(result) => {
|
||||||
|
this.handleGameEnd(result);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
this.currentGame.init();
|
||||||
|
|
||||||
|
if (this.emitStateCallback) {
|
||||||
|
this.emitStateCallback("match:new-round", this.getState());
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (e.response) {
|
||||||
|
console.error(
|
||||||
|
`❌ Erro API (${e.response.status}):`,
|
||||||
|
JSON.stringify(e.response.data)
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
console.error(`❌ Erro Código: ${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async handleGameEnd(result) {
|
||||||
|
console.log(
|
||||||
|
`[Match ${this.id}] Mão terminada. Vencedor: ${result.winnerId}`
|
||||||
|
);
|
||||||
|
|
||||||
|
this.points[result.player1_id] += result.player1_points;
|
||||||
|
this.points[result.player2_id] += result.player2_points;
|
||||||
|
|
||||||
|
if (this.currentGame && this.currentGame.dbId) {
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
status: "Ended",
|
||||||
|
winner_user_id: result.winnerId,
|
||||||
|
loser_user_id: result.loserId,
|
||||||
|
is_draw: result.isDraw,
|
||||||
|
player1_points: result.player1_points,
|
||||||
|
player2_points: result.player2_points,
|
||||||
|
ended_at: new Date().toISOString(),
|
||||||
|
};
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`📤 A enviar update para Game #${this.currentGame.dbId}...`
|
||||||
|
);
|
||||||
|
|
||||||
|
// --- CORREÇÃO IMPORTANTE: Forçar o header aqui ---
|
||||||
|
const config = {
|
||||||
|
headers: {
|
||||||
|
Authorization: this.token,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
await axios.put(
|
||||||
|
`${API_URL}/games/${this.currentGame.dbId}`,
|
||||||
|
payload,
|
||||||
|
config
|
||||||
|
);
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
`✅ Game #${this.currentGame.dbId} atualizado com sucesso.`
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
// --- LOG DETALHADO PARA VER O MOTIVO DO 403 ---
|
||||||
|
if (e.response) {
|
||||||
|
console.error(`❌ ERRO CRÍTICO API (${e.response.status}):`);
|
||||||
|
// Isto vai imprimir o JSON exato que o Laravel devolve
|
||||||
|
console.error(JSON.stringify(e.response.data, null, 2));
|
||||||
|
} else {
|
||||||
|
console.error("Erro Axios:", e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.warn("⚠️ Ignorado: Não há ID de jogo na DB para atualizar.");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ... (resto da lógica de atribuir marcas e finishMatch mantém-se igual)
|
||||||
|
let marksToAdd = 0;
|
||||||
|
let roundWinnerId = result.winnerId;
|
||||||
|
|
||||||
|
if (roundWinnerId) {
|
||||||
|
const winningScore =
|
||||||
|
roundWinnerId == result.player1_id
|
||||||
|
? result.player1_points
|
||||||
|
: result.player2_points;
|
||||||
|
if (winningScore === 120) marksToAdd = 4;
|
||||||
|
else if (winningScore > 90) marksToAdd = 2;
|
||||||
|
else if (winningScore >= 60) marksToAdd = 1;
|
||||||
|
this.marks[roundWinnerId] += marksToAdd;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.marks[this.player1Id] >= 4 || this.marks[this.player2Id] >= 4) {
|
||||||
|
await this.finishMatch();
|
||||||
|
if (this.emitStateCallback) {
|
||||||
|
this.emitStateCallback("match:ended", this.getState());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log(`[Match ${this.id}] Ninguém ganhou 4 marcas. A baralhar...`);
|
||||||
|
await this.startNewGame();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async finishMatch() {
|
||||||
|
this.status = "Ended";
|
||||||
|
|
||||||
|
const winnerId =
|
||||||
|
this.marks[this.player1Id] >= 4 ? this.player1Id : this.player2Id;
|
||||||
|
const loserId =
|
||||||
|
winnerId == this.player1Id ? this.player2Id : this.player1Id;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await axios.put(
|
||||||
|
`${API_URL}/matches/${this.id}`,
|
||||||
|
{
|
||||||
|
status: "Ended",
|
||||||
|
winner_user_id: winnerId,
|
||||||
|
loser_user_id: loserId,
|
||||||
|
player1_marks: this.marks[this.player1Id],
|
||||||
|
player2_marks: this.marks[this.player2Id],
|
||||||
|
player1_points: this.points[this.player1Id],
|
||||||
|
player2_points: this.points[this.player2Id],
|
||||||
|
},
|
||||||
|
this.getAuthHeaders()
|
||||||
|
);
|
||||||
|
console.log(`[Match ${this.id}] Encerrado com sucesso na API.`);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`Erro ao fechar Match API: ${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
playCard(userId, cardId) {
|
||||||
|
if (!this.currentGame || this.status !== "Playing") return;
|
||||||
|
return this.currentGame.playCard(userId, cardId);
|
||||||
|
}
|
||||||
|
|
||||||
|
getState() {
|
||||||
|
let gameState = null;
|
||||||
|
|
||||||
|
if (this.currentGame) {
|
||||||
|
const p1Id = this.player1Id;
|
||||||
|
const p2Id = this.player2Id;
|
||||||
|
|
||||||
|
if (this.currentGame.players && this.currentGame.players[p1Id]) {
|
||||||
|
gameState = this.currentGame.getStateForPlayer(p1Id);
|
||||||
|
} else if (this.currentGame.players && this.currentGame.players[p2Id]) {
|
||||||
|
gameState = this.currentGame.getStateForPlayer(p2Id);
|
||||||
|
} else if (this.currentGame.players) {
|
||||||
|
const availableIds = Object.keys(this.currentGame.players);
|
||||||
|
if (availableIds.length > 0) {
|
||||||
|
console.warn(
|
||||||
|
`⚠️ [Match ${this.id}] IDs desalinhados! A usar vista do user ${availableIds[0]}`
|
||||||
|
);
|
||||||
|
gameState = this.currentGame.getStateForPlayer(availableIds[0]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
matchId: this.id,
|
||||||
|
status: this.status,
|
||||||
|
marks: this.marks,
|
||||||
|
points: this.points,
|
||||||
|
game: gameState,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export default BiscaMatch;
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
import { addUser, removeUser } from "../state/connection";
|
import { addUser, removeUser } from "../state/connection.js";
|
||||||
|
|
||||||
const HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
const HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||||
const HEARTBEAT_TIMEOUT = 10000; // 10 seconds
|
const HEARTBEAT_TIMEOUT = 10000; // 10 seconds
|
||||||
@@ -27,20 +27,17 @@ export const handleConnectionEvents = (io, socket) => {
|
|||||||
socket.on("join", (user) => {
|
socket.on("join", (user) => {
|
||||||
addUser(socket, user);
|
addUser(socket, user);
|
||||||
console.log(`[Connection] User ${user.name} has joined the server`);
|
console.log(`[Connection] User ${user.name} has joined the server`);
|
||||||
console.log(`[Connection] ${getUserCount()} users online`);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on("leave", () => {
|
socket.on("leave", () => {
|
||||||
const user = removeUser(socket.id);
|
const user = removeUser(socket.id);
|
||||||
if (user) {
|
if (user) {
|
||||||
console.log(`[Connection] User ${user.name} has left the server`);
|
console.log(`[Connection] User ${user.name} has left the server`);
|
||||||
console.log(`[Connection] ${getUserCount()} users online`);
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on("disconnect", () => {
|
socket.on("disconnect", () => {
|
||||||
console.log("Connection Lost:", socket.id);
|
console.log("Connection Lost:", socket.id);
|
||||||
removeUser(socket.id);
|
removeUser(socket.id);
|
||||||
console.log(`[Connection] ${getUserCount()} users online`);
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
+215
-81
@@ -4,6 +4,71 @@ import { getUser } from "../state/connection.js";
|
|||||||
|
|
||||||
const API_URL = "http://localhost:8000/api/v1";
|
const API_URL = "http://localhost:8000/api/v1";
|
||||||
|
|
||||||
|
// --- HELPER: Card Strength for Auto-Play ---
|
||||||
|
const getStrength = (rank) => {
|
||||||
|
const strengthMap = { 1: 10, 7: 9, 13: 8, 11: 7, 12: 6, 6: 5, 5: 4, 4: 3, 3: 2, 2: 1 };
|
||||||
|
return strengthMap[rank] || 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- HELPER: Draw Card Logic ---
|
||||||
|
const drawCard = (game, playerId) => {
|
||||||
|
const player = game.players[playerId];
|
||||||
|
if (!player) return;
|
||||||
|
|
||||||
|
if (game.deck && game.deck.length > 0) {
|
||||||
|
const card = game.deck.pop();
|
||||||
|
player.hand.push(card);
|
||||||
|
} else if (game.trumpCard) {
|
||||||
|
player.hand.push(game.trumpCard);
|
||||||
|
game.trumpCard = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// --- HELPER: Sanitize Data ---
|
||||||
|
const sanitizeState = (state, game) => {
|
||||||
|
if (!state) return null;
|
||||||
|
const p1 = game.player1 || state.player1 || {};
|
||||||
|
const p2 = game.player2 || state.player2 || {};
|
||||||
|
|
||||||
|
return {
|
||||||
|
id: state.id,
|
||||||
|
status: state.status || game.status,
|
||||||
|
player1: { id: p1.id, name: p1.name },
|
||||||
|
player2: { id: p2.id, name: p2.name },
|
||||||
|
players: state.players,
|
||||||
|
hand: state.hand,
|
||||||
|
points: state.points,
|
||||||
|
opponent: {
|
||||||
|
id: state.opponent?.id,
|
||||||
|
name: state.opponent?.name,
|
||||||
|
points: state.opponent?.points,
|
||||||
|
cardCount: state.opponent?.cardCount
|
||||||
|
},
|
||||||
|
table: state.table,
|
||||||
|
trumpCard: state.trumpCard,
|
||||||
|
deckCount: game.deck ? game.deck.length : (state.deckCount || 0),
|
||||||
|
currentTurn: state.currentTurn,
|
||||||
|
turnStartedAt: state.turnStartedAt
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const broadcastState = (io, gameId, game) => {
|
||||||
|
const roomName = `game_${gameId}`;
|
||||||
|
const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
|
||||||
|
|
||||||
|
if (socketsInRoom) {
|
||||||
|
for (const socketId of socketsInRoom) {
|
||||||
|
const s = io.sockets.sockets.get(socketId);
|
||||||
|
const u = getUser(socketId);
|
||||||
|
if (u && game.players[u.id]) {
|
||||||
|
const rawState = game.getStateForPlayer(u.id);
|
||||||
|
const cleanState = sanitizeState(rawState, game);
|
||||||
|
s.emit("game-state", cleanState);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function saveGameResult(gameId, result, token) {
|
async function saveGameResult(gameId, result, token) {
|
||||||
try {
|
try {
|
||||||
const payload = {
|
const payload = {
|
||||||
@@ -13,21 +78,108 @@ async function saveGameResult(gameId, result, token) {
|
|||||||
player1_points: result.player1_points,
|
player1_points: result.player1_points,
|
||||||
player2_points: result.player2_points,
|
player2_points: result.player2_points,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (!result.isDraw && result.winnerId) {
|
if (!result.isDraw && result.winnerId) {
|
||||||
payload.winner_user_id = result.winnerId;
|
payload.winner_user_id = result.winnerId;
|
||||||
payload.loser_user_id = result.loserId;
|
payload.loser_user_id = result.loserId;
|
||||||
}
|
}
|
||||||
|
|
||||||
await axios.put(`${API_URL}/games/${gameId}`, payload, {
|
await axios.put(`${API_URL}/games/${gameId}`, payload, {
|
||||||
headers: { Authorization: token },
|
headers: { Authorization: token },
|
||||||
});
|
});
|
||||||
console.log(`[DB] Game ${gameId} saved.`);
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[DB Error] Game ${gameId}:`, error.message);
|
console.error(`[DB Error] Game ${gameId}:`, error.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- SHARED END GAME LOGIC ---
|
||||||
|
const performGameEnd = (io, game, gameId, winnerId, loserId, reason) => {
|
||||||
|
const result = {
|
||||||
|
action: "game_ended",
|
||||||
|
winnerId: parseInt(winnerId),
|
||||||
|
loserId: parseInt(loserId),
|
||||||
|
isDraw: false,
|
||||||
|
player1_points: game.players[Object.keys(game.players)[0]]?.points || 0,
|
||||||
|
player2_points: game.players[Object.keys(game.players)[1]]?.points || 0,
|
||||||
|
reason: reason
|
||||||
|
};
|
||||||
|
|
||||||
|
game.status = "ended";
|
||||||
|
if (game.timer) clearInterval(game.timer);
|
||||||
|
|
||||||
|
io.to(`game_${gameId}`).emit("game-over", {
|
||||||
|
winnerId: result.winnerId,
|
||||||
|
isDraw: result.isDraw,
|
||||||
|
p1Points: result.player1_points,
|
||||||
|
p2Points: result.player2_points,
|
||||||
|
message: reason === "surrender" ? "Opponent Surrendered!" : "Game Over"
|
||||||
|
});
|
||||||
|
|
||||||
|
const anyId = Object.keys(game.players)[0];
|
||||||
|
const token = game.players[anyId]?.token;
|
||||||
|
if (token) saveGameResult(gameId, result, token);
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleTimeout = (io, gameId, userId) => {
|
||||||
|
const game = getGame(gameId);
|
||||||
|
if (!game || game.status === 'ended') return;
|
||||||
|
|
||||||
|
console.log(`[Timeout] User ${userId} auto-playing lowest card.`);
|
||||||
|
|
||||||
|
const player = game.players[userId];
|
||||||
|
if (!player || !player.hand || player.hand.length === 0) return;
|
||||||
|
|
||||||
|
const trumpSuit = game.trumpCard?.suit || '';
|
||||||
|
|
||||||
|
const sortedHand = [...player.hand].sort((a, b) => {
|
||||||
|
const strengthA = getStrength(a.rank) + (a.suit === trumpSuit ? 100 : 0);
|
||||||
|
const strengthB = getStrength(b.rank) + (b.suit === trumpSuit ? 100 : 0);
|
||||||
|
return strengthA - strengthB;
|
||||||
|
});
|
||||||
|
|
||||||
|
const cardToPlay = sortedHand[0];
|
||||||
|
if (cardToPlay) {
|
||||||
|
handleGameMove(io, gameId, userId, cardToPlay.id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleGameMove = (io, gameId, userId, cardId) => {
|
||||||
|
const game = getGame(gameId);
|
||||||
|
if (!game) return;
|
||||||
|
|
||||||
|
const result = game.playCard(userId, cardId);
|
||||||
|
const roomName = `game_${gameId}`;
|
||||||
|
|
||||||
|
broadcastState(io, gameId, game);
|
||||||
|
|
||||||
|
if (result.action === "trick_resolved") {
|
||||||
|
io.to(roomName).emit("trick-end", result.trickResult);
|
||||||
|
|
||||||
|
setTimeout(() => {
|
||||||
|
if (game.status !== "ended") {
|
||||||
|
const canDraw = (game.deck && game.deck.length > 0) || game.trumpCard !== null;
|
||||||
|
|
||||||
|
if (canDraw) {
|
||||||
|
const winnerId = result.trickResult.winnerId;
|
||||||
|
const loserId = Object.keys(game.players).find(id => String(id) !== String(winnerId));
|
||||||
|
|
||||||
|
if (winnerId) drawCard(game, winnerId);
|
||||||
|
if (loserId) drawCard(game, loserId);
|
||||||
|
}
|
||||||
|
broadcastState(io, gameId, game);
|
||||||
|
}
|
||||||
|
}, 1500);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.action === "game_ended") {
|
||||||
|
performGameEnd(io, game, gameId, result.winnerId, result.loserId, "points");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.action === "next_turn" || result.action === "trick_resolved") {
|
||||||
|
game.startTurnTimer((timeoutUserId) => {
|
||||||
|
handleTimeout(io, gameId, timeoutUserId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export default (io, socket) => {
|
export default (io, socket) => {
|
||||||
socket.on("join-game", async ({ gameId }) => {
|
socket.on("join-game", async ({ gameId }) => {
|
||||||
const user = getUser(socket.id);
|
const user = getUser(socket.id);
|
||||||
@@ -37,110 +189,92 @@ export default (io, socket) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let game = getGame(gameId);
|
let game = getGame(gameId);
|
||||||
|
let gameData = null;
|
||||||
|
|
||||||
if (!game) {
|
try {
|
||||||
try {
|
|
||||||
const token = socket.handshake.auth.token;
|
const token = socket.handshake.auth.token;
|
||||||
const response = await axios.get(`${API_URL}/games/${gameId}`, {
|
const response = await axios.get(`${API_URL}/games/${gameId}`, {
|
||||||
headers: { Authorization: token },
|
headers: { Authorization: token },
|
||||||
});
|
});
|
||||||
|
gameData = response.data.data || response.data;
|
||||||
|
} catch (e) { console.error("DB Sync Failed"); }
|
||||||
|
|
||||||
const gameData = response.data.data || response.data;
|
if (!game && gameData) {
|
||||||
|
const p1Name = gameData.player1?.nickname || "Player 1";
|
||||||
if (gameData.status === "Ended") {
|
const p2Name = gameData.player2?.nickname || "Player 2";
|
||||||
socket.emit("error", { message: "Game already finished." });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (
|
|
||||||
gameData.player1_user_id != user.id &&
|
|
||||||
gameData.player2_user_id != user.id &&
|
|
||||||
gameData.player2_user_id !== 1
|
|
||||||
) {
|
|
||||||
socket.emit("error", { message: "You are not in this game." });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const p1Name = gameData.player1?.name || "Player 1";
|
|
||||||
const p2Name = gameData.player2?.name || "Player 2";
|
|
||||||
const type = gameData.type == "9" ? 9 : 3;
|
const type = gameData.type == "9" ? 9 : 3;
|
||||||
|
|
||||||
game = createGame(
|
game = createGame(
|
||||||
gameId,
|
gameId,
|
||||||
type,
|
type,
|
||||||
{ id: gameData.player1_user_id, name: p1Name },
|
{ id: gameData.player1_user_id, name: p1Name },
|
||||||
{ id: gameData.player2_user_id, name: p2Name }
|
{ id: gameData.player2_user_id, name: p2Name }
|
||||||
);
|
);
|
||||||
} catch (error) {
|
game.status = gameData.status === 'Playing' ? 'playing' : 'pending';
|
||||||
socket.emit("error", { message: "Failed to join game." });
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const GHOST_ID = 1;
|
if (!game) {
|
||||||
|
socket.emit("error", { message: "Game not found." });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (game && game.players) {
|
const myId = user.id;
|
||||||
if (!game.players[user.id]) {
|
const ghostKey = Object.keys(game.players).find(key => key == 1);
|
||||||
if (game.players[GHOST_ID]) {
|
const amIDbPlayer2 = gameData && gameData.player2_user_id == myId;
|
||||||
delete game.players[GHOST_ID];
|
|
||||||
game.players[user.id] = {
|
if (!game.players[myId] && (ghostKey || amIDbPlayer2)) {
|
||||||
id: user.id,
|
let ghostHand = [];
|
||||||
name: user.name,
|
let ghostPoints = 0;
|
||||||
hand: [],
|
let ghostTricks = 0;
|
||||||
points: 0,
|
if (ghostKey && game.players[ghostKey]) {
|
||||||
tricks: 0,
|
ghostHand = game.players[ghostKey].hand || [];
|
||||||
};
|
ghostPoints = game.players[ghostKey].points || 0;
|
||||||
|
ghostTricks = game.players[ghostKey].tricks || 0;
|
||||||
|
delete game.players[ghostKey];
|
||||||
|
}
|
||||||
|
|
||||||
|
game.players[myId] = {
|
||||||
|
id: myId,
|
||||||
|
name: user.nickname,
|
||||||
|
hand: ghostHand,
|
||||||
|
points: ghostPoints,
|
||||||
|
tricks: ghostTricks,
|
||||||
|
token: socket.handshake.auth.token,
|
||||||
|
};
|
||||||
|
game.player2 = { id: myId, name: user.nickname };
|
||||||
|
game.status = 'playing';
|
||||||
|
if(!game.timer) {
|
||||||
|
game.startTurnTimer((timeoutUserId) => handleTimeout(io, gameId, timeoutUserId));
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.join(`game_${gameId}`);
|
socket.join(`game_${gameId}`);
|
||||||
|
|
||||||
if (game && game.players[user.id]) {
|
if (game.players[myId]) {
|
||||||
socket.emit("game-state", game.getStateForPlayer(user.id));
|
game.players[myId].token = socket.handshake.auth.token;
|
||||||
console.log(`--> Estado enviado para User ${user.id}`);
|
|
||||||
} else {
|
const rawState = game.getStateForPlayer(myId);
|
||||||
socket.emit("error", { message: "Error joining game state." });
|
const cleanState = sanitizeState(rawState, game);
|
||||||
|
|
||||||
|
socket.emit("game-state", cleanState);
|
||||||
|
broadcastState(io, gameId, game);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on("play-card", ({ gameId, cardId }) => {
|
socket.on("play-card", ({ gameId, cardId }) => {
|
||||||
const user = getUser(socket.id);
|
const user = getUser(socket.id);
|
||||||
const game = getGame(gameId);
|
if (user) handleGameMove(io, gameId, user.id, cardId);
|
||||||
|
});
|
||||||
|
|
||||||
if (!game || !user) return;
|
// --- NEW: SURRENDER HANDLER ---
|
||||||
|
socket.on("surrender", ({ gameId }) => {
|
||||||
|
const user = getUser(socket.id);
|
||||||
|
const game = getGame(gameId);
|
||||||
|
|
||||||
|
if (!game || !user || !game.players[user.id]) return;
|
||||||
|
|
||||||
const result = game.playCard(user.id, cardId);
|
console.log(`[Game] User ${user.nickname} surrendered.`);
|
||||||
|
|
||||||
if (result.error) {
|
const winnerId = Object.keys(game.players).find(id => String(id) !== String(user.id));
|
||||||
socket.emit("game-error", { message: result.error });
|
performGameEnd(io, game, gameId, winnerId, user.id, "surrender");
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const roomName = `game_${gameId}`;
|
|
||||||
const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
|
|
||||||
if (socketsInRoom) {
|
|
||||||
for (const socketId of socketsInRoom) {
|
|
||||||
const s = io.sockets.sockets.get(socketId);
|
|
||||||
const u = getUser(socketId);
|
|
||||||
if (u && game.players[u.id]) {
|
|
||||||
s.emit("game-state", game.getStateForPlayer(u.id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.action === "trick_resolved") {
|
|
||||||
io.to(roomName).emit("trick-end", result.trickResult);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (result.action === "game_ended") {
|
|
||||||
io.to(roomName).emit("game-over", {
|
|
||||||
winnerId: result.winnerId,
|
|
||||||
isDraw: result.isDraw,
|
|
||||||
p1Points: result.player1_points,
|
|
||||||
p2Points: result.player2_points,
|
|
||||||
});
|
|
||||||
saveGameResult(gameId, result, socket.handshake.auth.token);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { getMatch, addMatch } from "../state/match.js";
|
||||||
|
import BiscaMatch from "../classes/BiscaMatch.js";
|
||||||
|
import axios from "axios";
|
||||||
|
|
||||||
|
const API_URL = "http://localhost:8000/api/v1";
|
||||||
|
|
||||||
|
export default (io, socket) => {
|
||||||
|
const createMatchEmitter = (matchId) => (eventName, payload) => {
|
||||||
|
io.to(`match_${matchId}`).emit(eventName, payload);
|
||||||
|
};
|
||||||
|
|
||||||
|
socket.on("match:enter", async (data) => {
|
||||||
|
const { matchId } = data;
|
||||||
|
|
||||||
|
if (!socket.user || !socket.user.id) {
|
||||||
|
return socket.emit("error", { message: "User not authenticated" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const userId = socket.user.id;
|
||||||
|
const room = `match_${matchId}`;
|
||||||
|
|
||||||
|
let match = getMatch(matchId);
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
try {
|
||||||
|
console.log(`A pedir match ${matchId} à API...`);
|
||||||
|
const res = await axios.get(`${API_URL}/matches/${matchId}`, {
|
||||||
|
headers: { Authorization: socket.token },
|
||||||
|
});
|
||||||
|
|
||||||
|
const matchData = res.data.data || res.data;
|
||||||
|
|
||||||
|
match = new BiscaMatch(
|
||||||
|
matchData,
|
||||||
|
createMatchEmitter(matchId),
|
||||||
|
socket.token
|
||||||
|
);
|
||||||
|
addMatch(match);
|
||||||
|
console.log(`Match ${matchId} carregado em memória.`);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Erro ao carregar Match da API:", e.message);
|
||||||
|
socket.emit("error", "Match not found or API error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
match.token = socket.token;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (match) {
|
||||||
|
match.token = socket.token;
|
||||||
|
}
|
||||||
|
|
||||||
|
match.emitStateCallback = createMatchEmitter(matchId);
|
||||||
|
|
||||||
|
if (userId !== match.player1Id && match.player2Id === 1) {
|
||||||
|
console.log(`User ${userId} a substituir o Ghost no Match ${matchId}`);
|
||||||
|
await match.joinPlayer(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
socket.join(room);
|
||||||
|
console.log(`Socket ${socket.id} entrou na sala ${room}`);
|
||||||
|
|
||||||
|
if (match.status === "Playing") {
|
||||||
|
socket.emit("match:update", match.getState());
|
||||||
|
} else {
|
||||||
|
socket.emit("match:waiting", { msg: "Waiting for opponent..." });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("game:play-card", (data) => {
|
||||||
|
const { matchId, cardId } = data;
|
||||||
|
const match = getMatch(matchId);
|
||||||
|
|
||||||
|
if (!match || match.status !== "Playing") {
|
||||||
|
console.log(
|
||||||
|
"Tentativa de jogar sem match ativo ou match não encontrado."
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = match.playCard(socket.user.id, cardId);
|
||||||
|
|
||||||
|
if (result && result.error) {
|
||||||
|
console.log(
|
||||||
|
`❌ [Erro Jogo] User ${socket.user.id} tentou jogar carta ${cardId} mas: ${result.error}`
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.emit("error", { message: result.error });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (match.currentGame) {
|
||||||
|
io.to(`match_${matchId}`).emit(
|
||||||
|
"game:update",
|
||||||
|
match.currentGame.getStateForPlayer(socket.user.id)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
socket.on("debug:end-game", async (data) => {
|
||||||
|
const { matchId } = data;
|
||||||
|
const match = getMatch(matchId);
|
||||||
|
if (match) {
|
||||||
|
console.log(`[DEBUG] User ${socket.user.id} a forçar fim de jogo.`);
|
||||||
|
// Simula que o user que clicou ganhou 120 pontos
|
||||||
|
const winnerId = socket.user.id;
|
||||||
|
const loserId =
|
||||||
|
winnerId == match.player1Id ? match.player2Id : match.player1Id;
|
||||||
|
|
||||||
|
// Objeto de resultado falso para fechar o jogo
|
||||||
|
const fakeResult = {
|
||||||
|
winnerId: winnerId,
|
||||||
|
loserId: loserId,
|
||||||
|
isDraw: false,
|
||||||
|
player1_points: winnerId == match.player1Id ? 120 : 0,
|
||||||
|
player2_points: winnerId == match.player2Id ? 120 : 0,
|
||||||
|
player1_id: match.player1Id,
|
||||||
|
player2_id: match.player2Id,
|
||||||
|
};
|
||||||
|
|
||||||
|
await match.handleGameEnd(fakeResult);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// DEBUG: Forçar fim do Match Completo
|
||||||
|
socket.on("debug:end-match", async (data) => {
|
||||||
|
const { matchId } = data;
|
||||||
|
const match = getMatch(matchId);
|
||||||
|
if (match) {
|
||||||
|
console.log(`[DEBUG] User ${socket.user.id} a forçar fim de MATCH.`);
|
||||||
|
// Dá 4 marcas a quem clicou
|
||||||
|
match.marks[socket.user.id] = 4;
|
||||||
|
await match.finishMatch();
|
||||||
|
|
||||||
|
// Emite o estado final
|
||||||
|
io.to(`match_${matchId}`).emit("match:ended", match.getState());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
"name": "websockets",
|
"name": "websockets",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"main": "index.js",
|
"main": "index.js",
|
||||||
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "nodemon index.js",
|
"dev": "nodemon index.js",
|
||||||
"start": "bun index.js "
|
"start": "bun index.js "
|
||||||
|
|||||||
+18
-7
@@ -3,6 +3,7 @@ import axios from "axios";
|
|||||||
import { handleConnectionEvents } from "./events/connection.js";
|
import { handleConnectionEvents } from "./events/connection.js";
|
||||||
import { addUser, removeUser } from "./state/connection.js";
|
import { addUser, removeUser } from "./state/connection.js";
|
||||||
import gameEvents from "./events/game.js";
|
import gameEvents from "./events/game.js";
|
||||||
|
import matchEvents from "./events/match.js";
|
||||||
|
|
||||||
export const server = {
|
export const server = {
|
||||||
io: null,
|
io: null,
|
||||||
@@ -18,15 +19,22 @@ export const serverStart = (port) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
server.io.use(async (socket, next) => {
|
server.io.use(async (socket, next) => {
|
||||||
const token = socket.handshake.auth.token;
|
let token = socket.handshake.auth.token;
|
||||||
|
|
||||||
if (!token) {
|
if (!token) {
|
||||||
return next(new Error("Authentication error: No token provided"));
|
return next(new Error("Authentication error: No token provided"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!token.startsWith("Bearer ")) {
|
||||||
|
token = "Bearer " + token;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await axios.get(`${API_URL}/users/me`, {
|
const response = await axios.get(`${API_URL}/users/me`, {
|
||||||
headers: { Authorization: token },
|
headers: {
|
||||||
|
Authorization: token,
|
||||||
|
Accept: "application/json"
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const user = response.data.data || response.data;
|
const user = response.data.data || response.data;
|
||||||
@@ -35,7 +43,11 @@ export const serverStart = (port) => {
|
|||||||
return next(new Error("Authentication error: User data not found"));
|
return next(new Error("Authentication error: User data not found"));
|
||||||
}
|
}
|
||||||
|
|
||||||
addUser(socket.id, user);
|
socket.user = user;
|
||||||
|
socket.token = token;
|
||||||
|
socket.handshake.auth.token = token;
|
||||||
|
|
||||||
|
addUser(socket.id, user);
|
||||||
|
|
||||||
next();
|
next();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -53,15 +65,14 @@ export const serverStart = (port) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
server.io.on("connection", (socket) => {
|
server.io.on("connection", (socket) => {
|
||||||
console.log("New connection:", socket.id);
|
|
||||||
|
|
||||||
gameEvents(server.io, socket);
|
gameEvents(server.io, socket);
|
||||||
|
|
||||||
|
matchEvents(server.io, socket);
|
||||||
|
|
||||||
handleConnectionEvents(server.io, socket);
|
handleConnectionEvents(server.io, socket);
|
||||||
|
|
||||||
socket.on("disconnect", () => {
|
socket.on("disconnect", () => {
|
||||||
removeUser(socket.id);
|
removeUser(socket.id);
|
||||||
console.log("Disconnected:", socket.id);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
@@ -14,4 +14,4 @@ export const removeUser = (socketId) => {
|
|||||||
|
|
||||||
export const getUserCount = () => {
|
export const getUserCount = () => {
|
||||||
return users.size;
|
return users.size;
|
||||||
};
|
};
|
||||||
|
|||||||
+17
-12
@@ -1,8 +1,15 @@
|
|||||||
const BiscaGame = require("../classes/BiscaGame");
|
import BiscaGame from "../classes/BiscaGame.js";
|
||||||
|
|
||||||
const activeGames = new Map();
|
const activeGames = new Map();
|
||||||
|
|
||||||
const createGame = (id, type, player1, player2) => {
|
export const createGame = (id, type, player1, player2) => {
|
||||||
|
const existingGame = activeGames.get(id);
|
||||||
|
if (existingGame) {
|
||||||
|
console.log(
|
||||||
|
`[Game State] Game ${id} already exists, returning existing instance`
|
||||||
|
);
|
||||||
|
return existingGame;
|
||||||
|
}
|
||||||
const game = new BiscaGame(id, type, player1, player2);
|
const game = new BiscaGame(id, type, player1, player2);
|
||||||
|
|
||||||
game.init();
|
game.init();
|
||||||
@@ -13,17 +20,15 @@ const createGame = (id, type, player1, player2) => {
|
|||||||
return game;
|
return game;
|
||||||
};
|
};
|
||||||
|
|
||||||
const getGame = (id) => {
|
export const getGame = (id) => {
|
||||||
return activeGames.get(id);
|
return activeGames.get(id);
|
||||||
};
|
};
|
||||||
|
|
||||||
const removeGame = (id) => {
|
export const removeGame = (id) => {
|
||||||
activeGames.delete(id);
|
const game = activeGames.get(id);
|
||||||
console.log(`[Game State] Game removed: ${id}`);
|
if (game) {
|
||||||
};
|
game.stopTimer();
|
||||||
|
activeGames.delete(id);
|
||||||
module.exports = {
|
console.log(`[Game State] Game removed: ${id}`);
|
||||||
createGame,
|
}
|
||||||
getGame,
|
|
||||||
removeGame,
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
const matches = new Map();
|
||||||
|
|
||||||
|
export const addMatch = (match) => {
|
||||||
|
matches.set(parseInt(match.id), match);
|
||||||
|
return match;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getMatch = (id) => {
|
||||||
|
return matches.get(parseInt(id));
|
||||||
|
};
|
||||||
|
|
||||||
|
export const removeMatch = (id) => {
|
||||||
|
matches.delete(parseInt(id));
|
||||||
|
};
|
||||||
|
|
||||||
|
export { matches };
|
||||||
Reference in New Issue
Block a user