Merge pull request 'feature/bestof-series-interface' (#99) from feature/bestof-series-interface into develop
Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/99 Reviewed-by: KZix <[email protected]> Reviewed-by: Edd <[email protected]> Reviewed-by: FernandoJVideira <[email protected]>
This commit was merged in pull request #99.
This commit is contained in:
@@ -244,4 +244,19 @@ class GameController extends Controller
|
||||
'game' => $game->fresh(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function destroy(Game $game)
|
||||
{
|
||||
// Ensure only the host can delete, and ONLY if it's still Pending
|
||||
if ($game->player1_user_id !== auth()->id()) {
|
||||
return response()->json(['message' => 'Unauthorized'], 403);
|
||||
}
|
||||
|
||||
if ($game->status !== 'Pending') {
|
||||
return response()->json(['message' => 'Cannot delete a game in progress'], 400);
|
||||
}
|
||||
|
||||
$game->delete();
|
||||
return response()->noContent();
|
||||
}
|
||||
}
|
||||
@@ -41,7 +41,7 @@ class MatchController extends Controller
|
||||
{
|
||||
$validated = $request->validated();
|
||||
$user = $request->user();
|
||||
$stake = $validated["stake"];
|
||||
$stake = $validated['stake'];
|
||||
|
||||
if ($user->coins_balance < $stake) {
|
||||
return response()->json(
|
||||
@@ -60,10 +60,7 @@ class MatchController extends Controller
|
||||
->exists();
|
||||
|
||||
if ($activeMatch) {
|
||||
return response()->json(
|
||||
["message" => "You already have an active match."],
|
||||
400,
|
||||
);
|
||||
return response()->json(['message' => 'You already have an active match.'], 400);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($validated, $user, $stake) {
|
||||
@@ -165,11 +162,11 @@ class MatchController extends Controller
|
||||
);
|
||||
|
||||
CoinTransaction::create([
|
||||
"user_id" => $user->id,
|
||||
"match_id" => $match->id,
|
||||
"coin_transaction_type_id" => $stakeType->id,
|
||||
"transaction_datetime" => now(),
|
||||
"coins" => -$match->stake,
|
||||
'user_id' => $user->id,
|
||||
'match_id' => $match->id,
|
||||
'coin_transaction_type_id' => $stakeType->id,
|
||||
'transaction_datetime' => now(),
|
||||
'coins' => -$match->stake,
|
||||
]);
|
||||
|
||||
$match->update([
|
||||
@@ -203,8 +200,8 @@ class MatchController extends Controller
|
||||
]);
|
||||
|
||||
return DB::transaction(function () use ($match, $data) {
|
||||
if (isset($data["status"]) && $data["status"] === "Ended") {
|
||||
$data["ended_at"] = now();
|
||||
if (isset($data['status']) && $data['status'] === 'Ended') {
|
||||
$data['ended_at'] = now();
|
||||
}
|
||||
|
||||
$match->update($data);
|
||||
@@ -280,18 +277,17 @@ class MatchController extends Controller
|
||||
);
|
||||
|
||||
$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,
|
||||
'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([
|
||||
@@ -308,16 +304,70 @@ class MatchController extends Controller
|
||||
|
||||
public function open(Request $request)
|
||||
{
|
||||
$type = $request->query("type", "9");
|
||||
$GHOST_ID = 1;
|
||||
$query = MatchGame::where('status', 'Pending')
|
||||
->where(function($q) {
|
||||
$q->whereNull('player2_user_id')
|
||||
->orWhere('player2_user_id', 1); // 1 = Ghost ID
|
||||
});
|
||||
|
||||
$matches = MatchGame::where("status", "Pending")
|
||||
->where("player2_user_id", $GHOST_ID)
|
||||
->where("type", $type)
|
||||
->with("player1")
|
||||
->orderBy("began_at", "asc")
|
||||
if ($request->has('type')) {
|
||||
$query->where('type', $request->type);
|
||||
}
|
||||
|
||||
$matches = $query->with('player1:id,nickname')
|
||||
->orderBy('began_at', 'desc')
|
||||
->paginate(10);
|
||||
|
||||
return response()->json($matches);
|
||||
}
|
||||
|
||||
// --- FIX: Safely Delete Match by removing dependencies first ---
|
||||
public function destroy(MatchGame $match)
|
||||
{
|
||||
$user = request()->user();
|
||||
|
||||
if ($match->player1_user_id !== $user->id) {
|
||||
return response()->json(['message' => 'Unauthorized'], 403);
|
||||
}
|
||||
|
||||
if ($match->status !== 'Pending') {
|
||||
return response()->json(['message' => 'Cannot cancel a match that has already started'], 400);
|
||||
}
|
||||
|
||||
return DB::transaction(function () use ($match, $user) {
|
||||
// 1. Delete associated Games first (The FK constraint cause)
|
||||
DB::table('games')->where('match_id', $match->id)->delete();
|
||||
|
||||
// 2. Unlink existing Coin Transactions (Set match_id to NULL)
|
||||
CoinTransaction::where('match_id', $match->id)->update(['match_id' => null]);
|
||||
|
||||
// 3. Process Refund
|
||||
if ($match->stake > 0) {
|
||||
$user->increment('coins_balance', $match->stake);
|
||||
|
||||
$refundType = CoinTransactionType::firstOrCreate(
|
||||
['name' => 'Refund'],
|
||||
['type' => 'C']
|
||||
);
|
||||
|
||||
// Create Refund Transaction with NO LINK to the deleted match
|
||||
CoinTransaction::create([
|
||||
'user_id' => $user->id,
|
||||
'match_id' => null, // IMPORTANT: Must be null
|
||||
'coin_transaction_type_id' => $refundType->id,
|
||||
'transaction_datetime' => now(),
|
||||
'coins' => $match->stake,
|
||||
'custom' => "Refund for Match #{$match->id}"
|
||||
]);
|
||||
}
|
||||
|
||||
// 4. Finally delete the match
|
||||
$match->delete();
|
||||
|
||||
return response()->json([
|
||||
'message' => 'Match canceled and refunded',
|
||||
'balance' => $user->coins_balance
|
||||
]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,17 +4,17 @@ namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||||
|
||||
class CoinTransactionType extends Model
|
||||
{
|
||||
use HasFactory, SoftDeletes;
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'coin_transaction_types';
|
||||
// FIX: Disable auto-timestamps because the table doesn't have updated_at/created_at columns
|
||||
public $timestamps = false;
|
||||
|
||||
protected $fillable = ['name', 'type', 'custom'];
|
||||
|
||||
protected $casts = [
|
||||
'custom' => 'array',
|
||||
protected $fillable = [
|
||||
'name',
|
||||
'type',
|
||||
'description' // Include description if your table has it
|
||||
];
|
||||
}
|
||||
+5
-3
@@ -58,10 +58,12 @@ 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::post('host', [MatchController::class, 'host']);
|
||||
Route::get('open', [MatchController::class, 'open']);
|
||||
Route::post('/{match}/join', [MatchController::class, 'join']);
|
||||
Route::post('/{match}/start', [MatchController::class, 'start']); // Changed to /start to be explicit
|
||||
Route::delete('/{match}', [MatchController::class, 'destroy']);
|
||||
Route::apiResource('/', MatchController::class)->parameters(['' => 'match']);
|
||||
});
|
||||
|
||||
// Admin Routes
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.1.17",
|
||||
"@tanstack/vue-table": "^8.21.3",
|
||||
"@vueuse/core": "^14.0.0",
|
||||
"@vueuse/core": "^14.1.0",
|
||||
"axios": "^1.13.2",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
@@ -24,7 +24,7 @@
|
||||
"lucide-react": "^0.562.0",
|
||||
"lucide-vue-next": "^0.554.0",
|
||||
"pinia": "^3.0.3",
|
||||
"reka-ui": "^2.6.0",
|
||||
"reka-ui": "^2.7.0",
|
||||
"socket.io-client": "^4.8.1",
|
||||
"tailwind-merge": "^3.4.0",
|
||||
"tailwindcss": "^4.1.17",
|
||||
|
||||
@@ -9,14 +9,9 @@
|
||||
</NavigationMenuItem>
|
||||
|
||||
<NavigationMenuItem v-else class="flex flex-row gap-4">
|
||||
<NavigationMenuLink
|
||||
v-if="userStore.coins > 0"
|
||||
href="/coins-purchase"
|
||||
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"
|
||||
>
|
||||
<NavigationMenuLink v-if="userStore.coins > 0" href="/coins-purchase"
|
||||
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">
|
||||
<span class="text-[10px] font-bold text-purple-900">$</span>
|
||||
</div>
|
||||
|
||||
@@ -83,7 +78,5 @@ watch(
|
||||
} else {
|
||||
userStore.coins = 0
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
<script setup>
|
||||
import { reactiveOmit } from "@vueuse/core";
|
||||
import { Label } from "reka-ui";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const props = defineProps({
|
||||
for: { type: String, required: false },
|
||||
asChild: { type: Boolean, required: false },
|
||||
as: { type: null, required: false },
|
||||
class: { type: null, required: false },
|
||||
});
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class");
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Label
|
||||
data-slot="label"
|
||||
v-bind="delegatedProps"
|
||||
:class="
|
||||
cn(
|
||||
'flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50',
|
||||
props.class,
|
||||
)
|
||||
"
|
||||
>
|
||||
<slot />
|
||||
</Label>
|
||||
</template>
|
||||
@@ -0,0 +1 @@
|
||||
export { default as Label } from "./Label.vue";
|
||||
@@ -0,0 +1,49 @@
|
||||
<script setup>
|
||||
import { reactiveOmit } from "@vueuse/core";
|
||||
import { SwitchRoot, SwitchThumb, useForwardPropsEmits } from "reka-ui";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const props = defineProps({
|
||||
defaultValue: { type: Boolean, required: false },
|
||||
modelValue: { type: [Boolean, null], required: false },
|
||||
disabled: { type: Boolean, required: false },
|
||||
id: { type: String, required: false },
|
||||
value: { type: String, required: false },
|
||||
asChild: { type: Boolean, required: false },
|
||||
as: { type: null, required: false },
|
||||
name: { type: String, required: false },
|
||||
required: { type: Boolean, required: false },
|
||||
class: { type: null, required: false },
|
||||
});
|
||||
|
||||
const emits = defineEmits(["update:modelValue"]);
|
||||
|
||||
const delegatedProps = reactiveOmit(props, "class");
|
||||
|
||||
const forwarded = useForwardPropsEmits(delegatedProps, emits);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<SwitchRoot
|
||||
v-slot="slotProps"
|
||||
data-slot="switch"
|
||||
v-bind="forwarded"
|
||||
:class="
|
||||
cn(
|
||||
'peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 inline-flex h-[1.15rem] w-8 shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50',
|
||||
props.class,
|
||||
)
|
||||
"
|
||||
>
|
||||
<SwitchThumb
|
||||
data-slot="switch-thumb"
|
||||
:class="
|
||||
cn(
|
||||
'bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block size-4 rounded-full ring-0 transition-transform data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0',
|
||||
)
|
||||
"
|
||||
>
|
||||
<slot name="thumb" v-bind="slotProps" />
|
||||
</SwitchThumb>
|
||||
</SwitchRoot>
|
||||
</template>
|
||||
@@ -0,0 +1 @@
|
||||
export { default as Switch } from "./Switch.vue";
|
||||
@@ -1,15 +1,14 @@
|
||||
<template>
|
||||
<div class="relative min-h-screen overflow-hidden bg-green-900">
|
||||
<div v-if="shouldShowBoard && !gameOver" class="absolute top-4 right-4 z-50">
|
||||
<button
|
||||
@click="handleSurrender"
|
||||
class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all transform hover:scale-105 flex items-center gap-2"
|
||||
>
|
||||
<button @click="handleSurrender"
|
||||
class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all transform hover:scale-105 flex items-center gap-2">
|
||||
<span>🏳️</span> Surrender
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="!wsStore.connected && hasConnectedOnce" class="absolute top-4 left-4 z-50 flex items-center gap-2 bg-gray-800 px-4 py-2 rounded-lg border border-gray-700 shadow-xl">
|
||||
<div v-if="!wsStore.connected && hasConnectedOnce"
|
||||
class="absolute top-4 left-4 z-50 flex items-center gap-2 bg-gray-800 px-4 py-2 rounded-lg border border-gray-700 shadow-xl">
|
||||
<div class="w-3 h-3 rounded-full bg-red-500 animate-pulse"></div>
|
||||
<span class="text-white text-sm">Reconnecting...</span>
|
||||
</div>
|
||||
@@ -18,7 +17,8 @@
|
||||
<div class="bg-gray-800 px-6 py-3 rounded-lg border-2 shadow-xl transition-colors duration-300"
|
||||
:class="timeLeft <= 5 ? 'border-red-500 bg-red-900/20' : 'border-gray-700'">
|
||||
<div class="flex items-center gap-3">
|
||||
<svg class="w-6 h-6" :class="timeLeft <= 5 ? 'text-red-500 animate-bounce' : 'text-white'" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
||||
<svg class="w-6 h-6" :class="timeLeft <= 5 ? 'text-red-500 animate-bounce' : 'text-white'" viewBox="0 0 24 24"
|
||||
fill="none" stroke="currentColor">
|
||||
<circle cx="12" cy="12" r="10" stroke-width="2" />
|
||||
<polyline points="12 6 12 12 16 14" stroke-width="2" />
|
||||
</svg>
|
||||
@@ -30,31 +30,19 @@
|
||||
</div>
|
||||
|
||||
<div v-if="shouldShowBoard">
|
||||
<GameBoard
|
||||
:trump-card="trumpCard"
|
||||
:cards-remaining="deckCount + (trumpCard ? 1 : 0)"
|
||||
|
||||
:player-hand="visibleHand"
|
||||
:opponent-hand="opponentHand"
|
||||
|
||||
:player-score="playerScore"
|
||||
:opponent-score="opponentScore"
|
||||
|
||||
:player-name="myDisplayName"
|
||||
:opponent-name="opponentDisplayName"
|
||||
:current-turn="currentTurnLabel"
|
||||
|
||||
:current-trick="displayedTrick"
|
||||
:is-my-turn="isMyTurn"
|
||||
@play-card="handlePlayCard"
|
||||
/>
|
||||
<GameBoard :trump-card="trumpCard" :cards-remaining="deckCount + (trumpCard ? 1 : 0)" :player-hand="visibleHand"
|
||||
:opponent-hand="opponentHand" :player-score="playerScore" :opponent-score="opponentScore"
|
||||
:player-name="myDisplayName" :opponent-name="opponentDisplayName" :current-turn="currentTurnLabel"
|
||||
:current-trick="displayedTrick" :is-my-turn="isMyTurn" @play-card="handlePlayCard" />
|
||||
</div>
|
||||
|
||||
<div v-else-if="!gameOver" class="flex h-screen items-center justify-center bg-green-900 text-white">
|
||||
<div class="text-center p-8 bg-green-800/50 rounded-2xl border border-green-700 shadow-2xl backdrop-blur-sm">
|
||||
<div class="relative mx-auto mb-6 h-16 w-16">
|
||||
<div class="absolute inset-0 rounded-full border-4 border-green-600"></div>
|
||||
<div class="absolute inset-0 rounded-full border-4 border-t-white border-r-transparent border-b-transparent border-l-transparent animate-spin"></div>
|
||||
<div
|
||||
class="absolute inset-0 rounded-full border-4 border-t-white border-r-transparent border-b-transparent border-l-transparent animate-spin">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 class="text-2xl font-bold mb-2">
|
||||
@@ -64,34 +52,25 @@
|
||||
<p class="text-green-100 mb-8 max-w-sm">
|
||||
Share the game code or wait for a player to join your lobby.
|
||||
</p>
|
||||
|
||||
<button
|
||||
@click="handleCloseModal"
|
||||
class="px-6 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-all shadow-lg hover:shadow-red-500/20"
|
||||
>
|
||||
<div class="bg-black/20 p-3 rounded mb-6 font-mono text-sm border border-white/10 text-green-100">
|
||||
Match ID: <span class="font-bold text-white">{{ matchState.id }}</span>
|
||||
</div>
|
||||
<button @click="handleCloseModal"
|
||||
class="px-6 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-all shadow-lg hover:shadow-red-500/20">
|
||||
Cancel & Return Home
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<GameOver
|
||||
:is-visible="gameOver"
|
||||
:winner="winnerResult"
|
||||
:player-score="playerScore"
|
||||
:opponent-score="opponentScore"
|
||||
:player-name="myDisplayName"
|
||||
:opponent-name="opponentDisplayName"
|
||||
:stats="{ playerTricks: 0, opponentTricks: 0 }"
|
||||
:is-logging-out="false"
|
||||
@play-again="handleCloseModal"
|
||||
@close="handleCloseModal"
|
||||
/>
|
||||
<GameOver :is-visible="gameOver" :winner="winnerResult" :player-score="playerScore" :opponent-score="opponentScore"
|
||||
:player-name="myDisplayName" :opponent-name="opponentDisplayName" :stats="{ playerTricks: 0, opponentTricks: 0 }"
|
||||
:is-logging-out="false" @play-again="handleCloseModal" @close="handleCloseModal" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onUnmounted, watch, inject } from 'vue'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
|
||||
import { useSocketStore } from '@/stores/socket'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { toast } from 'vue-sonner'
|
||||
@@ -115,6 +94,9 @@ const timeLeft = ref(20)
|
||||
const timerInterval = ref(null)
|
||||
const hasConnectedOnce = ref(false)
|
||||
|
||||
// --- STATE ---
|
||||
const matchState = computed(() => wsStore.gameState || { id: gameId.value })
|
||||
|
||||
const gameMetadata = ref({
|
||||
p1_id: null,
|
||||
p1_name: 'Player 1',
|
||||
@@ -284,22 +266,102 @@ const handlePlayCard = (card) => {
|
||||
wsStore.playCard(gameId.value, card.id)
|
||||
}
|
||||
|
||||
const handleBeforeUnload = (event) => {
|
||||
if (shouldShowBoard.value && !gameOver.value) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
}
|
||||
};
|
||||
|
||||
// --- FIX: SURRENDER LOGIC ---
|
||||
const handleSurrender = () => {
|
||||
if (confirm('Are you sure you want to surrender? You will lose.')) {
|
||||
// Send event to server. Do NOT disconnect locally yet.
|
||||
// Wait for the server to send "Game Over" event back.
|
||||
wsStore.surrender(gameId.value)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCloseModal = () => {
|
||||
wsStore.disconnect()
|
||||
router.push({ name: 'home' })
|
||||
const handleCloseModal = async () => {
|
||||
// 1. If game is still in Lobby (Pending) and I am the Host, DELETE it.
|
||||
if (!shouldShowBoard.value && amIHost.value && !gameOver.value) {
|
||||
try {
|
||||
// This calls Route::delete('/{game}', ...) in your api.php
|
||||
await axios.delete(`${API_BASE_URL}/games/${gameId.value}`);
|
||||
console.log("Lobby cancelled and deleted.");
|
||||
} catch (e) {
|
||||
console.error("Failed to delete pending game:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Notify server of voluntary exit (to skip the 10s reconnect timer)
|
||||
if (wsStore.socket) {
|
||||
wsStore.socket.emit('notify_disconnect');
|
||||
}
|
||||
|
||||
// 3. Disconnect and go home
|
||||
wsStore.disconnect();
|
||||
router.push({ name: 'home' });
|
||||
}
|
||||
|
||||
// --- LIFECYCLE ---
|
||||
|
||||
onBeforeRouteLeave(async (to, from, next) => {
|
||||
// CASE A: Game is Pending (Waiting Room)
|
||||
if (!shouldShowBoard.value && !gameOver.value) {
|
||||
if (amIHost.value) {
|
||||
// Ask for confirmation to close the lobby
|
||||
const confirmClose = window.confirm("This will cancel the lobby. Are you sure?");
|
||||
if (confirmClose) {
|
||||
try {
|
||||
// Delete the game from DB so it doesn't get stuck as "Pending"
|
||||
await axios.delete(`${API_BASE_URL}/games/${gameId.value}`);
|
||||
} catch (e) { console.error(e) }
|
||||
|
||||
if (wsStore.socket) wsStore.socket.emit('notify_disconnect');
|
||||
wsStore.disconnect();
|
||||
next();
|
||||
} else {
|
||||
next(false); // Stay on page
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
// If I am NOT host (just a guest waiting), just leave
|
||||
if (wsStore.socket) wsStore.socket.emit('notify_disconnect');
|
||||
wsStore.disconnect();
|
||||
next();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// CASE B: Game is Over (Standard exit)
|
||||
if (gameOver.value) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
// CASE C: Game is Active/Playing (The Surrender Logic we built before)
|
||||
const answer = window.confirm(
|
||||
"If you leave, you will be register has 'losing' or 'surrendered', Are you sure you want to leave?"
|
||||
);
|
||||
|
||||
if (answer) {
|
||||
// ... (Your existing surrender logic) ...
|
||||
try { await wsStore.surrender(gameId.value); } catch (e) { }
|
||||
|
||||
if (wsStore.socket) {
|
||||
wsStore.socket.emit('notify_disconnect', () => {
|
||||
wsStore.disconnect();
|
||||
next();
|
||||
});
|
||||
setTimeout(() => { if (wsStore.connected) { wsStore.disconnect(); next(); } }, 500);
|
||||
return;
|
||||
}
|
||||
wsStore.disconnect();
|
||||
next();
|
||||
} else {
|
||||
next(false);
|
||||
}
|
||||
});
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchGameMetadata()
|
||||
wsStore.connect()
|
||||
@@ -317,6 +379,8 @@ onMounted(async () => {
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload)
|
||||
|
||||
if (timerInterval.value) clearInterval(timerInterval.value)
|
||||
wsStore.disconnect()
|
||||
})
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
<script setup>
|
||||
import { ref, onMounted, computed, inject, onUnmounted, watch } from 'vue'
|
||||
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useSocketStore } from '@/stores/socket'
|
||||
import { Coins, Trophy, Frown } from 'lucide-vue-next'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import GameBoard from '@/components/game/GameBoard.vue'
|
||||
import axios from 'axios'
|
||||
import { toast } from 'vue-sonner'
|
||||
|
||||
const API_BASE_URL = inject('apiBaseURL')
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
const wsStore = useSocketStore()
|
||||
|
||||
// --- FIX: Flag to prevent double cancellation ---
|
||||
const isCancelling = ref(false)
|
||||
|
||||
const matchState = ref({
|
||||
id: route.params.id,
|
||||
wager: 0,
|
||||
myMarks: 0,
|
||||
oppMarks: 0,
|
||||
currentGameId: null,
|
||||
player1: null,
|
||||
player2: null,
|
||||
status: 'Pending'
|
||||
})
|
||||
|
||||
const timeLeft = ref(20)
|
||||
const timerInterval = ref(null)
|
||||
const showSurrenderModal = ref(false)
|
||||
const showTrickResult = ref(false)
|
||||
const lastTrickWinner = ref(null)
|
||||
const showRoundModal = ref(false)
|
||||
const roundData = ref({ winnerId: null, marksAdded: 0, myPoints: 0, oppPoints: 0, reason: '' })
|
||||
|
||||
const myUserId = computed(() => authStore.currentUser?.id)
|
||||
const amIHost = computed(() => matchState.value.player1?.id === myUserId.value)
|
||||
const isPending = computed(() => !matchState.value.player2 || matchState.value.player2.id <= 1)
|
||||
const matchOver = computed(() => matchState.value.myMarks >= 4 || matchState.value.oppMarks >= 4)
|
||||
const iWonMatch = computed(() => matchState.value.myMarks > matchState.value.oppMarks)
|
||||
const isMyTurn = computed(() => String(wsStore.gameState?.currentTurn) === String(myUserId.value))
|
||||
const currentTurnLabel = computed(() => isMyTurn.value ? 'player' : 'opponent')
|
||||
|
||||
const myDisplayName = computed(() => amIHost.value ? matchState.value.player1?.nickname : matchState.value.player2?.nickname)
|
||||
const opponentDisplayName = computed(() => amIHost.value ? matchState.value.player2?.nickname : matchState.value.player1?.nickname)
|
||||
|
||||
const opponentHand = computed(() => {
|
||||
const count = wsStore.gameState?.opponent?.cardCount || 0
|
||||
return Array.from({ length: count }, (_, i) => ({ id: `opp-${i}`, suit: 'back', rank: 0 }))
|
||||
})
|
||||
|
||||
// Timer
|
||||
watch(() => wsStore.gameState?.currentTurn, () => { startTimer() }, { deep: true })
|
||||
const startTimer = () => {
|
||||
if (timerInterval.value) clearInterval(timerInterval.value);
|
||||
timeLeft.value = 20;
|
||||
if(!wsStore.gameState) return;
|
||||
timerInterval.value = setInterval(() => {
|
||||
if(timeLeft.value > 0) timeLeft.value--;
|
||||
else clearInterval(timerInterval.value);
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
const handlePlayCard = (card) => {
|
||||
if (wsStore.socket) wsStore.socket.emit('game:play-card', { matchId: matchState.value.id, cardId: card.id })
|
||||
}
|
||||
|
||||
const openSurrenderModal = () => { showSurrenderModal.value = true }
|
||||
const confirmSurrenderRound = () => {
|
||||
showSurrenderModal.value = false;
|
||||
if (wsStore.socket) wsStore.socket.emit('game:surrender', { matchId: matchState.value.id });
|
||||
}
|
||||
const confirmSurrenderMatch = () => {
|
||||
showSurrenderModal.value = false;
|
||||
if (wsStore.socket) wsStore.socket.emit('match:surrender', { matchId: matchState.value.id });
|
||||
}
|
||||
const closeRoundModal = () => { showRoundModal.value = false; }
|
||||
|
||||
const updateLocalState = (data) => {
|
||||
if (!data) return
|
||||
if (data.player1) matchState.value.player1 = data.player1
|
||||
if (data.player2) matchState.value.player2 = data.player2
|
||||
if (data.stake) matchState.value.wager = data.stake
|
||||
matchState.value.status = data.status
|
||||
|
||||
if (data.marks) {
|
||||
const myId = authStore.currentUser?.id;
|
||||
const oppId = amIHost.value ? matchState.value.player2?.id : matchState.value.player1?.id;
|
||||
matchState.value.myMarks = data.marks[myId] || 0;
|
||||
matchState.value.oppMarks = data.marks[oppId] || 0;
|
||||
}
|
||||
|
||||
if (data.game) {
|
||||
matchState.value.currentGameId = data.game.id;
|
||||
wsStore.gameState = data.game;
|
||||
} else if (data.status === 'Playing') {
|
||||
matchState.value.currentGameId = null;
|
||||
wsStore.gameState = null;
|
||||
}
|
||||
}
|
||||
|
||||
// --- FIX: Cancel Match with Flag ---
|
||||
const cancelMatch = async () => {
|
||||
if (isCancelling.value) return;
|
||||
isCancelling.value = true;
|
||||
|
||||
try {
|
||||
await axios.delete(`${API_BASE_URL}/matches/${matchState.value.id}`)
|
||||
router.push({ name: 'home' })
|
||||
} catch (e) {
|
||||
// Ignore 404s if we just deleted it
|
||||
if (e.response && e.response.status === 404) {
|
||||
router.push({ name: 'home' })
|
||||
} else {
|
||||
isCancelling.value = false; // Reset if legitimate error
|
||||
alert(e.message)
|
||||
}
|
||||
}
|
||||
}
|
||||
const leaveMatch = () => router.push({ name: 'home' })
|
||||
|
||||
const handleBeforeUnload = (e) => {
|
||||
if (matchState.value.status === 'Playing' && !matchOver.value) {
|
||||
const msg = "If you leave now, you will lose the match and your wager.";
|
||||
e.returnValue = msg;
|
||||
return msg;
|
||||
}
|
||||
}
|
||||
|
||||
// --- FIX: Router Guard checks Flag ---
|
||||
onBeforeRouteLeave((to, from, next) => {
|
||||
// If we already clicked cancel, just let it go
|
||||
if (isCancelling.value) {
|
||||
return next();
|
||||
}
|
||||
|
||||
if (matchState.value.status === 'Playing' && !matchOver.value) {
|
||||
if (confirm("⚠️ WARNING: Leaving now triggers an automatic match surrender (Loss).\n\nAre you sure?")) {
|
||||
if(wsStore.socket) wsStore.socket.emit('match:surrender', { matchId: matchState.value.id });
|
||||
next();
|
||||
} else {
|
||||
next(false);
|
||||
}
|
||||
} else if (isPending.value && amIHost.value) {
|
||||
if(confirm("Cancel this lobby?")) {
|
||||
// Mark as cancelling so we don't trigger double requests if cancelMatch is weird
|
||||
isCancelling.value = true;
|
||||
cancelMatch().then(() => next());
|
||||
} else {
|
||||
next(false);
|
||||
}
|
||||
} else {
|
||||
next();
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
window.addEventListener('beforeunload', handleBeforeUnload)
|
||||
try {
|
||||
const res = await axios.get(`${API_BASE_URL}/matches/${matchState.value.id}`)
|
||||
const d = res.data.data || res.data
|
||||
matchState.value.player1 = d.player1
|
||||
matchState.value.player2 = d.player2
|
||||
matchState.value.wager = d.stake
|
||||
} catch (e) { }
|
||||
|
||||
wsStore.connect()
|
||||
if (wsStore.socket) {
|
||||
wsStore.socket.emit('match:enter', { matchId: matchState.value.id })
|
||||
wsStore.socket.on('match:update', updateLocalState)
|
||||
wsStore.socket.on('match:new-round', (data) => {
|
||||
updateLocalState(data);
|
||||
toast.info("New round started!");
|
||||
})
|
||||
wsStore.socket.on('match:ended', updateLocalState)
|
||||
wsStore.socket.on('game:update', (state) => { wsStore.gameState = state })
|
||||
wsStore.socket.on('game:trick-end', (result) => {
|
||||
lastTrickWinner.value = result.winnerId;
|
||||
showTrickResult.value = true;
|
||||
setTimeout(() => { showTrickResult.value = false }, 2000);
|
||||
});
|
||||
wsStore.socket.on('match:round-ended', (data) => {
|
||||
const myPoints = data.winnerId == myUserId.value ? (data.winnerId == matchState.value.player1.id ? data.p1Points : data.p2Points) : (data.winnerId == matchState.value.player1.id ? data.p2Points : data.p1Points);
|
||||
const oppPoints = data.winnerId != myUserId.value ? (data.winnerId == matchState.value.player1.id ? data.p1Points : data.p2Points) : (data.winnerId == matchState.value.player1.id ? data.p2Points : data.p1Points);
|
||||
|
||||
roundData.value = {
|
||||
winnerId: data.winnerId,
|
||||
marksAdded: data.marksAdded,
|
||||
myPoints: myPoints,
|
||||
oppPoints: oppPoints,
|
||||
reason: data.reason
|
||||
};
|
||||
showRoundModal.value = true;
|
||||
});
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
window.removeEventListener('beforeunload', handleBeforeUnload)
|
||||
if (wsStore.socket) {
|
||||
wsStore.socket.off('match:update')
|
||||
wsStore.socket.off('match:new-round')
|
||||
wsStore.socket.off('game:trick-end')
|
||||
wsStore.socket.off('match:round-ended')
|
||||
}
|
||||
wsStore.disconnect()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="relative min-h-screen bg-green-900 text-white overflow-hidden">
|
||||
<div class="fixed top-0 left-0 right-0 z-40 bg-green-950/90 backdrop-blur border-b border-green-800 p-2 shadow-xl">
|
||||
<div class="max-w-4xl mx-auto flex items-center justify-between">
|
||||
<div class="flex flex-col items-start">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="font-bold text-lg text-white drop-shadow-md">{{ myDisplayName }}</span>
|
||||
<span v-if="matchState.wager > 0" class="flex items-center text-xs text-yellow-300 bg-yellow-900/50 px-2 rounded border border-yellow-700/50">
|
||||
<Coins class="w-3 h-3 mr-1" /> {{ matchState.wager }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex gap-1 mt-1">
|
||||
<div v-for="i in 4" :key="i" class="w-3 h-3 rounded-full border border-green-400 bg-green-900"
|
||||
:class="{ '!bg-green-400 shadow-[0_0_10px_rgba(74,222,128,0.5)]': matchState.myMarks >= i }"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex flex-col items-center">
|
||||
<span class="text-[10px] uppercase tracking-widest text-green-400 font-bold">Match #{{ matchState.id }}</span>
|
||||
<span class="text-2xl font-black font-mono text-white drop-shadow-md">{{ matchState.myMarks }} - {{ matchState.oppMarks }}</span>
|
||||
</div>
|
||||
<div class="flex flex-col items-end">
|
||||
<span class="font-bold text-lg text-white drop-shadow-md">{{ opponentDisplayName }}</span>
|
||||
<div class="flex gap-1 mt-1">
|
||||
<div v-for="i in 4" :key="i" class="w-3 h-3 rounded-full border border-red-400 bg-green-900"
|
||||
:class="{ '!bg-red-500 shadow-[0_0_10px_rgba(239,68,68,0.5)]': matchState.oppMarks >= i }"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="wsStore.gameState && !matchOver" class="absolute top-24 right-4 z-50">
|
||||
<button @click="openSurrenderModal" class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all hover:scale-105 flex items-center gap-2 text-sm cursor-pointer">
|
||||
<span>🏳️</span> Surrender
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="wsStore.gameState && !matchOver && isMyTurn" class="absolute top-24 left-1/2 -translate-x-1/2 z-50">
|
||||
<div class="bg-gray-800 px-6 py-2 rounded-lg border-2 shadow-xl transition-colors duration-300" :class="timeLeft <= 5 ? 'border-red-500 bg-red-900/20' : 'border-gray-700'">
|
||||
<div class="flex items-center gap-3">
|
||||
<svg class="w-5 h-5" :class="timeLeft <= 5 ? 'text-red-500 animate-bounce' : 'text-white'" viewBox="0 0 24 24" fill="none" stroke="currentColor">
|
||||
<circle cx="12" cy="12" r="10" stroke-width="2" />
|
||||
<polyline points="12 6 12 12 16 14" stroke-width="2" />
|
||||
</svg>
|
||||
<span :class="['text-2xl font-mono font-bold', timeLeft <= 5 ? 'text-red-500' : 'text-white']">{{ timeLeft }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="pt-20 h-screen">
|
||||
<GameBoard
|
||||
v-if="wsStore.gameState && !matchOver"
|
||||
:game-id="matchState.currentGameId"
|
||||
@play-card="handlePlayCard"
|
||||
:trump-card="wsStore.gameState?.trumpCard"
|
||||
:cards-remaining="wsStore.gameState?.deckCount"
|
||||
:player-hand="wsStore.gameState?.hand"
|
||||
:opponent-hand="opponentHand"
|
||||
:player-score="wsStore.gameState?.points"
|
||||
:opponent-score="wsStore.gameState?.opponent?.points"
|
||||
:current-turn="currentTurnLabel"
|
||||
:current-trick="wsStore.gameState?.table"
|
||||
:is-my-turn="isMyTurn"
|
||||
:player-name="myDisplayName"
|
||||
:opponent-name="opponentDisplayName"
|
||||
/>
|
||||
<div v-else-if="isPending" class="flex h-full items-center justify-center flex-col gap-6">
|
||||
<div class="text-center p-8 bg-green-800/60 rounded-2xl border border-green-600 shadow-2xl backdrop-blur-md max-w-sm w-full mx-4">
|
||||
<div class="relative mx-auto mb-6 h-16 w-16">
|
||||
<div class="absolute inset-0 rounded-full border-4 border-green-700/50"></div>
|
||||
<div class="absolute inset-0 rounded-full border-4 border-t-white border-r-transparent border-b-transparent border-l-transparent animate-spin"></div>
|
||||
</div>
|
||||
<h2 class="text-2xl font-bold mb-2 text-white">Waiting for Opponent</h2>
|
||||
<button v-if="amIHost" @click="cancelMatch" class="bg-red-600 hover:bg-red-700 text-white py-2 px-4 rounded shadow mt-4">Cancel Match</button>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="!matchOver && !wsStore.gameState" class="flex h-full items-center justify-center flex-col gap-4">
|
||||
<div class="text-3xl font-bold animate-pulse text-white drop-shadow">Preparing next round...</div>
|
||||
</div>
|
||||
<div v-if="matchOver" class="absolute inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-md">
|
||||
<div class="text-center space-y-6 p-8 bg-green-900 border-2 border-green-500 rounded-2xl shadow-2xl max-w-md w-full">
|
||||
<Trophy v-if="iWonMatch" class="w-24 h-24 text-yellow-400 mx-auto animate-bounce" />
|
||||
<Frown v-else class="w-24 h-24 text-green-300 mx-auto opacity-75" />
|
||||
<h1 class="text-5xl font-black uppercase mb-2" :class="iWonMatch ? 'text-yellow-400' : 'text-gray-300'">{{ iWonMatch ? 'Victory!' : 'Defeat' }}</h1>
|
||||
<p class="text-green-100 text-lg">Marks: <span class="font-bold">{{ matchState.myMarks }} - {{ matchState.oppMarks }}</span></p>
|
||||
<Button @click="leaveMatch" class="w-full py-6 text-lg bg-purple-600 hover:bg-purple-700">Return to Lobby</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="showRoundModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-md">
|
||||
<div class="bg-gray-800 p-8 rounded-2xl border-2 border-yellow-500/50 shadow-2xl max-w-md w-full text-center relative overflow-hidden">
|
||||
<div class="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-transparent via-yellow-500 to-transparent"></div>
|
||||
<h2 class="text-3xl font-black text-white mb-2 uppercase">Round Over</h2>
|
||||
<p class="text-gray-400 mb-6 uppercase text-xs tracking-widest">{{ roundData.reason === 'surrender' ? 'Opponent Surrendered' : 'Points Limit Reached' }}</p>
|
||||
|
||||
<div class="flex justify-between items-center bg-black/30 p-4 rounded-lg mb-6">
|
||||
<div class="text-left">
|
||||
<p class="text-xs text-gray-500 uppercase">You</p>
|
||||
<p class="text-2xl font-bold text-white">{{ roundData.myPoints }} pts</p>
|
||||
</div>
|
||||
<div class="text-xl font-bold text-yellow-500">VS</div>
|
||||
<div class="text-right">
|
||||
<p class="text-xs text-gray-500 uppercase">Opponent</p>
|
||||
<p class="text-2xl font-bold text-white">{{ roundData.oppPoints }} pts</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mb-8">
|
||||
<p class="text-lg text-white" v-if="roundData.winnerId == myUserId">
|
||||
You won <span class="text-yellow-400 font-bold">+{{ roundData.marksAdded }} marks</span>!
|
||||
</p>
|
||||
<p class="text-lg text-white" v-else>
|
||||
Opponent won <span class="text-red-400 font-bold">+{{ roundData.marksAdded }} marks</span>.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<button @click="closeRoundModal" class="w-full py-4 bg-emerald-600 hover:bg-emerald-500 text-white font-bold rounded-xl shadow-lg transition-transform hover:scale-105">
|
||||
Ready for Next Round
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="showSurrenderModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-black/70 backdrop-blur-sm">
|
||||
<div class="bg-gray-800 p-6 rounded-lg border border-gray-600 shadow-2xl max-w-sm w-full text-center">
|
||||
<h3 class="text-xl font-bold text-white mb-6">Surrender Options</h3>
|
||||
<div class="space-y-3">
|
||||
<button @click="confirmSurrenderRound" class="w-full px-4 py-3 bg-gray-700 hover:bg-gray-600 rounded text-white font-bold border border-gray-500 flex justify-between items-center group">
|
||||
<span>Surrender Round</span>
|
||||
<span class="text-xs bg-black/40 px-2 py-1 rounded text-gray-300 group-hover:bg-red-500 group-hover:text-white">-2 Marks</span>
|
||||
</button>
|
||||
<button @click="confirmSurrenderMatch" class="w-full px-4 py-3 bg-red-900/50 hover:bg-red-600 rounded text-red-200 hover:text-white font-bold border border-red-800 flex justify-between items-center group">
|
||||
<span>Surrender Match</span>
|
||||
<span class="text-xs bg-black/40 px-2 py-1 rounded text-red-300 group-hover:bg-red-800 group-hover:text-white">Defeat</span>
|
||||
</button>
|
||||
</div>
|
||||
<button @click="showSurrenderModal = false" class="mt-6 text-gray-400 hover:text-white text-sm underline">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Transition enter-active-class="transition-all duration-300 ease-out" enter-from-class="opacity-0 scale-50" enter-to-class="opacity-100 scale-100" leave-active-class="transition-all duration-200 ease-in" leave-from-class="opacity-100 scale-100" leave-to-class="opacity-0 scale-75">
|
||||
<div v-if="showTrickResult" class="fixed top-1/3 left-1/2 -translate-x-1/2 z-[70] pointer-events-none">
|
||||
<div class="bg-black/70 backdrop-blur-md px-8 py-4 rounded-2xl border border-white/10 shadow-2xl text-center">
|
||||
<p class="text-sm uppercase tracking-widest text-gray-300 font-bold mb-1">Trick Winner</p>
|
||||
<h2 class="text-3xl font-black" :class="lastTrickWinner === myUserId ? 'text-green-400' : 'text-red-400'">{{ lastTrickWinner === myUserId ? 'YOU' : 'OPPONENT' }}</h2>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,7 +1,11 @@
|
||||
<script setup>
|
||||
import { User, Trophy } from 'lucide-vue-next'
|
||||
import { ref, onMounted, nextTick, inject } from 'vue'
|
||||
import { User, Trophy, Coins } from 'lucide-vue-next'
|
||||
import { ref, onMounted, nextTick, inject, computed } from 'vue'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { watch } from 'vue';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
@@ -12,7 +16,9 @@ import {
|
||||
import { useAPIStore } from '@/stores/api'
|
||||
import { useRouter } from 'vue-router'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { useUserStore } from '@/stores/user'
|
||||
import axios from 'axios'
|
||||
import { toast } from 'vue-sonner'
|
||||
|
||||
const API_BASE_URL = inject('apiBaseURL')
|
||||
const apiStore = useAPIStore()
|
||||
@@ -44,6 +50,15 @@ const lbObserver = ref(null)
|
||||
const lbMorePages = ref(true)
|
||||
const publicStats = ref(null)
|
||||
const isLoggedIn = useAuthStore().isLoggedIn
|
||||
const isBestOfThree = ref(false)
|
||||
const wagerAmount = ref(0)
|
||||
const authStore = useAuthStore()
|
||||
const userStore = useUserStore()
|
||||
const userLoggedIn = computed(() => authStore.isLoggedIn)
|
||||
const userCoins = ref(0)
|
||||
const hostLoading = ref(false)
|
||||
const gHasMore = ref(true);
|
||||
const mHasMore = ref(true);
|
||||
|
||||
const setupMatchesObserver = () => {
|
||||
if (mObserver.value) mObserver.value.disconnect();
|
||||
@@ -74,38 +89,40 @@ const setupGamesObserver = () => {
|
||||
}
|
||||
|
||||
const getPendingGames = async (mode = selectedMode.value) => {
|
||||
if (gLoading.value) return;
|
||||
if (gLoading.value || !gHasMore.value) return;
|
||||
gLoading.value = true;
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${API_BASE_URL}/games/open`, {
|
||||
params: {
|
||||
type: mode,
|
||||
page: gPage.value
|
||||
}
|
||||
params: { type: mode, page: gPage.value }
|
||||
});
|
||||
|
||||
const newGames = response.data.data;
|
||||
if (newGames.length === 0) {
|
||||
gHasMore.value = false;
|
||||
} else {
|
||||
openGames.value = [...openGames.value, ...newGames];
|
||||
gPage.value++;
|
||||
}
|
||||
} finally {
|
||||
gLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const getPendingMatches = async (mode = selectedMode.value) => {
|
||||
if (mLoading.value) return;
|
||||
if (mLoading.value || !mHasMore.value) return;
|
||||
mLoading.value = true;
|
||||
|
||||
try {
|
||||
const response = await axios.get(`${API_BASE_URL}/matches/open`, {
|
||||
params: {
|
||||
type: mode,
|
||||
page: mPage.value
|
||||
}
|
||||
params: { type: mode, page: mPage.value }
|
||||
});
|
||||
|
||||
const newMatches = response.data.data;
|
||||
if (newMatches.length === 0) {
|
||||
mHasMore.value = false;
|
||||
} else {
|
||||
openMatches.value = [...openMatches.value, ...newMatches];
|
||||
mPage.value++;
|
||||
}
|
||||
} finally {
|
||||
mLoading.value = false;
|
||||
}
|
||||
@@ -135,8 +152,8 @@ const openStats = async () => {
|
||||
|
||||
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`;
|
||||
? `${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 () => {
|
||||
@@ -145,11 +162,9 @@ const fetchLeaderboard = async () => {
|
||||
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 {
|
||||
@@ -173,7 +188,6 @@ const setupLeaderboardObserver = () => {
|
||||
fetchLeaderboard();
|
||||
}
|
||||
}, { threshold: 0.1 });
|
||||
|
||||
if (lbObserverTarget.value) {
|
||||
lbObserver.value.observe(lbObserverTarget.value);
|
||||
}
|
||||
@@ -183,9 +197,11 @@ const clickMode = async (mode) => {
|
||||
if (selectedMode.value === mode) return;
|
||||
selectedMode.value = mode;
|
||||
openGames.value = [];
|
||||
gPage.value = 1;
|
||||
openMatches.value = [];
|
||||
gPage.value = 1;
|
||||
mPage.value = 1;
|
||||
gHasMore.value = true;
|
||||
mHasMore.value = true;
|
||||
await Promise.all([getPendingGames(), getPendingMatches()]);
|
||||
setupGamesObserver();
|
||||
setupMatchesObserver();
|
||||
@@ -195,10 +211,101 @@ const startSingle = () => {
|
||||
router.push({ name: 'bisca' + selectedMode.value });
|
||||
}
|
||||
|
||||
const toggleReady = () => {
|
||||
isReady.value = !isReady.value
|
||||
// --- FIX: Correct Wager Logic ---
|
||||
const joinMatch = async (match) => {
|
||||
// Use 'stake' because that's what the API returns
|
||||
const cost = match.stake || match.wager || 0;
|
||||
|
||||
if (cost > userCoins.value) {
|
||||
toast.error(`Insufficient funds! You need ${cost} coins.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm(`Join match for ${cost} coins?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await axios.post(`${API_BASE_URL}/matches/${match.id}/join`)
|
||||
router.push({
|
||||
name: 'multiplayer-match',
|
||||
params: { id: match.id },
|
||||
query: { type: selectedMode.value }
|
||||
})
|
||||
} catch (error) {
|
||||
toast.error(error.response?.data?.message || 'Failed to join match');
|
||||
}
|
||||
}
|
||||
|
||||
const hostGame = async () => {
|
||||
if (isBestOfThree.value) {
|
||||
if (wagerAmount.value <= 0) {
|
||||
toast.error("Stake must be at least 1 coin.");
|
||||
return;
|
||||
}
|
||||
if (wagerAmount.value > userCoins.value) {
|
||||
toast.error("Insufficient coins!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
hostLoading.value = true;
|
||||
const endpoint = isBestOfThree.value ? '/matches/host' : '/games/host'
|
||||
const payload = isBestOfThree.value
|
||||
? { type: parseInt(selectedMode.value), stake: parseInt(wagerAmount.value) }
|
||||
: { type: parseInt(selectedMode.value) }
|
||||
|
||||
try {
|
||||
const response = await axios.post(`${API_BASE_URL}${endpoint}`, payload)
|
||||
const resultId = response.data.match?.id || response.data.id || response.data.data?.id;
|
||||
|
||||
if (!resultId) throw new Error("Missing ID");
|
||||
|
||||
showHostModal.value = false;
|
||||
router.push({
|
||||
name: isBestOfThree.value ? 'multiplayer-match' : 'multiplayer-game',
|
||||
params: { id: resultId },
|
||||
query: { type: selectedMode.value }
|
||||
})
|
||||
} catch (error) {
|
||||
if (error.response?.data?.message) {
|
||||
toast.error(error.response.data.message);
|
||||
} else {
|
||||
toast.error('Failed to host game');
|
||||
}
|
||||
} finally {
|
||||
hostLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const joinGame = async (game) => {
|
||||
try {
|
||||
await axios.post(`${API_BASE_URL}/games/${game.id}/join`)
|
||||
router.push({
|
||||
name: 'multiplayer-game',
|
||||
params: { id: game.id },
|
||||
query: { type: selectedMode.value }
|
||||
})
|
||||
} catch (error) {
|
||||
toast.error(error.response?.data?.message || 'Failed to join game');
|
||||
}
|
||||
}
|
||||
|
||||
const openHostModal = (forMatch) => {
|
||||
isBestOfThree.value = forMatch;
|
||||
showHostModal.value = true;
|
||||
wagerAmount.value = 0;
|
||||
}
|
||||
|
||||
watch(() => userLoggedIn, async (isLoggedIn) => {
|
||||
if (isLoggedIn) {
|
||||
await userStore.fetchCoins()
|
||||
userCoins.value = userStore.coins
|
||||
} else {
|
||||
userStore.coins = 0
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchPublicStats();
|
||||
if (isLoggedIn) {
|
||||
@@ -208,57 +315,10 @@ onMounted(async () => {
|
||||
setupMatchesObserver();
|
||||
}
|
||||
})
|
||||
|
||||
const hostGame = async () => {
|
||||
showHostModal.value = true
|
||||
|
||||
try {
|
||||
const response = await axios.post(`${API_BASE_URL}/games/host`, {
|
||||
type: selectedMode.value
|
||||
})
|
||||
|
||||
const gameId = response.data.id
|
||||
|
||||
console.log('Game hosted:', gameId)
|
||||
|
||||
router.push({
|
||||
name: 'multiplayer-game',
|
||||
params: { id: gameId },
|
||||
query: { type: selectedMode.value }
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Failed to host game:', error)
|
||||
console.error('Error details:', error.response?.data)
|
||||
showHostModal.value = false
|
||||
alert('Failed to host game: ' + (error.response?.data?.message || error.message))
|
||||
}
|
||||
}
|
||||
|
||||
const joinGame = async (game) => {
|
||||
selectedGame.value = game
|
||||
|
||||
try {
|
||||
await axios.post(`${API_BASE_URL}/games/${game.id}/join`)
|
||||
|
||||
console.log('Joined game:', game.id)
|
||||
|
||||
router.push({
|
||||
name: 'multiplayer-game',
|
||||
params: { id: game.id },
|
||||
query: { type: selectedMode.value }
|
||||
})
|
||||
} catch (error) {
|
||||
console.error('Failed to join game:', error)
|
||||
console.error('Error details:', error.response?.data)
|
||||
alert('Failed to join game: ' + (error.response?.data?.message || error.message))
|
||||
}
|
||||
}
|
||||
|
||||
</script>
|
||||
|
||||
<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 pb-10 px-4">
|
||||
|
||||
<Card v-if="publicStats" class="w-full max-w-2xl border-[#a855f7] bg-[#f8f0ff] shadow-sm">
|
||||
@@ -284,91 +344,72 @@ const joinGame = async (game) => {
|
||||
|
||||
<div class="relative w-full max-w-md bg-card rounded-lg border shadow-sm overflow-hidden">
|
||||
<div class="relative h-14 flex items-center">
|
||||
|
||||
<button @click="clickMode('9')"
|
||||
class="h-full flex items-center justify-center font-semibold transition-all duration-500 ease-in-out border-r last:border-r-0"
|
||||
:class="{
|
||||
'w-2/3 z-10 text-purple-600 dark:text-purple-400 bg-purple-500/10': selectedMode === '9',
|
||||
'w-1/3 z-0 text-muted-foreground/40 bg-transparent': selectedMode !== '9'
|
||||
}">
|
||||
:class="{ 'w-2/3 z-10 text-purple-600 bg-purple-500/10': selectedMode === '9', 'w-1/3 z-0 text-muted-foreground/40': selectedMode !== '9' }">
|
||||
<span>Bisca de 9</span>
|
||||
</button>
|
||||
|
||||
<button @click="clickMode('3')"
|
||||
class="h-full flex items-center justify-center font-semibold transition-all duration-500 ease-in-out"
|
||||
:class="{
|
||||
'w-2/3 z-10 text-purple-600 dark:text-purple-400 bg-purple-500/10': selectedMode === '3',
|
||||
'w-1/3 z-0 text-muted-foreground/40 bg-transparent': selectedMode !== '3'
|
||||
}">
|
||||
:class="{ 'w-2/3 z-10 text-purple-600 bg-purple-500/10': selectedMode === '3', 'w-1/3 z-0 text-muted-foreground/40': selectedMode !== '3' }">
|
||||
<span>Bisca de 3</span>
|
||||
</button>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-col items-center gap-5 w-[100vw]">
|
||||
<Card class="w-full max-w-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle class="text-3xl font-bold text-center">
|
||||
Single Player
|
||||
</CardTitle>
|
||||
<CardDescription class="text-center">
|
||||
Go against one of our bots!
|
||||
</CardDescription>
|
||||
<CardTitle class="text-3xl font-bold text-center">Single Player</CardTitle>
|
||||
<CardDescription class="text-center">Go against one of our bots!</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-6">
|
||||
<div class="flex justify-center">
|
||||
<Button @click="startSingle()" size="lg" variant="secondary"
|
||||
class="hover:bg-purple-500 hover:text-slate-200">
|
||||
<Button @click="startSingle()" size="lg" variant="secondary" class="hover:bg-purple-500 hover:text-slate-200">
|
||||
Start Game
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<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>
|
||||
</CardHeader>
|
||||
|
||||
<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">
|
||||
<label class="text-sm font-bold uppercase tracking-wider text-muted-foreground">Open Matches (Best of 3)</label>
|
||||
<Button v-if="isLoggedIn" @click="openHostModal(true)" size="sm" variant="outline" class="border-purple-500 text-purple-500 hover:bg-purple-500 hover:text-white 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 macthes yet. Try hosting one!
|
||||
<div v-if="openMatches.length === 0" class="p-6 text-center text-sm text-muted-foreground">
|
||||
No open matches.
|
||||
</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"
|
||||
<div v-for="(match, index) in openMatches" :key="match.id" @click="joinMatch(match)"
|
||||
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">
|
||||
<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 class="font-medium text-sm flex items-center gap-2">
|
||||
Match #{{ match.id }}
|
||||
<span class="flex items-center text-xs bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded-full">
|
||||
<Coins class="w-3 h-3 mr-1" /> {{ match.stake || match.wager }}
|
||||
</span>
|
||||
</div>
|
||||
<div class="text-[10px] text-muted-foreground">Host: {{ match.player1?.nickname || 'Unknown' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div ref="mObserverTarget" class="h-10 flex items-center justify-center">
|
||||
<span v-if="mLoading" class="text-xs text-purple-500 animate-pulse">Loading
|
||||
matches...</span>
|
||||
<span v-if="mLoading" class="text-xs text-purple-500 animate-pulse">Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -376,211 +417,60 @@ const joinGame = async (game) => {
|
||||
|
||||
<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">
|
||||
<label class="text-sm font-medium uppercase tracking-wider text-muted-foreground">Open Games (Single)</label>
|
||||
<Button v-if="isLoggedIn" @click="openHostModal(false)" size="sm" variant="outline" class="border-purple-500 text-purple-500 hover:bg-purple-500 hover:text-white 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 v-if="openGames.length === 0" class="p-6 text-center text-sm text-muted-foreground">
|
||||
No open games.
|
||||
</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">
|
||||
<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 class="font-medium text-sm">Host: {{ game.player1?.nickname || 'Anonymous' }}</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>
|
||||
<span v-if="gLoading" class="text-xs text-purple-500 animate-pulse">Loading...</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="showHostModal"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
|
||||
|
||||
<div v-if="showHostModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
|
||||
<Card class="w-full max-w-sm border-purple-500 shadow-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle class="text-center">Hosting Game</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="flex flex-col items-center gap-6 py-10">
|
||||
<CardHeader><CardTitle class="text-center">{{ isBestOfThree ? 'Host Match (Best of 3)' : 'Host Game' }}</CardTitle></CardHeader>
|
||||
<CardContent class="flex flex-col gap-6 py-4">
|
||||
<div v-if="isBestOfThree" class="space-y-2">
|
||||
<Label>Wager (Coins)</Label>
|
||||
<div class="relative">
|
||||
<div
|
||||
class="h-16 w-16 animate-spin rounded-full border-4 border-purple-500 border-t-transparent">
|
||||
<Coins class="absolute left-3 top-2.5 h-4 w-4 text-yellow-500" />
|
||||
<Input v-model="wagerAmount" type="number" min="0" class="pl-9" />
|
||||
</div>
|
||||
<p class="text-xs text-muted-foreground text-right">Balance: {{ userCoins }}</p>
|
||||
</div>
|
||||
<p class="animate-pulse text-lg font-medium text-muted-foreground">Waiting for opponents...</p>
|
||||
<Button variant="outline" @click="showHostModal = false">Cancel Hosting</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
<div v-if="showJoinModal"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
|
||||
<Card class="w-full max-w-md border-purple-500 shadow-2xl">
|
||||
<CardHeader>
|
||||
<CardTitle>Join Game</CardTitle>
|
||||
<CardDescription v-if="selectedGame">
|
||||
Hosted by {{ selectedGame.player1?.nickname || 'Anonymous' }}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent class="space-y-4">
|
||||
<div class="rounded-lg bg-muted p-4 text-sm">
|
||||
<p><strong>Game Type:</strong> Bisca de {{ selectedMode }}</p>
|
||||
<p><strong>Started at:</strong> {{ selectedGame?.began_at }}</p>
|
||||
</div>
|
||||
|
||||
<div v-if="isReady"
|
||||
class="flex items-center justify-center rounded-md bg-green-500/10 p-3 text-green-600 dark:text-green-400">
|
||||
<span class="animate-pulse font-semibold">Waiting for the host to start...</span>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-3 pt-4">
|
||||
<Button variant="destructive" class="flex-1" @click="showJoinModal = false">
|
||||
Leave
|
||||
</Button>
|
||||
|
||||
<Button class="flex-1 transition-all duration-300" :variant="isReady ? 'outline' : 'default'"
|
||||
:class="!isReady ? 'bg-purple-600 hover:bg-purple-700' : ''" @click="toggleReady">
|
||||
{{ isReady ? 'Cancel Ready' : 'Ready up' }}
|
||||
<div class="flex gap-2">
|
||||
<Button variant="outline" class="flex-1" @click="showHostModal = false" :disabled="hostLoading">Cancel</Button>
|
||||
<Button class="flex-1 bg-purple-600 hover:bg-purple-700" @click="hostGame" :disabled="hostLoading">
|
||||
{{ hostLoading ? 'Creating...' : 'Create' }}
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</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>
|
||||
</template>
|
||||
|
||||
@@ -605,7 +605,8 @@
|
||||
</div>
|
||||
|
||||
<div class="text-right">
|
||||
<div class="font-bold text-sm">{{ game.amount }} pts</div>
|
||||
|
||||
<div class="font-bold text-sm">{{ game.points }} pts</div>
|
||||
<div class="text-[10px] text-muted-foreground">
|
||||
{{ new Date(game.began_at).toLocaleDateString() }} •
|
||||
{{
|
||||
@@ -1151,10 +1152,15 @@ const fetchData = async () => {
|
||||
|
||||
return {
|
||||
id: game.id,
|
||||
player1_id: game.player1.id,
|
||||
player2_id: game.player2.id,
|
||||
variant: `Type ${game.type}`,
|
||||
outcome: outcome,
|
||||
opponent: null,
|
||||
amount: game.total_points || 0,
|
||||
points: game.player1_user_id === authStore.currentUser.id
|
||||
? game.player1_points
|
||||
: game.player2_points,
|
||||
duration: `${Math.floor(game.total_time / 60)}m ${game.total_time % 60}s`,
|
||||
began_at: game.began_at,
|
||||
details: {
|
||||
|
||||
@@ -4,6 +4,7 @@ import UserPage from '@/pages/user/UserPage.vue'
|
||||
import { createRouter, createWebHistory } from 'vue-router'
|
||||
import SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue'
|
||||
import MultiplayerGamePage from '@/pages/game/MultiplayerGamePage.vue'
|
||||
import MultiplayerMatchPage from '@/pages/game/MultiplayerMatchPage.vue'
|
||||
import RegisterPage from '@/pages/register/RegisterPage.vue'
|
||||
import CoinsPurchasePage from '@/pages/purchase/CoinPurchasePage.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
@@ -48,6 +49,12 @@ const router = createRouter({
|
||||
component: MultiplayerGamePage,
|
||||
meta: { requiresAuth: true },
|
||||
},
|
||||
{
|
||||
path: '/match/:id',
|
||||
name: 'multiplayer-match',
|
||||
component: MultiplayerMatchPage,
|
||||
meta: { requiresAuth: true }
|
||||
},
|
||||
{
|
||||
path: '/user',
|
||||
component: UserPage,
|
||||
|
||||
@@ -92,7 +92,6 @@ export const useSocketStore = defineStore('websocket', () => {
|
||||
socket.value.emit('play-card', { gameId, cardId })
|
||||
}
|
||||
|
||||
// --- NEW: Surrender Action ---
|
||||
const surrender = (gameId) => {
|
||||
if (!socket.value?.connected) return
|
||||
console.log('[Game] Surrendering:', gameId)
|
||||
|
||||
Generated
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "DADProject",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
||||
@@ -189,7 +189,9 @@ class BiscaGame {
|
||||
this.players[winnerId].tricks += 1;
|
||||
this.currentTurn = winnerId;
|
||||
|
||||
if (this.type == 3) {
|
||||
// --- CRITICAL FIX: Always draw if cards remain ---
|
||||
// Removed "if (this.type == 3)" check
|
||||
if (this.deck.length > 0 || this.trumpCard) {
|
||||
this.drawCard(winnerId);
|
||||
this.drawCard(this.getOpponentId(winnerId));
|
||||
}
|
||||
@@ -221,7 +223,7 @@ class BiscaGame {
|
||||
? p2Obj.id
|
||||
: p1Obj.id;
|
||||
|
||||
return {
|
||||
const result = {
|
||||
action: "game_ended",
|
||||
trickResult,
|
||||
winnerId: finalWinner,
|
||||
@@ -233,6 +235,7 @@ class BiscaGame {
|
||||
player2_points: p2Obj.points,
|
||||
totalTime: totalTime,
|
||||
};
|
||||
|
||||
if (this.onGameEnd) {
|
||||
this.onGameEnd(result);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@ import axios from "axios";
|
||||
const API_URL = "http://localhost:8000/api/v1";
|
||||
|
||||
class BiscaMatch {
|
||||
constructor(apiData, emitStateCallback, token) {
|
||||
// FIX: Added autoPlayCallback parameter
|
||||
constructor(apiData, emitStateCallback, token, autoPlayCallback) {
|
||||
this.id = apiData.id;
|
||||
this.emitStateCallback = emitStateCallback;
|
||||
this.autoPlayCallback = autoPlayCallback;
|
||||
this.token = token;
|
||||
this.stake = apiData.stake;
|
||||
this.type = apiData.type;
|
||||
@@ -14,6 +16,8 @@ class BiscaMatch {
|
||||
|
||||
this.player1Id = apiData.player1_user_id;
|
||||
this.player2Id = apiData.player2_user_id;
|
||||
this.player1 = apiData.player1;
|
||||
this.player2 = apiData.player2;
|
||||
|
||||
this.marks = {
|
||||
[this.player1Id]: apiData.player1_marks || 0,
|
||||
@@ -33,11 +37,12 @@ class BiscaMatch {
|
||||
}
|
||||
}
|
||||
|
||||
async joinPlayer(userId) {
|
||||
async joinPlayer(userId, user) {
|
||||
if (this.player2Id !== this.GHOST_ID) return false;
|
||||
if (userId === this.player1Id) return false;
|
||||
|
||||
this.player2Id = userId;
|
||||
this.player2 = user;
|
||||
this.marks[userId] = 0;
|
||||
this.points[userId] = 0;
|
||||
this.status = "Playing";
|
||||
@@ -48,90 +53,83 @@ class BiscaMatch {
|
||||
|
||||
getAuthHeaders() {
|
||||
return {
|
||||
headers: { Authorization: this.token },
|
||||
headers: {
|
||||
Authorization: this.token,
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async startNewGame() {
|
||||
console.log(`[Match ${this.id}] A iniciar nova mão (Game DB)...`);
|
||||
|
||||
console.log(`[Match ${this.id}] Starting new round...`);
|
||||
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,
|
||||
player1_user_id: this.player1Id,
|
||||
player2_user_id: this.player2Id,
|
||||
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 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}` };
|
||||
const p1Name = this.player1?.nickname || `User ${this.player1Id}`;
|
||||
const p2Name = this.player2?.nickname || `User ${this.player2Id}`;
|
||||
|
||||
this.currentGame = new BiscaGame(
|
||||
this.id,
|
||||
this.type,
|
||||
p1,
|
||||
p2,
|
||||
{ id: this.player1Id, name: p1Name },
|
||||
{ id: this.player2Id, name: p2Name },
|
||||
newGameDbId,
|
||||
(result) => {
|
||||
this.handleGameEnd(result);
|
||||
}
|
||||
(result) => { this.handleGameEnd(result); }
|
||||
);
|
||||
|
||||
this.currentGame.init();
|
||||
|
||||
// FIX: Start Timer & Connect Callback
|
||||
this.currentGame.startTurnTimer((uid, cid) => {
|
||||
if (this.autoPlayCallback) this.autoPlayCallback(uid, cid);
|
||||
});
|
||||
|
||||
if (this.emitStateCallback) {
|
||||
this.emitStateCallback("match:new-round", this.getState());
|
||||
this.emitStateCallback("match:new-round-start", null);
|
||||
}
|
||||
} 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}`);
|
||||
console.error(`❌ Start Game Error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// --- FIX: Close DB Game row on surrender ---
|
||||
async abortCurrentGame(loserId) {
|
||||
if (this.currentGame && this.currentGame.dbId) {
|
||||
console.log(`[Match ${this.id}] Aborting Game #${this.currentGame.dbId}`);
|
||||
try {
|
||||
// Determine winner for the DB record based on who DIDN'T lose
|
||||
const winnerId = loserId == this.player1Id ? this.player2Id : this.player1Id;
|
||||
|
||||
const payload = {
|
||||
status: "Ended",
|
||||
winner_user_id: winnerId,
|
||||
loser_user_id: loserId,
|
||||
is_draw: false,
|
||||
ended_at: new Date().toISOString(),
|
||||
};
|
||||
await axios.put(`${API_URL}/games/${this.currentGame.dbId}`, payload, this.getAuthHeaders());
|
||||
} catch(e) { console.error("Error aborting game:", e.message); }
|
||||
}
|
||||
}
|
||||
|
||||
async handleGameEnd(result) {
|
||||
console.log(
|
||||
`[Match ${this.id}] Mão terminada. Vencedor: ${result.winnerId}`
|
||||
);
|
||||
console.log(`[Match ${this.id}] Round ended. Winner: ${result.winnerId}`);
|
||||
|
||||
this.points[result.player1_id] += result.player1_points;
|
||||
this.points[result.player2_id] += result.player2_points;
|
||||
if (this.points[result.player1_id] !== undefined) this.points[result.player1_id] += result.player1_points;
|
||||
if (this.points[result.player2_id] !== undefined) this.points[result.player2_id] += result.player2_points;
|
||||
|
||||
if (this.currentGame && this.currentGame.dbId) {
|
||||
try {
|
||||
@@ -144,81 +142,50 @@ class BiscaMatch {
|
||||
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.");
|
||||
await axios.put(`${API_URL}/games/${this.currentGame.dbId}`, payload, this.getAuthHeaders());
|
||||
} catch (e) { console.error("DB Game Update Error:", e.message); }
|
||||
}
|
||||
|
||||
// ... (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;
|
||||
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[roundWinnerId] !== undefined) this.marks[roundWinnerId] += marksToAdd;
|
||||
}
|
||||
|
||||
if (this.emitStateCallback) {
|
||||
this.emitStateCallback("match:round-ended", {
|
||||
winnerId: roundWinnerId,
|
||||
marksAdded: marksToAdd,
|
||||
p1Points: result.player1_points,
|
||||
p2Points: result.player2_points,
|
||||
p1Marks: this.marks[this.player1Id],
|
||||
p2Marks: this.marks[this.player2Id],
|
||||
reason: result.reason || 'points'
|
||||
});
|
||||
}
|
||||
|
||||
if (this.marks[this.player1Id] >= 4 || this.marks[this.player2Id] >= 4) {
|
||||
await this.finishMatch();
|
||||
if (this.emitStateCallback) {
|
||||
this.emitStateCallback("match:ended", this.getState());
|
||||
}
|
||||
if (this.emitStateCallback) this.emitStateCallback("match:ended-signal", null);
|
||||
} else {
|
||||
console.log(`[Match ${this.id}] Ninguém ganhou 4 marcas. A baralhar...`);
|
||||
await this.startNewGame();
|
||||
setTimeout(() => {
|
||||
this.startNewGame();
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
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}`,
|
||||
{
|
||||
const payload = {
|
||||
status: "Ended",
|
||||
winner_user_id: winnerId,
|
||||
loser_user_id: loserId,
|
||||
@@ -226,48 +193,45 @@ class BiscaMatch {
|
||||
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.`);
|
||||
};
|
||||
|
||||
try {
|
||||
await axios.put(`${API_URL}/matches/${this.id}`, payload, this.getAuthHeaders());
|
||||
console.log(`[Match ${this.id}] Match Closed in DB.`);
|
||||
} catch (e) {
|
||||
console.error(`Erro ao fechar Match API: ${e.message}`);
|
||||
console.error(`Match Close Error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
playCard(userId, cardId) {
|
||||
if (!this.currentGame || this.status !== "Playing") return;
|
||||
return this.currentGame.playCard(userId, cardId);
|
||||
|
||||
const result = this.currentGame.playCard(userId, cardId);
|
||||
|
||||
// FIX: Restart timer if game continues
|
||||
if (result && (result.action === 'next_turn' || result.action === 'trick_resolved')) {
|
||||
this.currentGame.startTurnTimer((uid, cid) => {
|
||||
if (this.autoPlayCallback) this.autoPlayCallback(uid, cid);
|
||||
});
|
||||
}
|
||||
|
||||
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 result;
|
||||
}
|
||||
|
||||
getGameState(userId) {
|
||||
if (!this.currentGame) return null;
|
||||
if (this.currentGame.players[userId]) return this.currentGame.getStateForPlayer(userId);
|
||||
return null;
|
||||
}
|
||||
|
||||
getPublicState() {
|
||||
return {
|
||||
matchId: this.id,
|
||||
status: this.status,
|
||||
marks: this.marks,
|
||||
points: this.points,
|
||||
game: gameState,
|
||||
player1: this.player1,
|
||||
player2: this.player2
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -96,6 +96,7 @@ const performGameEnd = (io, game, gameId, winnerId, loserId, reason) => {
|
||||
action: "game_ended",
|
||||
winnerId: parseInt(winnerId),
|
||||
loserId: parseInt(loserId),
|
||||
totalTime: game.startTime ? Math.floor((Date.now() - game.startTime) / 1000) : 0,
|
||||
isDraw: false,
|
||||
player1_points: game.players[Object.keys(game.players)[0]]?.points || 0,
|
||||
player2_points: game.players[Object.keys(game.players)[1]]?.points || 0,
|
||||
@@ -248,6 +249,7 @@ export default (io, socket) => {
|
||||
}
|
||||
|
||||
socket.join(`game_${gameId}`);
|
||||
socket.activeGameId = gameId;
|
||||
|
||||
if (game.players[myId]) {
|
||||
game.players[myId].token = socket.handshake.auth.token;
|
||||
|
||||
+104
-84
@@ -5,134 +5,154 @@ import axios from "axios";
|
||||
const API_URL = "http://localhost:8000/api/v1";
|
||||
|
||||
export default (io, socket) => {
|
||||
|
||||
const broadcastMatchUpdate = (matchId, match) => {
|
||||
const roomName = `match_${matchId}`;
|
||||
const room = io.sockets.adapter.rooms.get(roomName);
|
||||
if (room) {
|
||||
for (const socketId of room) {
|
||||
const clientSocket = io.sockets.sockets.get(socketId);
|
||||
if (!clientSocket || !clientSocket.user) continue;
|
||||
const userId = clientSocket.user.id;
|
||||
const publicState = match.getPublicState();
|
||||
const gameState = match.getGameState(userId);
|
||||
clientSocket.emit("match:update", { ...publicState, game: gameState });
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const createMatchEmitter = (matchId) => (eventName, payload) => {
|
||||
const match = getMatch(matchId);
|
||||
if (!match) return;
|
||||
|
||||
if (eventName === 'match:new-round-start' || eventName === 'match:ended-signal') {
|
||||
broadcastMatchUpdate(matchId, match);
|
||||
} else if (eventName === 'match:round-ended') {
|
||||
io.to(`match_${matchId}`).emit('match:round-ended', payload);
|
||||
} else {
|
||||
io.to(`match_${matchId}`).emit(eventName, payload);
|
||||
}
|
||||
};
|
||||
|
||||
// --- FIX: Timer Callback ---
|
||||
const handleAutoPlay = (matchId) => (userId, cardId) => {
|
||||
const match = getMatch(matchId);
|
||||
if (!match || match.status !== "Playing") return;
|
||||
|
||||
console.log(`[Match ${matchId}] Auto-playing for User ${userId}`);
|
||||
const result = match.playCard(userId, cardId);
|
||||
|
||||
if (result && result.action === "trick_resolved") {
|
||||
io.to(`match_${matchId}`).emit("game:trick-end", result.trickResult);
|
||||
setTimeout(() => { broadcastMatchUpdate(matchId, match); }, 1500);
|
||||
} else {
|
||||
broadcastMatchUpdate(matchId, match);
|
||||
}
|
||||
};
|
||||
|
||||
socket.on("match:enter", async (data) => {
|
||||
const { matchId } = data;
|
||||
|
||||
if (!socket.user || !socket.user.id) {
|
||||
return socket.emit("error", { message: "User not authenticated" });
|
||||
}
|
||||
|
||||
if (!socket.user || !socket.user.id) return socket.emit("error", { message: "Auth failed" });
|
||||
const userId = socket.user.id;
|
||||
const room = `match_${matchId}`;
|
||||
socket.activeMatchId = matchId;
|
||||
|
||||
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 },
|
||||
headers: { Authorization: socket.token || socket.handshake.auth.token },
|
||||
});
|
||||
|
||||
const matchData = res.data.data || res.data;
|
||||
|
||||
// Pass handleAutoPlay to constructor
|
||||
match = new BiscaMatch(
|
||||
matchData,
|
||||
createMatchEmitter(matchId),
|
||||
socket.token
|
||||
socket.token,
|
||||
handleAutoPlay(matchId)
|
||||
);
|
||||
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;
|
||||
return socket.emit("error", "Match not found");
|
||||
}
|
||||
} 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);
|
||||
}
|
||||
if (userId !== match.player1Id && match.player2Id === 1) await match.joinPlayer(userId, socket.user);
|
||||
|
||||
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..." });
|
||||
}
|
||||
const publicState = match.getPublicState();
|
||||
const gameState = match.getGameState(userId);
|
||||
socket.emit("match:update", { ...publicState, game: gameState });
|
||||
if (match.status === 'Playing') broadcastMatchUpdate(matchId, match);
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
if (!match || match.status !== "Playing") 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)
|
||||
);
|
||||
if (result && result.error) return socket.emit("error", { message: result.error });
|
||||
if (result && result.action === "trick_resolved") {
|
||||
io.to(`match_${matchId}`).emit("game:trick-end", result.trickResult);
|
||||
setTimeout(() => { broadcastMatchUpdate(matchId, match); }, 1500);
|
||||
} else {
|
||||
broadcastMatchUpdate(matchId, match);
|
||||
}
|
||||
});
|
||||
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,
|
||||
socket.on("game:surrender", async ({ matchId }) => {
|
||||
const match = getMatch(matchId);
|
||||
if(!match || match.status !== "Playing") return;
|
||||
const userId = socket.user.id;
|
||||
console.log(`[Match ${matchId}] User ${userId} surrendered ROUND.`);
|
||||
const opponentId = match.player1Id == userId ? match.player2Id : match.player1Id;
|
||||
const result = {
|
||||
winnerId: opponentId,
|
||||
loserId: userId,
|
||||
isDraw: false,
|
||||
player1_points: winnerId == match.player1Id ? 120 : 0,
|
||||
player2_points: winnerId == match.player2Id ? 120 : 0,
|
||||
player1_id: match.player1Id,
|
||||
player2_id: match.player2Id,
|
||||
player1_points: match.player1Id == opponentId ? 91 : 0,
|
||||
player2_points: match.player2Id == opponentId ? 91 : 0,
|
||||
reason: 'surrender'
|
||||
};
|
||||
|
||||
await match.handleGameEnd(fakeResult);
|
||||
}
|
||||
await match.handleGameEnd(result);
|
||||
});
|
||||
|
||||
// DEBUG: Forçar fim do Match Completo
|
||||
socket.on("debug:end-match", async (data) => {
|
||||
const { matchId } = data;
|
||||
socket.on("match:surrender", async ({ matchId }) => {
|
||||
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();
|
||||
if(!match || match.status !== "Playing") return;
|
||||
const userId = socket.user.id;
|
||||
|
||||
// Emite o estado final
|
||||
io.to(`match_${matchId}`).emit("match:ended", match.getState());
|
||||
// FIX: Abort current game to remove ghost
|
||||
await match.abortCurrentGame(userId);
|
||||
|
||||
console.log(`[Match ${matchId}] User ${userId} surrendered MATCH.`);
|
||||
const opponentId = match.player1Id == userId ? match.player2Id : match.player1Id;
|
||||
match.marks[opponentId] = 4;
|
||||
await match.finishMatch();
|
||||
broadcastMatchUpdate(matchId, match);
|
||||
});
|
||||
|
||||
socket.on("disconnect", async () => {
|
||||
if (socket.activeMatchId) {
|
||||
const match = getMatch(socket.activeMatchId);
|
||||
if (match && match.status === 'Playing') {
|
||||
const userId = socket.user?.id;
|
||||
if (userId === match.player1Id || userId === match.player2Id) {
|
||||
console.log(`[Match ${match.id}] Player ${userId} disconnected.`);
|
||||
|
||||
// FIX: Abort current game
|
||||
await match.abortCurrentGame(userId);
|
||||
|
||||
const opponentId = match.player1Id == userId ? match.player2Id : match.player1Id;
|
||||
match.marks[opponentId] = 4;
|
||||
await match.finishMatch();
|
||||
broadcastMatchUpdate(match.id, match);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
+65
-1
@@ -11,6 +11,11 @@ export const server = {
|
||||
|
||||
const API_URL = "http://localhost:8000/api/v1";
|
||||
|
||||
const disconnectTimers = new Map();
|
||||
const RECONNECT_GRACE_PERIOD = 1 * 60 * 1000; // 1 minutes
|
||||
|
||||
const userId = (socket) => socket.user && socket.user.id;
|
||||
|
||||
export const serverStart = (port) => {
|
||||
server.io = new Server(port, {
|
||||
cors: {
|
||||
@@ -47,6 +52,12 @@ export const serverStart = (port) => {
|
||||
socket.token = token;
|
||||
socket.handshake.auth.token = token;
|
||||
|
||||
if (disconnectTimers.has(user.id)) {
|
||||
console.log(`[Connection] User ${user.id} reconnected! Cancelling surrender timer.`);
|
||||
clearTimeout(disconnectTimers.get(user.id));
|
||||
disconnectTimers.delete(user.id);
|
||||
}
|
||||
|
||||
addUser(socket.id, user);
|
||||
|
||||
next();
|
||||
@@ -66,13 +77,66 @@ export const serverStart = (port) => {
|
||||
|
||||
server.io.on("connection", (socket) => {
|
||||
gameEvents(server.io, socket);
|
||||
|
||||
matchEvents(server.io, socket);
|
||||
|
||||
handleConnectionEvents(server.io, socket);
|
||||
|
||||
socket.on("notify_disconnect", () => {
|
||||
socket.isVoluntaryDisconnect = true;
|
||||
});
|
||||
|
||||
socket.on("disconnect", () => {
|
||||
// Remove from active socket list
|
||||
removeUser(socket.id);
|
||||
|
||||
if (socket.isVoluntaryDisconnect) {
|
||||
console.log(`[Disconnect] User ${userId} disconnected voluntarily. No surrender needed.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (userId) {
|
||||
console.log(`[Disconnect] User ${userId} disconnected. Waiting ${RECONNECT_GRACE_PERIOD / 1000}s...`);
|
||||
|
||||
// -----------------------------------------------------------
|
||||
// 2. START SURRENDER TIMER
|
||||
// -----------------------------------------------------------
|
||||
const timer = setTimeout(async () => {
|
||||
console.log(`[Timeout] User ${userId} did not return. Forcing surrender.`);
|
||||
|
||||
// A. Find the Game ID this user is playing (You need a way to look this up)
|
||||
// Ideally, your 'socket' object or a global map knows which gameID the user is in.
|
||||
// For this example, let's assume you stored `socket.activeGameId` when they joined.
|
||||
const gameId = socket.activeGameId;
|
||||
|
||||
if (gameId) {
|
||||
try {
|
||||
// B. Call Laravel API to resign on their behalf
|
||||
// We use the token we saved during the handshake
|
||||
await axios.post(`${API_URL}/games/${gameId}/resign`, {}, {
|
||||
headers: {
|
||||
Authorization: socket.handshake.auth.token,
|
||||
Accept: "application/json"
|
||||
}
|
||||
});
|
||||
|
||||
// C. Notify the room (The API likely triggers a Pusher/Socket event,
|
||||
// but we can also emit locally if needed)
|
||||
server.io.to(gameId).emit("game_over", {
|
||||
winner: "opponent",
|
||||
reason: "disconnect"
|
||||
});
|
||||
|
||||
console.log(`[Timeout] Successfully resigned game ${gameId} for user ${userId}`);
|
||||
} catch (err) {
|
||||
console.error(`[Timeout] Failed to resign game for user ${userId}:`, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
disconnectTimers.delete(userId);
|
||||
}, RECONNECT_GRACE_PERIOD);
|
||||
|
||||
disconnectTimers.set(userId, timer);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
@@ -32,3 +32,4 @@ export const removeGame = (id) => {
|
||||
console.log(`[Game State] Game removed: ${id}`);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user