Compare commits

..
7 Commits
21 changed files with 1039 additions and 3502 deletions
+2 -1
View File
@@ -44,7 +44,8 @@ dist
frontend/.env
frontend/.env.local
frontend/.env.*.local
frontend/.env.production
websockets/.env.production
# Misc frontend files that should be ignored
/frontend/public/hot
/frontend/public/storage
+1 -2
View File
@@ -9,12 +9,11 @@ class CoinTransactionType extends Model
{
use HasFactory;
// FIX: Disable auto-timestamps because the table doesn't have updated_at/created_at columns
public $timestamps = false;
protected $fillable = [
'name',
'type',
'description' // Include description if your table has it
'description'
];
}
-2376
View File
File diff suppressed because it is too large Load Diff
@@ -3,7 +3,7 @@ apiVersion: apps/v1
kind: Deployment
metadata:
name: mysql
namespace: dad-group-x
namespace: dad-group-46
spec:
selector:
matchLabels:
@@ -37,7 +37,7 @@ apiVersion: v1
kind: Service
metadata:
name: mysql
namespace: dad-group-x
namespace: dad-group-46
spec:
ports:
- port: 3306
+4 -4
View File
@@ -3,10 +3,10 @@ apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: app-ingress
namespace: dad-group-x
namespace: dad-group-46
spec:
rules:
- host: web-dad-group-x-172.22.21.253.sslip.io
- host: web-dad-group-46-172.22.21.253.sslip.io
http:
paths:
- path: /
@@ -16,7 +16,7 @@ spec:
name: vue-app
port:
number: 80
- host: api-dad-group-x-172.22.21.253.sslip.io
- host: api-dad-group-46-172.22.21.253.sslip.io
http:
paths:
- path: /
@@ -26,7 +26,7 @@ spec:
name: laravel-app
port:
number: 80
- host: ws-dad-group-x-172.22.21.253.sslip.io
- host: ws-dad-group-46-172.22.21.253.sslip.io
http:
paths:
- path: /
+3 -3
View File
@@ -3,7 +3,7 @@ apiVersion: apps/v1
kind: Deployment
metadata:
name: laravel-app
namespace: dad-group-x
namespace: dad-group-46
spec:
replicas: 1
selector:
@@ -17,7 +17,7 @@ spec:
priorityClassName: high-priority
containers:
- name: api
image: registry-172.22.21.115.sslip.io/dad-group-x/api:v1.0.0
image: registry-172.22.21.115.sslip.io/dad-group-46/api:v2.0.9
resources:
requests:
memory: "256Mi"
@@ -31,7 +31,7 @@ apiVersion: v1
kind: Service
metadata:
name: laravel-app
namespace: dad-group-x
namespace: dad-group-46
spec:
ports:
- port: 80
+3 -3
View File
@@ -3,7 +3,7 @@ apiVersion: apps/v1
kind: Deployment
metadata:
name: vue-app
namespace: dad-group-x
namespace: dad-group-46
spec:
replicas: 1
selector:
@@ -17,7 +17,7 @@ spec:
priorityClassName: low-priority
containers:
- name: web
image: registry-172.22.21.115.sslip.io/dad-group-46/web:v1.0.1
image: registry-172.22.21.115.sslip.io/dad-group-46/web:v2.0.9
resources:
requests:
memory: "64Mi"
@@ -31,7 +31,7 @@ apiVersion: v1
kind: Service
metadata:
name: vue-app
namespace: dad-group-x
namespace: dad-group-46
spec:
ports:
- port: 80
+3 -3
View File
@@ -3,7 +3,7 @@ apiVersion: apps/v1
kind: Deployment
metadata:
name: websocket-server
namespace: dad-group-x
namespace: dad-group-46
spec:
replicas: 1
selector:
@@ -17,7 +17,7 @@ spec:
priorityClassName: low-priority
containers:
- name: web
image: registry-172.22.21.115.sslip.io/dad-group-x/ws:v1.0.0
image: registry-172.22.21.115.sslip.io/dad-group-46/ws:v2.0.9
resources:
requests:
memory: "128Mi"
@@ -31,7 +31,7 @@ apiVersion: v1
kind: Service
metadata:
name: websocket-server
namespace: dad-group-x
namespace: dad-group-46
spec:
ports:
- port: 3000
-4
View File
@@ -1,15 +1,12 @@
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { io } from 'socket.io-client'
import App from './App.vue'
import router from './router'
const apiDomain = import.meta.env.VITE_API_DOMAIN
const wsConnection = import.meta.env.VITE_WS_CONNECTION
console.log('[main.js] api domain', apiDomain)
console.log('[main.js] ws connection', wsConnection)
const app = createApp(App)
@@ -20,4 +17,3 @@ app.use(createPinia())
app.use(router)
app.mount('#app')
+119 -108
View File
@@ -15,7 +15,6 @@ const router = useRouter()
const authStore = useAuthStore()
const wsStore = useSocketStore()
// --- FIX: Flag to prevent double cancellation ---
const isCancelling = ref(false)
const matchState = ref({
@@ -53,16 +52,15 @@ const opponentHand = computed(() => {
return Array.from({ length: count }, (_, i) => ({ id: `opp-${i}`, suit: 'back', rank: 0 }))
})
// Timer
watch(() => wsStore.gameState?.currentTurn, () => { startTimer() }, { deep: true })
const startTimer = () => {
if (timerInterval.value) clearInterval(timerInterval.value);
timeLeft.value = 20;
if(!wsStore.gameState) return;
timerInterval.value = setInterval(() => {
if(timeLeft.value > 0) timeLeft.value--;
else clearInterval(timerInterval.value);
}, 1000);
if (timerInterval.value) clearInterval(timerInterval.value);
timeLeft.value = 20;
if (!wsStore.gameState) return;
timerInterval.value = setInterval(() => {
if (timeLeft.value > 0) timeLeft.value--;
else clearInterval(timerInterval.value);
}, 1000);
}
const handlePlayCard = (card) => {
@@ -71,12 +69,12 @@ const handlePlayCard = (card) => {
const openSurrenderModal = () => { showSurrenderModal.value = true }
const confirmSurrenderRound = () => {
showSurrenderModal.value = false;
if (wsStore.socket) wsStore.socket.emit('game:surrender', { matchId: matchState.value.id });
showSurrenderModal.value = false;
if (wsStore.socket) wsStore.socket.emit('game:surrender', { matchId: matchState.value.id });
}
const confirmSurrenderMatch = () => {
showSurrenderModal.value = false;
if (wsStore.socket) wsStore.socket.emit('match:surrender', { matchId: matchState.value.id });
showSurrenderModal.value = false;
if (wsStore.socket) wsStore.socket.emit('match:surrender', { matchId: matchState.value.id });
}
const closeRoundModal = () => { showRoundModal.value = false; }
@@ -103,7 +101,6 @@ const updateLocalState = (data) => {
}
}
// --- FIX: Cancel Match with Flag ---
const cancelMatch = async () => {
if (isCancelling.value) return;
isCancelling.value = true;
@@ -112,12 +109,11 @@ const cancelMatch = async () => {
await axios.delete(`${API_BASE_URL}/matches/${matchState.value.id}`)
router.push({ name: 'home' })
} catch (e) {
// Ignore 404s if we just deleted it
if (e.response && e.response.status === 404) {
router.push({ name: 'home' })
router.push({ name: 'home' })
} else {
isCancelling.value = false; // Reset if legitimate error
alert(e.message)
isCancelling.value = false;
alert(e.message)
}
}
}
@@ -131,28 +127,25 @@ const handleBeforeUnload = (e) => {
}
}
// --- FIX: Router Guard checks Flag ---
onBeforeRouteLeave((to, from, next) => {
// If we already clicked cancel, just let it go
if (isCancelling.value) {
return next();
}
if (matchState.value.status === 'Playing' && !matchOver.value) {
if (confirm("⚠️ WARNING: Leaving now triggers an automatic match surrender (Loss).\n\nAre you sure?")) {
if(wsStore.socket) wsStore.socket.emit('match:surrender', { matchId: matchState.value.id });
if (wsStore.socket) wsStore.socket.emit('match:surrender', { matchId: matchState.value.id });
next();
} else {
next(false);
}
} else if (isPending.value && amIHost.value) {
if(confirm("Cancel this lobby?")) {
// Mark as cancelling so we don't trigger double requests if cancelMatch is weird
isCancelling.value = true;
cancelMatch().then(() => next());
} else {
next(false);
}
if (confirm("Cancel this lobby?")) {
isCancelling.value = true;
cancelMatch().then(() => next());
} else {
next(false);
}
} else {
next();
}
@@ -179,22 +172,22 @@ onMounted(async () => {
wsStore.socket.on('match:ended', updateLocalState)
wsStore.socket.on('game:update', (state) => { wsStore.gameState = state })
wsStore.socket.on('game:trick-end', (result) => {
lastTrickWinner.value = result.winnerId;
showTrickResult.value = true;
setTimeout(() => { showTrickResult.value = false }, 2000);
lastTrickWinner.value = result.winnerId;
showTrickResult.value = true;
setTimeout(() => { showTrickResult.value = false }, 2000);
});
wsStore.socket.on('match:round-ended', (data) => {
const myPoints = data.winnerId == myUserId.value ? (data.winnerId == matchState.value.player1.id ? data.p1Points : data.p2Points) : (data.winnerId == matchState.value.player1.id ? data.p2Points : data.p1Points);
const oppPoints = data.winnerId != myUserId.value ? (data.winnerId == matchState.value.player1.id ? data.p1Points : data.p2Points) : (data.winnerId == matchState.value.player1.id ? data.p2Points : data.p1Points);
const myPoints = data.winnerId == myUserId.value ? (data.winnerId == matchState.value.player1.id ? data.p1Points : data.p2Points) : (data.winnerId == matchState.value.player1.id ? data.p2Points : data.p1Points);
const oppPoints = data.winnerId != myUserId.value ? (data.winnerId == matchState.value.player1.id ? data.p1Points : data.p2Points) : (data.winnerId == matchState.value.player1.id ? data.p2Points : data.p1Points);
roundData.value = {
winnerId: data.winnerId,
marksAdded: data.marksAdded,
myPoints: myPoints,
oppPoints: oppPoints,
reason: data.reason
};
showRoundModal.value = true;
roundData.value = {
winnerId: data.winnerId,
marksAdded: data.marksAdded,
myPoints: myPoints,
oppPoints: oppPoints,
reason: data.reason
};
showRoundModal.value = true;
});
}
})
@@ -218,7 +211,8 @@ onUnmounted(() => {
<div class="flex flex-col items-start">
<div class="flex items-center gap-2">
<span class="font-bold text-lg text-white drop-shadow-md">{{ myDisplayName }}</span>
<span v-if="matchState.wager > 0" class="flex items-center text-xs text-yellow-300 bg-yellow-900/50 px-2 rounded border border-yellow-700/50">
<span v-if="matchState.wager > 0"
class="flex items-center text-xs text-yellow-300 bg-yellow-900/50 px-2 rounded border border-yellow-700/50">
<Coins class="w-3 h-3 mr-1" /> {{ matchState.wager }}
</span>
</div>
@@ -229,7 +223,8 @@ onUnmounted(() => {
</div>
<div class="flex flex-col items-center">
<span class="text-[10px] uppercase tracking-widest text-green-400 font-bold">Match #{{ matchState.id }}</span>
<span class="text-2xl font-black font-mono text-white drop-shadow-md">{{ matchState.myMarks }} - {{ matchState.oppMarks }}</span>
<span class="text-2xl font-black font-mono text-white drop-shadow-md">{{ matchState.myMarks }} - {{
matchState.oppMarks }}</span>
</div>
<div class="flex flex-col items-end">
<span class="font-bold text-lg text-white drop-shadow-md">{{ opponentDisplayName }}</span>
@@ -242,119 +237,135 @@ onUnmounted(() => {
</div>
<div v-if="wsStore.gameState && !matchOver" class="absolute top-24 right-4 z-50">
<button @click="openSurrenderModal" 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 hover:scale-105 flex items-center gap-2 text-sm cursor-pointer">
<button @click="openSurrenderModal"
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 hover:scale-105 flex items-center gap-2 text-sm cursor-pointer">
<span>🏳</span> Surrender
</button>
</div>
<div v-if="wsStore.gameState && !matchOver && isMyTurn" class="absolute top-24 left-1/2 -translate-x-1/2 z-50">
<div class="bg-gray-800 px-6 py-2 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="bg-gray-800 px-6 py-2 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-5 h-5" :class="timeLeft <= 5 ? 'text-red-500 animate-bounce' : 'text-white'" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<svg class="w-5 h-5" :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-2xl font-mono font-bold', timeLeft <= 5 ? 'text-red-500' : 'text-white']">{{ timeLeft }}</span>
<span :class="['text-2xl font-mono font-bold', timeLeft <= 5 ? 'text-red-500' : 'text-white']">{{ timeLeft
}}</span>
</div>
</div>
</div>
<div class="pt-20 h-screen">
<GameBoard
v-if="wsStore.gameState && !matchOver"
:game-id="matchState.currentGameId"
@play-card="handlePlayCard"
:trump-card="wsStore.gameState?.trumpCard"
:cards-remaining="wsStore.gameState?.deckCount"
:player-hand="wsStore.gameState?.hand"
:opponent-hand="opponentHand"
:player-score="wsStore.gameState?.points"
:opponent-score="wsStore.gameState?.opponent?.points"
:current-turn="currentTurnLabel"
:current-trick="wsStore.gameState?.table"
:is-my-turn="isMyTurn"
:player-name="myDisplayName"
:opponent-name="opponentDisplayName"
/>
<GameBoard v-if="wsStore.gameState && !matchOver" :game-id="matchState.currentGameId" @play-card="handlePlayCard"
:trump-card="wsStore.gameState?.trumpCard" :cards-remaining="wsStore.gameState?.deckCount"
:player-hand="wsStore.gameState?.hand" :opponent-hand="opponentHand" :player-score="wsStore.gameState?.points"
:opponent-score="wsStore.gameState?.opponent?.points" :current-turn="currentTurnLabel"
:current-trick="wsStore.gameState?.table" :is-my-turn="isMyTurn" :player-name="myDisplayName"
:opponent-name="opponentDisplayName" />
<div v-else-if="isPending" class="flex h-full items-center justify-center flex-col gap-6">
<div class="text-center p-8 bg-green-800/60 rounded-2xl border border-green-600 shadow-2xl backdrop-blur-md max-w-sm w-full mx-4">
<div
class="text-center p-8 bg-green-800/60 rounded-2xl border border-green-600 shadow-2xl backdrop-blur-md max-w-sm w-full mx-4">
<div class="relative mx-auto mb-6 h-16 w-16">
<div class="absolute inset-0 rounded-full border-4 border-green-700/50"></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 class="absolute inset-0 rounded-full border-4 border-green-700/50"></div>
<div
class="absolute inset-0 rounded-full border-4 border-t-white border-r-transparent border-b-transparent border-l-transparent animate-spin">
</div>
</div>
<h2 class="text-2xl font-bold mb-2 text-white">Waiting for Opponent</h2>
<button v-if="amIHost" @click="cancelMatch" class="bg-red-600 hover:bg-red-700 text-white py-2 px-4 rounded shadow mt-4">Cancel Match</button>
<button v-if="amIHost" @click="cancelMatch"
class="bg-red-600 hover:bg-red-700 text-white py-2 px-4 rounded shadow mt-4">Cancel Match</button>
</div>
</div>
<div v-else-if="!matchOver && !wsStore.gameState" class="flex h-full items-center justify-center flex-col gap-4">
<div class="text-3xl font-bold animate-pulse text-white drop-shadow">Preparing next round...</div>
</div>
<div v-if="matchOver" class="absolute inset-0 z-50 flex items-center justify-center bg-black/80 backdrop-blur-md">
<div class="text-center space-y-6 p-8 bg-green-900 border-2 border-green-500 rounded-2xl shadow-2xl max-w-md w-full">
<div
class="text-center space-y-6 p-8 bg-green-900 border-2 border-green-500 rounded-2xl shadow-2xl max-w-md w-full">
<Trophy v-if="iWonMatch" class="w-24 h-24 text-yellow-400 mx-auto animate-bounce" />
<Frown v-else class="w-24 h-24 text-green-300 mx-auto opacity-75" />
<h1 class="text-5xl font-black uppercase mb-2" :class="iWonMatch ? 'text-yellow-400' : 'text-gray-300'">{{ iWonMatch ? 'Victory!' : 'Defeat' }}</h1>
<p class="text-green-100 text-lg">Marks: <span class="font-bold">{{ matchState.myMarks }} - {{ matchState.oppMarks }}</span></p>
<Button @click="leaveMatch" class="w-full py-6 text-lg bg-purple-600 hover:bg-purple-700">Return to Lobby</Button>
<h1 class="text-5xl font-black uppercase mb-2" :class="iWonMatch ? 'text-yellow-400' : 'text-gray-300'">{{
iWonMatch ? 'Victory!' : 'Defeat' }}</h1>
<p class="text-green-100 text-lg">Marks: <span class="font-bold">{{ matchState.myMarks }} - {{
matchState.oppMarks }}</span></p>
<Button @click="leaveMatch" class="w-full py-6 text-lg bg-purple-600 hover:bg-purple-700">Return to
Lobby</Button>
</div>
</div>
</div>
<div v-if="showRoundModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-md">
<div class="bg-gray-800 p-8 rounded-2xl border-2 border-yellow-500/50 shadow-2xl max-w-md w-full text-center relative overflow-hidden">
<div class="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-transparent via-yellow-500 to-transparent"></div>
<h2 class="text-3xl font-black text-white mb-2 uppercase">Round Over</h2>
<p class="text-gray-400 mb-6 uppercase text-xs tracking-widest">{{ roundData.reason === 'surrender' ? 'Opponent Surrendered' : 'Points Limit Reached' }}</p>
<div v-if="showRoundModal"
class="fixed inset-0 z-[100] flex items-center justify-center bg-black/80 backdrop-blur-md">
<div
class="bg-gray-800 p-8 rounded-2xl border-2 border-yellow-500/50 shadow-2xl max-w-md w-full text-center relative overflow-hidden">
<div class="absolute top-0 left-0 w-full h-2 bg-gradient-to-r from-transparent via-yellow-500 to-transparent">
</div>
<h2 class="text-3xl font-black text-white mb-2 uppercase">Round Over</h2>
<p class="text-gray-400 mb-6 uppercase text-xs tracking-widest">
{{ roundData.reason === 'surrender' ? 'Opponent Surrendered' : 'Points Limit Reached' }}</p>
<div class="flex justify-between items-center bg-black/30 p-4 rounded-lg mb-6">
<div class="text-left">
<p class="text-xs text-gray-500 uppercase">You</p>
<p class="text-2xl font-bold text-white">{{ roundData.myPoints }} pts</p>
</div>
<div class="text-xl font-bold text-yellow-500">VS</div>
<div class="text-right">
<p class="text-xs text-gray-500 uppercase">Opponent</p>
<p class="text-2xl font-bold text-white">{{ roundData.oppPoints }} pts</p>
</div>
</div>
<div class="flex justify-between items-center bg-black/30 p-4 rounded-lg mb-6">
<div class="text-left">
<p class="text-xs text-gray-500 uppercase">You</p>
<p class="text-2xl font-bold text-white">{{ roundData.myPoints }} pts</p>
</div>
<div class="text-xl font-bold text-yellow-500">VS</div>
<div class="text-right">
<p class="text-xs text-gray-500 uppercase">Opponent</p>
<p class="text-2xl font-bold text-white">{{ roundData.oppPoints }} pts</p>
</div>
</div>
<div class="mb-8">
<p class="text-lg text-white" v-if="roundData.winnerId == myUserId">
You won <span class="text-yellow-400 font-bold">+{{ roundData.marksAdded }} marks</span>!
</p>
<p class="text-lg text-white" v-else>
Opponent won <span class="text-red-400 font-bold">+{{ roundData.marksAdded }} marks</span>.
</p>
</div>
<div class="mb-8">
<p class="text-lg text-white" v-if="roundData.winnerId == myUserId">
You won <span class="text-yellow-400 font-bold">+{{ roundData.marksAdded }} marks</span>!
</p>
<p class="text-lg text-white" v-else>
Opponent won <span class="text-red-400 font-bold">+{{ roundData.marksAdded }} marks</span>.
</p>
</div>
<button @click="closeRoundModal" class="w-full py-4 bg-emerald-600 hover:bg-emerald-500 text-white font-bold rounded-xl shadow-lg transition-transform hover:scale-105">
Ready for Next Round
</button>
<button @click="closeRoundModal"
class="w-full py-4 bg-emerald-600 hover:bg-emerald-500 text-white font-bold rounded-xl shadow-lg transition-transform hover:scale-105">
Ready for Next Round
</button>
</div>
</div>
<div v-if="showSurrenderModal" class="fixed inset-0 z-[100] flex items-center justify-center bg-black/70 backdrop-blur-sm">
<div v-if="showSurrenderModal"
class="fixed inset-0 z-[100] flex items-center justify-center bg-black/70 backdrop-blur-sm">
<div class="bg-gray-800 p-6 rounded-lg border border-gray-600 shadow-2xl max-w-sm w-full text-center">
<h3 class="text-xl font-bold text-white mb-6">Surrender Options</h3>
<div class="space-y-3">
<button @click="confirmSurrenderRound" class="w-full px-4 py-3 bg-gray-700 hover:bg-gray-600 rounded text-white font-bold border border-gray-500 flex justify-between items-center group">
<button @click="confirmSurrenderRound"
class="w-full px-4 py-3 bg-gray-700 hover:bg-gray-600 rounded text-white font-bold border border-gray-500 flex justify-between items-center group">
<span>Surrender Round</span>
<span class="text-xs bg-black/40 px-2 py-1 rounded text-gray-300 group-hover:bg-red-500 group-hover:text-white">-2 Marks</span>
<span
class="text-xs bg-black/40 px-2 py-1 rounded text-gray-300 group-hover:bg-red-500 group-hover:text-white">-2
Marks</span>
</button>
<button @click="confirmSurrenderMatch" class="w-full px-4 py-3 bg-red-900/50 hover:bg-red-600 rounded text-red-200 hover:text-white font-bold border border-red-800 flex justify-between items-center group">
<button @click="confirmSurrenderMatch"
class="w-full px-4 py-3 bg-red-900/50 hover:bg-red-600 rounded text-red-200 hover:text-white font-bold border border-red-800 flex justify-between items-center group">
<span>Surrender Match</span>
<span class="text-xs bg-black/40 px-2 py-1 rounded text-red-300 group-hover:bg-red-800 group-hover:text-white">Defeat</span>
<span
class="text-xs bg-black/40 px-2 py-1 rounded text-red-300 group-hover:bg-red-800 group-hover:text-white">Defeat</span>
</button>
</div>
<button @click="showSurrenderModal = false" class="mt-6 text-gray-400 hover:text-white text-sm underline">Cancel</button>
<button @click="showSurrenderModal = false"
class="mt-6 text-gray-400 hover:text-white text-sm underline">Cancel</button>
</div>
</div>
<Transition enter-active-class="transition-all duration-300 ease-out" enter-from-class="opacity-0 scale-50" enter-to-class="opacity-100 scale-100" leave-active-class="transition-all duration-200 ease-in" leave-from-class="opacity-100 scale-100" leave-to-class="opacity-0 scale-75">
<Transition enter-active-class="transition-all duration-300 ease-out" enter-from-class="opacity-0 scale-50"
enter-to-class="opacity-100 scale-100" leave-active-class="transition-all duration-200 ease-in"
leave-from-class="opacity-100 scale-100" leave-to-class="opacity-0 scale-75">
<div v-if="showTrickResult" class="fixed top-1/3 left-1/2 -translate-x-1/2 z-[70] pointer-events-none">
<div class="bg-black/70 backdrop-blur-md px-8 py-4 rounded-2xl border border-white/10 shadow-2xl text-center">
<p class="text-sm uppercase tracking-widest text-gray-300 font-bold mb-1">Trick Winner</p>
<h2 class="text-3xl font-black" :class="lastTrickWinner === myUserId ? 'text-green-400' : 'text-red-400'">{{ lastTrickWinner === myUserId ? 'YOU' : 'OPPONENT' }}</h2>
<p class="text-sm uppercase tracking-widest text-gray-300 font-bold mb-1">Trick Winner</p>
<h2 class="text-3xl font-black" :class="lastTrickWinner === myUserId ? 'text-green-400' : 'text-red-400'">{{
lastTrickWinner === myUserId ? 'YOU' : 'OPPONENT' }}</h2>
</div>
</div>
</Transition>
+136 -17
View File
@@ -4,7 +4,6 @@ import { ref, onMounted, nextTick, inject, computed } from 'vue'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { watch } from 'vue';
import {
Card,
@@ -35,9 +34,6 @@ const mObserver = ref(null);
const mLoading = ref(false);
const mPage = ref(1);
const showHostModal = ref(false)
const showJoinModal = ref(false)
const selectedGame = ref(null)
const isReady = ref(false)
const showLeaderboardModal = ref(false)
const showStatsModal = ref(false)
const userStats = ref(null)
@@ -211,9 +207,7 @@ const startSingle = () => {
router.push({ name: 'bisca' + selectedMode.value });
}
// --- FIX: Correct Wager Logic ---
const joinMatch = async (match) => {
// Use 'stake' because that's what the API returns
const cost = match.stake || match.wager || 0;
if (cost > userCoins.value) {
@@ -365,7 +359,8 @@ onMounted(async () => {
</CardHeader>
<CardContent class="space-y-6">
<div class="flex justify-center">
<Button @click="startSingle()" size="lg" variant="secondary" class="hover:bg-purple-500 hover:text-slate-200">
<Button @click="startSingle()" size="lg" variant="secondary"
class="hover:bg-purple-500 hover:text-slate-200">
Start Game
</Button>
</div>
@@ -381,8 +376,10 @@ onMounted(async () => {
<div class="flex flex-col flex-1">
<div class="flex justify-between items-end mb-2">
<label class="text-sm font-bold uppercase tracking-wider text-muted-foreground">Open Matches (Best of 3)</label>
<Button v-if="isLoggedIn" @click="openHostModal(true)" size="sm" variant="outline" class="border-purple-500 text-purple-500 hover:bg-purple-500 hover:text-white font-bold">
<label class="text-sm font-bold uppercase tracking-wider text-muted-foreground">Open Matches (Best of
3)</label>
<Button v-if="isLoggedIn" @click="openHostModal(true)" size="sm" variant="outline"
class="border-purple-500 text-purple-500 hover:bg-purple-500 hover:text-white font-bold">
Host
</Button>
</div>
@@ -394,17 +391,20 @@ onMounted(async () => {
<div v-for="(match, index) in openMatches" :key="match.id" @click="joinMatch(match)"
class="flex items-center justify-between p-3 mb-2 border border-transparent rounded-lg cursor-pointer transition-all hover:bg-muted/50 hover:border-purple-500">
<div class="flex items-center gap-3">
<div class="flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold bg-red-100 text-red-700">
<div
class="flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold bg-red-100 text-red-700">
{{ index + 1 }}
</div>
<div>
<div class="font-medium text-sm flex items-center gap-2">
Match #{{ match.id }}
<span class="flex items-center text-xs bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded-full">
<span
class="flex items-center text-xs bg-yellow-100 text-yellow-700 px-2 py-0.5 rounded-full">
<Coins class="w-3 h-3 mr-1" /> {{ match.stake || match.wager }}
</span>
</div>
<div class="text-[10px] text-muted-foreground">Host: {{ match.player1?.nickname || 'Unknown' }}</div>
<div class="text-[10px] text-muted-foreground">Host: {{ match.player1?.nickname || 'Unknown' }}
</div>
</div>
</div>
</div>
@@ -417,8 +417,10 @@ onMounted(async () => {
<div class="flex flex-col flex-1">
<div class="flex justify-between items-end mb-2">
<label class="text-sm font-medium uppercase tracking-wider text-muted-foreground">Open Games (Single)</label>
<Button v-if="isLoggedIn" @click="openHostModal(false)" size="sm" variant="outline" class="border-purple-500 text-purple-500 hover:bg-purple-500 hover:text-white font-bold">
<label class="text-sm font-medium uppercase tracking-wider text-muted-foreground">Open Games
(Single)</label>
<Button v-if="isLoggedIn" @click="openHostModal(false)" size="sm" variant="outline"
class="border-purple-500 text-purple-500 hover:bg-purple-500 hover:text-white font-bold">
Host
</Button>
</div>
@@ -430,7 +432,8 @@ onMounted(async () => {
<div v-for="(game, index) in openGames" :key="game.id" @click="joinGame(game)"
class="flex items-center justify-between p-3 mb-2 border border-transparent rounded-lg cursor-pointer transition-all hover:bg-muted/50 hover:border-purple-500">
<div class="flex items-center gap-3">
<div class="flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold bg-green-100 text-green-700">
<div
class="flex h-8 w-8 items-center justify-center rounded-full text-xs font-bold bg-green-100 text-green-700">
{{ index + 1 }}
</div>
<div>
@@ -450,9 +453,113 @@ onMounted(async () => {
</div>
</div>
<div v-if="showStatsModal"
class="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
<Card class="w-full max-w-sm max-h-2/3 border-purple-500 shadow-2xl">
<CardHeader class="border-b bg-muted/20">
<div class="flex justify-between items-center">
<CardTitle class="flex items-center gap-2">
<User class="text-yellow-500" /> My Statistics
</CardTitle>
<Button variant="ghost" size="sm" @click="showStatsModal = false">X</Button>
</div>
</CardHeader>
<CardContent class="py-6">
<div v-if="statsLoading" class="flex flex-col items-center py-10 gap-4">
<div class="h-8 w-8 animate-spin rounded-full border-4 border-purple-500 border-t-transparent">
</div>
<p class="text-sm text-muted-foreground">Calculating your glory...</p>
</div>
<div v-else-if="userStats" class="space-y-6">
<div class="text-center">
<h3 class="text-2xl font-bold text-purple-600">{{ userStats.nickname }}</h3>
<p class="text-sm text-muted-foreground">Performance Overview</p>
</div>
<div class="grid grid-cols-2 gap-4">
<div
class="rounded-lg bg-muted/50 p-4 text-center border border-transparent hover:border-purple-500/30 transition-all">
<p class="text-xs uppercase text-muted-foreground font-semibold">Total Games</p>
<p class="text-2xl font-bold">{{ userStats.total_games }}</p>
</div>
<div class="rounded-lg bg-purple-500/10 p-4 text-center border border-purple-500/20">
<p class="text-xs uppercase text-purple-600 font-semibold">Win Rate</p>
<p class="text-2xl font-bold text-purple-600">{{ userStats.win_rate }}</p>
</div>
<div class="rounded-lg bg-green-500/10 p-4 text-center border border-green-500/20">
<p class="text-xs uppercase text-green-600 font-semibold">Wins</p>
<p class="text-2xl font-bold text-green-600">{{ userStats.total_wins }}</p>
</div>
<div class="rounded-lg bg-red-500/10 p-4 text-center border border-red-500/20">
<p class="text-xs uppercase text-red-600 font-semibold">Losses</p>
<p class="text-2xl font-bold text-red-600">{{ userStats.total_losses }}</p>
</div>
</div>
<div class="space-y-2">
<div class="flex justify-between text-xs font-medium">
<span>Win/Loss Ratio</span>
<span>{{ userStats.total_wins }}W - {{ userStats.total_losses }}L</span>
</div>
<div class="h-2 w-full bg-red-500/20 rounded-full overflow-hidden flex">
<div class="bg-green-500 h-full" :style="{ width: userStats.win_rate }"></div>
</div>
</div>
</div>
</CardContent>
</Card>
</div>
<div v-if="showLeaderboardModal"
class="fixed inset-0 z-[60] flex items-center justify-center bg-black/60 backdrop-blur-sm p-4">
<Card class="w-full max-w-lg max-h-1/2 h-[80vh] flex flex-col border-purple-500 shadow-2xl">
<CardHeader class="border-b">
<div class="flex justify-between items-center">
<CardTitle class="flex items-center gap-2">
<Trophy class="text-purple-500" /> Leaderboard
</CardTitle>
<Button variant="ghost" size="sm" @click="showLeaderboardModal = false">X</Button>
</div>
</CardHeader>
<CardContent class="flex-1 overflow-y-auto custom-scrollbar p-0">
<div v-for="(user, index) in leaderboardEntries" :key="user.id"
class="flex items-center justify-between p-4 border-b last:border-0 hover:bg-muted/30 transition-colors">
<div class="flex items-center gap-4">
<span class="font-bold text-muted-foreground w-6 text-center"
:class="{ 'text-yellow-500': index === 0, 'text-slate-400': index === 1, 'text-orange-400': index === 2 }">
#{{ index + 1 }}
</span>
<img :src="getAvatarUrl(user.photo_avatar_filename)"
class="h-10 w-10 rounded-full border border-purple-200 object-cover" alt="Avatar" />
<div>
<p class="font-semibold text-sm">{{ user.nickname }}</p>
<p class="text-[10px] text-muted-foreground uppercase tracking-wider">Player</p>
</div>
</div>
<div class="text-right">
<p class="text-lg font-bold text-purple-600">{{ user.won_games_count }}</p>
<p class="text-[10px] text-muted-foreground uppercase">Wins</p>
</div>
</div>
<div ref="lbObserverTarget" class="h-20 flex items-center justify-center">
<span v-if="lbLoading" class="text-purple-500 animate-bounce">Loading rankings...</span>
</div>
</CardContent>
</Card>
</div>
<div v-if="showHostModal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm">
<Card class="w-full max-w-sm border-purple-500 shadow-2xl">
<CardHeader><CardTitle class="text-center">{{ isBestOfThree ? 'Host Match (Best of 3)' : 'Host Game' }}</CardTitle></CardHeader>
<CardHeader>
<CardTitle class="text-center">{{ isBestOfThree ? 'Host Match (Best of 3)' : 'Host Game' }}</CardTitle>
</CardHeader>
<CardContent class="flex flex-col gap-6 py-4">
<div v-if="isBestOfThree" class="space-y-2">
<Label>Wager (Coins)</Label>
@@ -463,7 +570,8 @@ onMounted(async () => {
<p class="text-xs text-muted-foreground text-right">Balance: {{ userCoins }}</p>
</div>
<div class="flex gap-2">
<Button variant="outline" class="flex-1" @click="showHostModal = false" :disabled="hostLoading">Cancel</Button>
<Button variant="outline" class="flex-1" @click="showHostModal = false"
:disabled="hostLoading">Cancel</Button>
<Button class="flex-1 bg-purple-600 hover:bg-purple-700" @click="hostGame" :disabled="hostLoading">
{{ hostLoading ? 'Creating...' : 'Create' }}
</Button>
@@ -472,5 +580,16 @@ onMounted(async () => {
</Card>
</div>
<div class="fixed right-4 top-1/2 -translate-y-1/2 flex flex-col gap-4 z-40">
<Button @click="openLeaderboard" variant="outline" size="icon"
class="h-12 w-12 rounded-full shadow-lg border-purple-500 bg-card hover:bg-purple-500 hover:text-white transition-all">
<Trophy class="h-6 w-6" />
</Button>
<Button v-if="useAuthStore().isLoggedIn" @click="openStats" variant="outline" size="icon"
class="h-12 w-12 rounded-full shadow-lg border-purple-500 bg-card hover:bg-purple-500 hover:text-white transition-all">
<User class="h-6 w-6" />
</Button>
</div>
</div>
</template>
+1 -1
View File
@@ -101,7 +101,7 @@ const handleFileChange = (event) => {
}
const validateForm = () => {
errors.value = {} // Reset errors
errors.value = {}
let isValid = true
if (!formData.value.email.match(/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/)) {
File diff suppressed because it is too large Load Diff
+8 -6
View File
@@ -12,7 +12,7 @@ export const useSocketStore = defineStore('websocket', () => {
const lastError = ref(null)
const currentGameId = ref(null)
const WS_URL = 'http://localhost:3000'
const WS_URL = import.meta.env.VITE_WS_CONNECTION || 'ws://localhost:3000'
const connect = () => {
if (socket.value?.connected) return
@@ -27,13 +27,15 @@ export const useSocketStore = defineStore('websocket', () => {
auth: { token: `Bearer ${token}` },
reconnection: true,
reconnectionAttempts: 5,
reconnectionDelay: 1000
reconnectionDelay: 1000,
})
console.log('[WebSocket] Attempting to connect to', WS_URL)
socket.value.on('connect', () => {
if (currentGameId.value) {
console.log("Reconnected to socket. Rejoining game...");
socket.emit("join-game", { gameId: currentGameId.value });
console.log('Reconnected to socket. Rejoining game...')
socket.emit('join-game', { gameId: currentGameId.value })
}
connected.value = true
@@ -122,8 +124,8 @@ export const useSocketStore = defineStore('websocket', () => {
disconnect,
joinGame,
playCard,
surrender,
surrender,
onTrickEnd,
onGameOver
onGameOver,
}
})
+2 -2
View File
@@ -1,6 +1,6 @@
GROUP := "dad-group-x"
VERSION := "1.0.0"
GROUP := "dad-group-46"
VERSION := "2.0.9"
kubectl-pods:
-2
View File
@@ -1,2 +0,0 @@
PORT=
API_URL=
+4 -7
View File
@@ -48,11 +48,9 @@ class BiscaGame {
this.dealInitialCards();
// --- FIX: Ensure currentTurn uses the original ID type (Number) ---
// Object.keys returns strings ("1"), which breaks strict checks against user.id (1)
const playerKeys = Object.keys(this.players);
const startKey = playerKeys.find((key) => key != 1) || playerKeys[0];
this.currentTurn = this.players[startKey].id;
this.currentTurn = this.players[startKey].id;
this.startTime = Date.now();
this.status = "playing";
@@ -192,7 +190,6 @@ class BiscaGame {
this.players[winnerId].tricks += 1;
this.currentTurn = winnerId;
// --- FIX: Always draw if deck has cards (Removed type check) ---
if (this.deck.length > 0 || this.trumpCard) {
this.drawCard(winnerId);
this.drawCard(this.getOpponentId(winnerId));
@@ -222,8 +219,8 @@ class BiscaGame {
const finalLoser = isDraw
? null
: gameWinnerId == p1Obj.id
? p2Obj.id
: p1Obj.id;
? p2Obj.id
: p1Obj.id;
const result = {
action: "game_ended",
@@ -237,7 +234,7 @@ class BiscaGame {
player2_points: p2Obj.points,
totalTime: totalTime,
};
if (this.onGameEnd) {
this.onGameEnd(result);
}
+102 -66
View File
@@ -1,13 +1,13 @@
import BiscaGame from "../classes/BiscaGame.js";
import axios from "axios";
const API_URL = "http://localhost:8000/api/v1";
const API_URL = process.env.API_URL || "http://localhost:8000/api/v1";
class BiscaMatch {
constructor(apiData, emitStateCallback, token, autoPlayCallback) {
this.id = apiData.id;
this.emitStateCallback = emitStateCallback;
this.autoPlayCallback = autoPlayCallback;
this.autoPlayCallback = autoPlayCallback;
this.token = token;
this.stake = apiData.stake;
this.type = apiData.type;
@@ -52,10 +52,10 @@ class BiscaMatch {
getAuthHeaders() {
return {
headers: {
Authorization: this.token,
"Content-Type": "application/json",
"Accept": "application/json"
headers: {
Authorization: this.token,
"Content-Type": "application/json",
Accept: "application/json",
},
};
}
@@ -72,8 +72,12 @@ class BiscaMatch {
status: "Playing",
began_at: new Date().toISOString(),
};
const res = await axios.post(`${API_URL}/games`, payload, this.getAuthHeaders());
const res = await axios.post(
`${API_URL}/games`,
payload,
this.getAuthHeaders()
);
const gameData = res.data.game || res.data.data || res.data;
newGameDbId = gameData.id;
@@ -86,17 +90,19 @@ class BiscaMatch {
{ id: this.player1Id, name: p1Name },
{ id: this.player2Id, name: p2Name },
newGameDbId,
(result) => { this.handleGameEnd(result); }
(result) => {
this.handleGameEnd(result);
}
);
this.currentGame.init();
this.currentGame.startTurnTimer((uid, cid) => {
if (this.autoPlayCallback) this.autoPlayCallback(uid, cid);
if (this.autoPlayCallback) this.autoPlayCallback(uid, cid);
});
if (this.emitStateCallback) {
this.emitStateCallback("match:new-round-start", null);
this.emitStateCallback("match:new-round-start", null);
}
} catch (e) {
console.error(`❌ Start Game Error: ${e.message}`);
@@ -104,82 +110,104 @@ class BiscaMatch {
}
async abortCurrentGame(loserId) {
if (this.currentGame && this.currentGame.dbId) {
console.log(`[Match ${this.id}] Aborting Game #${this.currentGame.dbId}`);
try {
const winnerId = loserId == this.player1Id ? this.player2Id : this.player1Id;
const payload = {
status: "Ended",
winner_user_id: winnerId,
loser_user_id: loserId,
is_draw: false,
ended_at: new Date().toISOString(),
};
await axios.put(`${API_URL}/games/${this.currentGame.dbId}`, payload, this.getAuthHeaders());
} catch(e) { console.error("Error aborting game:", e.message); }
if (this.currentGame && this.currentGame.dbId) {
console.log(`[Match ${this.id}] Aborting Game #${this.currentGame.dbId}`);
try {
const winnerId =
loserId == this.player1Id ? this.player2Id : this.player1Id;
const payload = {
status: "Ended",
winner_user_id: winnerId,
loser_user_id: loserId,
is_draw: false,
ended_at: new Date().toISOString(),
};
await axios.put(
`${API_URL}/games/${this.currentGame.dbId}`,
payload,
this.getAuthHeaders()
);
} catch (e) {
console.error("Error aborting game:", e.message);
}
}
}
async handleGameEnd(result) {
console.log(`[Match ${this.id}] Round ended. Winner: ${result.winnerId}`);
if (this.points[result.player1_id] !== undefined) this.points[result.player1_id] += result.player1_points;
if (this.points[result.player2_id] !== undefined) this.points[result.player2_id] += result.player2_points;
if (this.points[result.player1_id] !== undefined)
this.points[result.player1_id] += result.player1_points;
if (this.points[result.player2_id] !== undefined)
this.points[result.player2_id] += result.player2_points;
if (this.currentGame && this.currentGame.dbId) {
try {
const payload = {
status: "Ended",
winner_user_id: result.winnerId,
loser_user_id: result.loserId,
is_draw: result.isDraw,
player1_points: result.player1_points,
player2_points: result.player2_points,
ended_at: new Date().toISOString(),
};
await axios.put(`${API_URL}/games/${this.currentGame.dbId}`, payload, this.getAuthHeaders());
} catch (e) { console.error("DB Game Update Error:", e.message); }
try {
const payload = {
status: "Ended",
winner_user_id: result.winnerId,
loser_user_id: result.loserId,
is_draw: result.isDraw,
player1_points: result.player1_points,
player2_points: result.player2_points,
ended_at: new Date().toISOString(),
};
await axios.put(
`${API_URL}/games/${this.currentGame.dbId}`,
payload,
this.getAuthHeaders()
);
} catch (e) {
console.error("DB Game Update Error:", e.message);
}
}
let marksToAdd = 0;
let roundWinnerId = result.winnerId;
if (roundWinnerId) {
const winningScore = roundWinnerId == result.player1_id ? result.player1_points : result.player2_points;
const winningScore =
roundWinnerId == result.player1_id
? result.player1_points
: result.player2_points;
if (winningScore === 120) marksToAdd = 4;
else if (winningScore > 90) marksToAdd = 2;
else if (winningScore >= 60) marksToAdd = 1;
if (this.marks[roundWinnerId] !== undefined) this.marks[roundWinnerId] += marksToAdd;
if (this.marks[roundWinnerId] !== undefined)
this.marks[roundWinnerId] += marksToAdd;
}
if (this.emitStateCallback) {
this.emitStateCallback("match:round-ended", {
winnerId: roundWinnerId,
marksAdded: marksToAdd,
p1Points: result.player1_points,
p2Points: result.player2_points,
p1Marks: this.marks[this.player1Id],
p2Marks: this.marks[this.player2Id],
reason: result.reason || 'points'
});
this.emitStateCallback("match:round-ended", {
winnerId: roundWinnerId,
marksAdded: marksToAdd,
p1Points: result.player1_points,
p2Points: result.player2_points,
p1Marks: this.marks[this.player1Id],
p2Marks: this.marks[this.player2Id],
reason: result.reason || "points",
});
}
if (this.marks[this.player1Id] >= 4 || this.marks[this.player2Id] >= 4) {
await this.finishMatch();
if (this.emitStateCallback) this.emitStateCallback("match:ended-signal", null);
if (this.emitStateCallback)
this.emitStateCallback("match:ended-signal", null);
} else {
setTimeout(() => {
this.startNewGame();
this.startNewGame();
}, 1000);
}
}
async finishMatch() {
this.status = "Ended";
const winnerId = this.marks[this.player1Id] >= 4 ? this.player1Id : this.player2Id;
const loserId = winnerId == this.player1Id ? this.player2Id : this.player1Id;
const winnerId =
this.marks[this.player1Id] >= 4 ? this.player1Id : this.player2Id;
const loserId =
winnerId == this.player1Id ? this.player2Id : this.player1Id;
const payload = {
status: "Ended",
@@ -192,7 +220,11 @@ class BiscaMatch {
};
try {
await axios.put(`${API_URL}/matches/${this.id}`, payload, this.getAuthHeaders());
await axios.put(
`${API_URL}/matches/${this.id}`,
payload,
this.getAuthHeaders()
);
console.log(`[Match ${this.id}] Match Closed in DB.`);
} catch (e) {
console.error(`Match Close Error: ${e.message}`);
@@ -201,21 +233,25 @@ class BiscaMatch {
playCard(userId, cardId) {
if (!this.currentGame || this.status !== "Playing") return;
const result = this.currentGame.playCard(userId, cardId);
if (result && (result.action === 'next_turn' || result.action === 'trick_resolved')) {
this.currentGame.startTurnTimer((uid, cid) => {
if (this.autoPlayCallback) this.autoPlayCallback(uid, cid);
});
if (
result &&
(result.action === "next_turn" || result.action === "trick_resolved")
) {
this.currentGame.startTurnTimer((uid, cid) => {
if (this.autoPlayCallback) this.autoPlayCallback(uid, cid);
});
}
return result;
}
getGameState(userId) {
if (!this.currentGame) return null;
if (this.currentGame.players[userId]) return this.currentGame.getStateForPlayer(userId);
if (this.currentGame.players[userId])
return this.currentGame.getStateForPlayer(userId);
return null;
}
@@ -226,7 +262,7 @@ class BiscaMatch {
marks: this.marks,
points: this.points,
player1: this.player1,
player2: this.player2
player2: this.player2,
};
}
}
+174 -149
View File
@@ -2,69 +2,80 @@ import axios from "axios";
import { getGame, createGame } from "../state/game.js";
import { getUser } from "../state/connection.js";
const API_URL = "http://localhost:8000/api/v1";
const API_URL = process.env.API_URL || "http://localhost:8000/api/v1";
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;
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;
};
const drawCard = (game, playerId) => {
const player = game.players[playerId];
if (!player) return;
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;
}
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;
}
};
const sanitizeState = (state, game) => {
if (!state) return null;
const p1 = game.player1 || state.player1 || {};
const p2 = game.player2 || state.player2 || {};
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
};
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);
}
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 {
@@ -79,8 +90,11 @@ async function saveGameResult(gameId, result, token) {
payload.winner_user_id = result.winnerId;
payload.loser_user_id = result.loserId;
}
const authHeader = token.startsWith("Bearer ") ? token : `Bearer ${token}`;
await axios.put(`${API_URL}/games/${gameId}`, payload, {
headers: { Authorization: token },
headers: { Authorization: authHeader },
});
} catch (error) {
console.error(`[DB Error] Game ${gameId}:`, error.message);
@@ -88,53 +102,55 @@ async function saveGameResult(gameId, result, token) {
}
const performGameEnd = (io, game, gameId, winnerId, loserId, reason) => {
const result = {
action: "game_ended",
winnerId: parseInt(winnerId),
loserId: parseInt(loserId),
totalTime: game.startTime ? Math.floor((Date.now() - game.startTime) / 1000) : 0,
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
};
const result = {
action: "game_ended",
winnerId: parseInt(winnerId),
loserId: parseInt(loserId),
totalTime: game.startTime
? Math.floor((Date.now() - game.startTime) / 1000)
: 0,
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);
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"
});
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 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;
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 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 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);
handleGameMove(io, gameId, userId, cardToPlay.id);
}
};
@@ -144,30 +160,33 @@ const handleGameMove = (io, gameId, userId, cardId) => {
const result = game.playCard(userId, cardId);
const roomName = `game_${gameId}`;
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 (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 (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);
if (winnerId) drawCard(game, winnerId);
if (loserId) drawCard(game, loserId);
}
}, 1500);
broadcastState(io, gameId, game);
}
}, 1500);
}
if (result.action === "game_ended") {
performGameEnd(io, game, gameId, result.winnerId, result.loserId, "points");
performGameEnd(io, game, gameId, result.winnerId, result.loserId, "points");
}
if (result.action === "next_turn" || result.action === "trick_resolved") {
@@ -189,72 +208,76 @@ export default (io, socket) => {
let gameData = null;
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 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");
}
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 }
);
game.status = gameData.status === 'Playing' ? 'playing' : 'pending';
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 }
);
game.status = gameData.status === "Playing" ? "playing" : "pending";
}
if (!game) {
socket.emit("error", { message: "Game not found." });
return;
socket.emit("error", { message: "Game not found." });
return;
}
const myId = user.id;
const ghostKey = Object.keys(game.players).find(key => key == 1);
const ghostKey = Object.keys(game.players).find((key) => key == 1);
const amIDbPlayer2 = gameData && gameData.player2_user_id == myId;
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];
}
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];
}
game.players[myId] = {
id: myId,
name: user.nickname,
hand: ghostHand,
points: ghostPoints,
tricks: ghostTricks,
token: socket.handshake.auth.token,
};
game.player2 = { id: myId, name: user.nickname };
game.status = 'playing';
if(!game.timer) {
game.startTurnTimer((timeoutUserId) => handleTimeout(io, gameId, timeoutUserId));
}
game.players[myId] = {
id: myId,
name: user.nickname,
hand: ghostHand,
points: ghostPoints,
tricks: ghostTricks,
token: socket.handshake.auth.token,
};
game.player2 = { id: myId, name: user.nickname };
game.status = "playing";
if (!game.timer) {
game.startTurnTimer((timeoutUserId) =>
handleTimeout(io, gameId, timeoutUserId)
);
}
}
socket.join(`game_${gameId}`);
socket.activeGameId = gameId;
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);
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);
}
});
@@ -264,14 +287,16 @@ export default (io, socket) => {
});
socket.on("surrender", ({ gameId }) => {
const user = getUser(socket.id);
const game = getGame(gameId);
if (!game || !user || !game.players[user.id]) return;
const user = getUser(socket.id);
const game = getGame(gameId);
console.log(`[Game] User ${user.nickname} surrendered.`);
const winnerId = Object.keys(game.players).find(id => String(id) !== String(user.id));
performGameEnd(io, game, gameId, winnerId, user.id, "surrender");
if (!game || !user || !game.players[user.id]) return;
console.log(`[Game] User ${user.nickname} surrendered.`);
const winnerId = Object.keys(game.players).find(
(id) => String(id) !== String(user.id)
);
performGameEnd(io, game, gameId, winnerId, user.id, "surrender");
});
};
+151 -137
View File
@@ -2,153 +2,167 @@ import { getMatch, addMatch } from "../state/match.js";
import BiscaMatch from "../classes/BiscaMatch.js";
import axios from "axios";
const API_URL = "http://localhost:8000/api/v1";
const API_URL = process.env.API_URL || "http://localhost:8000/api/v1";
export default (io, socket) => {
const broadcastMatchUpdate = (matchId, match) => {
const roomName = `match_${matchId}`;
const room = io.sockets.adapter.rooms.get(roomName);
if (room) {
for (const socketId of room) {
const clientSocket = io.sockets.sockets.get(socketId);
if (!clientSocket || !clientSocket.user) continue;
const userId = clientSocket.user.id;
const publicState = match.getPublicState();
const gameState = match.getGameState(userId);
clientSocket.emit("match:update", { ...publicState, game: gameState });
}
}
};
const createMatchEmitter = (matchId) => (eventName, payload) => {
const match = getMatch(matchId);
if (!match) return;
if (eventName === 'match:new-round-start' || eventName === 'match:ended-signal') {
broadcastMatchUpdate(matchId, match);
} else if (eventName === 'match:round-ended') {
io.to(`match_${matchId}`).emit('match:round-ended', payload);
} else {
io.to(`match_${matchId}`).emit(eventName, payload);
}
};
const handleAutoPlay = (matchId) => (userId, cardId) => {
const match = getMatch(matchId);
if (!match || match.status !== "Playing") return;
console.log(`[Match ${matchId}] Auto-playing for User ${userId}`);
const result = match.playCard(userId, cardId);
if (result && result.action === "trick_resolved") {
io.to(`match_${matchId}`).emit("game:trick-end", result.trickResult);
setTimeout(() => { broadcastMatchUpdate(matchId, match); }, 1500);
} else {
broadcastMatchUpdate(matchId, match);
}
};
socket.on("match:enter", async (data) => {
const { matchId } = data;
if (!socket.user || !socket.user.id) return socket.emit("error", { message: "Auth failed" });
const userId = socket.user.id;
socket.activeMatchId = matchId;
const room = `match_${matchId}`;
let match = getMatch(matchId);
if (!match) {
try {
const res = await axios.get(`${API_URL}/matches/${matchId}`, {
headers: { Authorization: socket.token || socket.handshake.auth.token },
});
const matchData = res.data.data || res.data;
match = new BiscaMatch(
matchData,
createMatchEmitter(matchId),
socket.token,
handleAutoPlay(matchId)
);
addMatch(match);
} catch (e) {
return socket.emit("error", "Match not found");
}
}
match.emitStateCallback = createMatchEmitter(matchId);
if (userId !== match.player1Id && match.player2Id === 1) await match.joinPlayer(userId, socket.user);
socket.join(room);
const broadcastMatchUpdate = (matchId, match) => {
const roomName = `match_${matchId}`;
const room = io.sockets.adapter.rooms.get(roomName);
if (room) {
for (const socketId of room) {
const clientSocket = io.sockets.sockets.get(socketId);
if (!clientSocket || !clientSocket.user) continue;
const userId = clientSocket.user.id;
const publicState = match.getPublicState();
const gameState = match.getGameState(userId);
socket.emit("match:update", { ...publicState, game: gameState });
if (match.status === 'Playing') broadcastMatchUpdate(matchId, match);
});
clientSocket.emit("match:update", { ...publicState, game: gameState });
}
}
};
socket.on("game:play-card", (data) => {
const { matchId, cardId } = data;
const match = getMatch(matchId);
if (!match || match.status !== "Playing") return;
const result = match.playCard(socket.user.id, cardId);
if (result && result.error) return socket.emit("error", { message: result.error });
if (result && result.action === "trick_resolved") {
io.to(`match_${matchId}`).emit("game:trick-end", result.trickResult);
setTimeout(() => { broadcastMatchUpdate(matchId, match); }, 1500);
} else {
broadcastMatchUpdate(matchId, match);
}
});
const createMatchEmitter = (matchId) => (eventName, payload) => {
const match = getMatch(matchId);
if (!match) return;
socket.on("game:surrender", async ({ matchId }) => {
const match = getMatch(matchId);
if(!match || match.status !== "Playing") return;
const userId = socket.user.id;
console.log(`[Match ${matchId}] User ${userId} surrendered ROUND.`);
const opponentId = match.player1Id == userId ? match.player2Id : match.player1Id;
const result = {
winnerId: opponentId,
loserId: userId,
isDraw: false,
player1_id: match.player1Id,
player2_id: match.player2Id,
player1_points: match.player1Id == opponentId ? 91 : 0,
player2_points: match.player2Id == opponentId ? 91 : 0,
reason: 'surrender'
};
await match.handleGameEnd(result);
});
if (
eventName === "match:new-round-start" ||
eventName === "match:ended-signal"
) {
broadcastMatchUpdate(matchId, match);
} else if (eventName === "match:round-ended") {
io.to(`match_${matchId}`).emit("match:round-ended", payload);
} else {
io.to(`match_${matchId}`).emit(eventName, payload);
}
};
socket.on("match:surrender", async ({ matchId }) => {
const match = getMatch(matchId);
if(!match || match.status !== "Playing") return;
const userId = socket.user.id;
await match.abortCurrentGame(userId);
const handleAutoPlay = (matchId) => (userId, cardId) => {
const match = getMatch(matchId);
if (!match || match.status !== "Playing") return;
console.log(`[Match ${matchId}] User ${userId} surrendered MATCH.`);
const opponentId = match.player1Id == userId ? match.player2Id : match.player1Id;
match.marks[opponentId] = 4;
await match.finishMatch();
console.log(`[Match ${matchId}] Auto-playing for User ${userId}`);
const result = match.playCard(userId, cardId);
if (result && result.action === "trick_resolved") {
io.to(`match_${matchId}`).emit("game:trick-end", result.trickResult);
setTimeout(() => {
broadcastMatchUpdate(matchId, match);
});
}, 1500);
} else {
broadcastMatchUpdate(matchId, match);
}
};
socket.on("disconnect", async () => {
if (socket.activeMatchId) {
const match = getMatch(socket.activeMatchId);
if (match && match.status === 'Playing') {
const userId = socket.user?.id;
if (userId === match.player1Id || userId === match.player2Id) {
console.log(`[Match ${match.id}] Player ${userId} disconnected.`);
await match.abortCurrentGame(userId);
socket.on("match:enter", async (data) => {
const { matchId } = data;
if (!socket.user || !socket.user.id)
return socket.emit("error", { message: "Auth failed" });
const userId = socket.user.id;
socket.activeMatchId = matchId;
const opponentId = match.player1Id == userId ? match.player2Id : match.player1Id;
match.marks[opponentId] = 4;
await match.finishMatch();
broadcastMatchUpdate(match.id, match);
}
}
const room = `match_${matchId}`;
let match = getMatch(matchId);
if (!match) {
try {
const res = await axios.get(`${API_URL}/matches/${matchId}`, {
headers: {
Authorization: socket.token || socket.handshake.auth.token,
},
});
const matchData = res.data.data || res.data;
match = new BiscaMatch(
matchData,
createMatchEmitter(matchId),
socket.token,
handleAutoPlay(matchId)
);
addMatch(match);
} catch (e) {
return socket.emit("error", "Match not found");
}
}
match.emitStateCallback = createMatchEmitter(matchId);
if (userId !== match.player1Id && match.player2Id === 1)
await match.joinPlayer(userId, socket.user);
socket.join(room);
const publicState = match.getPublicState();
const gameState = match.getGameState(userId);
socket.emit("match:update", { ...publicState, game: gameState });
if (match.status === "Playing") broadcastMatchUpdate(matchId, match);
});
socket.on("game:play-card", (data) => {
const { matchId, cardId } = data;
const match = getMatch(matchId);
if (!match || match.status !== "Playing") return;
const result = match.playCard(socket.user.id, cardId);
if (result && result.error)
return socket.emit("error", { message: result.error });
if (result && result.action === "trick_resolved") {
io.to(`match_${matchId}`).emit("game:trick-end", result.trickResult);
setTimeout(() => {
broadcastMatchUpdate(matchId, match);
}, 1500);
} else {
broadcastMatchUpdate(matchId, match);
}
});
socket.on("game:surrender", async ({ matchId }) => {
const match = getMatch(matchId);
if (!match || match.status !== "Playing") return;
const userId = socket.user.id;
console.log(`[Match ${matchId}] User ${userId} surrendered ROUND.`);
const opponentId =
match.player1Id == userId ? match.player2Id : match.player1Id;
const result = {
winnerId: opponentId,
loserId: userId,
isDraw: false,
player1_id: match.player1Id,
player2_id: match.player2Id,
player1_points: match.player1Id == opponentId ? 91 : 0,
player2_points: match.player2Id == opponentId ? 91 : 0,
reason: "surrender",
};
await match.handleGameEnd(result);
});
socket.on("match:surrender", async ({ matchId }) => {
const match = getMatch(matchId);
if (!match || match.status !== "Playing") return;
const userId = socket.user.id;
await match.abortCurrentGame(userId);
console.log(`[Match ${matchId}] User ${userId} surrendered MATCH.`);
const opponentId =
match.player1Id == userId ? match.player2Id : match.player1Id;
match.marks[opponentId] = 4;
await match.finishMatch();
broadcastMatchUpdate(matchId, match);
});
socket.on("disconnect", async () => {
if (socket.activeMatchId) {
const match = getMatch(socket.activeMatchId);
if (match && match.status === "Playing") {
const userId = socket.user?.id;
if (userId === match.player1Id || userId === match.player2Id) {
console.log(`[Match ${match.id}] Player ${userId} disconnected.`);
await match.abortCurrentGame(userId);
const opponentId =
match.player1Id == userId ? match.player2Id : match.player1Id;
match.marks[opponentId] = 4;
await match.finishMatch();
broadcastMatchUpdate(match.id, match);
}
});
}
}
});
};
+134 -113
View File
@@ -6,137 +6,158 @@ import gameEvents from "./events/game.js";
import matchEvents from "./events/match.js";
export const server = {
io: null,
io: null,
};
const API_URL = "http://localhost:8000/api/v1";
const API_URL = process.env.API_URL || "http://localhost:8000/api/v1";
const disconnectTimers = new Map();
const RECONNECT_GRACE_PERIOD = 1 * 60 * 1000; // 1 minutes
const RECONNECT_GRACE_PERIOD = 1 * 60 * 1000;
const userId = (socket) => socket.user && socket.user.id;
export const serverStart = (port) => {
server.io = new Server(port, {
cors: {
origin: "*",
server.io = new Server(port, {
cors: {
origin: "*",
},
});
console.log(`[WebSocket] API_URL is set to ${API_URL}`);
server.io.use(async (socket, next) => {
let token = socket.handshake.auth.token;
if (!token) {
return next(new Error("Authentication error: No token provided"));
}
if (!token.startsWith("Bearer ")) {
token = "Bearer " + token;
}
try {
const response = await axios.get(`${API_URL}/users/me`, {
headers: {
Authorization: token,
Accept: "application/json",
},
});
const user = response.data.data || response.data;
if (!user || !user.id) {
return next(new Error("Authentication error: User data not found"));
}
socket.user = user;
socket.token = token;
socket.handshake.auth.token = token;
if (disconnectTimers.has(user.id)) {
console.log(
`[Connection] User ${user.id} reconnected! Cancelling surrender timer.`
);
clearTimeout(disconnectTimers.get(user.id));
disconnectTimers.delete(user.id);
}
addUser(socket.id, user);
next();
} catch (error) {
if (error.response) {
console.error(
"❌ Erro Laravel:",
error.response.status,
error.response.data
);
} else {
console.error("❌ Erro Rede:", error.message);
}
next(new Error("Authentication error: Invalid token"));
}
});
server.io.on("connection", (socket) => {
gameEvents(server.io, socket);
matchEvents(server.io, socket);
handleConnectionEvents(server.io, socket);
socket.on("notify_disconnect", () => {
socket.isVoluntaryDisconnect = true;
});
server.io.use(async (socket, next) => {
let token = socket.handshake.auth.token;
socket.on("disconnect", () => {
// Remove from active socket list
removeUser(socket.id);
if (!token) {
return next(new Error("Authentication error: No token provided"));
}
if (socket.isVoluntaryDisconnect) {
console.log(
`[Disconnect] User ${userId} disconnected voluntarily. No surrender needed.`
);
return;
}
if (!token.startsWith("Bearer ")) {
token = "Bearer " + token;
}
if (userId) {
console.log(
`[Disconnect] User ${userId} disconnected. Waiting ${
RECONNECT_GRACE_PERIOD / 1000
}s...`
);
try {
const response = await axios.get(`${API_URL}/users/me`, {
headers: {
Authorization: token,
Accept: "application/json"
},
});
// -----------------------------------------------------------
// 2. START SURRENDER TIMER
// -----------------------------------------------------------
const timer = setTimeout(async () => {
console.log(
`[Timeout] User ${userId} did not return. Forcing surrender.`
);
const user = response.data.data || response.data;
// A. Find the Game ID this user is playing (You need a way to look this up)
// Ideally, your 'socket' object or a global map knows which gameID the user is in.
// For this example, let's assume you stored `socket.activeGameId` when they joined.
const gameId = socket.activeGameId;
if (!user || !user.id) {
return next(new Error("Authentication error: User data not found"));
if (gameId) {
try {
// B. Call Laravel API to resign on their behalf
// We use the token we saved during the handshake
await axios.post(
`${API_URL}/games/${gameId}/resign`,
{},
{
headers: {
Authorization: socket.handshake.auth.token,
Accept: "application/json",
},
}
);
// C. Notify the room (The API likely triggers a Pusher/Socket event,
// but we can also emit locally if needed)
server.io.to(gameId).emit("game_over", {
winner: "opponent",
reason: "disconnect",
});
console.log(
`[Timeout] Successfully resigned game ${gameId} for user ${userId}`
);
} catch (err) {
console.error(
`[Timeout] Failed to resign game for user ${userId}:`,
err.message
);
}
}
socket.user = user;
socket.token = token;
socket.handshake.auth.token = token;
disconnectTimers.delete(userId);
}, RECONNECT_GRACE_PERIOD);
if (disconnectTimers.has(user.id)) {
console.log(`[Connection] User ${user.id} reconnected! Cancelling surrender timer.`);
clearTimeout(disconnectTimers.get(user.id));
disconnectTimers.delete(user.id);
}
addUser(socket.id, user);
next();
} catch (error) {
if (error.response) {
console.error(
"❌ Erro Laravel:",
error.response.status,
error.response.data
);
} else {
console.error("❌ Erro Rede:", error.message);
}
next(new Error("Authentication error: Invalid token"));
}
});
server.io.on("connection", (socket) => {
gameEvents(server.io, socket);
matchEvents(server.io, socket);
handleConnectionEvents(server.io, socket);
socket.on("notify_disconnect", () => {
socket.isVoluntaryDisconnect = true;
});
socket.on("disconnect", () => {
// Remove from active socket list
removeUser(socket.id);
if (socket.isVoluntaryDisconnect) {
console.log(`[Disconnect] User ${userId} disconnected voluntarily. No surrender needed.`);
return;
}
if (userId) {
console.log(`[Disconnect] User ${userId} disconnected. Waiting ${RECONNECT_GRACE_PERIOD / 1000}s...`);
// -----------------------------------------------------------
// 2. START SURRENDER TIMER
// -----------------------------------------------------------
const timer = setTimeout(async () => {
console.log(`[Timeout] User ${userId} did not return. Forcing surrender.`);
// A. Find the Game ID this user is playing (You need a way to look this up)
// Ideally, your 'socket' object or a global map knows which gameID the user is in.
// For this example, let's assume you stored `socket.activeGameId` when they joined.
const gameId = socket.activeGameId;
if (gameId) {
try {
// B. Call Laravel API to resign on their behalf
// We use the token we saved during the handshake
await axios.post(`${API_URL}/games/${gameId}/resign`, {}, {
headers: {
Authorization: socket.handshake.auth.token,
Accept: "application/json"
}
});
// C. Notify the room (The API likely triggers a Pusher/Socket event,
// but we can also emit locally if needed)
server.io.to(gameId).emit("game_over", {
winner: "opponent",
reason: "disconnect"
});
console.log(`[Timeout] Successfully resigned game ${gameId} for user ${userId}`);
} catch (err) {
console.error(`[Timeout] Failed to resign game for user ${userId}:`, err.message);
}
}
disconnectTimers.delete(userId);
}, RECONNECT_GRACE_PERIOD);
disconnectTimers.set(userId, timer);
}
});
disconnectTimers.set(userId, timer);
}
});
});
};