SyntaxSquad/DADProject#14 added protection to logout inside a game and going to another page

This commit is contained in:
2025-12-29 11:15:33 +00:00
committed by FernandoJVideira
parent e68f1357cc
commit 3ec6f8971c
6 changed files with 226 additions and 32 deletions
-1
View File
@@ -49,4 +49,3 @@ onMounted(async () => {
</script>
<style></style>
`
+17 -4
View File
@@ -33,7 +33,10 @@
]"
>
<!-- Confetti Effect (if player wins) -->
<div v-if="winner === 'player' && showConfetti" class="absolute inset-0 pointer-events-none">
<div
v-if="winner === 'player' && showConfetti"
class="absolute inset-0 pointer-events-none"
>
<div
v-for="i in 30"
:key="i"
@@ -140,17 +143,23 @@
<!-- Actions -->
<div class="flex gap-3">
<button
v-if="!isLoggingOut"
@click="$emit('play-again')"
class="flex-1 bg-gradient-to-r from-emerald-500 to-emerald-600 hover:from-emerald-600 hover:to-emerald-700 text-white font-bold py-3 px-6 rounded-lg transition-all duration-200 hover:scale-105 active:scale-95 shadow-lg"
class="flex-1 bg-gradient-to-r from-emerald-500 to-emerald-600 hover:from-emerald-600 hover:to-emerald-700 text-white font-bold py-3 px-6 rounded-lg transition-all shadow-lg"
>
Play Again
</button>
<button
v-if="!hideClose"
@click="handleClose"
class="flex-1 bg-gray-700 hover:bg-gray-600 text-white font-bold py-3 px-6 rounded-lg transition-all duration-200 hover:scale-105 active:scale-95"
class="flex-1 font-bold py-3 px-6 rounded-lg transition-all"
:class="[
isLoggingOut
? 'bg-red-600 hover:bg-red-700 text-white w-full' // Estilo de destaque para Logout
: 'bg-gray-700 hover:bg-gray-600 text-white',
]"
>
Close
{{ isLoggingOut ? 'Confirmar Logout' : 'Close' }}
</button>
</div>
</div>
@@ -197,6 +206,10 @@ const props = defineProps({
type: Boolean,
default: false,
},
isLoggingOut: {
type: Boolean,
default: false,
},
})
const emit = defineEmits(['close', 'play-again'])
+23 -3
View File
@@ -15,14 +15,16 @@
</li>
</NavigationMenuContent>
</NavigationMenuItem>
<NavigationMenuItem v-if="!userLoggedIn">
<NavigationMenuLink>
<RouterLink to="/login">Login</RouterLink>
</NavigationMenuLink>
</NavigationMenuItem>
<NavigationMenuItem v-else>
<NavigationMenuLink>
<a @click.prevent="logoutClickHandler">Logout</a>
<a href="/home" @click.prevent="logoutClickHandler" class="cursor-pointer">Logout</a>
</NavigationMenuLink>
<NavigationMenuLink>
<RouterLink to="/user">Profile</RouterLink>
@@ -34,6 +36,8 @@
</template>
<script setup>
import { useRouter } from 'vue-router'
import { useBiscaStore } from '@/stores/bisca'
import {
NavigationMenu,
NavigationMenuContent,
@@ -44,12 +48,28 @@ import {
} from '@/components/ui/navigation-menu'
import router from '@/router';
const emits = defineEmits(['logout'])
const { userLoggedIn } = defineProps(['userLoggedIn'])
const router = useRouter()
const biscaStore = useBiscaStore()
const logoutClickHandler = () => {
if (biscaStore.isGameRunning) {
const confirmLogout = window.confirm(
'⚠️ Jogo em Progresso!\n\nSe fizeres Logout agora, perderás o jogo atual e serás considerado PERDEDOR.\n\nQueres mesmo sair?'
)
if (!confirmLogout) return
biscaStore.isLoggingOut = true
biscaStore.quitGame()
return
}
emits('logout')
router.push('/login')
router.push({ name: 'home' })
}
</script>
@@ -1,11 +1,11 @@
<template>
<div class="relative min-h-screen overflow-hidden">
<div v-if="store.trumpCard">
<GameBoard
:trump-card="store.trumpCard"
:cards-remaining="store.deck.length"
:player-hand="store.playerHand"
:opponent-hand="store.opponentHand"
:player-score="store.playerScore"
:opponent-score="store.opponentScore"
:current-turn="store.currentTurn"
@@ -13,15 +13,31 @@
@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">A baralhar cartas...</div>
<div class="animate-pulse text-xl">A preparar baralho...</div>
</div>
<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"
/>
</div>
</template>
<script setup>
import { onMounted, onUnmounted } from 'vue'
import { onMounted, onUnmounted, onBeforeMount } from 'vue'
import { useRouter, onBeforeRouteLeave } from 'vue-router'
import { useBiscaStore } from '@/stores/bisca'
import GameBoard from '@/components/game/GameBoard.vue'
import GameOver from '@/components/game/GameOver.vue'
import { useAuthStore } from '@/stores/auth'
const props = defineProps({
gameType: {
@@ -31,13 +47,71 @@ const props = defineProps({
})
const store = useBiscaStore()
const router = useRouter()
const authStore = useAuthStore()
onMounted(() => {
console.log(`A iniciar Bisca de ${props.gameType}...`)
store.startGame(props.gameType)
window.addEventListener('beforeunload', handleBrowserUnload)
})
const handlePlayAgain = () => {
store.startGame(props.gameType)
}
const handleCloseModal = () => {
if (store.isLoggingOut) {
localStorage.removeItem('token')
authStore.logout()
store.$reset()
router.push({ name: 'login' })
return
}
store.isGameRunning = false
store.isGameOver = false
router.push({ name: 'home' })
}
onUnmounted(() => {
window.removeEventListener('beforeunload', handleBrowserUnload)
store.isGameOver = false
store.isGameRunning = false
store.isLoggingOut = false
})
onBeforeMount(() => {
store.isGameOver = false
})
const handlePlayCard = (card) => {
store.playerPlayCard(card)
}
const handleBrowserUnload = (event) => {
if (store.isGameRunning) {
event.preventDefault()
event.returnValue = ''
}
}
onBeforeRouteLeave((to, from, next) => {
if (!store.isGameRunning) {
next()
return
}
const confirmExit = window.confirm(
'⚠️ Jogo em Progresso!\n\nSe saíres agora, o jogo será cancelado e contarás como PERDEDOR.\n\nQueres mesmo sair?',
)
if (confirmExit) {
store.quitGame()
next()
} else {
next(false)
}
})
</script>
+7 -7
View File
@@ -15,10 +15,12 @@ const router = createRouter({
routes: [
{
path: '/',
name: 'home',
component: HomePage,
},
{
path: '/login',
name: 'login',
component: LoginPage,
},
{
@@ -68,15 +70,13 @@ const router = createRouter({
})
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
const token = localStorage.getItem('token') // Ou useAuthStore().token
const requiresAuth = to.matched.some((record) => record.meta.requiresAuth)
if (requiresAuth) {
const token = localStorage.getItem('token')
if (!token) {
toast.error('Acesso Negado', {
description: 'Precisas de fazer login para aceder ao jogo.',
duration: 4000,
})
return next({ name: 'home' })
return next({ name: 'login' })
}
}
next()
+88
View File
@@ -4,7 +4,9 @@ import { ref } from 'vue'
export const useBiscaStore = defineStore('bisca', () => {
const isDealing = ref(false)
const isGameRunning = ref(false)
const isGameOver = ref(false)
const gameType = ref(3)
const isLoggingOut = ref(false)
const deck = ref([])
const playerHand = ref([])
@@ -15,6 +17,11 @@ export const useBiscaStore = defineStore('bisca', () => {
const currentTurn = ref('player')
const playerTricks = ref(0)
const opponentTricks = ref(0)
const winner = ref(null)
const table = ref({
playerCard: null,
opponentCard: null,
@@ -27,9 +34,13 @@ export const useBiscaStore = defineStore('bisca', () => {
isDealing.value = true
isGameRunning.value = true
gameType.value = type
isGameOver.value = false
isLoggingOut.value = false
playerScore.value = 0
opponentScore.value = 0
playerTricks.value = 0
opponentTricks.value = 0
deck.value = []
playerHand.value = []
@@ -55,6 +66,66 @@ export const useBiscaStore = defineStore('bisca', () => {
isDealing.value = false
}
const resolveTrick = () => {
const pCard = table.value.playerCard
const oCard = table.value.opponentCard
const trumpSuit = trumpCard.value.suit
let trickWinner = ''
if (pCard.suit === trumpSuit && oCard.suit !== trumpSuit) trickWinner = 'player'
else if (oCard.suit === trumpSuit && pCard.suit !== trumpSuit) trickWinner = 'opponent'
else if (pCard.suit === oCard.suit) {
trickWinner = getStrength(pCard.rank) > getStrength(oCard.rank) ? 'player' : 'opponent'
} else {
trickWinner = table.value.firstToPlay
}
const points = pCard.points + oCard.points
if (trickWinner === 'player') {
playerScore.value += points
playerTricks.value++
} else {
opponentScore.value += points
opponentTricks.value++
}
table.value = { playerCard: null, opponentCard: null, firstToPlay: null }
if (
deck.value.length === 0 &&
playerHand.value.length === 0 &&
opponentHand.value.length === 0
) {
endGame()
return
}
if (deck.value.length > 0) {
if (trickWinner === 'player') {
playerHand.value.push(deck.value.pop())
opponentHand.value.push(deck.value.pop())
} else {
opponentHand.value.push(deck.value.pop())
playerHand.value.push(deck.value.pop())
}
}
currentTurn.value = trickWinner
if (trickWinner === 'opponent') {
setTimeout(botPlayCard, 1000)
}
}
const endGame = () => {
isGameRunning.value = false
isGameOver.value = true
if (playerScore.value > opponentScore.value) winner.value = 'player'
else if (opponentScore.value > playerScore.value) winner.value = 'opponent'
else winner.value = 'draw'
}
const dealInitialCards = async () => {
const cardsToDeal = gameType.value === 9 ? 9 : 3
@@ -108,6 +179,16 @@ export const useBiscaStore = defineStore('bisca', () => {
return strengthMap[rank] || 0
}
const quitGame = () => {
if (!isGameRunning.value) return
opponentScore.value = 120
playerScore.value = 0
winner.value = 'opponent'
isGameRunning.value = false
isGameOver.value = true
}
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
return {
@@ -117,11 +198,18 @@ export const useBiscaStore = defineStore('bisca', () => {
deck,
playerHand,
opponentHand,
isLoggingOut,
trumpCard,
playerScore,
opponentScore,
currentTurn,
table,
playerTricks,
opponentTricks,
isGameOver,
winner,
startGame,
quitGame,
resolveTrick,
}
})