Merge pull request 'feature/multiplayer-game-interface' (#94) from feature/multiplayer-game-interface into develop

Reviewed-on: https://gitea.fernandovideira.com/SyntaxSquad/DADProject/pulls/94
Reviewed-by: FernandoJVideira <[email protected]>
Reviewed-by: Edd <[email protected]>
Reviewed-by: KZix <[email protected]>
This commit was merged in pull request #94.
This commit is contained in:
2026-01-02 19:18:04 +00:00
15 changed files with 828 additions and 295 deletions
+18 -26
View File
@@ -89,34 +89,26 @@ class GameController extends Controller
], 201); ], 201);
} }
public function join(Game $game) public function join(Request $request, Game $game)
{ {
$this->authorize('join', $game); // Prevent joining if already full or started
if ($game->status !== 'Pending' || $game->player2_user_id !== 1) {
$user = Auth::user(); return response()->json(['message' => 'Game is not available'], 400);
if ($game->player1_user_id == $user->id) {
return response()->json([
"message" => "You are the host. Waiting for opponent...",
"game" => $game
], 200);
}
if ($game->player2_user_id !== self::GHOST_ID) {
return response()->json(["message" => "Game is full"], 400);
}
$game->update([
"status" => "Playing",
"player2_user_id" => $user->id,
]);
return response()->json([
"message" => "Joined successfully!",
"game" => $game,
], 200);
} }
// Prevent joining your own game
if ($game->player1_user_id === $request->user()->id) {
return response()->json(['message' => 'Cannot join your own game'], 400);
}
$game->update([
'player2_user_id' => $request->user()->id,
'status' => 'Playing',
]);
return response()->json($game);
}
public function show(Game $game) public function show(Game $game)
{ {
$this->authorize('view', $game); $this->authorize('view', $game);
+11
View File
@@ -29,11 +29,22 @@ class Game extends Model
'match_id' 'match_id'
]; ];
protected $casts = [
'began_at' => 'datetime',
'ended_at' => 'datetime',
'is_draw' => 'boolean',
];
public function winner() public function winner()
{ {
return $this->belongsTo(User::class, "winner_user_id"); return $this->belongsTo(User::class, "winner_user_id");
} }
public function loser()
{
return $this->belongsTo(User::class, "loser_user_id");
}
public function player1() public function player1()
{ {
return $this->belongsTo(User::class, 'player1_user_id'); return $this->belongsTo(User::class, 'player1_user_id');
+39 -13
View File
@@ -47,24 +47,50 @@ Route::prefix('v1')->group(function () {
Route::get('/{user}/transactions', [UserController::class, 'getTransactions']); Route::get('/{user}/transactions', [UserController::class, 'getTransactions']);
}); });
// Game Resources
Route::prefix('games')->group(function () { Route::prefix('games')->group(function () {
Route::apiResource('/', GameController::class)->parameters([ //Host a new multiplayer game - MUST come before resource routes
'' => 'game', Route::post('host', function (\Illuminate\Http\Request $request) {
]); $request->validate([
Route::post('/{game}/join', [GameController::class, 'join']); 'type' => 'required|in:3,9'
]);
$game = \App\Models\Game::create([
'type' => $request->type,
'status' => 'Pending',
'player1_user_id' => $request->user()->id,
'player2_user_id' => 1, // Ghost player
'began_at' => now(),
]);
return response()->json($game);
});
// List open games (available to join)
Route::get('open', function (\Illuminate\Http\Request $request) {
$type = $request->query('type', '9');
$games = \App\Models\Game::where('status', 'Pending')
->where('player2_user_id', 1) // Only games waiting for a second player
->where('type', $type)
->with('player1') // Load player1 relationship
->orderBy('began_at', 'asc')
->paginate(10);
return response()->json($games);
});
Route::get('/', [GameController::class, 'index']);
Route::get('/{game}', [GameController::class, 'show']);
Route::post('/', [GameController::class, 'store']);
Route::put('/{game}', [GameController::class, 'update']);
Route::delete('/{game}', [GameController::class, 'destroy']);
Route::post('/{game}/resign', [GameController::class, 'resign']); Route::post('/{game}/resign', [GameController::class, 'resign']);
Route::post('/{game}/join', [GameController::class, 'join']);
}); });
// Match Resources
Route::prefix('matches')->group(function () { Route::prefix('matches')->group(function () {
Route::apiResource('/', MatchController::class)->parameters([ Route::apiResource('/', MatchController::class)->parameters(['' => 'match']);
'' => 'match', Route::post('/{match}/join', [MatchController::class, 'join']);
]);
Route::post('/{match}/join', [
MatchController::class,
'join',
]);
}); });
// Admin Routes // Admin Routes
+2 -1
View File
@@ -42,7 +42,8 @@ const logout = () => {
onMounted(async () => { onMounted(async () => {
await authStore.restoreSession() await authStore.restoreSession()
socketStore.handleConnection() // REMOVED - The WebSocket for multiplayer is handled separately in the WebSocketStore
// socketStore.handleConnection()
}) })
</script> </script>
@@ -7,6 +7,8 @@
:player-score="playerScore" :player-score="playerScore"
:opponent-score="opponentScore" :opponent-score="opponentScore"
:current-turn="currentTurn" :current-turn="currentTurn"
:player-name="playerName"
:opponent-name="opponentName"
:round-number="1" :round-number="1"
/> />
</div> </div>
@@ -62,16 +64,20 @@ const props = defineProps({
// REMOVIDO: playableCardIndices (já não precisamos dele) // REMOVIDO: playableCardIndices (já não precisamos dele)
playerScore: { type: Number, default: 0 }, playerScore: { type: Number, default: 0 },
opponentScore: { type: Number, default: 0 }, opponentScore: { type: Number, default: 0 },
playerName: { type: String, default: 'You' },
opponentName: { type: String, default: 'Bot' },
currentTurn: { currentTurn: {
type: String, type: String,
default: 'player', default: 'player',
validator: (value) => ['player', 'opponent'].includes(value), validator: (value) => ['player', 'opponent'].includes(value),
}, },
isMyTurn: { type: Boolean, default: false },
}) })
const emit = defineEmits(['play-card']) const emit = defineEmits(['play-card'])
const handleCardClick = (payload) => { const handleCardClick = (payload) => {
if (!props.isMyTurn) return
emit('play-card', payload.card) emit('play-card', payload.card)
} }
</script> </script>
@@ -51,6 +51,10 @@ const props = defineProps({
default: 3, default: 3,
validator: (value) => [3, 9].includes(value), validator: (value) => [3, 9].includes(value),
}, },
isDisabled: {
type: Boolean,
default: false,
},
}) })
const emit = defineEmits(['card-clicked']) const emit = defineEmits(['card-clicked'])
@@ -33,7 +33,8 @@
turnChanged && 'animate-pulse', turnChanged && 'animate-pulse',
]" ]"
> >
{{ currentTurn === 'player' ? 'Your Turn' : "Bot's Turn" }} <!-- You can replace the above line with the following if you want to show names instead -->
{{ currentTurn === 'player' ? playerName + "'s Turn" : opponentName + "'s Turn" }}
</div> </div>
<span v-if="roundNumber" class="text-gray-500 text-[10px] font-medium"> <span v-if="roundNumber" class="text-gray-500 text-[10px] font-medium">
Round {{ roundNumber }} Round {{ roundNumber }}
@@ -0,0 +1,323 @@
<template>
<div class="relative min-h-screen overflow-hidden bg-green-900">
<div v-if="shouldShowBoard && !gameOver" class="absolute top-4 right-4 z-50">
<button
@click="handleSurrender"
class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all transform hover:scale-105 flex items-center gap-2"
>
<span>🏳</span> Surrender
</button>
</div>
<div v-if="!wsStore.connected && hasConnectedOnce" class="absolute top-4 left-4 z-50 flex items-center gap-2 bg-gray-800 px-4 py-2 rounded-lg border border-gray-700 shadow-xl">
<div class="w-3 h-3 rounded-full bg-red-500 animate-pulse"></div>
<span class="text-white text-sm">Reconnecting...</span>
</div>
<div v-if="shouldShowBoard && !gameOver && isMyTurn" class="absolute top-4 left-1/2 -translate-x-1/2 z-50">
<div class="bg-gray-800 px-6 py-3 rounded-lg border-2 shadow-xl transition-colors duration-300"
:class="timeLeft <= 5 ? 'border-red-500 bg-red-900/20' : 'border-gray-700'">
<div class="flex items-center gap-3">
<svg class="w-6 h-6" :class="timeLeft <= 5 ? 'text-red-500 animate-bounce' : 'text-white'" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<circle cx="12" cy="12" r="10" stroke-width="2"/>
<polyline points="12 6 12 12 16 14" stroke-width="2"/>
</svg>
<span :class="['text-3xl font-mono font-bold', timeLeft <= 5 ? 'text-red-500' : 'text-white']">
{{ timeLeft }}
</span>
</div>
</div>
</div>
<div v-if="shouldShowBoard">
<GameBoard
:trump-card="trumpCard"
:cards-remaining="deckCount + (trumpCard ? 1 : 0)"
:player-hand="visibleHand"
:opponent-hand="opponentHand"
:player-score="playerScore"
:opponent-score="opponentScore"
:player-name="myDisplayName"
:opponent-name="opponentDisplayName"
:current-turn="currentTurnLabel"
:current-trick="displayedTrick"
:is-my-turn="isMyTurn"
@play-card="handlePlayCard"
/>
</div>
<div v-else-if="!gameOver" class="flex h-screen items-center justify-center bg-green-900 text-white">
<div class="text-center p-8 bg-green-800/50 rounded-2xl border border-green-700 shadow-2xl backdrop-blur-sm">
<div class="relative mx-auto mb-6 h-16 w-16">
<div class="absolute inset-0 rounded-full border-4 border-green-600"></div>
<div class="absolute inset-0 rounded-full border-4 border-t-white border-r-transparent border-b-transparent border-l-transparent animate-spin"></div>
</div>
<h2 class="text-2xl font-bold mb-2">
Waiting for Opponent...
</h2>
<p class="text-green-100 mb-8 max-w-sm">
Share the game code or wait for a player to join your lobby.
</p>
<button
@click="handleCloseModal"
class="px-6 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-all shadow-lg hover:shadow-red-500/20"
>
Cancel & Return Home
</button>
</div>
</div>
<GameOver
:is-visible="gameOver"
:winner="winnerResult"
:player-score="playerScore"
:opponent-score="opponentScore"
:player-name="myDisplayName"
:opponent-name="opponentDisplayName"
:stats="{ playerTricks: 0, opponentTricks: 0 }"
:is-logging-out="false"
@play-again="handleCloseModal"
@close="handleCloseModal"
/>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted, watch, inject } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useSocketStore } from '@/stores/socket'
import { useAuthStore } from '@/stores/auth'
import { toast } from 'vue-sonner'
import axios from 'axios'
import GameBoard from '@/components/game/GameBoard.vue'
import GameOver from '@/components/game/GameOver.vue'
const route = useRoute()
const router = useRouter()
const wsStore = useSocketStore()
const authStore = useAuthStore()
const API_BASE_URL = inject('apiBaseURL')
const gameId = ref(route.params.id)
const visibleHand = ref([])
const gameOver = ref(false)
const isDealing = ref(false)
const hasInitialDealHappened = ref(false)
const winnerResult = ref('draw')
const timeLeft = ref(20)
const timerInterval = ref(null)
const hasConnectedOnce = ref(false)
const gameMetadata = ref({
p1_id: null,
p1_name: 'Player 1',
p2_id: null,
p2_name: 'Opponent'
})
const displayedTrick = ref({ playerCard: null, opponentCard: null })
const trickClearTimer = ref(null)
// --- COMPUTED ---
const myUserId = computed(() => authStore.currentUser?.id)
const shouldShowBoard = computed(() => {
const s = wsStore.gameState;
if (s && s.player2 && s.player2.id > 1) {
return true;
}
return false;
})
const amIHost = computed(() => {
if (gameMetadata.value.p1_id) {
return String(gameMetadata.value.p1_id) === String(myUserId.value)
}
const p1Id = wsStore.gameState?.player1_user_id || wsStore.gameState?.player1?.id
return String(p1Id) === String(myUserId.value)
})
const myDisplayName = computed(() => amIHost.value ? gameMetadata.value.p1_name : gameMetadata.value.p2_name)
const opponentDisplayName = computed(() => amIHost.value ? gameMetadata.value.p2_name : gameMetadata.value.p1_name)
const mappedTrick = computed(() => {
const table = wsStore.gameState?.table
if (!table) return { playerCard: null, opponentCard: null }
if (amIHost.value) {
return { playerCard: table.playerCard, opponentCard: table.opponentCard }
} else {
return { playerCard: table.opponentCard, opponentCard: table.playerCard }
}
})
const currentTurnLabel = computed(() => {
const turnId = wsStore.gameState?.currentTurn
if (!turnId) return 'player'
return String(turnId) === String(myUserId.value) ? 'player' : 'opponent'
})
const trumpCard = computed(() => wsStore.gameState?.trumpCard || null)
const deckCount = computed(() => wsStore.gameState?.deckCount || 0)
const playerScore = computed(() => wsStore.gameState?.points || 0)
const opponentScore = computed(() => wsStore.gameState?.opponent?.points || 0)
const serverHand = computed(() => wsStore.gameState?.hand || [])
const isMyTurn = computed(() => String(wsStore.gameState?.currentTurn) === String(myUserId.value))
const opponentHand = computed(() => {
const count = wsStore.gameState?.opponent?.cardCount || 0
return Array.from({ length: count }, (_, i) => ({ id: `opp-${i}`, suit: 'back', rank: 0 }))
})
// --- WATCHERS ---
watch(() => wsStore.connected, (isConnected) => {
if (isConnected) {
hasConnectedOnce.value = true
wsStore.joinGame(gameId.value)
}
}, { immediate: true })
watch(() => wsStore.gameState, async (newState, oldState) => {
const oldP2 = oldState?.player2?.id;
const newP2 = newState?.player2?.id;
if (newP2 && newP2 > 1 && newP2 !== oldP2) {
await fetchGameMetadata();
}
}, { deep: true })
watch(mappedTrick, (newVal) => {
if (newVal.playerCard || newVal.opponentCard) {
if (trickClearTimer.value) clearTimeout(trickClearTimer.value)
displayedTrick.value = { ...newVal }
} else {
const currentlyShowing = displayedTrick.value.playerCard || displayedTrick.value.opponentCard
if (currentlyShowing) {
trickClearTimer.value = setTimeout(() => {
displayedTrick.value = { playerCard: null, opponentCard: null }
}, 1500)
} else {
displayedTrick.value = { playerCard: null, opponentCard: null }
}
}
}, { deep: true })
// --- FIX: TIMER GHOSTING ---
const startTimer = () => {
if (timerInterval.value) clearInterval(timerInterval.value)
if (!shouldShowBoard.value && wsStore.gameState?.status !== 'playing') {
timeLeft.value = 20;
return;
}
// FORCE RESET to avoid showing old time for 1 frame
timeLeft.value = 20;
const startAt = wsStore.gameState?.turnStartedAt ? new Date(wsStore.gameState.turnStartedAt).getTime() : Date.now()
// Define update function
const update = () => {
const now = Date.now()
const elapsed = Math.floor((now - startAt) / 1000)
timeLeft.value = Math.max(0, 20 - elapsed)
if (timeLeft.value <= 0) clearInterval(timerInterval.value)
}
// EXECUTE IMMEDIATELY
update();
// Then set interval
timerInterval.value = setInterval(update, 1000)
}
watch(() => wsStore.gameState?.currentTurn, (newTurn) => {
if (newTurn) startTimer()
}, { immediate: true })
const animateDeal = async (cards) => {
if (isDealing.value) return
isDealing.value = true
visibleHand.value = []
for (const card of cards) {
visibleHand.value.push(card)
await new Promise(r => setTimeout(r, 150))
}
isDealing.value = false
}
watch(serverHand, (newHand) => {
if (visibleHand.value.length === 0 && newHand.length > 0 && !hasInitialDealHappened.value) {
animateDeal(newHand)
hasInitialDealHappened.value = true
} else if (!isDealing.value) {
visibleHand.value = [...newHand]
}
}, { deep: true })
// --- METHODS ---
const fetchGameMetadata = async () => {
try {
const response = await axios.get(`${API_BASE_URL}/games/${gameId.value}`)
const game = response.data.data || response.data
gameMetadata.value = {
p1_id: game.player1_user_id,
p1_name: game.player1?.nickname || 'Host',
p2_id: game.player2_user_id,
p2_name: game.player2?.nickname || 'Opponent'
}
} catch (e) {
console.error("Failed to load metadata", e)
}
}
const handlePlayCard = (card) => {
if (!isMyTurn.value || gameOver.value) return
visibleHand.value = visibleHand.value.filter(c => c.id !== card.id)
wsStore.playCard(gameId.value, card.id)
}
// --- FIX: SURRENDER LOGIC ---
const handleSurrender = () => {
if(confirm('Are you sure you want to surrender? You will lose.')) {
// Send event to server. Do NOT disconnect locally yet.
// Wait for the server to send "Game Over" event back.
wsStore.surrender(gameId.value)
}
}
const handleCloseModal = () => {
wsStore.disconnect()
router.push({ name: 'home' })
}
// --- LIFECYCLE ---
onMounted(async () => {
await fetchGameMetadata()
wsStore.connect()
wsStore.onTrickEnd((result) => {
const winnerName = result.winnerId == authStore.currentUser?.id ? "You" : "Opponent"
toast.success(`${winnerName} won the trick!`, { position: 'top-center', duration: 1500 })
})
wsStore.onGameOver((result) => {
gameOver.value = true
if (result.isDraw) winnerResult.value = 'draw'
else winnerResult.value = result.winnerId == authStore.currentUser?.id ? 'player' : 'opponent'
})
})
onUnmounted(() => {
if (timerInterval.value) clearInterval(timerInterval.value)
wsStore.disconnect()
})
</script>
+60 -8
View File
@@ -12,6 +12,7 @@ import {
import { useAPIStore } from '@/stores/api' import { useAPIStore } from '@/stores/api'
import { useRouter } from 'vue-router' import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth' import { useAuthStore } from '@/stores/auth'
import axios from 'axios'
const API_BASE_URL = inject('apiBaseURL') const API_BASE_URL = inject('apiBaseURL')
const apiStore = useAPIStore() const apiStore = useAPIStore()
@@ -56,14 +57,19 @@ const getPendingGames = async (mode = selectedMode.value) => {
if (gLoading.value) return; if (gLoading.value) return;
gLoading.value = true; gLoading.value = true;
apiStore.gameQueryParameters.page = gPage.value++;
apiStore.gameQueryParameters.filters.sort_direction = "asc"
apiStore.gameQueryParameters.filters.type = mode
apiStore.gameQueryParameters.filters.status = 'Pending'
try { try {
const response = await apiStore.getGames(); const response = await axios.get(`${API_BASE_URL}/games/open`, {
params: {
type: mode,
page: gPage.value
}
});
const newGames = response.data.data; const newGames = response.data.data;
openGames.value = [...openGames.value, ...newGames]; openGames.value = [...openGames.value, ...newGames];
gPage.value++;
} catch (error) {
console.error('Failed to fetch games:', error);
} finally { } finally {
gLoading.value = false; gLoading.value = false;
} }
@@ -170,6 +176,52 @@ onMounted(async () => {
await nextTick(); await nextTick();
setupGamesObserver(); setupGamesObserver();
}) })
const hostGame = async () => {
showHostModal.value = true
try {
const response = await axios.post(`${API_BASE_URL}/games/host`, {
type: selectedMode.value
})
const gameId = response.data.id
console.log('Game hosted:', gameId)
router.push({
name: 'multiplayer-game',
params: { id: gameId },
query: { type: selectedMode.value }
})
} catch (error) {
console.error('Failed to host game:', error)
console.error('Error details:', error.response?.data)
showHostModal.value = false
alert('Failed to host game: ' + (error.response?.data?.message || error.message))
}
}
const joinGame = async (game) => {
selectedGame.value = game
try {
await axios.post(`${API_BASE_URL}/games/${game.id}/join`)
console.log('Joined game:', game.id)
router.push({
name: 'multiplayer-game',
params: { id: game.id },
query: { type: selectedMode.value }
})
} catch (error) {
console.error('Failed to join game:', error)
console.error('Error details:', error.response?.data)
alert('Failed to join game: ' + (error.response?.data?.message || error.message))
}
}
</script> </script>
<template> <template>
@@ -244,7 +296,7 @@ onMounted(async () => {
<Card class="w-full max-w-2xl"> <Card class="w-full max-w-2xl">
<CardHeader> <CardHeader>
<CardTitle class="text-3xl font-bold text-center"> <CardTitle class="text-3xl font-bold text-center">
MultiPlayer Multi Player
</CardTitle> </CardTitle>
<CardDescription class="text-center"> <CardDescription class="text-center">
Go one on one with another player! Go one on one with another player!
@@ -258,7 +310,7 @@ onMounted(async () => {
</div> </div>
<div v-else class="max-h-[350px] overflow-y-auto custom-scrollbar p-1"> <div v-else class="max-h-[350px] overflow-y-auto custom-scrollbar p-1">
<div v-for="(game, index) in openGames" :key="game.id" @click="JoinGameModal(game)" <div v-for="(game, index) in openGames" :key="game.id" @click="joinGame(game)"
class="flex items-center justify-between p-3 mb-2 border border-transparent rounded-lg transition-all hover:bg-muted/50 hover:border-purple-500"> class="flex items-center justify-between p-3 mb-2 border border-transparent rounded-lg transition-all hover:bg-muted/50 hover:border-purple-500">
<div class="flex items-center gap-3"> <div class="flex items-center gap-3">
@@ -281,7 +333,7 @@ onMounted(async () => {
</div> </div>
</div> </div>
<div class="flex justify-center"> <div class="flex justify-center">
<Button @click="hostGameModal()" size="lg" variant="secondary" <Button @click="hostGame()" size="lg" variant="secondary"
class="hover:bg-purple-500 hover:text-slate-200"> class="hover:bg-purple-500 hover:text-slate-200">
Host Game Host Game
</Button> </Button>
+7
View File
@@ -9,6 +9,7 @@ import TestDealing from '@/pages/TestDealing.vue'
import TestAllAnimations from '@/pages/TestAllAnimations.vue' import TestAllAnimations from '@/pages/TestAllAnimations.vue'
import TestGameBoard from '@/pages/TestGameBoard.vue' import TestGameBoard from '@/pages/TestGameBoard.vue'
import SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue' import SinglePlayerGamePage from '@/pages/game/SinglePlayerGamePage.vue'
import MultiplayerGamePage from '@/pages/game/MultiplayerGamePage.vue'
import RegisterPage from '@/pages/register/RegisterPage.vue' import RegisterPage from '@/pages/register/RegisterPage.vue'
import CoinsPurchasePage from '@/pages/purchase/CoinPurchasePage.vue' import CoinsPurchasePage from '@/pages/purchase/CoinPurchasePage.vue'
import { useAuthStore } from '@/stores/auth' import { useAuthStore } from '@/stores/auth'
@@ -47,6 +48,12 @@ const router = createRouter({
props: { gameType: 9 }, props: { gameType: 9 },
meta: { requiresAuth: true }, meta: { requiresAuth: true },
}, },
{
path: '/game/multiplayer/:id',
name: 'multiplayer-game',
component: MultiplayerGamePage,
meta: { requiresAuth: true }
},
{ {
path: '/user', path: '/user',
component: UserPage, component: UserPage,
+121 -15
View File
@@ -1,24 +1,130 @@
import { defineStore } from 'pinia' import { defineStore } from 'pinia'
import { inject } from 'vue' import { ref } from 'vue'
import { io } from 'socket.io-client'
import { useAuthStore } from './auth'
export const useSocketStore = defineStore('socket', () => { export const useSocketStore = defineStore('websocket', () => {
const socket = inject('socket') const authStore = useAuthStore()
const handleConnection = () => { const socket = ref(null)
try { const connected = ref(false)
socket.on('connect', () => { const gameState = ref(null)
console.log(`[Socket] Connected -- ${socket.id}`) const lastError = ref(null)
}) const currentGameId = ref(null)
socket.on('disconnect', () => {
console.log(`[Socket] Disconnected -- ${socket.id}`) const WS_URL = 'http://localhost:3000'
})
} catch (error) { const connect = () => {
console.error('[Socket] Connection error:', error) if (socket.value?.connected) return
const token = authStore.getToken()
if (!token) {
console.error('No token available for WebSocket connection')
return
}
socket.value = io(WS_URL, {
auth: { token: `Bearer ${token}` },
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000
})
socket.value.on('connect', () => {
if (currentGameId.value) {
console.log("Reconnected to socket. Rejoining game...");
socket.emit("join-game", { gameId: currentGameId.value });
}
connected.value = true
console.log('[WebSocket] Connected:', socket.value.id)
})
socket.value.on('disconnect', (reason) => {
connected.value = false
console.log('[WebSocket] Disconnected:', reason)
})
socket.value.on('connect_error', (error) => {
console.error('[WebSocket] Connection error:', error.message)
lastError.value = error.message
})
socket.value.on('heartbeat', () => {
socket.value.emit('heartbeat_ack')
})
socket.value.on('game-state', (state) => {
gameState.value = state
})
socket.value.on('game-error', (data) => {
lastError.value = data.message
console.error('[Game] Error:', data.message)
})
socket.value.on('error', (data) => {
lastError.value = data.message
console.error('[Socket] Error:', data.message)
})
}
const disconnect = () => {
if (socket.value) {
socket.value.disconnect()
socket.value = null
connected.value = false
gameState.value = null
lastError.value = null
currentGameId.value = null
}
}
const joinGame = (gameId) => {
currentGameId.value = gameId
if (!socket.value?.connected) return
console.log('[Game] Joining game:', gameId)
socket.value.emit('join-game', { gameId })
}
const playCard = (gameId, cardId) => {
if (!socket.value?.connected) return
socket.value.emit('play-card', { gameId, cardId })
}
// --- NEW: Surrender Action ---
const surrender = (gameId) => {
if (!socket.value?.connected) return
console.log('[Game] Surrendering:', gameId)
socket.value.emit('surrender', { gameId })
}
const onTrickEnd = (callback) => {
if (socket.value) {
socket.value.off('trick-end')
socket.value.on('trick-end', callback)
}
}
const onGameOver = (callback) => {
if (socket.value) {
socket.value.off('game-over')
socket.value.on('game-over', callback)
} }
} }
return { return {
handleConnection, socket,
connected,
gameState,
lastError,
currentGameId,
connect,
disconnect,
joinGame,
playCard,
surrender, // Exported
onTrickEnd,
onGameOver
} }
}) })
+2 -1
View File
@@ -1,4 +1,5 @@
import { addUser, removeUser } from '../state/connection.js'; import { addUser, removeUser } from "../state/connection.js";
const HEARTBEAT_INTERVAL = 30000; // 30 seconds const HEARTBEAT_INTERVAL = 30000; // 30 seconds
const HEARTBEAT_TIMEOUT = 10000; // 10 seconds const HEARTBEAT_TIMEOUT = 10000; // 10 seconds
+190 -199
View File
@@ -4,6 +4,71 @@ import { getUser } from "../state/connection.js";
const API_URL = "http://localhost:8000/api/v1"; const API_URL = "http://localhost:8000/api/v1";
// --- HELPER: Card Strength for Auto-Play ---
const getStrength = (rank) => {
const strengthMap = { 1: 10, 7: 9, 13: 8, 11: 7, 12: 6, 6: 5, 5: 4, 4: 3, 3: 2, 2: 1 };
return strengthMap[rank] || 0;
};
// --- HELPER: Draw Card Logic ---
const drawCard = (game, playerId) => {
const player = game.players[playerId];
if (!player) return;
if (game.deck && game.deck.length > 0) {
const card = game.deck.pop();
player.hand.push(card);
} else if (game.trumpCard) {
player.hand.push(game.trumpCard);
game.trumpCard = null;
}
};
// --- HELPER: Sanitize Data ---
const sanitizeState = (state, game) => {
if (!state) return null;
const p1 = game.player1 || state.player1 || {};
const p2 = game.player2 || state.player2 || {};
return {
id: state.id,
status: state.status || game.status,
player1: { id: p1.id, name: p1.name },
player2: { id: p2.id, name: p2.name },
players: state.players,
hand: state.hand,
points: state.points,
opponent: {
id: state.opponent?.id,
name: state.opponent?.name,
points: state.opponent?.points,
cardCount: state.opponent?.cardCount
},
table: state.table,
trumpCard: state.trumpCard,
deckCount: game.deck ? game.deck.length : (state.deckCount || 0),
currentTurn: state.currentTurn,
turnStartedAt: state.turnStartedAt
};
};
const broadcastState = (io, gameId, game) => {
const roomName = `game_${gameId}`;
const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
if (socketsInRoom) {
for (const socketId of socketsInRoom) {
const s = io.sockets.sockets.get(socketId);
const u = getUser(socketId);
if (u && game.players[u.id]) {
const rawState = game.getStateForPlayer(u.id);
const cleanState = sanitizeState(rawState, game);
s.emit("game-state", cleanState);
}
}
}
}
async function saveGameResult(gameId, result, token) { async function saveGameResult(gameId, result, token) {
try { try {
const payload = { const payload = {
@@ -13,90 +78,105 @@ async function saveGameResult(gameId, result, token) {
player1_points: result.player1_points, player1_points: result.player1_points,
player2_points: result.player2_points, player2_points: result.player2_points,
}; };
if (!result.isDraw && result.winnerId) { if (!result.isDraw && result.winnerId) {
payload.winner_user_id = result.winnerId; payload.winner_user_id = result.winnerId;
payload.loser_user_id = result.loserId; payload.loser_user_id = result.loserId;
} }
await axios.put(`${API_URL}/games/${gameId}`, payload, { await axios.put(`${API_URL}/games/${gameId}`, payload, {
headers: { Authorization: token }, headers: { Authorization: token },
}); });
console.log(`[DB] Game ${gameId} saved.`);
} catch (error) { } catch (error) {
console.error(`[DB Error] Game ${gameId}:`, error.message); console.error(`[DB Error] Game ${gameId}:`, error.message);
} }
} }
// --- SHARED END GAME LOGIC ---
const performGameEnd = (io, game, gameId, winnerId, loserId, reason) => {
const result = {
action: "game_ended",
winnerId: parseInt(winnerId),
loserId: parseInt(loserId),
isDraw: false,
player1_points: game.players[Object.keys(game.players)[0]]?.points || 0,
player2_points: game.players[Object.keys(game.players)[1]]?.points || 0,
reason: reason
};
game.status = "ended";
if (game.timer) clearInterval(game.timer);
io.to(`game_${gameId}`).emit("game-over", {
winnerId: result.winnerId,
isDraw: result.isDraw,
p1Points: result.player1_points,
p2Points: result.player2_points,
message: reason === "surrender" ? "Opponent Surrendered!" : "Game Over"
});
const anyId = Object.keys(game.players)[0];
const token = game.players[anyId]?.token;
if (token) saveGameResult(gameId, result, token);
}
const handleTimeout = (io, gameId, userId) => {
const game = getGame(gameId);
if (!game || game.status === 'ended') return;
console.log(`[Timeout] User ${userId} auto-playing lowest card.`);
const player = game.players[userId];
if (!player || !player.hand || player.hand.length === 0) return;
const trumpSuit = game.trumpCard?.suit || '';
const sortedHand = [...player.hand].sort((a, b) => {
const strengthA = getStrength(a.rank) + (a.suit === trumpSuit ? 100 : 0);
const strengthB = getStrength(b.rank) + (b.suit === trumpSuit ? 100 : 0);
return strengthA - strengthB;
});
const cardToPlay = sortedHand[0];
if (cardToPlay) {
handleGameMove(io, gameId, userId, cardToPlay.id);
}
};
const handleGameMove = (io, gameId, userId, cardId) => { const handleGameMove = (io, gameId, userId, cardId) => {
const game = getGame(gameId); const game = getGame(gameId);
if (!game) return; if (!game) return;
const result = game.playCard(userId, cardId); const result = game.playCard(userId, cardId);
if (result.error) {
console.log(`[Game Error] ${result.error}`);
return;
}
const roomName = `game_${gameId}`; const roomName = `game_${gameId}`;
const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
if (socketsInRoom) { broadcastState(io, gameId, game);
for (const socketId of socketsInRoom) {
const s = io.sockets.sockets.get(socketId);
const u = getUser(socketId);
if (u && game.players[u.id]) {
s.emit("game-state", game.getStateForPlayer(u.id));
}
}
}
if (result.action === "trick_resolved") { if (result.action === "trick_resolved") {
io.to(roomName).emit("trick-end", result.trickResult); io.to(roomName).emit("trick-end", result.trickResult);
setTimeout(() => {
if (game.status !== "ended") {
const canDraw = (game.deck && game.deck.length > 0) || game.trumpCard !== null;
if (canDraw) {
const winnerId = result.trickResult.winnerId;
const loserId = Object.keys(game.players).find(id => String(id) !== String(winnerId));
if (winnerId) drawCard(game, winnerId);
if (loserId) drawCard(game, loserId);
}
broadcastState(io, gameId, game);
}
}, 1500);
} }
if (result.action === "game_ended") { if (result.action === "game_ended") {
io.to(roomName).emit("game-over", { performGameEnd(io, game, gameId, result.winnerId, result.loserId, "points");
winnerId: result.winnerId,
isDraw: result.isDraw,
p1Points: result.player1_points,
p2Points: result.player2_points,
});
let tokenToUse = null;
const playerIds = Object.keys(game.players);
for (const pid of playerIds) {
if (game.players[pid] && game.players[pid].token) {
tokenToUse = game.players[pid].token;
break;
}
}
if (tokenToUse) {
saveGameResult(gameId, result, tokenToUse);
console.log(`[DB] Jogo salvo usando o token de um dos jogadores.`);
} else {
console.error(
`[DB Error] CRÍTICO: Nenhum jogador tem token. O jogo ${gameId} não foi salvo.`
);
}
} }
if (result.action === "next_turn" || result.action === "trick_resolved") { if (result.action === "next_turn" || result.action === "trick_resolved") {
game.startTurnTimer((timeoutUserId, timeoutCardId) => { game.startTurnTimer((timeoutUserId) => {
handleGameMove(io, gameId, timeoutUserId, timeoutCardId); handleTimeout(io, gameId, timeoutUserId);
}); });
if (socketsInRoom) {
for (const socketId of socketsInRoom) {
const s = io.sockets.sockets.get(socketId);
const u = getUser(socketId);
if (u && game.players[u.id])
s.emit("game-state", game.getStateForPlayer(u.id));
}
}
} }
}; };
@@ -109,181 +189,92 @@ export default (io, socket) => {
} }
let game = getGame(gameId); let game = getGame(gameId);
let gameData = null;
if (!game) { try {
try {
const token = socket.handshake.auth.token; const token = socket.handshake.auth.token;
const response = await axios.get(`${API_URL}/games/${gameId}`, { const response = await axios.get(`${API_URL}/games/${gameId}`, {
headers: { Authorization: token }, headers: { Authorization: token },
}); });
gameData = response.data.data || response.data;
} catch (e) { console.error("DB Sync Failed"); }
const gameData = response.data.data || response.data; if (!game && gameData) {
const p1Name = gameData.player1?.nickname || "Player 1";
console.log( const p2Name = gameData.player2?.nickname || "Player 2";
`[Join Debug] API Data recebida para Jogo ${gameId}:`,
gameData ? "OK" : "NULL"
);
if (
gameData.player2_user_id == 1 &&
user.id != gameData.player1_user_id
) {
try {
console.log(
`[API Sync] A oficializar User ${user.id} como Player 2 na BD...`
);
await axios.post(
`${API_URL}/games/${gameId}/join`,
{},
{
headers: { Authorization: token },
}
);
console.log(`[API Sync] Sucesso! O jogo passou a 'Playing' na BD.`);
gameData.player2_user_id = user.id;
gameData.player2 = { name: user.name };
gameData.status = "Playing";
} catch (joinError) {
console.error(
`[API Sync Error] Falha ao fazer join na BD:`,
joinError.message
);
}
}
if (gameData.status === "Ended") {
socket.emit("error", { message: "Game already finished." });
return;
}
if (
gameData.player1_user_id != user.id &&
gameData.player2_user_id != user.id &&
gameData.player2_user_id !== 1
) {
socket.emit("error", { message: "You are not in this game." });
return;
}
const p1Name = gameData.player1?.name || "Player 1";
const p2Name = gameData.player2?.name || "Player 2";
const type = gameData.type == "9" ? 9 : 3; const type = gameData.type == "9" ? 9 : 3;
game = createGame( game = createGame(
gameId, gameId,
type, type,
{ id: gameData.player1_user_id, name: p1Name }, { id: gameData.player1_user_id, name: p1Name },
{ id: gameData.player2_user_id, name: p2Name } { id: gameData.player2_user_id, name: p2Name }
); );
console.log( game.status = gameData.status === 'Playing' ? 'playing' : 'pending';
`[Join Debug] Jogo criado?`,
game ? "SIM" : "NÃO (Undefined)"
);
} catch (error) {
if (error.response) {
console.error(`[Join Error] Status: ${error.response.status}`);
console.error(`[Join Error] Data:`, error.response.data);
} else {
console.error(`[Join Error] Message:`, error.message);
}
socket.emit("error", { message: "Failed to join game." });
return;
}
} }
const GHOST_ID = 1; if (!game) {
socket.emit("error", { message: "Game not found." });
return;
}
if (game && game.players) { const myId = user.id;
if (game.players[user.id]) { const ghostKey = Object.keys(game.players).find(key => key == 1);
game.players[user.id].token = socket.handshake.auth.token; const amIDbPlayer2 = gameData && gameData.player2_user_id == myId;
}
if (!game.players[user.id] && game.players[GHOST_ID]) { if (!game.players[myId] && (ghostKey || amIDbPlayer2)) {
console.log(`[Ghost Swap] User ${user.name} substituiu o Fantasma.`); let ghostHand = [];
let ghostPoints = 0;
let ghostTricks = 0;
if (ghostKey && game.players[ghostKey]) {
ghostHand = game.players[ghostKey].hand || [];
ghostPoints = game.players[ghostKey].points || 0;
ghostTricks = game.players[ghostKey].tricks || 0;
delete game.players[ghostKey];
}
delete game.players[GHOST_ID]; game.players[myId] = {
game.players[user.id] = { id: myId,
id: user.id, name: user.nickname,
name: user.name, hand: ghostHand,
hand: [], points: ghostPoints,
points: 0, tricks: ghostTricks,
tricks: 0, token: socket.handshake.auth.token,
token: socket.handshake.auth.token,
}; };
game.player2 = { id: myId, name: user.nickname };
const token = socket.handshake.auth.token; game.status = 'playing';
if(!game.timer) {
axios game.startTurnTimer((timeoutUserId) => handleTimeout(io, gameId, timeoutUserId));
.post( }
`${API_URL}/games/${gameId}/join`,
{},
{
headers: { Authorization: token },
}
)
.then(() =>
console.log(`[API Sync] Sucesso! BD atualizada para 'Playing'.`)
)
.catch((err) => console.error(`[API Sync Error]`, err.message));
}
} }
socket.join(`game_${gameId}`); socket.join(`game_${gameId}`);
if (game && game.players[user.id]) { if (game.players[myId]) {
socket.emit("game-state", game.getStateForPlayer(user.id)); game.players[myId].token = socket.handshake.auth.token;
console.log(`--> Estado enviado para User ${user.id}`);
game.players[user.id].token = socket.handshake.auth.token; const rawState = game.getStateForPlayer(myId);
if (!game.timer && game.status === "playing") { const cleanState = sanitizeState(rawState, game);
game.startTurnTimer((uId, cId) => handleGameMove(io, gameId, uId, cId));
} socket.emit("game-state", cleanState);
socket.emit("game-state", game.getStateForPlayer(user.id)); broadcastState(io, gameId, game);
} else {
socket.emit("error", { message: "Error joining game state." });
} }
}); });
socket.on("play-card", ({ gameId, cardId }) => { socket.on("play-card", ({ gameId, cardId }) => {
const user = getUser(socket.id); const user = getUser(socket.id);
const game = getGame(gameId); if (user) handleGameMove(io, gameId, user.id, cardId);
});
if (!game || !user) return; // --- NEW: SURRENDER HANDLER ---
socket.on("surrender", ({ gameId }) => {
const user = getUser(socket.id);
const game = getGame(gameId);
const result = game.playCard(user.id, cardId); if (!game || !user || !game.players[user.id]) return;
if (result.error) { console.log(`[Game] User ${user.nickname} surrendered.`);
socket.emit("game-error", { message: result.error });
return;
}
handleGameMove(io, gameId, user.id, cardId); const winnerId = Object.keys(game.players).find(id => String(id) !== String(user.id));
performGameEnd(io, game, gameId, winnerId, user.id, "surrender");
const roomName = `game_${gameId}`;
const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
if (socketsInRoom) {
for (const socketId of socketsInRoom) {
const s = io.sockets.sockets.get(socketId);
const u = getUser(socketId);
if (u && game.players[u.id]) {
s.emit("game-state", game.getStateForPlayer(u.id));
}
}
}
if (result.action === "trick_resolved") {
io.to(roomName).emit("trick-end", result.trickResult);
}
if (result.action === "game_ended") {
io.to(roomName).emit("game-over", {
winnerId: result.winnerId,
isDraw: result.isDraw,
p1Points: result.player1_points,
p2Points: result.player2_points,
});
saveGameResult(gameId, result, socket.handshake.auth.token);
}
}); });
}; };
+25 -13
View File
@@ -3,27 +3,39 @@ import BiscaGame from '../classes/BiscaGame.js';
const activeGames = new Map(); const activeGames = new Map();
const createGame = (id, type, player1, player2) => { const createGame = (id, type, player1, player2) => {
const game = new BiscaGame(id, type, player1, player2); const existingGame = activeGames.get(id);
if (existingGame) {
console.log(
`[Game State] Game ${id} already exists, returning existing instance`,
);
return existingGame;
}
const game = new BiscaGame(id, type, player1, player2);
game.init(); game.init();
activeGames.set(id, game); activeGames.set(id, game);
console.log(`[Game State] Game created: ${id} (Type: ${type})`); console.log(`[Game State] Game created: ${id} (Type: ${type})`);
return game; return game;
}; };
const getGame = (id) => { const getGame = (id) => {
return activeGames.get(id); return activeGames.get(id);
}; };
const removeGame = (id) => { const removeGame = (id) => {
const game = activeGames.get(id); const game = activeGames.get(id);
if (game) { if (game) {
game.stopTimer(); game.stopTimer();
activeGames.delete(id); activeGames.delete(id);
console.log(`[Game State] Game removed: ${id}`); console.log(`[Game State] Game removed: ${id}`);
} }
};
module.exports = {
createGame,
getGame,
removeGame,
}; };
export { createGame, getGame, removeGame };