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
+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;
}