removed comments
This commit is contained in:
@@ -42,8 +42,6 @@ const logout = () => {
|
||||
|
||||
onMounted(async () => {
|
||||
await authStore.restoreSession()
|
||||
// REMOVED - The WebSocket for multiplayer is handled separately in the WebSocketStore
|
||||
// socketStore.handleConnection()
|
||||
})
|
||||
</script>
|
||||
|
||||
|
||||
@@ -88,7 +88,6 @@ const props = defineProps({
|
||||
const deckPulse = ref(false)
|
||||
const trumpReveal = ref(false)
|
||||
|
||||
// Pulse animation when cards remaining changes
|
||||
watch(
|
||||
() => props.cardsRemaining,
|
||||
() => {
|
||||
@@ -99,7 +98,6 @@ watch(
|
||||
},
|
||||
)
|
||||
|
||||
// Trump reveal animation
|
||||
watch(
|
||||
() => props.revealTrump,
|
||||
(newValue) => {
|
||||
@@ -107,7 +105,7 @@ watch(
|
||||
trumpReveal.value = true
|
||||
setTimeout(() => {
|
||||
trumpReveal.value = false
|
||||
}, 3000) // Show for 3 seconds
|
||||
}, 3000)
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
@@ -54,18 +54,14 @@ const isAnimating = ref(false)
|
||||
const currentPosition = ref({ x: 0, y: 0 })
|
||||
|
||||
onMounted(() => {
|
||||
// Start at the deck position
|
||||
currentPosition.value = { ...props.startPosition }
|
||||
isVisible.value = true
|
||||
|
||||
// Wait for delay, then start animation
|
||||
setTimeout(() => {
|
||||
// Force a reflow to ensure starting position is set
|
||||
requestAnimationFrame(() => {
|
||||
isAnimating.value = true
|
||||
currentPosition.value = { ...props.endPosition }
|
||||
|
||||
// After animation completes, emit event and hide
|
||||
setTimeout(() => {
|
||||
emit('complete')
|
||||
isVisible.value = false
|
||||
|
||||
@@ -61,7 +61,6 @@ const props = defineProps({
|
||||
cardsRemaining: { type: Number, default: 0 },
|
||||
deckIsEmpty: { type: Boolean, default: false },
|
||||
maxCards: { type: Number, default: 3 },
|
||||
// REMOVIDO: playableCardIndices (já não precisamos dele)
|
||||
playerScore: { type: Number, default: 0 },
|
||||
opponentScore: { type: Number, default: 0 },
|
||||
playerName: { type: String, default: 'You' },
|
||||
|
||||
@@ -218,21 +218,18 @@ const showConfetti = ref(false)
|
||||
const displayPlayerScore = ref(0)
|
||||
const displayOpponentScore = ref(0)
|
||||
|
||||
// Computed title based on winner
|
||||
const title = computed(() => {
|
||||
if (props.winner === 'player') return 'Victory!'
|
||||
if (props.winner === 'opponent') return 'Defeat'
|
||||
return 'Draw!'
|
||||
})
|
||||
|
||||
// Computed subtitle
|
||||
const subtitle = computed(() => {
|
||||
if (props.winner === 'player') return 'Congratulations! You won the game!'
|
||||
if (props.winner === 'opponent') return 'Better luck next time!'
|
||||
return 'The game ended in a draw'
|
||||
})
|
||||
|
||||
// Animate score count-up
|
||||
const animateScore = (fromValue, toValue, callback) => {
|
||||
const duration = 1000
|
||||
const steps = 30
|
||||
@@ -255,19 +252,16 @@ const animateScore = (fromValue, toValue, callback) => {
|
||||
}, stepDuration)
|
||||
}
|
||||
|
||||
// Watch for visibility and trigger animations
|
||||
watch(
|
||||
() => props.isVisible,
|
||||
(newValue) => {
|
||||
if (newValue) {
|
||||
// Start confetti if player wins
|
||||
if (props.winner === 'player') {
|
||||
setTimeout(() => {
|
||||
showConfetti.value = true
|
||||
}, 300)
|
||||
}
|
||||
|
||||
// Animate scores counting up
|
||||
setTimeout(() => {
|
||||
animateScore(0, props.playerScore, (value) => {
|
||||
displayPlayerScore.value = value
|
||||
|
||||
@@ -99,10 +99,9 @@ const turnChanged = ref(false)
|
||||
const displayPlayerScore = ref(props.playerScore)
|
||||
const displayOpponentScore = ref(props.opponentScore)
|
||||
|
||||
// Animate score count-up
|
||||
const animateScore = (fromValue, toValue, callback) => {
|
||||
const duration = 500 // Total animation duration in ms
|
||||
const steps = 20 // Number of increments
|
||||
const duration = 500
|
||||
const steps = 20
|
||||
const stepDuration = duration / steps
|
||||
const increment = (toValue - fromValue) / steps
|
||||
|
||||
@@ -122,7 +121,6 @@ const animateScore = (fromValue, toValue, callback) => {
|
||||
}, stepDuration)
|
||||
}
|
||||
|
||||
// Watch for player score changes and trigger count-up animation
|
||||
watch(
|
||||
() => props.playerScore,
|
||||
(newScore, oldScore) => {
|
||||
@@ -143,7 +141,6 @@ watch(
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// Watch for opponent score changes and trigger count-up animation
|
||||
watch(
|
||||
() => props.opponentScore,
|
||||
(newScore, oldScore) => {
|
||||
@@ -164,7 +161,6 @@ watch(
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
// Watch for turn changes and trigger pulse animation
|
||||
watch(
|
||||
() => props.currentTurn,
|
||||
() => {
|
||||
|
||||
@@ -13,7 +13,6 @@ console.log('[main.js] ws connection', wsConnection)
|
||||
|
||||
const app = createApp(App)
|
||||
|
||||
//app.provide('socket', io(wsConnection))
|
||||
app.provide('serverBaseURL', `http://${apiDomain}`)
|
||||
app.provide('apiBaseURL', `http://${apiDomain}/api/v1`)
|
||||
|
||||
|
||||
@@ -812,7 +812,7 @@ const stats = ref({})
|
||||
const users = ref([])
|
||||
const transactions = ref([])
|
||||
const games = ref([])
|
||||
const matches = ref([]) // NEW
|
||||
const matches = ref([])
|
||||
const isLoading = ref(false)
|
||||
const loadMoreTrigger = ref(null)
|
||||
|
||||
@@ -822,7 +822,7 @@ const pagination = reactive({
|
||||
users: { page: 1, lastPage: 1 },
|
||||
transactions: { page: 1, lastPage: 1 },
|
||||
games: { page: 1, lastPage: 1 },
|
||||
matches: { page: 1, lastPage: 1 }, // NEW
|
||||
matches: { page: 1, lastPage: 1 },
|
||||
})
|
||||
|
||||
const filters = reactive({
|
||||
@@ -832,7 +832,6 @@ const filters = reactive({
|
||||
sort_coins: null,
|
||||
game_sort_direction: 'desc',
|
||||
game_type: null,
|
||||
// Match filters
|
||||
match_type: null,
|
||||
match_outcome: null,
|
||||
match_date_from: '',
|
||||
@@ -852,7 +851,7 @@ const tabs = [
|
||||
{ id: 'users', name: 'User Management' },
|
||||
{ id: 'transactions', name: 'Transactions' },
|
||||
{ id: 'games', name: 'Games History' },
|
||||
{ id: 'matches', name: 'Matches History' }, // NEW
|
||||
{ id: 'matches', name: 'Matches History' },
|
||||
]
|
||||
|
||||
const chartData = computed(() => {
|
||||
@@ -1028,10 +1027,10 @@ const handleSort = async (column) => {
|
||||
filters.match_type =
|
||||
filters.match_type === null ? '9' : filters.match_type === '9' ? '3' : null
|
||||
} else if (column === 'date') {
|
||||
filters.pot = null // Reset pot sort when sorting by date
|
||||
filters.pot = null
|
||||
filters.match_sort_direction = filters.match_sort_direction === 'desc' ? 'asc' : 'desc'
|
||||
} else if (column === 'pot') {
|
||||
filters.match_sort_direction = null // Reset date sort when sorting by pot
|
||||
filters.match_sort_direction = null
|
||||
if (filters.pot === null) filters.pot = 'desc'
|
||||
else if (filters.pot === 'desc') filters.pot = 'asc'
|
||||
else filters.pot = 'desc'
|
||||
|
||||
@@ -1,28 +1,44 @@
|
||||
<template>
|
||||
<div class="relative min-h-screen overflow-hidden bg-green-900">
|
||||
<div v-if="shouldShowBoard && !gameOver" class="absolute top-4 right-4 z-50">
|
||||
<button @click="handleSurrender"
|
||||
class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all transform hover:scale-105 flex items-center gap-2">
|
||||
<button
|
||||
@click="handleSurrender"
|
||||
class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all transform hover:scale-105 flex items-center gap-2"
|
||||
>
|
||||
<span>🏳️</span> Surrender
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="!wsStore.connected && hasConnectedOnce"
|
||||
class="absolute top-4 left-4 z-50 flex items-center gap-2 bg-gray-800 px-4 py-2 rounded-lg border border-gray-700 shadow-xl">
|
||||
<div
|
||||
v-if="!wsStore.connected && hasConnectedOnce"
|
||||
class="absolute top-4 left-4 z-50 flex items-center gap-2 bg-gray-800 px-4 py-2 rounded-lg border border-gray-700 shadow-xl"
|
||||
>
|
||||
<div class="w-3 h-3 rounded-full bg-red-500 animate-pulse"></div>
|
||||
<span class="text-white text-sm">Reconnecting...</span>
|
||||
</div>
|
||||
|
||||
<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
|
||||
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">
|
||||
<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']">
|
||||
<span
|
||||
:class="['text-3xl font-mono font-bold', timeLeft <= 5 ? 'text-red-500' : 'text-white']"
|
||||
>
|
||||
{{ timeLeft }}
|
||||
</span>
|
||||
</div>
|
||||
@@ -30,41 +46,67 @@
|
||||
</div>
|
||||
|
||||
<div v-if="shouldShowBoard">
|
||||
<GameBoard :trump-card="trumpCard" :cards-remaining="deckCount + (trumpCard ? 1 : 0)" :player-hand="visibleHand"
|
||||
:opponent-hand="opponentHand" :player-score="playerScore" :opponent-score="opponentScore"
|
||||
:player-name="myDisplayName" :opponent-name="opponentDisplayName" :current-turn="currentTurnLabel"
|
||||
:current-trick="displayedTrick" :is-my-turn="isMyTurn" @play-card="handlePlayCard" />
|
||||
<GameBoard
|
||||
:trump-card="trumpCard"
|
||||
:cards-remaining="deckCount + (trumpCard ? 1 : 0)"
|
||||
:player-hand="visibleHand"
|
||||
:opponent-hand="opponentHand"
|
||||
:player-score="playerScore"
|
||||
:opponent-score="opponentScore"
|
||||
:player-name="myDisplayName"
|
||||
:opponent-name="opponentDisplayName"
|
||||
:current-turn="currentTurnLabel"
|
||||
:current-trick="displayedTrick"
|
||||
:is-my-turn="isMyTurn"
|
||||
@play-card="handlePlayCard"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-else-if="!gameOver" class="flex h-screen items-center justify-center bg-green-900 text-white">
|
||||
<div class="text-center p-8 bg-green-800/50 rounded-2xl border border-green-700 shadow-2xl backdrop-blur-sm">
|
||||
<div
|
||||
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>
|
||||
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>
|
||||
<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>
|
||||
<div class="bg-black/20 p-3 rounded mb-6 font-mono text-sm border border-white/10 text-green-100">
|
||||
<div
|
||||
class="bg-black/20 p-3 rounded mb-6 font-mono text-sm border border-white/10 text-green-100"
|
||||
>
|
||||
Match ID: <span class="font-bold text-white">{{ matchState.id }}</span>
|
||||
</div>
|
||||
<button @click="handleCloseModal"
|
||||
class="px-6 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-all shadow-lg hover:shadow-red-500/20">
|
||||
<button
|
||||
@click="handleCloseModal"
|
||||
class="px-6 py-3 bg-red-600 hover:bg-red-700 text-white rounded-lg font-semibold transition-all shadow-lg hover:shadow-red-500/20"
|
||||
>
|
||||
Cancel & Return Home
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<GameOver :is-visible="gameOver" :winner="winnerResult" :player-score="playerScore" :opponent-score="opponentScore"
|
||||
:player-name="myDisplayName" :opponent-name="opponentDisplayName" :stats="{ playerTricks: 0, opponentTricks: 0 }"
|
||||
:is-logging-out="false" @play-again="handleCloseModal" @close="handleCloseModal" />
|
||||
<GameOver
|
||||
:is-visible="gameOver"
|
||||
:winner="winnerResult"
|
||||
:player-score="playerScore"
|
||||
:opponent-score="opponentScore"
|
||||
:player-name="myDisplayName"
|
||||
:opponent-name="opponentDisplayName"
|
||||
:stats="{ playerTricks: 0, opponentTricks: 0 }"
|
||||
:is-logging-out="false"
|
||||
@play-again="handleCloseModal"
|
||||
@close="handleCloseModal"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -94,29 +136,26 @@ const timeLeft = ref(20)
|
||||
const timerInterval = ref(null)
|
||||
const hasConnectedOnce = ref(false)
|
||||
|
||||
// --- STATE ---
|
||||
const matchState = computed(() => wsStore.gameState || { id: gameId.value })
|
||||
|
||||
const gameMetadata = ref({
|
||||
p1_id: null,
|
||||
p1_name: 'Player 1',
|
||||
p2_id: null,
|
||||
p2_name: 'Opponent'
|
||||
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;
|
||||
const s = wsStore.gameState
|
||||
if (s && s.player2 && s.player2.id > 1) {
|
||||
return true;
|
||||
return true
|
||||
}
|
||||
return false;
|
||||
return false
|
||||
})
|
||||
|
||||
const amIHost = computed(() => {
|
||||
@@ -127,8 +166,12 @@ const amIHost = computed(() => {
|
||||
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 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
|
||||
@@ -157,54 +200,63 @@ const opponentHand = computed(() => {
|
||||
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 }
|
||||
watch(
|
||||
() => wsStore.connected,
|
||||
(isConnected) => {
|
||||
if (isConnected) {
|
||||
hasConnectedOnce.value = true
|
||||
wsStore.joinGame(gameId.value)
|
||||
}
|
||||
}
|
||||
}, { deep: true })
|
||||
},
|
||||
{ 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;
|
||||
timeLeft.value = 20
|
||||
return
|
||||
}
|
||||
|
||||
// FORCE RESET to avoid showing old time for 1 frame
|
||||
timeLeft.value = 20;
|
||||
timeLeft.value = 20
|
||||
|
||||
const startAt = wsStore.gameState?.turnStartedAt ? new Date(wsStore.gameState.turnStartedAt).getTime() : Date.now()
|
||||
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)
|
||||
@@ -212,16 +264,18 @@ const startTimer = () => {
|
||||
if (timeLeft.value <= 0) clearInterval(timerInterval.value)
|
||||
}
|
||||
|
||||
// EXECUTE IMMEDIATELY
|
||||
update();
|
||||
update()
|
||||
|
||||
// Then set interval
|
||||
timerInterval.value = setInterval(update, 1000)
|
||||
}
|
||||
|
||||
watch(() => wsStore.gameState?.currentTurn, (newTurn) => {
|
||||
if (newTurn) startTimer()
|
||||
}, { immediate: true })
|
||||
watch(
|
||||
() => wsStore.gameState?.currentTurn,
|
||||
(newTurn) => {
|
||||
if (newTurn) startTimer()
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
const animateDeal = async (cards) => {
|
||||
if (isDealing.value) return
|
||||
@@ -229,21 +283,23 @@ const animateDeal = async (cards) => {
|
||||
visibleHand.value = []
|
||||
for (const card of cards) {
|
||||
visibleHand.value.push(card)
|
||||
await new Promise(r => setTimeout(r, 150))
|
||||
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 ---
|
||||
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 },
|
||||
)
|
||||
|
||||
const fetchGameMetadata = async () => {
|
||||
try {
|
||||
@@ -253,27 +309,26 @@ const fetchGameMetadata = async () => {
|
||||
p1_id: game.player1_user_id,
|
||||
p1_name: game.player1?.nickname || 'Host',
|
||||
p2_id: game.player2_user_id,
|
||||
p2_name: game.player2?.nickname || 'Opponent'
|
||||
p2_name: game.player2?.nickname || 'Opponent',
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("Failed to load metadata", 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)
|
||||
visibleHand.value = visibleHand.value.filter((c) => c.id !== card.id)
|
||||
wsStore.playCard(gameId.value, card.id)
|
||||
}
|
||||
|
||||
const handleBeforeUnload = (event) => {
|
||||
if (shouldShowBoard.value && !gameOver.value) {
|
||||
event.preventDefault();
|
||||
event.returnValue = '';
|
||||
event.preventDefault()
|
||||
event.returnValue = ''
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// --- FIX: SURRENDER LOGIC ---
|
||||
const handleSurrender = () => {
|
||||
if (confirm('Are you sure you want to surrender? You will lose.')) {
|
||||
wsStore.surrender(gameId.value)
|
||||
@@ -281,93 +336,90 @@ const handleSurrender = () => {
|
||||
}
|
||||
|
||||
const handleCloseModal = async () => {
|
||||
// 1. If game is still in Lobby (Pending) and I am the Host, DELETE it.
|
||||
if (!shouldShowBoard.value && amIHost.value && !gameOver.value) {
|
||||
try {
|
||||
// This calls Route::delete('/{game}', ...) in your api.php
|
||||
await axios.delete(`${API_BASE_URL}/games/${gameId.value}`);
|
||||
console.log("Lobby cancelled and deleted.");
|
||||
await axios.delete(`${API_BASE_URL}/games/${gameId.value}`)
|
||||
console.log('Lobby cancelled and deleted.')
|
||||
} catch (e) {
|
||||
console.error("Failed to delete pending game:", e);
|
||||
console.error('Failed to delete pending game:', e)
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Notify server of voluntary exit (to skip the 10s reconnect timer)
|
||||
if (wsStore.socket) {
|
||||
wsStore.socket.emit('notify_disconnect');
|
||||
wsStore.socket.emit('notify_disconnect')
|
||||
}
|
||||
|
||||
// 3. Disconnect and go home
|
||||
wsStore.disconnect();
|
||||
router.push({ name: 'home' });
|
||||
wsStore.disconnect()
|
||||
router.push({ name: 'home' })
|
||||
}
|
||||
|
||||
// --- LIFECYCLE ---
|
||||
|
||||
onBeforeRouteLeave(async (to, from, next) => {
|
||||
// CASE A: Game is Pending (Waiting Room)
|
||||
if (!shouldShowBoard.value && !gameOver.value) {
|
||||
if (amIHost.value) {
|
||||
// Ask for confirmation to close the lobby
|
||||
const confirmClose = window.confirm("This will cancel the lobby. Are you sure?");
|
||||
const confirmClose = window.confirm('This will cancel the lobby. Are you sure?')
|
||||
if (confirmClose) {
|
||||
try {
|
||||
// Delete the game from DB so it doesn't get stuck as "Pending"
|
||||
await axios.delete(`${API_BASE_URL}/games/${gameId.value}`);
|
||||
} catch (e) { console.error(e) }
|
||||
await axios.delete(`${API_BASE_URL}/games/${gameId.value}`)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
|
||||
if (wsStore.socket) wsStore.socket.emit('notify_disconnect');
|
||||
wsStore.disconnect();
|
||||
next();
|
||||
if (wsStore.socket) wsStore.socket.emit('notify_disconnect')
|
||||
wsStore.disconnect()
|
||||
next()
|
||||
} else {
|
||||
next(false); // Stay on page
|
||||
next(false)
|
||||
}
|
||||
return;
|
||||
return
|
||||
} else {
|
||||
// If I am NOT host (just a guest waiting), just leave
|
||||
if (wsStore.socket) wsStore.socket.emit('notify_disconnect');
|
||||
wsStore.disconnect();
|
||||
next();
|
||||
return;
|
||||
if (wsStore.socket) wsStore.socket.emit('notify_disconnect')
|
||||
wsStore.disconnect()
|
||||
next()
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// CASE B: Game is Over (Standard exit)
|
||||
if (gameOver.value) {
|
||||
next();
|
||||
return;
|
||||
next()
|
||||
return
|
||||
}
|
||||
|
||||
// CASE C: Game is Active/Playing (The Surrender Logic we built before)
|
||||
const answer = window.confirm(
|
||||
"If you leave, you will be register has 'losing' or 'surrendered', Are you sure you want to leave?"
|
||||
);
|
||||
"If you leave, you will be register has 'losing' or 'surrendered', Are you sure you want to leave?",
|
||||
)
|
||||
|
||||
if (answer) {
|
||||
// ... (Your existing surrender logic) ...
|
||||
try { await wsStore.surrender(gameId.value); } catch (e) { }
|
||||
try {
|
||||
await wsStore.surrender(gameId.value)
|
||||
} catch (e) {}
|
||||
|
||||
if (wsStore.socket) {
|
||||
wsStore.socket.emit('notify_disconnect', () => {
|
||||
wsStore.disconnect();
|
||||
next();
|
||||
});
|
||||
setTimeout(() => { if (wsStore.connected) { wsStore.disconnect(); next(); } }, 500);
|
||||
return;
|
||||
wsStore.disconnect()
|
||||
next()
|
||||
})
|
||||
setTimeout(() => {
|
||||
if (wsStore.connected) {
|
||||
wsStore.disconnect()
|
||||
next()
|
||||
}
|
||||
}, 500)
|
||||
return
|
||||
}
|
||||
wsStore.disconnect();
|
||||
next();
|
||||
wsStore.disconnect()
|
||||
next()
|
||||
} else {
|
||||
next(false);
|
||||
next(false)
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchGameMetadata()
|
||||
wsStore.connect()
|
||||
|
||||
wsStore.onTrickEnd((result) => {
|
||||
const winnerName = result.winnerId == authStore.currentUser?.id ? "You" : "Opponent"
|
||||
const winnerName = result.winnerId == authStore.currentUser?.id ? 'You' : 'Opponent'
|
||||
toast.success(`${winnerName} won the trick!`, { position: 'top-center', duration: 1500 })
|
||||
})
|
||||
|
||||
|
||||
@@ -1,35 +1,52 @@
|
||||
<template>
|
||||
<div class="relative min-h-screen overflow-hidden">
|
||||
<div v-if="store.isGameRunning" class="absolute top-4 right-4 z-50">
|
||||
<button @click="handleSurrender"
|
||||
class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all transform hover:scale-105 flex items-center gap-2">
|
||||
<button
|
||||
@click="handleSurrender"
|
||||
class="bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded-lg shadow-lg border-2 border-red-800 transition-all transform hover:scale-105 flex items-center gap-2"
|
||||
>
|
||||
<span>🏳️</span> Surrender
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="store.isGameRunning">
|
||||
<GameBoard :trump-card="store.trumpCard" :cards-remaining="store.deck.length + (store.trumpCard ? 1 : 0)"
|
||||
:player-hand="store.playerHand" :opponent-hand="store.opponentHand" :player-score="store.playerScore"
|
||||
:opponent-score="store.opponentScore" :current-turn="'player'" :is-my-turn="true" :current-trick="store.table"
|
||||
:player-name="'You'" :opponent-name="'CPU'" @play-card="handlePlayCard" />
|
||||
<GameBoard
|
||||
:trump-card="store.trumpCard"
|
||||
:cards-remaining="store.deck.length + (store.trumpCard ? 1 : 0)"
|
||||
:player-hand="store.playerHand"
|
||||
:opponent-hand="store.opponentHand"
|
||||
:player-score="store.playerScore"
|
||||
:opponent-score="store.opponentScore"
|
||||
:current-turn="'player'"
|
||||
:is-my-turn="true"
|
||||
:current-trick="store.table"
|
||||
:player-name="'You'"
|
||||
:opponent-name="'CPU'"
|
||||
@play-card="handlePlayCard"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-else class="flex h-screen items-center justify-center bg-green-900 text-white">
|
||||
<div class="animate-pulse text-xl">Preparing game...</div>
|
||||
</div>
|
||||
|
||||
|
||||
<GameOver :is-visible="store.isGameOver" :winner="store.winner || 'draw'" :player-score="store.playerScore"
|
||||
<GameOver
|
||||
:is-visible="store.isGameOver"
|
||||
:winner="store.winner || 'draw'"
|
||||
:player-score="store.playerScore"
|
||||
:opponent-score="store.opponentScore"
|
||||
:stats="{ playerTricks: store.playerTricks, opponentTricks: store.opponentTricks }"
|
||||
:is-logging-out="store.isLoggingOut" @play-again="handlePlayAgain" @close="handleCloseModal" />
|
||||
:is-logging-out="store.isLoggingOut"
|
||||
@play-again="handlePlayAgain"
|
||||
@close="handleCloseModal"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, onUnmounted, onBeforeMount, watch } from 'vue'
|
||||
import { useRouter, onBeforeRouteLeave } from 'vue-router'
|
||||
import { toast } from 'vue-sonner' // Import Toast for feedback
|
||||
import { toast } from 'vue-sonner'
|
||||
import { useBiscaStore } from '@/stores/bisca'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import GameBoard from '@/components/game/GameBoard.vue'
|
||||
@@ -46,10 +63,13 @@ const store = useBiscaStore()
|
||||
const router = useRouter()
|
||||
const authStore = useAuthStore()
|
||||
|
||||
// DEBUG: Watch the store state
|
||||
watch(() => store.playerHand, (newHand) => {
|
||||
console.log('Player hand updated:', newHand)
|
||||
}, { deep: true })
|
||||
watch(
|
||||
() => store.playerHand,
|
||||
(newHand) => {
|
||||
console.log('Player hand updated:', newHand)
|
||||
},
|
||||
{ deep: true },
|
||||
)
|
||||
|
||||
onBeforeMount(() => {
|
||||
store.isGameOver = false
|
||||
@@ -59,12 +79,11 @@ onMounted(() => {
|
||||
store.startGame(props.gameType)
|
||||
window.addEventListener('beforeunload', handleBrowserUnload)
|
||||
|
||||
// DEBUG: Log initial state
|
||||
setTimeout(() => {
|
||||
console.log('Game state after init:', {
|
||||
playerHand: store.playerHand,
|
||||
currentTurn: store.currentTurn,
|
||||
isGameRunning: store.isGameRunning
|
||||
isGameRunning: store.isGameRunning,
|
||||
})
|
||||
}, 500)
|
||||
})
|
||||
|
||||
@@ -1183,22 +1183,17 @@ const fetchData = async () => {
|
||||
if (game.is_draw) outcome = 'draw'
|
||||
else if (game.winner_user_id === authStore.currentUser.id) outcome = 'win'
|
||||
|
||||
// LÓGICA CORRIGIDA PARA COINS
|
||||
// A API devolve 'stake' (o valor que cada um apostou)
|
||||
let stakeAmount = 0
|
||||
if (game.stake) {
|
||||
stakeAmount = parseFloat(game.stake)
|
||||
}
|
||||
|
||||
// Se Ganhou: O lucro é o valor da stake (ex: apostou 10, recebeu 20, lucro +10)
|
||||
// Se Perdeu: O prejuízo é o valor da stake (ex: -10)
|
||||
// Se Empate: Normalmente devolve-se a aposta, por isso é 0 (ou ajusta conforme a tua regra)
|
||||
let displayAmount = 0
|
||||
|
||||
if (outcome === 'win') {
|
||||
displayAmount = stakeAmount // Ganhou a aposta do outro
|
||||
displayAmount = stakeAmount
|
||||
} else if (outcome === 'loss') {
|
||||
displayAmount = stakeAmount // Perdeu a sua aposta (o sinal negativo é adicionado no HTML)
|
||||
displayAmount = stakeAmount
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -1206,7 +1201,7 @@ const fetchData = async () => {
|
||||
variant: `Type ${game.type}`,
|
||||
outcome: outcome,
|
||||
opponent: opponent?.nickname || 'Unknown Player',
|
||||
amount: displayAmount, // Valor corrigido
|
||||
amount: displayAmount,
|
||||
duration: `${Math.floor(game.total_time / 60)}m ${game.total_time % 60}s`,
|
||||
began_at: game.began_at,
|
||||
details: {
|
||||
|
||||
@@ -76,7 +76,6 @@ export const useAPIStore = defineStore('api', () => {
|
||||
return axios.get(`${API_BASE_URL}/games?${queryParams}`)
|
||||
}
|
||||
|
||||
// --- ADICIONADO: Função que faltava ---
|
||||
const getCurrentUserGames = (params = {}) => {
|
||||
const queryParams = new URLSearchParams({
|
||||
page: params.page || 1,
|
||||
@@ -91,7 +90,6 @@ export const useAPIStore = defineStore('api', () => {
|
||||
|
||||
return axios.get(`${API_BASE_URL}/users/${authStore.currentUserID}/games?${queryParams}`)
|
||||
}
|
||||
// --------------------------------------
|
||||
|
||||
const getCurrentUserMatches = (params = {}) => {
|
||||
const queryParams = new URLSearchParams({
|
||||
|
||||
@@ -3,13 +3,14 @@ import { ref, computed } from 'vue'
|
||||
import { useAPIStore } from './api'
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
|
||||
const DEFAULT_TIMEOUT = 30 * 60 * 1000
|
||||
const REMEMBER_ME_TIMEOUT = 365 * 24 * 60 * 60 * 1000
|
||||
|
||||
const currentUser = ref(undefined)
|
||||
const token = ref(localStorage.getItem('token') || null)
|
||||
const tokenExpiry = ref(localStorage.getItem('tokenExpiry') ? parseInt(localStorage.getItem('tokenExpiry')) : null)
|
||||
const tokenExpiry = ref(
|
||||
localStorage.getItem('tokenExpiry') ? parseInt(localStorage.getItem('tokenExpiry')) : null,
|
||||
)
|
||||
const rememberMe = ref(false)
|
||||
|
||||
const isLoggedIn = computed(() => {
|
||||
@@ -25,9 +26,9 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
})
|
||||
|
||||
const isTokenAlmostExpired = () => {
|
||||
if (!tokenExpiry.value) return false;
|
||||
return Date.now() > (tokenExpiry.value - 60 * 1000);
|
||||
};
|
||||
if (!tokenExpiry.value) return false
|
||||
return Date.now() > tokenExpiry.value - 60 * 1000
|
||||
}
|
||||
|
||||
const resetTokenExpiry = () => {
|
||||
const timeout = rememberMe.value ? REMEMBER_ME_TIMEOUT : DEFAULT_TIMEOUT
|
||||
@@ -106,7 +107,6 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
currentUser.value = userResp.data
|
||||
localStorage.setItem('currentUser', JSON.stringify(userResp.data))
|
||||
} catch (apiError) {
|
||||
// API call failed, likely token is invalid
|
||||
logout()
|
||||
return false
|
||||
}
|
||||
@@ -117,7 +117,7 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
}
|
||||
|
||||
const updateCurrentUserCoins = (coins) => {
|
||||
if (!currentUser.value) return;
|
||||
if (!currentUser.value) return
|
||||
currentUser.value.coins_balance = coins
|
||||
}
|
||||
|
||||
|
||||
@@ -273,7 +273,6 @@ export const useBiscaStore = defineStore('bisca', () => {
|
||||
playerScore.value = 0
|
||||
winner.value = 'opponent'
|
||||
|
||||
// Parar o jogo imediatamente
|
||||
isGameRunning.value = false
|
||||
isGameOver.value = true
|
||||
}
|
||||
|
||||
@@ -122,7 +122,7 @@ export const useSocketStore = defineStore('websocket', () => {
|
||||
disconnect,
|
||||
joinGame,
|
||||
playCard,
|
||||
surrender, // Exported
|
||||
surrender,
|
||||
onTrickEnd,
|
||||
onGameOver
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user