Compare commits

...
Author SHA1 Message Date
FernandoJVideira 3a7b1b9794 fix:websocket errors & polict change 2026-01-02 14:26:54 +00:00
AfonsoCMSousa ef277a3cfd Merge pull request 'Issues Websockets #48 #49 #51 e #54' (#91) from feature/websockets-game-continue into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/91
Reviewed-by: FernandoJVideira <[email protected]>
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
2026-01-02 13:33:21 +00:00
KZix e23ca3d1ff Issues Websockets #48 #49 #51 e #54 2026-01-02 13:24:20 +00:00
FernandoJVideira bcdf542606 Merge pull request 'Created statistics personal and general' (#90) from feature/statistics into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/90
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2026-01-01 12:34:40 +00:00
Edd 16f8d3bdfc Created statistics personal and general 2025-12-31 23:57:54 +00:00
AfonsoCMSousa 45d8aa0035 Merge pull request 'Implemented coin purchase-flow' (#89) from feature/coin-purchase into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/89
Reviewed-by: FernandoJVideira <[email protected]>
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
2025-12-31 22:41:09 +00:00
Edd c0af76abd3 Implemented coin purchase-flow 2025-12-31 18:28:29 +00:00
FernandoJVideira ff16a57a97 Merge pull request 'Bugfix: Added api logic with transactions when match is finished, started and joined' (#88) from bugfix/matches-transactions into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/88
Reviewed-by: Edd <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2025-12-31 15:54:20 +00:00
KZix cf238d5451 Added api logic with transactions when match is finished, started and joined 2025-12-31 15:48:24 +00:00
Edd 50ae1b7f1f Merge pull request 'Added endpoint to create tranasactions' (#87) from feature/api-coinpurchase into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/87
Reviewed-by: Edd <[email protected]>
Reviewed-by: FernandoJVideira <[email protected]>
2025-12-31 11:07:11 +00:00
KZix 5975208877 Added endpoint to create tranasactions 2025-12-31 01:13:27 +00:00
KZix f3e8ffc400 Merge pull request 'matches and transactions history fully operational' (#86) from na/fix-histories into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/86
Reviewed-by: Afonso Clerigo Mendes de Sousa <[email protected]>
Reviewed-by: KZix <[email protected]>
2025-12-31 00:31:59 +00:00
22 changed files with 937 additions and 151 deletions
@@ -0,0 +1,76 @@
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Models\CoinPurchase;
use App\Models\CoinTransaction;
use App\Models\CoinTransactionType;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class CoinPurchaseController extends Controller
{
public function store(Request $request)
{
$validated = $request->validate([
'euros' => 'required|numeric|min:1|max:100',
'payment_type' => 'required|in:MBWAY,MB,VISA,PAYPAL',
'payment_reference' => [
'required',
function ($attribute, $value, $fail) use ($request) {
$type = $request->payment_type;
$regex = null;
switch ($type) {
case 'MBWAY': $regex = '/^9[0-9]{8}$/'; break;
case 'MB': $regex = '/^[0-9]{5}-[0-9]{9}$/'; break;
case 'VISA': $regex = '/^4[0-9]{15}$/'; break;
case 'PAYPAL':
if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
$fail("Invalid PayPal email.");
}
return;
}
if ($regex && !preg_match($regex, $value)) {
$fail("Invalid format for $type.");
}
},
],
]);
$user = $request->user();
$coinsAmount = $validated['euros'] * 10;
return DB::transaction(function () use ($user, $validated, $coinsAmount) {
$type = CoinTransactionType::firstOrCreate(['name' => 'Coin purchase'], ['type' => 'C']);
$transaction = CoinTransaction::create([
'user_id' => $user->id,
'coin_transaction_type_id' => $type->id,
'transaction_datetime' => now(),
'coins' => $coinsAmount,
]);
$purchase = CoinPurchase::create([
'purchase_datetime' => now(),
'user_id' => $user->id,
'coin_transaction_id' => $transaction->id,
'euros' => $validated['euros'],
'payment_type' => $validated['payment_type'],
'payment_reference' => $validated['payment_reference'],
]);
$user->increment('coins_balance', $coinsAmount);
return response()->json([
'message' => 'Purchase successful',
'balance' => $user->coins_balance,
'transaction_id' => $transaction->id,
'purchase' => $purchase,
], 201);
});
}
}
@@ -4,9 +4,7 @@ namespace App\Http\Controllers;
use App\Models\Game; use App\Models\Game;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use App\Http\Requests\StoreGameRequest;
use Illuminate\Support\Facades\Auth; use Illuminate\Support\Facades\Auth;
use App\Models\MatchGame;
class GameController extends Controller class GameController extends Controller
{ {
+110 -45
View File
@@ -4,12 +4,15 @@ namespace App\Http\Controllers;
use App\Models\MatchGame; use App\Models\MatchGame;
use App\Models\Game; use App\Models\Game;
use App\Models\CoinTransaction;
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\Auth;
use Illuminate\Support\Facades\DB;
class MatchController extends Controller class MatchController extends Controller
{ {
public function index(Request $request) public function index(Request $request)
{ {
$query = MatchGame::query()->with(['winner', 'player1', 'player2']); $query = MatchGame::query()->with(['winner', 'player1', 'player2']);
@@ -28,44 +31,61 @@ class MatchController extends Controller
} }
public function store(StoreMatchRequest $request) public function store(StoreMatchRequest $request)
{ {
$validated = $request->validated(); $validated = $request->validated();
$user = Auth::user(); $user = $request->user();
$stake = $validated['stake'];
if ($user->coins_balance < $stake) {
return response()->json(['message' => 'Insufficient coin balance'], 400);
}
$activeMatch = MatchGame::where(function ($q) use ($user) { $activeMatch = MatchGame::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'])->exists(); })->whereIn('status', ['Pending', 'Playing'])->exists();
$activeGame = Game::where(function ($q) use ($user) { if ($activeMatch) {
$q->where('player1_user_id', $user->id) return response()->json(['message' => 'You already have an active match.'], 400);
->orWhere('player2_user_id', $user->id);
})->whereIn('status', ['Pending', 'Playing'])->exists();
if ($activeMatch || $activeGame) {
return response()->json(['message' => 'You already have an active game or match.'], 400);
} }
$match = MatchGame::create([ return DB::transaction(function () use ($validated, $user, $stake) {
'type' => $validated['type'], $GHOST_ID = 1;
'status' => 'Pending',
'player1_user_id' => $user->id,
'player2_user_id' => $user->id,
'winner_user_id' => $user->id,
'loser_user_id' => $user->id,
'stake' => $validated['stake'],
'began_at' => now(),
'player1_marks' => 0,
'player2_marks' => 0,
'player1_points' => 0,
'player2_points' => 0,
'custom' => null
]);
return response()->json([ $user->decrement('coins_balance', $stake);
'message' => 'Match created successfully',
'match' => $match $stakeType = CoinTransactionType::firstOrCreate(
], 201); ['name' => 'Match stake'],
['type' => 'D'] // Debit
);
$match = MatchGame::create([
'type' => $validated['type'],
'status' => 'Pending',
'player1_user_id' => $user->id,
'player2_user_id' => $GHOST_ID,
'winner_user_id' => $GHOST_ID,
'loser_user_id' => $GHOST_ID,
'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([
'message' => 'Match created successfully',
'match' => $match,
'balance' => $user->coins_balance
], 201);
});
} }
public function show(MatchGame $match) public function show(MatchGame $match)
@@ -76,16 +96,19 @@ class MatchController extends Controller
public function join(MatchGame $match) public function join(MatchGame $match)
{ {
$user = Auth::user(); $user = request()->user();
if ($match->player1_user_id == $user->id) { if ($match->player1_user_id == $user->id) {
return response()->json(['message' => 'Waiting for opponent...', 'match' => $match]); return response()->json(['message' => 'You cannot join your own match'], 400);
} }
if ($match->status !== 'Pending') { if ($match->status !== 'Pending') {
return response()->json(['message' => 'Match is full or started'], 400); return response()->json(['message' => 'Match is full or started'], 400);
} }
if ($user->coins_balance < $match->stake) {
return response()->json(['message' => 'Insufficient coin balance to join this match'], 400);
}
$activeMatch = MatchGame::where(function ($q) use ($user) { $activeMatch = MatchGame::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);
@@ -95,15 +118,33 @@ class MatchController extends Controller
return response()->json(['message' => 'You are already in another active match.'], 400); return response()->json(['message' => 'You are already in another active match.'], 400);
} }
$match->update([ return DB::transaction(function () use ($match, $user) {
'status' => 'Playing', $user->decrement('coins_balance', $match->stake);
'player2_user_id' => $user->id
]);
return response()->json([ $stakeType = CoinTransactionType::firstOrCreate(
'message' => 'Joined match successfully!', ['name' => 'Match stake'],
'match' => $match ['type' => 'D']
]); );
CoinTransaction::create([
'user_id' => $user->id,
'match_id' => $match->id,
'coin_transaction_type_id' => $stakeType->id,
'transaction_datetime' => now(),
'coins' => -$match->stake,
]);
$match->update([
'status' => 'Playing',
'player2_user_id' => $user->id
]);
return response()->json([
'message' => 'Joined match successfully!',
'match' => $match,
'balance' => $user->coins_balance
]);
});
} }
public function update(Request $request, MatchGame $match) public function update(Request $request, MatchGame $match)
@@ -123,12 +164,36 @@ class MatchController extends Controller
'total_time' => 'numeric' 'total_time' => 'numeric'
]); ]);
if (isset($data['status']) && $data['status'] === 'Ended') { return DB::transaction(function () use ($match, $data) {
$data['ended_at'] = now();
} if (isset($data['status']) && $data['status'] === 'Ended') {
$data['ended_at'] = now();
}
$match->update($data); $match->update($data);
return response()->json($match); if ($match->status === 'Ended' && $match->stake > 0 && $match->winner_user_id) {
$payoutType = CoinTransactionType::firstOrCreate(
['name' => 'Match payout'],
['type' => 'C'] // Credit
);
$totalPrize = $match->stake * 2;
CoinTransaction::create([
'user_id' => $match->winner_user_id,
'match_id' => $match->id,
'coin_transaction_type_id' => $payoutType->id,
'transaction_datetime' => now(),
'coins' => $totalPrize,
]);
$match->winner->increment('coins_balance', $totalPrize);
}
return response()->json($match);
});
} }
} }
@@ -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);
} }
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CoinPurchase extends Model
{
use HasFactory;
protected $table = 'coin_purchases';
public $timestamps = false;
protected $fillable = [
'purchase_datetime',
'user_id',
'coin_transaction_id',
'euros',
'payment_type',
'payment_reference',
'custom'
];
protected $casts = [
'purchase_datetime' => 'datetime',
'custom' => 'array',
];
public function transaction()
{
return $this->belongsTo(CoinTransaction::class, 'coin_transaction_id');
}
}
+17 -9
View File
@@ -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)
) { ) {
@@ -84,12 +92,12 @@ class GamePolicy
*/ */
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 (
$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)
) { ) {
@@ -105,7 +113,7 @@ class GamePolicy
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";
} }
/** /**
+2
View File
@@ -6,6 +6,7 @@ use App\Http\Controllers\MatchController;
use App\Http\Controllers\ProfileController; 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 Illuminate\Support\Facades\Route; use Illuminate\Support\Facades\Route;
Route::prefix('v1')->group(function () { Route::prefix('v1')->group(function () {
@@ -19,6 +20,7 @@ Route::prefix('v1')->group(function () {
// Authenticated Routes // Authenticated Routes
Route::middleware(['auth:sanctum', 'throttle:60,1'])->group(function () { Route::middleware(['auth:sanctum', 'throttle:60,1'])->group(function () {
Route::post('/logout', [AuthController::class, 'logout']); Route::post('/logout', [AuthController::class, 'logout']);
Route::post('/coin-purchases', [CoinPurchaseController::class, 'store']);
Route::get('/statistics/me', [StatisticsController::class, 'getPersonalStats']); Route::get('/statistics/me', [StatisticsController::class, 'getPersonalStats']);
Route::prefix('users/me')->group(function () { Route::prefix('users/me')->group(function () {
Route::get('/', [ProfileController::class, 'show']); Route::get('/', [ProfileController::class, 'show']);
+29
View File
@@ -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,27 @@ 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 public stats
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}} Authorization: Bearer {{token}}
+15
View File
@@ -0,0 +1,15 @@
meta {
name: Create Game
type: http
seq: 3
}
post {
url: {{api_url}}/games
body: none
auth: inherit
}
settings {
encodeUrl: true
}
+6 -16
View File
@@ -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>
+204 -21
View File
@@ -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,40 +11,51 @@ 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'
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 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 setupObserver = () => { const setupGamesObserver = () => {
if (observer.value) observer.value.disconnect(); if (gObserver.value) gObserver.value.disconnect();
observer.value = new IntersectionObserver((entries) => { gObserver.value = new IntersectionObserver((entries) => {
if (entries[0].isIntersecting && !isLoading.value && openGames.value.length > 0) { 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 = gPage.value++;
apiStore.gameQueryParameters.page = pageCounter.value++;
apiStore.gameQueryParameters.filters.sort_direction = "asc" apiStore.gameQueryParameters.filters.sort_direction = "asc"
apiStore.gameQueryParameters.filters.type = mode apiStore.gameQueryParameters.filters.type = mode
apiStore.gameQueryParameters.filters.status = 'Pending' apiStore.gameQueryParameters.filters.status = 'Pending'
@@ -52,7 +64,66 @@ const getPendingGames = async (mode = selectedMode.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 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);
} }
} }
@@ -60,9 +131,9 @@ const clickMode = async (mode) => {
if (selectedMode.value === mode) return; if (selectedMode.value === mode) return;
openGames.value = []; openGames.value = [];
selectedMode.value = mode; selectedMode.value = mode;
pageCounter.value = 1; gPage.value = 1;
await getPendingGames(); await getPendingGames();
setupObserver(); setupGamesObserver();
} }
const startSingle = () => { const startSingle = () => {
@@ -86,7 +157,7 @@ const toggleReady = () => {
onMounted(async () => { onMounted(async () => {
await getPendingGames(); await getPendingGames();
await nextTick(); await nextTick();
setupObserver(); setupGamesObserver();
}) })
</script> </script>
@@ -171,8 +242,8 @@ onMounted(async () => {
</div> </div>
</div> </div>
<div ref="observerTarget" class="h-10 flex items-center justify-center"> <div ref="gObserverTarget" class="h-10 flex items-center justify-center">
<span v-if="isLoading" class="text-xs text-purple-500 animate-pulse">Loading <span v-if="gLoading" class="text-xs text-purple-500 animate-pulse">Loading
more...</span> more...</span>
</div> </div>
</div> </div>
@@ -238,5 +309,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>
+7
View File
@@ -10,6 +10,7 @@ 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 RegisterPage from '@/pages/register/RegisterPage.vue' import RegisterPage from '@/pages/register/RegisterPage.vue'
import CoinsPurchasePage from '@/pages/purchase/CoinPurchasePage.vue'
const router = createRouter({ const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL), history: createWebHistory(import.meta.env.BASE_URL),
@@ -46,6 +47,12 @@ const router = createRouter({
{ {
path: '/user', path: '/user',
component: UserPage, component: UserPage,
meta: { requiresAuth: true },
},
{
path: '/coins-purchase',
component: CoinsPurchasePage,
meta: { requiresAuth: true },
}, },
{ {
path: '/testing', path: '/testing',
+14
View File
@@ -102,6 +102,18 @@ export const useAPIStore = defineStore('api', () => {
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`)
}
return { return {
postLogin, postLogin,
postLogout, postLogout,
@@ -109,6 +121,8 @@ export const useAPIStore = defineStore('api', () => {
getGames, getGames,
getCurrentUserMatches, getCurrentUserMatches,
getCurrentUserTransactions, getCurrentUserTransactions,
getCurrentUserStats,
getLeaderboard,
gameQueryParameters, gameQueryParameters,
} }
}) })
+16
View File
@@ -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,
}
})
+14 -6
View File
@@ -1,16 +1,24 @@
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'
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
return response
} catch (error) {
console.error('Error fetching coins', error)
throw error
}
} }
return { return {
getCoins, coins,
fetchCoins,
} }
}) })
+59 -12
View File
@@ -6,6 +6,9 @@ class BiscaGame {
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,
@@ -14,7 +17,7 @@ class BiscaGame {
}; };
this.currentTurn = null; this.currentTurn = null;
this.status = "pending"; this.status = 'pending';
this.startTime = null; this.startTime = null;
this.players = { this.players = {
@@ -47,11 +50,51 @@ class BiscaGame {
this.currentTurn = playerIds.find((id) => id != 1) || playerIds[0]; this.currentTurn = playerIds.find((id) => id != 1) || playerIds[0];
this.startTime = Date.now(); this.startTime = Date.now();
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];
let deck = []; let deck = [];
@@ -87,7 +130,7 @@ class BiscaGame {
} }
playCard(userId, cardId) { 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 player = this.players[userId];
const cardIndex = player.hand.findIndex((c) => c.id === cardId); const cardIndex = player.hand.findIndex((c) => c.id === cardId);
@@ -101,17 +144,19 @@ class BiscaGame {
const suitToFollow = this.table.playerCard.suit; const suitToFollow = this.table.playerCard.suit;
const hasSuit = player.hand.some((c) => c.suit === suitToFollow); const hasSuit = player.hand.some((c) => c.suit === suitToFollow);
if (hasSuit && card.suit !== suitToFollow) { if (hasSuit && card.suit !== suitToFollow) {
return { error: "You must follow the suit!" }; return { error: 'You must follow the suit!' };
} }
} }
this.stopTimer();
player.hand.splice(cardIndex, 1); player.hand.splice(cardIndex, 1);
if (!this.table.playerCard) { if (!this.table.playerCard) {
this.table.playerCard = card; this.table.playerCard = card;
this.table.firstPlayerId = userId; this.table.firstPlayerId = userId;
this.currentTurn = this.getOpponentId(userId); this.currentTurn = this.getOpponentId(userId);
return { action: "next_turn" }; return { action: 'next_turn' };
} else { } else {
this.table.opponentCard = card; this.table.opponentCard = card;
return this.resolveTrick(); return this.resolveTrick();
@@ -151,7 +196,8 @@ class BiscaGame {
this.table = { playerCard: null, opponentCard: null, firstPlayerId: null }; this.table = { playerCard: null, opponentCard: null, firstPlayerId: null };
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]];
@@ -170,11 +216,11 @@ class BiscaGame {
const finalLoser = isDraw const finalLoser = isDraw
? null ? null
: gameWinnerId == p1Obj.id : gameWinnerId == p1Obj.id
? p2Obj.id ? p2Obj.id
: p1Obj.id; : p1Obj.id;
return { return {
action: "game_ended", action: 'game_ended',
trickResult, trickResult,
winnerId: finalWinner, winnerId: finalWinner,
loserId: finalLoser, loserId: finalLoser,
@@ -187,7 +233,7 @@ class BiscaGame {
}; };
} }
return { action: "trick_resolved", trickResult }; return { action: 'trick_resolved', trickResult };
} }
getStateForPlayer(userId) { getStateForPlayer(userId) {
@@ -205,6 +251,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 +279,4 @@ class BiscaGame {
} }
} }
module.exports = BiscaGame; export default BiscaGame;
+8 -11
View File
@@ -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
@@ -8,39 +8,36 @@ export const handleConnectionEvents = (io, socket) => {
let heartbeatTimeout; let heartbeatTimeout;
const startHeartbeat = () => { const startHeartbeat = () => {
heartbeatInterval = setInterval(() => { heartbeatInterval = setInterval(() => {
socket.emit("heartbeat"); socket.emit('heartbeat');
heartbeatTimeout = setTimeout(() => { heartbeatTimeout = setTimeout(() => {
console.log( console.log(
`[Heartbeat] No response from ${socket.id}, disconnecting...` `[Heartbeat] No response from ${socket.id}, disconnecting...`,
); );
socket.disconnect(true); socket.disconnect(true);
}, HEARTBEAT_TIMEOUT); }, HEARTBEAT_TIMEOUT);
}, HEARTBEAT_INTERVAL); }, HEARTBEAT_INTERVAL);
}; };
socket.on("heartbeat_ack", () => { socket.on('heartbeat_ack', () => {
clearTimeout(heartbeatTimeout); clearTimeout(heartbeatTimeout);
console.log(`[Heartbeat] Received pong from ${socket.id}`); console.log(`[Heartbeat] Received pong from ${socket.id}`);
}); });
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`);
}); });
}; };
+154 -11
View File
@@ -28,6 +28,78 @@ async function saveGameResult(gameId, result, token) {
} }
} }
const handleGameMove = (io, gameId, userId, cardId) => {
const game = getGame(gameId);
if (!game) return;
const result = game.playCard(userId, cardId);
if (result.error) {
console.log(`[Game Error] ${result.error}`);
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,
});
let tokenToUse = null;
const playerIds = Object.keys(game.players);
for (const pid of playerIds) {
if (game.players[pid] && game.players[pid].token) {
tokenToUse = game.players[pid].token;
break;
}
}
if (tokenToUse) {
saveGameResult(gameId, result, tokenToUse);
console.log(`[DB] Jogo salvo usando o token de um dos jogadores.`);
} else {
console.error(
`[DB Error] CRÍTICO: Nenhum jogador tem token. O jogo ${gameId} não foi salvo.`
);
}
}
if (result.action === "next_turn" || result.action === "trick_resolved") {
game.startTurnTimer((timeoutUserId, timeoutCardId) => {
handleGameMove(io, gameId, timeoutUserId, timeoutCardId);
});
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));
}
}
}
};
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);
@@ -47,6 +119,39 @@ export default (io, socket) => {
const gameData = response.data.data || response.data; const gameData = response.data.data || response.data;
console.log(
`[Join Debug] API Data recebida para Jogo ${gameId}:`,
gameData ? "OK" : "NULL"
);
if (
gameData.player2_user_id == 1 &&
user.id != gameData.player1_user_id
) {
try {
console.log(
`[API Sync] A oficializar User ${user.id} como Player 2 na BD...`
);
await axios.post(
`${API_URL}/games/${gameId}/join`,
{},
{
headers: { Authorization: token },
}
);
console.log(`[API Sync] Sucesso! O jogo passou a 'Playing' na BD.`);
gameData.player2_user_id = user.id;
gameData.player2 = { name: user.name };
gameData.status = "Playing";
} catch (joinError) {
console.error(
`[API Sync Error] Falha ao fazer join na BD:`,
joinError.message
);
}
}
if (gameData.status === "Ended") { if (gameData.status === "Ended") {
socket.emit("error", { message: "Game already finished." }); socket.emit("error", { message: "Game already finished." });
return; return;
@@ -71,7 +176,18 @@ export default (io, socket) => {
{ 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 }
); );
console.log(
`[Join Debug] Jogo criado?`,
game ? "SIM" : "NÃO (Undefined)"
);
} catch (error) { } catch (error) {
if (error.response) {
console.error(`[Join Error] Status: ${error.response.status}`);
console.error(`[Join Error] Data:`, error.response.data);
} else {
console.error(`[Join Error] Message:`, error.message);
}
socket.emit("error", { message: "Failed to join game." }); socket.emit("error", { message: "Failed to join game." });
return; return;
} }
@@ -80,17 +196,37 @@ export default (io, socket) => {
const GHOST_ID = 1; const GHOST_ID = 1;
if (game && game.players) { if (game && game.players) {
if (!game.players[user.id]) { if (game.players[user.id]) {
if (game.players[GHOST_ID]) { game.players[user.id].token = socket.handshake.auth.token;
delete game.players[GHOST_ID]; }
game.players[user.id] = {
id: user.id, if (!game.players[user.id] && game.players[GHOST_ID]) {
name: user.name, console.log(`[Ghost Swap] User ${user.name} substituiu o Fantasma.`);
hand: [],
points: 0, delete game.players[GHOST_ID];
tricks: 0, game.players[user.id] = {
}; id: user.id,
} name: user.name,
hand: [],
points: 0,
tricks: 0,
token: socket.handshake.auth.token,
};
const token = socket.handshake.auth.token;
axios
.post(
`${API_URL}/games/${gameId}/join`,
{},
{
headers: { Authorization: token },
}
)
.then(() =>
console.log(`[API Sync] Sucesso! BD atualizada para 'Playing'.`)
)
.catch((err) => console.error(`[API Sync Error]`, err.message));
} }
} }
@@ -99,6 +235,11 @@ export default (io, socket) => {
if (game && game.players[user.id]) { if (game && game.players[user.id]) {
socket.emit("game-state", game.getStateForPlayer(user.id)); socket.emit("game-state", game.getStateForPlayer(user.id));
console.log(`--> Estado enviado para User ${user.id}`); console.log(`--> Estado enviado para User ${user.id}`);
game.players[user.id].token = socket.handshake.auth.token;
if (!game.timer && game.status === "playing") {
game.startTurnTimer((uId, cId) => handleGameMove(io, gameId, uId, cId));
}
socket.emit("game-state", game.getStateForPlayer(user.id));
} else { } else {
socket.emit("error", { message: "Error joining game state." }); socket.emit("error", { message: "Error joining game state." });
} }
@@ -117,6 +258,8 @@ export default (io, socket) => {
return; return;
} }
handleGameMove(io, gameId, user.id, cardId);
const roomName = `game_${gameId}`; const roomName = `game_${gameId}`;
const socketsInRoom = io.sockets.adapter.rooms.get(roomName); const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
if (socketsInRoom) { if (socketsInRoom) {
+1
View File
@@ -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 "
+14 -7
View File
@@ -18,15 +18,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 +42,10 @@ 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.handshake.auth.token = token;
addUser(socket.id, user);
next(); next();
} catch (error) { } catch (error) {
@@ -53,15 +63,12 @@ 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);
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);
}); });
}); });
}; };
+8 -8
View File
@@ -1,4 +1,4 @@
const BiscaGame = require("../classes/BiscaGame"); import BiscaGame from '../classes/BiscaGame.js';
const activeGames = new Map(); const activeGames = new Map();
@@ -18,12 +18,12 @@ const getGame = (id) => {
}; };
const removeGame = (id) => { 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);
console.log(`[Game State] Game removed: ${id}`);
}
}; };
module.exports = { export { createGame, getGame, removeGame };
createGame,
getGame,
removeGame,
};