SyntaxSquad/DADProject#15 feat: Added Multiplayer View and Stuff

This commit is contained in:
AfonsoCMSousa
2026-01-02 19:07:27 +00:00
parent 5880960c42
commit 5e90de812b
9 changed files with 529 additions and 504 deletions
+18 -26
View File
@@ -92,34 +92,26 @@ class GameController extends Controller
], 201);
}
public function join(Game $game)
{
$this->authorize('join', $game);
$user = Auth::user();
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);
public function join(Request $request, Game $game)
{
// Prevent joining if already full or started
if ($game->status !== 'Pending' || $game->player2_user_id !== 1) {
return response()->json(['message' => 'Game is not available'], 400);
}
// Prevent joining your own game
if ($game->player1_user_id === $request->user()->id) {
return response()->json(['message' => 'Cannot join your own game'], 400);
}
$game->update([
'player2_user_id' => $request->user()->id,
'status' => 'Playing',
]);
return response()->json($game);
}
public function show(Game $game)
{
$this->authorize('view', $game);
+18 -4
View File
@@ -47,8 +47,8 @@ Route::prefix('v1')->group(function () {
});
Route::prefix('games')->group(function () {
// Host a new multiplayer game
Route::post('/host', function (\Illuminate\Http\Request $request) {
//Host a new multiplayer game - MUST come before resource routes
Route::post('host', function (\Illuminate\Http\Request $request) {
$request->validate([
'type' => 'required|in:3,9'
]);
@@ -61,7 +61,21 @@ Route::prefix('v1')->group(function () {
'began_at' => now(),
]);
return response()->json($game);
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']);
@@ -75,7 +89,7 @@ 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('/{match}/join', [MatchController::class, 'join']);
});
// Admin Routes
@@ -7,6 +7,8 @@
:player-score="playerScore"
:opponent-score="opponentScore"
:current-turn="currentTurn"
:player-name="playerName"
:opponent-name="opponentName"
:round-number="1"
/>
</div>
@@ -62,6 +64,8 @@ const props = defineProps({
// REMOVIDO: playableCardIndices (já não precisamos dele)
playerScore: { type: Number, default: 0 },
opponentScore: { type: Number, default: 0 },
playerName: { type: String, default: 'You' },
opponentName: { type: String, default: 'Bot' },
currentTurn: {
type: String,
default: 'player',
@@ -33,7 +33,8 @@
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>
<span v-if="roundNumber" class="text-gray-500 text-[10px] font-medium">
Round {{ roundNumber }}
+228 -209
View File
@@ -1,7 +1,6 @@
<template>
<div class="relative min-h-screen overflow-hidden">
<!-- Surrender Button -->
<div v-if="isGameRunning && !gameOver" class="absolute top-4 right-4 z-50">
<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"
@@ -10,295 +9,315 @@
</button>
</div>
<!-- Connection Status -->
<div 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">
<div :class="['w-3 h-3 rounded-full', wsStore.connected ? 'bg-green-500' : 'bg-red-500']"></div>
<span class="text-white text-sm">{{ wsStore.connected ? 'Connected' : 'Disconnected' }}</span>
<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>
<!-- Timer -->
<div v-if="isMyTurn && isGameRunning && !gameOver" 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" :class="timeLeft <= 5 ? 'border-red-500 animate-pulse' : 'border-gray-700'">
<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 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>
<span :class="['text-3xl font-mono font-bold', timeLeft <= 5 ? 'text-red-500' : 'text-white']">
{{ timeLeft }}s
{{ timeLeft }}
</span>
</div>
</div>
</div>
<!-- Game Board -->
<div v-if="isGameRunning">
<div v-if="shouldShowBoard">
<GameBoard
:trump-card="trumpCard"
:cards-remaining="deckCount"
:player-hand="playerHand"
:cards-remaining="deckCount + (trumpCard ? 1 : 0)"
:player-hand="visibleHand"
:opponent-hand="opponentHand"
:player-score="playerScore"
:opponent-score="opponentScore"
:current-turn="currentTurn"
:current-trick="currentTrick"
:player-name="myDisplayName"
:opponent-name="opponentDisplayName"
:current-turn="currentTurnLabel"
:current-trick="displayedTrick"
:is-my-turn="isMyTurn"
@play-card="handlePlayCard"
/>
</div>
<!-- Loading State -->
<div v-else-if="!gameOver" class="flex h-screen items-center justify-center bg-green-900 text-white">
<div class="text-center">
<div class="animate-spin h-12 w-12 border-4 border-white border-t-transparent rounded-full mx-auto mb-4"></div>
<div class="text-xl">Connecting to game...</div>
</div>
</div>
<!-- Trick Result Modal -->
<div v-if="showTrickResult" class="fixed inset-0 bg-black bg-opacity-70 flex items-center justify-center z-50">
<div class="bg-gray-800 border-4 border-yellow-500 p-8 max-w-md rounded-lg">
<h3 class="text-3xl font-bold mb-4 text-center text-white">
{{ trickWinnerId === authStore.currentUser?.id ? '🎉 You won the trick!' : '😞 Opponent won the trick' }}
</h3>
<div class="text-center mb-4">
<div class="text-5xl font-bold text-yellow-500">+{{ trickPoints }} points</div>
<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>
</div>
</div>
<!-- Game Over Modal -->
<GameOver
:is-visible="gameOver"
:winner="gameResult"
:player-score="playerScore"
:opponent-score="opponentScore"
:stats="{ playerTricks: 0, opponentTricks: 0 }"
:is-logging-out="false"
@play-again="handlePlayAgain"
@close="handleCloseModal"
/>
<h2 class="text-2xl font-bold mb-2">
Waiting for Opponent...
</h2>
<!-- Error Notification -->
<div v-if="wsStore.lastError" class="fixed bottom-4 right-4 bg-red-600 border-2 border-red-500 p-4 max-w-sm z-50 rounded-lg">
<div class="flex items-start gap-3">
<svg class="w-6 h-6 flex-shrink-0 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<circle cx="12" cy="12" r="10" stroke-width="2"/>
<line x1="12" y1="8" x2="12" y2="12" stroke-width="2"/>
<line x1="12" y1="16" x2="12.01" y2="16" stroke-width="2"/>
</svg>
<div class="text-white">
<div class="font-semibold">Error</div>
<div class="text-sm">{{ wsStore.lastError }}</div>
</div>
<button @click="wsStore.lastError = null" class="ml-auto text-white">
<svg class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<line x1="18" y1="6" x2="6" y2="18" stroke-width="2"/>
<line x1="6" y1="6" x2="18" y2="18" stroke-width="2"/>
</svg>
<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, onBeforeMount } from 'vue'
import { useRoute, useRouter, onBeforeRouteLeave } from 'vue-router'
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 = useWebSocketStore()
const wsStore = useSocketStore()
const authStore = useAuthStore()
const API_BASE_URL = inject('apiBaseURL')
const gameId = ref(route.params.id)
const gameType = ref(route.query.type || '9')
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 isCardAnimating = ref(false)
const showTrickResult = ref(false)
const trickWinnerId = ref(null)
const trickPoints = ref(0)
const gameOver = ref(false)
const gameResult = ref(null)
const isGameRunning = ref(false)
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'
})
// Computed properties from game state
const trumpCard = computed(() => wsStore.gameState?.trumpCard || null)
const deckCount = computed(() => wsStore.gameState?.deckCount || 0)
const playerHand = computed(() => wsStore.gameState?.hand || [])
const opponentHand = computed(() => {
const count = wsStore.gameState?.opponent?.cardCount || 0
return Array(count).fill({ id: 'back', suit: 'back', rank: 0 })
})
const playerScore = computed(() => wsStore.gameState?.points || 0)
const opponentScore = computed(() => wsStore.gameState?.opponent?.points || 0)
const currentTurn = computed(() => wsStore.gameState?.currentTurn)
const currentTrick = computed(() => ({
playerCard: wsStore.gameState?.table?.playerCard || null,
opponentCard: wsStore.gameState?.table?.opponentCard || null
}))
const isMyTurn = computed(() => {
return currentTurn.value == authStore.currentUser?.id
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 }))
})
const startTimer = () => {
stopTimer()
timeLeft.value = 20
// --- WATCHERS ---
timerInterval.value = setInterval(() => {
timeLeft.value--
if (timeLeft.value <= 0) {
stopTimer()
handleTimeout()
watch(() => wsStore.connected, (isConnected) => {
if (isConnected) {
hasConnectedOnce.value = true
wsStore.joinGame(gameId.value)
}
}, 1000)
}, { 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)
}
const stopTimer = () => {
if (timerInterval.value) {
clearInterval(timerInterval.value)
timerInterval.value = null
}
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
}
const handleTimeout = () => {
if (playerHand.value.length > 0) {
const randomCard = playerHand.value[0]
handlePlayCard(randomCard)
toast.warning('Time\'s up!', {
description: 'Auto-played first card'
})
}
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 || isCardAnimating.value || gameOver.value) return
isCardAnimating.value = true
if (!isMyTurn.value || gameOver.value) return
visibleHand.value = visibleHand.value.filter(c => c.id !== card.id)
wsStore.playCard(gameId.value, card.id)
stopTimer()
setTimeout(() => {
isCardAnimating.value = false
}, 500)
}
// --- FIX: SURRENDER LOGIC ---
const handleSurrender = () => {
const confirmSurrender = window.confirm(
'Are you sure you want to surrender? Your opponent will be awarded the win.'
)
if (!confirmSurrender) return
toast.error('Game Surrendered', {
description: 'You forfeited the match.'
})
wsStore.disconnect()
router.push({ name: 'home' })
}
const handlePlayAgain = () => {
wsStore.disconnect()
router.push({ name: 'home' })
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' })
wsStore.disconnect()
router.push({ name: 'home' })
}
const handleBrowserUnload = (event) => {
if (isGameRunning.value && !gameOver.value) {
event.preventDefault()
event.returnValue = ''
}
}
// --- LIFECYCLE ---
// Watch for turn changes
watch(() => currentTurn.value, (newTurn, oldTurn) => {
if (newTurn == authStore.currentUser?.id && newTurn !== oldTurn) {
startTimer()
} else {
stopTimer()
}
})
// Watch for game state to mark game as running
watch(() => wsStore.gameState, (state) => {
if (state && !isGameRunning.value) {
isGameRunning.value = true
}
})
onBeforeMount(() => {
gameOver.value = false
})
onMounted(() => {
onMounted(async () => {
await fetchGameMetadata()
wsStore.connect()
setTimeout(() => {
wsStore.joinGame(gameId.value)
}, 500)
wsStore.onTrickEnd((result) => {
trickWinnerId.value = result.winnerId
trickPoints.value = result.points
showTrickResult.value = true
setTimeout(() => {
showTrickResult.value = false
}, 3000)
const winnerName = result.winnerId == authStore.currentUser?.id ? "You" : "Opponent"
toast.success(`${winnerName} won the trick!`, { position: 'top-center', duration: 1500 })
})
wsStore.onGameOver((result) => {
stopTimer()
gameOver.value = true
if (result.isDraw) {
gameResult.value = 'draw'
} else if (result.winnerId === authStore.currentUser?.id) {
gameResult.value = 'player'
} else {
gameResult.value = 'opponent'
}
if (result.isDraw) winnerResult.value = 'draw'
else winnerResult.value = result.winnerId == authStore.currentUser?.id ? 'player' : 'opponent'
})
window.addEventListener('beforeunload', handleBrowserUnload)
})
onUnmounted(() => {
stopTimer()
wsStore.offTrickEnd()
wsStore.offGameOver()
if (timerInterval.value) clearInterval(timerInterval.value)
wsStore.disconnect()
window.removeEventListener('beforeunload', handleBrowserUnload)
})
onBeforeRouteLeave((to, from, next) => {
if (!isGameRunning.value || gameOver.value) {
next()
return
}
const confirmExit = window.confirm(
'⚠️ Game in Progress!\n\nIf you leave now, you will forfeit the match.\n\nAre you sure you want to leave?'
)
if (confirmExit) {
wsStore.disconnect()
next()
} else {
next(false)
}
})
</script>
+10 -5
View File
@@ -56,14 +56,19 @@ const getPendingGames = async (mode = selectedMode.value) => {
if (gLoading.value) return;
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 {
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;
openGames.value = [...openGames.value, ...newGames];
gPage.value++;
} catch (error) {
console.error('Failed to fetch games:', error);
} finally {
gLoading.value = false;
}
+23 -31
View File
@@ -10,6 +10,7 @@ export const useSocketStore = defineStore('websocket', () => {
const connected = ref(false)
const gameState = ref(null)
const lastError = ref(null)
const currentGameId = ref(null)
const WS_URL = 'http://localhost:3000'
@@ -23,16 +24,18 @@ export const useSocketStore = defineStore('websocket', () => {
}
socket.value = io(WS_URL, {
auth: {
token: `Bearer ${token}`
},
auth: { token: `Bearer ${token}` },
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000
})
// Connection events
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)
})
@@ -47,15 +50,12 @@ export const useSocketStore = defineStore('websocket', () => {
lastError.value = error.message
})
// Heartbeat
socket.value.on('heartbeat', () => {
socket.value.emit('heartbeat_ack')
})
// Game events
socket.value.on('game-state', (state) => {
gameState.value = state
console.log('[Game] State updated:', state)
})
socket.value.on('game-error', (data) => {
@@ -76,48 +76,40 @@ export const useSocketStore = defineStore('websocket', () => {
connected.value = false
gameState.value = null
lastError.value = null
currentGameId.value = null
}
}
const joinGame = (gameId) => {
if (!socket.value?.connected) {
console.error('[Game] Socket not connected')
return
}
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) {
console.error('[Game] Socket not connected')
return
}
console.log('[Game] Playing card:', 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.on('game-over', callback)
}
}
const offTrickEnd = () => {
if (socket.value) {
socket.value.off('trick-end')
}
}
const offGameOver = () => {
if (socket.value) {
socket.value.off('game-over')
socket.value.on('game-over', callback)
}
}
@@ -126,13 +118,13 @@ export const useSocketStore = defineStore('websocket', () => {
connected,
gameState,
lastError,
currentGameId,
connect,
disconnect,
joinGame,
playCard,
surrender, // Exported
onTrickEnd,
onGameOver,
offTrickEnd,
offGameOver
onGameOver
}
})
+190 -199
View File
@@ -4,6 +4,71 @@ import { getUser } from "../state/connection.js";
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) {
try {
const payload = {
@@ -13,90 +78,105 @@ async function saveGameResult(gameId, result, token) {
player1_points: result.player1_points,
player2_points: result.player2_points,
};
if (!result.isDraw && result.winnerId) {
payload.winner_user_id = result.winnerId;
payload.loser_user_id = result.loserId;
}
await axios.put(`${API_URL}/games/${gameId}`, payload, {
headers: { Authorization: token },
});
console.log(`[DB] Game ${gameId} saved.`);
} catch (error) {
console.error(`[DB Error] Game ${gameId}:`, error.message);
}
}
// --- SHARED END GAME LOGIC ---
const performGameEnd = (io, game, gameId, winnerId, loserId, reason) => {
const result = {
action: "game_ended",
winnerId: parseInt(winnerId),
loserId: parseInt(loserId),
isDraw: false,
player1_points: game.players[Object.keys(game.players)[0]]?.points || 0,
player2_points: game.players[Object.keys(game.players)[1]]?.points || 0,
reason: reason
};
game.status = "ended";
if (game.timer) clearInterval(game.timer);
io.to(`game_${gameId}`).emit("game-over", {
winnerId: result.winnerId,
isDraw: result.isDraw,
p1Points: result.player1_points,
p2Points: result.player2_points,
message: reason === "surrender" ? "Opponent Surrendered!" : "Game Over"
});
const anyId = Object.keys(game.players)[0];
const token = game.players[anyId]?.token;
if (token) saveGameResult(gameId, result, token);
}
const handleTimeout = (io, gameId, userId) => {
const game = getGame(gameId);
if (!game || game.status === 'ended') return;
console.log(`[Timeout] User ${userId} auto-playing lowest card.`);
const player = game.players[userId];
if (!player || !player.hand || player.hand.length === 0) return;
const trumpSuit = game.trumpCard?.suit || '';
const sortedHand = [...player.hand].sort((a, b) => {
const strengthA = getStrength(a.rank) + (a.suit === trumpSuit ? 100 : 0);
const strengthB = getStrength(b.rank) + (b.suit === trumpSuit ? 100 : 0);
return strengthA - strengthB;
});
const cardToPlay = sortedHand[0];
if (cardToPlay) {
handleGameMove(io, gameId, userId, cardToPlay.id);
}
};
const handleGameMove = (io, gameId, userId, cardId) => {
const game = getGame(gameId);
if (!game) return;
const result = game.playCard(userId, cardId);
if (result.error) {
console.log(`[Game Error] ${result.error}`);
return;
}
const roomName = `game_${gameId}`;
const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
if (socketsInRoom) {
for (const socketId of socketsInRoom) {
const s = io.sockets.sockets.get(socketId);
const u = getUser(socketId);
if (u && game.players[u.id]) {
s.emit("game-state", game.getStateForPlayer(u.id));
}
}
}
broadcastState(io, gameId, game);
if (result.action === "trick_resolved") {
io.to(roomName).emit("trick-end", result.trickResult);
setTimeout(() => {
if (game.status !== "ended") {
const canDraw = (game.deck && game.deck.length > 0) || game.trumpCard !== null;
if (canDraw) {
const winnerId = result.trickResult.winnerId;
const loserId = Object.keys(game.players).find(id => String(id) !== String(winnerId));
if (winnerId) drawCard(game, winnerId);
if (loserId) drawCard(game, loserId);
}
broadcastState(io, gameId, game);
}
}, 1500);
}
if (result.action === "game_ended") {
io.to(roomName).emit("game-over", {
winnerId: result.winnerId,
isDraw: result.isDraw,
p1Points: result.player1_points,
p2Points: result.player2_points,
});
let tokenToUse = null;
const playerIds = Object.keys(game.players);
for (const pid of playerIds) {
if (game.players[pid] && game.players[pid].token) {
tokenToUse = game.players[pid].token;
break;
}
}
if (tokenToUse) {
saveGameResult(gameId, result, tokenToUse);
console.log(`[DB] Jogo salvo usando o token de um dos jogadores.`);
} else {
console.error(
`[DB Error] CRÍTICO: Nenhum jogador tem token. O jogo ${gameId} não foi salvo.`
);
}
performGameEnd(io, game, gameId, result.winnerId, result.loserId, "points");
}
if (result.action === "next_turn" || result.action === "trick_resolved") {
game.startTurnTimer((timeoutUserId, timeoutCardId) => {
handleGameMove(io, gameId, timeoutUserId, timeoutCardId);
game.startTurnTimer((timeoutUserId) => {
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 gameData = null;
if (!game) {
try {
try {
const token = socket.handshake.auth.token;
const response = await axios.get(`${API_URL}/games/${gameId}`, {
headers: { Authorization: token },
});
gameData = response.data.data || response.data;
} catch (e) { console.error("DB Sync Failed"); }
const gameData = response.data.data || response.data;
console.log(
`[Join Debug] API Data recebida para Jogo ${gameId}:`,
gameData ? "OK" : "NULL"
);
if (
gameData.player2_user_id == 1 &&
user.id != gameData.player1_user_id
) {
try {
console.log(
`[API Sync] A oficializar User ${user.id} como Player 2 na BD...`
);
await axios.post(
`${API_URL}/games/${gameId}/join`,
{},
{
headers: { Authorization: token },
}
);
console.log(`[API Sync] Sucesso! O jogo passou a 'Playing' na BD.`);
gameData.player2_user_id = user.id;
gameData.player2 = { name: user.name };
gameData.status = "Playing";
} catch (joinError) {
console.error(
`[API Sync Error] Falha ao fazer join na BD:`,
joinError.message
);
}
}
if (gameData.status === "Ended") {
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";
if (!game && gameData) {
const p1Name = gameData.player1?.nickname || "Player 1";
const p2Name = gameData.player2?.nickname || "Player 2";
const type = gameData.type == "9" ? 9 : 3;
game = createGame(
gameId,
type,
{ id: gameData.player1_user_id, name: p1Name },
{ id: gameData.player2_user_id, name: p2Name }
);
console.log(
`[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;
}
game.status = gameData.status === 'Playing' ? 'playing' : 'pending';
}
const GHOST_ID = 1;
if (!game) {
socket.emit("error", { message: "Game not found." });
return;
}
if (game && game.players) {
if (game.players[user.id]) {
game.players[user.id].token = socket.handshake.auth.token;
}
const myId = user.id;
const ghostKey = Object.keys(game.players).find(key => key == 1);
const amIDbPlayer2 = gameData && gameData.player2_user_id == myId;
if (!game.players[user.id] && game.players[GHOST_ID]) {
console.log(`[Ghost Swap] User ${user.name} substituiu o Fantasma.`);
if (!game.players[myId] && (ghostKey || amIDbPlayer2)) {
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[user.id] = {
id: user.id,
name: user.name,
hand: [],
points: 0,
tricks: 0,
token: socket.handshake.auth.token,
game.players[myId] = {
id: myId,
name: user.nickname,
hand: ghostHand,
points: ghostPoints,
tricks: ghostTricks,
token: socket.handshake.auth.token,
};
const token = socket.handshake.auth.token;
axios
.post(
`${API_URL}/games/${gameId}/join`,
{},
{
headers: { Authorization: token },
}
)
.then(() =>
console.log(`[API Sync] Sucesso! BD atualizada para 'Playing'.`)
)
.catch((err) => console.error(`[API Sync Error]`, err.message));
}
game.player2 = { id: myId, name: user.nickname };
game.status = 'playing';
if(!game.timer) {
game.startTurnTimer((timeoutUserId) => handleTimeout(io, gameId, timeoutUserId));
}
}
socket.join(`game_${gameId}`);
if (game && game.players[user.id]) {
socket.emit("game-state", game.getStateForPlayer(user.id));
console.log(`--> Estado enviado para User ${user.id}`);
game.players[user.id].token = socket.handshake.auth.token;
if (!game.timer && game.status === "playing") {
game.startTurnTimer((uId, cId) => handleGameMove(io, gameId, uId, cId));
}
socket.emit("game-state", game.getStateForPlayer(user.id));
} else {
socket.emit("error", { message: "Error joining game state." });
if (game.players[myId]) {
game.players[myId].token = socket.handshake.auth.token;
const rawState = game.getStateForPlayer(myId);
const cleanState = sanitizeState(rawState, game);
socket.emit("game-state", cleanState);
broadcastState(io, gameId, game);
}
});
socket.on("play-card", ({ gameId, cardId }) => {
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) {
socket.emit("game-error", { message: result.error });
return;
}
console.log(`[Game] User ${user.nickname} surrendered.`);
handleGameMove(io, gameId, user.id, cardId);
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);
}
const winnerId = Object.keys(game.players).find(id => String(id) !== String(user.id));
performGameEnd(io, game, gameId, winnerId, user.id, "surrender");
});
};
+22 -15
View File
@@ -3,31 +3,38 @@ const BiscaGame = require("../classes/BiscaGame");
const activeGames = new Map();
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})`);
return game;
console.log(`[Game State] Game created: ${id} (Type: ${type})`);
return game;
};
const getGame = (id) => {
return activeGames.get(id);
return activeGames.get(id);
};
const removeGame = (id) => {
const game = activeGames.get(id);
if (game) {
game.stopTimer();
activeGames.delete(id);
console.log(`[Game State] Game removed: ${id}`);
}
const game = activeGames.get(id);
if (game) {
game.stopTimer();
activeGames.delete(id);
console.log(`[Game State] Game removed: ${id}`);
}
};
module.exports = {
createGame,
getGame,
removeGame,
createGame,
getGame,
removeGame,
};