SyntaxSquad/DADProject#16 merge: fix merge conflics
This commit is contained in:
@@ -17,6 +17,7 @@ class GameController extends Controller
|
||||
$user = Auth::user();
|
||||
$query = Game::query()->with(["winner", "player1", "player2"]);
|
||||
|
||||
// Se não for Admin, mostra apenas os jogos do utilizador
|
||||
if ($user->type !== 'A') {
|
||||
$query->where(function ($q) use ($user) {
|
||||
$q->where('player1_user_id', $user->id)
|
||||
@@ -40,75 +41,154 @@ class GameController extends Controller
|
||||
$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);
|
||||
}else{
|
||||
} else {
|
||||
$query->orderBy("began_at", "desc");
|
||||
}
|
||||
|
||||
return response()->json($query->paginate(15));
|
||||
}
|
||||
|
||||
// --- MÉTODOS ADICIONADOS ---
|
||||
|
||||
// Host a new multiplayer Game
|
||||
public function host(Request $request)
|
||||
{
|
||||
$request->validate([
|
||||
'type' => 'required|in:3,9'
|
||||
]);
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
// Check for active game
|
||||
$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);
|
||||
}
|
||||
|
||||
$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);
|
||||
$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);
|
||||
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([
|
||||
"type" => $validated["type"],
|
||||
"status" => "Pending",
|
||||
"status" => $initialStatus,
|
||||
"player1_user_id" => $user->id,
|
||||
"player2_user_id" => self::GHOST_ID,
|
||||
"winner_user_id" => self::GHOST_ID,
|
||||
"loser_user_id" => self::GHOST_ID,
|
||||
"began_at" => now(),
|
||||
"player2_user_id" => $player2Id,
|
||||
"winner_user_id" => null,
|
||||
"loser_user_id" => null,
|
||||
"match_id" => $request->input('match_id', null),
|
||||
"began_at" => $request->input('began_at', now()),
|
||||
"player1_points" => 0,
|
||||
"player2_points" => 0,
|
||||
"custom" => null,
|
||||
]);
|
||||
|
||||
return response()->json([
|
||||
"message" => "Multiplayer game room created",
|
||||
"message" => "Game created",
|
||||
"game" => $game,
|
||||
], 201);
|
||||
}
|
||||
|
||||
public function join(Request $request, Game $game)
|
||||
{
|
||||
// Prevent joining if already full or started
|
||||
if ($game->status !== 'Pending' || $game->player2_user_id !== 1) {
|
||||
return response()->json(['message' => 'Game is not available'], 400);
|
||||
public function join(Request $request, Game $game)
|
||||
{
|
||||
// Prevent joining if already full or started
|
||||
if ($game->status !== 'Pending' || $game->player2_user_id !== self::GHOST_ID) {
|
||||
return response()->json(['message' => 'Game is not available'], 400);
|
||||
}
|
||||
|
||||
// Prevent joining your own game
|
||||
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([
|
||||
'player2_user_id' => $request->user()->id,
|
||||
'status' => 'Playing',
|
||||
]);
|
||||
|
||||
return response()->json($game);
|
||||
}
|
||||
|
||||
// Prevent joining your own game
|
||||
if ($game->player1_user_id === $request->user()->id) {
|
||||
return response()->json(['message' => 'Cannot join your own game'], 400);
|
||||
}
|
||||
|
||||
$game->update([
|
||||
'player2_user_id' => $request->user()->id,
|
||||
'status' => 'Playing',
|
||||
]);
|
||||
|
||||
return response()->json($game);
|
||||
}
|
||||
|
||||
public function show(Game $game)
|
||||
{
|
||||
$this->authorize('view', $game);
|
||||
@@ -164,4 +244,4 @@ public function join(Request $request, Game $game)
|
||||
'game' => $game->fresh(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,10 @@
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\MatchGame;
|
||||
use App\Models\Game;
|
||||
use App\Models\CoinTransaction;
|
||||
use App\Models\CoinTransactionType;
|
||||
use Illuminate\Http\Request;
|
||||
use App\Http\Requests\StoreMatchRequest;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class MatchController extends Controller
|
||||
@@ -196,4 +194,77 @@ class MatchController extends Controller
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ namespace App\Http\Controllers;
|
||||
|
||||
use App\Models\Game;
|
||||
use App\Models\User;
|
||||
use App\Models\MatchGame;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
@@ -178,72 +179,87 @@ class UserController extends Controller
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/users/{user}/matches
|
||||
* Histórico de Jogos Multiplayer do Utilizador
|
||||
* GET /api/users/{user}/games
|
||||
* Histórico de Partidas Individuais (Cartas)
|
||||
*/
|
||||
public function getMatches(Request $request, User $user)
|
||||
public function getGames(Request $request, User $user)
|
||||
{
|
||||
$this->authorize('view', $user);
|
||||
|
||||
$outcomeSql = "CASE
|
||||
WHEN is_draw = 1 THEN 'DRAW'
|
||||
WHEN winner_user_id = {$user->id} THEN 'WIN'
|
||||
ELSE 'LOSS'
|
||||
END";
|
||||
|
||||
$query = Game::query()
|
||||
->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']);
|
||||
// Define a query base para GAMES
|
||||
$query = \App\Models\Game::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);
|
||||
$query->where('type', $request->type);
|
||||
}
|
||||
|
||||
if ($request->has('status')) {
|
||||
$query->where('status', $request->status);
|
||||
}
|
||||
|
||||
if ($request->filled('outcome')) {
|
||||
switch ($request->outcome) {
|
||||
case 'win':
|
||||
$query->where('winner_user_id', $user->id)
|
||||
->where('is_draw', 0);
|
||||
break;
|
||||
case 'loss':
|
||||
case 'forfeit': // Forfeit treated as loss for now
|
||||
$query->where('loser_user_id', $user->id)
|
||||
->where('is_draw', 0);
|
||||
break;
|
||||
case 'draw':
|
||||
$query->where('is_draw', 1);
|
||||
break;
|
||||
}
|
||||
$sortDirection = $request->get('sort_direction', 'desc');
|
||||
$query->orderBy('began_at', $sortDirection);
|
||||
|
||||
|
||||
$games = $query->paginate(10);
|
||||
|
||||
$games->getCollection()->transform(function ($game) use ($user) {
|
||||
if ($game->winner_user_id == $user->id) {
|
||||
$game->outcome = 'win';
|
||||
} elseif ($game->is_draw) {
|
||||
$game->outcome = 'draw';
|
||||
} else {
|
||||
$game->outcome = 'loss';
|
||||
}
|
||||
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')) {
|
||||
$query->whereDate('ended_at', '<=', $request->date_to);
|
||||
}
|
||||
$sortDirection = $request->get('sort_direction', 'desc');
|
||||
$query->orderBy('began_at', $sortDirection);
|
||||
|
||||
$order = $request->get('sort_by', 'began_at');
|
||||
$direction = $request->get('sort_direction', 'desc');
|
||||
$matches = $query->paginate(10);
|
||||
|
||||
if ($order === 'outcome') {
|
||||
$query->orderBy('outcome_text', $direction);
|
||||
} else {
|
||||
$query->orderBy($order, $direction);
|
||||
}
|
||||
|
||||
$matches = $query->orderBy($order, $direction)
|
||||
->paginate(10);
|
||||
$matches->getCollection()->transform(function ($match) use ($user) {
|
||||
if ($match->winner_user_id == $user->id) {
|
||||
$match->outcome = 'win';
|
||||
} elseif ($match->winner_user_id && $match->winner_user_id != $user->id) {
|
||||
$match->outcome = 'loss';
|
||||
} else {
|
||||
$match->outcome = 'interrupted'; // Matches geralmente não empatam (alguém chega a 4 marcas)
|
||||
}
|
||||
return $match;
|
||||
});
|
||||
|
||||
return response()->json($matches);
|
||||
}
|
||||
|
||||
@@ -86,7 +86,6 @@ class GamePolicy
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can update the model.
|
||||
*/
|
||||
@@ -96,17 +95,16 @@ class GamePolicy
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
$game->status !== "Playing" ||
|
||||
($game->player1_user_id !== $user->id &&
|
||||
$game->player2_user_id !== $user->id)
|
||||
) {
|
||||
if (!in_array($game->status, ['Playing', 'Pending'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($game->player1_user_id !== $user->id && $game->player2_user_id !== $user->id) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether the user can delete the model.
|
||||
*/
|
||||
|
||||
+8
-35
@@ -40,45 +40,14 @@ Route::prefix('v1')->group(function () {
|
||||
// User Resources
|
||||
Route::prefix('/users')->group(function () {
|
||||
Route::get('/{user}', [UserController::class, 'show']);
|
||||
Route::get('/{user}/matches', [
|
||||
UserController::class,
|
||||
'getMatches',
|
||||
]);
|
||||
Route::get('/{user}/transactions', [UserController::class, 'getTransactions']);
|
||||
Route::get('/{user}/games', [UserController::class, 'getGames']);
|
||||
Route::get('/{user}/matches', [UserController::class, 'getMatches']);
|
||||
});
|
||||
|
||||
Route::prefix('games')->group(function () {
|
||||
//Host a new multiplayer game - MUST come before resource routes
|
||||
Route::post('host', function (\Illuminate\Http\Request $request) {
|
||||
$request->validate([
|
||||
'type' => 'required|in:3,9'
|
||||
]);
|
||||
|
||||
$game = \App\Models\Game::create([
|
||||
'type' => $request->type,
|
||||
'status' => 'Pending',
|
||||
'player1_user_id' => $request->user()->id,
|
||||
'player2_user_id' => 1, // Ghost player
|
||||
'began_at' => now(),
|
||||
]);
|
||||
|
||||
return response()->json($game);
|
||||
});
|
||||
|
||||
// List open games (available to join)
|
||||
Route::get('open', function (\Illuminate\Http\Request $request) {
|
||||
$type = $request->query('type', '9');
|
||||
|
||||
$games = \App\Models\Game::where('status', 'Pending')
|
||||
->where('player2_user_id', 1) // Only games waiting for a second player
|
||||
->where('type', $type)
|
||||
->with('player1') // Load player1 relationship
|
||||
->orderBy('began_at', 'asc')
|
||||
->paginate(10);
|
||||
|
||||
return response()->json($games);
|
||||
});
|
||||
|
||||
Route::post('host', [GameController::class, 'host']);
|
||||
Route::get('open', [GameController::class, 'open']);
|
||||
Route::get('/', [GameController::class, 'index']);
|
||||
Route::get('/{game}', [GameController::class, 'show']);
|
||||
Route::post('/', [GameController::class, 'store']);
|
||||
@@ -91,6 +60,8 @@ Route::prefix('v1')->group(function () {
|
||||
Route::prefix('matches')->group(function () {
|
||||
Route::apiResource('/', MatchController::class)->parameters(['' => 'match']);
|
||||
Route::post('/{match}/join', [MatchController::class, 'join']);
|
||||
Route::post('host', [MatchController::class, 'host']); // <--- NOVA
|
||||
Route::get('open', [MatchController::class, 'open']);
|
||||
});
|
||||
|
||||
// Admin Routes
|
||||
@@ -99,6 +70,8 @@ Route::prefix('v1')->group(function () {
|
||||
->group(function () {
|
||||
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::get('/', [UserController::class, 'index']);
|
||||
Route::post('/', [UserController::class, 'store']);
|
||||
|
||||
+1042
-645
File diff suppressed because it is too large
Load Diff
@@ -23,6 +23,11 @@ const gObserverTarget = ref(null);
|
||||
const gObserver = ref(null);
|
||||
const gLoading = ref(false);
|
||||
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 showJoinModal = ref(false)
|
||||
const selectedGame = ref(null)
|
||||
@@ -38,6 +43,21 @@ const lbObserverTarget = ref(null)
|
||||
const lbObserver = ref(null)
|
||||
const lbMorePages = ref(true)
|
||||
const publicStats = ref(null)
|
||||
const isLoggedIn = useAuthStore().isLoggedIn
|
||||
|
||||
const setupMatchesObserver = () => {
|
||||
if (mObserver.value) mObserver.value.disconnect();
|
||||
|
||||
mObserver.value = new IntersectionObserver((entries) => {
|
||||
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();
|
||||
@@ -67,14 +87,30 @@ const getPendingGames = async (mode = selectedMode.value) => {
|
||||
|
||||
const newGames = response.data.data;
|
||||
openGames.value = [...openGames.value, ...newGames];
|
||||
gPage.value++;
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch games:', error);
|
||||
} finally {
|
||||
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()
|
||||
@@ -145,81 +181,77 @@ const setupLeaderboardObserver = () => {
|
||||
|
||||
const clickMode = async (mode) => {
|
||||
if (selectedMode.value === mode) return;
|
||||
openGames.value = [];
|
||||
selectedMode.value = mode;
|
||||
openGames.value = [];
|
||||
gPage.value = 1;
|
||||
await getPendingGames();
|
||||
openMatches.value = [];
|
||||
mPage.value = 1;
|
||||
await Promise.all([getPendingGames(), getPendingMatches()]);
|
||||
setupGamesObserver();
|
||||
setupMatchesObserver();
|
||||
}
|
||||
|
||||
const startSingle = () => {
|
||||
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 = () => {
|
||||
isReady.value = !isReady.value
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchPublicStats();
|
||||
await getPendingGames();
|
||||
await nextTick();
|
||||
setupGamesObserver();
|
||||
if (isLoggedIn) {
|
||||
await Promise.all([getPendingGames(), getPendingMatches()]);
|
||||
await nextTick();
|
||||
setupGamesObserver();
|
||||
setupMatchesObserver();
|
||||
}
|
||||
})
|
||||
|
||||
const hostGame = async () => {
|
||||
showHostModal.value = true
|
||||
showHostModal.value = true
|
||||
|
||||
try {
|
||||
const response = await axios.post(`${API_BASE_URL}/games/host`, {
|
||||
type: selectedMode.value
|
||||
})
|
||||
try {
|
||||
const response = await axios.post(`${API_BASE_URL}/games/host`, {
|
||||
type: selectedMode.value
|
||||
})
|
||||
|
||||
const gameId = response.data.id
|
||||
const gameId = response.data.id
|
||||
|
||||
console.log('Game hosted:', gameId)
|
||||
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))
|
||||
}
|
||||
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
|
||||
selectedGame.value = game
|
||||
|
||||
try {
|
||||
await axios.post(`${API_BASE_URL}/games/${game.id}/join`)
|
||||
try {
|
||||
await axios.post(`${API_BASE_URL}/games/${game.id}/join`)
|
||||
|
||||
console.log('Joined game:', game.id)
|
||||
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))
|
||||
}
|
||||
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>
|
||||
@@ -227,7 +259,7 @@ const joinGame = async (game) => {
|
||||
<template>
|
||||
<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">
|
||||
@@ -293,50 +325,95 @@ const joinGame = async (game) => {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card class="w-full max-w-2xl">
|
||||
<Card class="w-full max-w-2xl flex flex-col">
|
||||
<CardHeader>
|
||||
<CardTitle class="text-3xl font-bold text-center">
|
||||
Multi Player
|
||||
</CardTitle>
|
||||
<CardDescription class="text-center">
|
||||
Go one on one with another player!
|
||||
</CardDescription>
|
||||
<CardTitle class="text-3xl font-bold text-center">Multi Player</CardTitle>
|
||||
<CardDescription class="text-center">Go one on one with another player!</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-6">
|
||||
<label class="text-sm font-medium">Open games (oldest first)</label>
|
||||
<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!
|
||||
|
||||
<CardContent class="flex-1 flex flex-col space-y-6">
|
||||
<div class="flex flex-col flex-1">
|
||||
<div class="flex justify-between items-end mb-2">
|
||||
<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 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 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">Started: {{ game.began_at }}</div>
|
||||
<div class="text-xs text-muted-foreground">host: {{
|
||||
game.player1?.nickname || 'Anonymous' }}</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 macthes yet. Try hosting one!
|
||||
</div>
|
||||
<div v-else class="max-h-[350px] overflow-y-auto custom-scrollbar p-1">
|
||||
<div v-for="(match, index) in openMatches" :key="match.id"
|
||||
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-red-100 text-red-700">
|
||||
{{ 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 ref="gObserverTarget" class="h-10 flex items-center justify-center">
|
||||
<span v-if="gLoading" class="text-xs text-purple-500 animate-pulse">Loading
|
||||
more...</span>
|
||||
<div ref="mObserverTarget" class="h-10 flex items-center justify-center">
|
||||
<span v-if="mLoading" class="text-xs text-purple-500 animate-pulse">Loading
|
||||
matches...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-center">
|
||||
<Button @click="hostGame()" size="lg" variant="secondary"
|
||||
class="hover:bg-purple-500 hover:text-slate-200">
|
||||
Host Game
|
||||
</Button>
|
||||
|
||||
<div class="flex flex-col flex-1">
|
||||
<div class="flex justify-between items-end mb-2">
|
||||
<label class="text-sm font-medium uppercase tracking-wider text-muted-foreground">Open
|
||||
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>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -76,6 +76,23 @@ export const useAPIStore = defineStore('api', () => {
|
||||
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 queryParams = new URLSearchParams({
|
||||
page: params.page || 1,
|
||||
@@ -157,19 +174,34 @@ export const useAPIStore = defineStore('api', () => {
|
||||
...(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 {
|
||||
postLogin,
|
||||
postLogout,
|
||||
getAuthUser,
|
||||
getGames,
|
||||
getCurrentUserGames,
|
||||
getCurrentUserMatches,
|
||||
getCurrentUserTransactions,
|
||||
getCurrentUserStats,
|
||||
@@ -182,6 +214,7 @@ export const useAPIStore = defineStore('api', () => {
|
||||
deleteUser,
|
||||
getAdminTransactions,
|
||||
getAdminGames,
|
||||
getAdminMatches,
|
||||
postAdmin,
|
||||
gameQueryParameters,
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
class BiscaGame {
|
||||
constructor(id, type, player1, player2) {
|
||||
constructor(id, type, player1, player2, dbId = null, onGameEnd = null) {
|
||||
this.id = id;
|
||||
this.dbId = dbId;
|
||||
this.type = type;
|
||||
this.onGameEnd = onGameEnd;
|
||||
|
||||
this.deck = [];
|
||||
this.trumpCard = null;
|
||||
@@ -17,7 +19,7 @@ class BiscaGame {
|
||||
};
|
||||
|
||||
this.currentTurn = null;
|
||||
this.status = 'pending';
|
||||
this.status = "pending";
|
||||
this.startTime = null;
|
||||
|
||||
this.players = {
|
||||
@@ -50,7 +52,7 @@ class BiscaGame {
|
||||
this.currentTurn = playerIds.find((id) => id != 1) || playerIds[0];
|
||||
|
||||
this.startTime = Date.now();
|
||||
this.status = 'playing';
|
||||
this.status = "playing";
|
||||
}
|
||||
|
||||
startTurnTimer(callback) {
|
||||
@@ -75,7 +77,7 @@ class BiscaGame {
|
||||
|
||||
handleTimeout() {
|
||||
console.log(
|
||||
`[Game ${this.id}] Timeout! Auto-playing for ${this.currentTurn}`,
|
||||
`[Game ${this.id}] Timeout! Auto-playing for ${this.currentTurn}`
|
||||
);
|
||||
|
||||
const lowestCard = this.getLowestCard(this.currentTurn);
|
||||
@@ -94,7 +96,7 @@ class BiscaGame {
|
||||
}
|
||||
|
||||
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];
|
||||
let deck = [];
|
||||
|
||||
@@ -130,7 +132,7 @@ class BiscaGame {
|
||||
}
|
||||
|
||||
playCard(userId, cardId) {
|
||||
if (this.currentTurn != userId) return { error: 'Not your turn!' };
|
||||
if (this.currentTurn != userId) return { error: "Not your turn!" };
|
||||
|
||||
const player = this.players[userId];
|
||||
const cardIndex = player.hand.findIndex((c) => c.id === cardId);
|
||||
@@ -144,7 +146,7 @@ class BiscaGame {
|
||||
const suitToFollow = this.table.playerCard.suit;
|
||||
const hasSuit = player.hand.some((c) => c.suit === suitToFollow);
|
||||
if (hasSuit && card.suit !== suitToFollow) {
|
||||
return { error: 'You must follow the suit!' };
|
||||
return { error: "You must follow the suit!" };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -156,7 +158,7 @@ class BiscaGame {
|
||||
this.table.playerCard = card;
|
||||
this.table.firstPlayerId = userId;
|
||||
this.currentTurn = this.getOpponentId(userId);
|
||||
return { action: 'next_turn' };
|
||||
return { action: "next_turn" };
|
||||
} else {
|
||||
this.table.opponentCard = card;
|
||||
return this.resolveTrick();
|
||||
@@ -196,7 +198,7 @@ class BiscaGame {
|
||||
this.table = { playerCard: null, opponentCard: null, firstPlayerId: null };
|
||||
|
||||
if (this.players[winnerId].hand.length === 0) {
|
||||
this.status = 'finished';
|
||||
this.status = "finished";
|
||||
this.stopTimer();
|
||||
|
||||
const pIds = Object.keys(this.players);
|
||||
@@ -216,11 +218,11 @@ class BiscaGame {
|
||||
const finalLoser = isDraw
|
||||
? null
|
||||
: gameWinnerId == p1Obj.id
|
||||
? p2Obj.id
|
||||
: p1Obj.id;
|
||||
? p2Obj.id
|
||||
: p1Obj.id;
|
||||
|
||||
return {
|
||||
action: 'game_ended',
|
||||
action: "game_ended",
|
||||
trickResult,
|
||||
winnerId: finalWinner,
|
||||
loserId: finalLoser,
|
||||
@@ -231,15 +233,20 @@ class BiscaGame {
|
||||
player2_points: p2Obj.points,
|
||||
totalTime: totalTime,
|
||||
};
|
||||
if (this.onGameEnd) {
|
||||
this.onGameEnd(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
return { action: 'trick_resolved', trickResult };
|
||||
return { action: "trick_resolved", trickResult };
|
||||
}
|
||||
|
||||
getStateForPlayer(userId) {
|
||||
const oppId = this.getOpponentId(userId);
|
||||
return {
|
||||
id: this.id,
|
||||
dbId: this.dbId,
|
||||
trumpCard: this.trumpCard,
|
||||
trumpSuit: this.trumpSuit,
|
||||
deckCount: this.deck.length + (this.trumpCard ? 1 : 0),
|
||||
|
||||
@@ -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,6 +1,5 @@
|
||||
import { addUser, removeUser } from "../state/connection.js";
|
||||
|
||||
|
||||
const HEARTBEAT_INTERVAL = 30000; // 30 seconds
|
||||
const HEARTBEAT_TIMEOUT = 10000; // 10 seconds
|
||||
|
||||
@@ -9,36 +8,36 @@ export const handleConnectionEvents = (io, socket) => {
|
||||
let heartbeatTimeout;
|
||||
const startHeartbeat = () => {
|
||||
heartbeatInterval = setInterval(() => {
|
||||
socket.emit('heartbeat');
|
||||
socket.emit("heartbeat");
|
||||
|
||||
heartbeatTimeout = setTimeout(() => {
|
||||
console.log(
|
||||
`[Heartbeat] No response from ${socket.id}, disconnecting...`,
|
||||
`[Heartbeat] No response from ${socket.id}, disconnecting...`
|
||||
);
|
||||
socket.disconnect(true);
|
||||
}, HEARTBEAT_TIMEOUT);
|
||||
}, HEARTBEAT_INTERVAL);
|
||||
};
|
||||
|
||||
socket.on('heartbeat_ack', () => {
|
||||
socket.on("heartbeat_ack", () => {
|
||||
clearTimeout(heartbeatTimeout);
|
||||
console.log(`[Heartbeat] Received pong from ${socket.id}`);
|
||||
});
|
||||
|
||||
socket.on('join', (user) => {
|
||||
socket.on("join", (user) => {
|
||||
addUser(socket, user);
|
||||
console.log(`[Connection] User ${user.name} has joined the server`);
|
||||
});
|
||||
|
||||
socket.on('leave', () => {
|
||||
socket.on("leave", () => {
|
||||
const user = removeUser(socket.id);
|
||||
if (user) {
|
||||
console.log(`[Connection] User ${user.name} has left the server`);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('Connection Lost:', socket.id);
|
||||
socket.on("disconnect", () => {
|
||||
console.log("Connection Lost:", socket.id);
|
||||
removeUser(socket.id);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -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());
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -3,6 +3,7 @@ import axios from "axios";
|
||||
import { handleConnectionEvents } from "./events/connection.js";
|
||||
import { addUser, removeUser } from "./state/connection.js";
|
||||
import gameEvents from "./events/game.js";
|
||||
import matchEvents from "./events/match.js";
|
||||
|
||||
export const server = {
|
||||
io: null,
|
||||
@@ -46,6 +47,7 @@ export const serverStart = (port) => {
|
||||
}
|
||||
|
||||
socket.user = user;
|
||||
socket.token = token;
|
||||
socket.handshake.auth.token = token;
|
||||
|
||||
if (disconnectTimers.has(user.id)) {
|
||||
@@ -75,7 +77,9 @@ export const serverStart = (port) => {
|
||||
gameEvents(server.io, socket);
|
||||
console.log(`[Connection] User ${userId} connected. Socket ID: ${socket.id}`);
|
||||
|
||||
handleConnectionEvents(socket);
|
||||
matchEvents(server.io, socket);
|
||||
|
||||
handleConnectionEvents(server.io, socket);
|
||||
|
||||
socket.on("disconnect", () => {
|
||||
// Remove from active socket list
|
||||
|
||||
+24
-23
@@ -1,36 +1,37 @@
|
||||
import BiscaGame from '../classes/BiscaGame.js';
|
||||
import BiscaGame from "../classes/BiscaGame.js";
|
||||
|
||||
const activeGames = new Map();
|
||||
|
||||
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);
|
||||
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);
|
||||
|
||||
game.init();
|
||||
game.init();
|
||||
|
||||
activeGames.set(id, game);
|
||||
activeGames.set(id, game);
|
||||
|
||||
console.log(`[Game State] Game created: ${id} (Type: ${type})`);
|
||||
return game;
|
||||
console.log(`[Game State] Game created: ${id} (Type: ${type})`);
|
||||
return game;
|
||||
};
|
||||
|
||||
const getGame = (id) => {
|
||||
return activeGames.get(id);
|
||||
export const getGame = (id) => {
|
||||
return activeGames.get(id);
|
||||
};
|
||||
|
||||
const removeGame = (id) => {
|
||||
const game = activeGames.get(id);
|
||||
if (game) {
|
||||
game.stopTimer();
|
||||
activeGames.delete(id);
|
||||
console.log(`[Game State] Game removed: ${id}`);
|
||||
}
|
||||
export const removeGame = (id) => {
|
||||
const game = activeGames.get(id);
|
||||
if (game) {
|
||||
game.stopTimer();
|
||||
activeGames.delete(id);
|
||||
console.log(`[Game State] Game removed: ${id}`);
|
||||
}
|
||||
};
|
||||
|
||||
export { 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