This commit is contained in:
2026-01-03 17:22:09 +00:00
parent 5ea8c0df23
commit 5b504d10bd
13 changed files with 581 additions and 480 deletions
@@ -3,7 +3,7 @@ apiVersion: apps/v1
kind: Deployment kind: Deployment
metadata: metadata:
name: mysql name: mysql
namespace: dad-group-x namespace: dad-group-46
spec: spec:
selector: selector:
matchLabels: matchLabels:
@@ -37,7 +37,7 @@ apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: mysql name: mysql
namespace: dad-group-x namespace: dad-group-46
spec: spec:
ports: ports:
- port: 3306 - port: 3306
+4 -4
View File
@@ -3,10 +3,10 @@ apiVersion: networking.k8s.io/v1
kind: Ingress kind: Ingress
metadata: metadata:
name: app-ingress name: app-ingress
namespace: dad-group-x namespace: dad-group-46
spec: spec:
rules: rules:
- host: web-dad-group-x-172.22.21.253.sslip.io - host: web-dad-group-46-172.22.21.253.sslip.io
http: http:
paths: paths:
- path: / - path: /
@@ -16,7 +16,7 @@ spec:
name: vue-app name: vue-app
port: port:
number: 80 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: http:
paths: paths:
- path: / - path: /
@@ -26,7 +26,7 @@ spec:
name: laravel-app name: laravel-app
port: port:
number: 80 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: http:
paths: paths:
- path: / - path: /
+3 -3
View File
@@ -3,7 +3,7 @@ apiVersion: apps/v1
kind: Deployment kind: Deployment
metadata: metadata:
name: laravel-app name: laravel-app
namespace: dad-group-x namespace: dad-group-46
spec: spec:
replicas: 1 replicas: 1
selector: selector:
@@ -17,7 +17,7 @@ spec:
priorityClassName: high-priority priorityClassName: high-priority
containers: containers:
- name: api - 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.2
resources: resources:
requests: requests:
memory: "256Mi" memory: "256Mi"
@@ -31,7 +31,7 @@ apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: laravel-app name: laravel-app
namespace: dad-group-x namespace: dad-group-46
spec: spec:
ports: ports:
- port: 80 - port: 80
+3 -3
View File
@@ -3,7 +3,7 @@ apiVersion: apps/v1
kind: Deployment kind: Deployment
metadata: metadata:
name: vue-app name: vue-app
namespace: dad-group-x namespace: dad-group-46
spec: spec:
replicas: 1 replicas: 1
selector: selector:
@@ -17,7 +17,7 @@ spec:
priorityClassName: low-priority priorityClassName: low-priority
containers: containers:
- name: web - 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.4
resources: resources:
requests: requests:
memory: "64Mi" memory: "64Mi"
@@ -31,7 +31,7 @@ apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: vue-app name: vue-app
namespace: dad-group-x namespace: dad-group-46
spec: spec:
ports: ports:
- port: 80 - port: 80
+3 -3
View File
@@ -3,7 +3,7 @@ apiVersion: apps/v1
kind: Deployment kind: Deployment
metadata: metadata:
name: websocket-server name: websocket-server
namespace: dad-group-x namespace: dad-group-46
spec: spec:
replicas: 1 replicas: 1
selector: selector:
@@ -17,7 +17,7 @@ spec:
priorityClassName: low-priority priorityClassName: low-priority
containers: containers:
- name: web - 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.6
resources: resources:
requests: requests:
memory: "128Mi" memory: "128Mi"
@@ -31,7 +31,7 @@ apiVersion: v1
kind: Service kind: Service
metadata: metadata:
name: websocket-server name: websocket-server
namespace: dad-group-x namespace: dad-group-46
spec: spec:
ports: ports:
- port: 3000 - port: 3000
-4
View File
@@ -1,15 +1,12 @@
import { createApp } from 'vue' import { createApp } from 'vue'
import { createPinia } from 'pinia' import { createPinia } from 'pinia'
import { io } from 'socket.io-client'
import App from './App.vue' import App from './App.vue'
import router from './router' import router from './router'
const apiDomain = import.meta.env.VITE_API_DOMAIN 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] api domain', apiDomain)
console.log('[main.js] ws connection', wsConnection)
const app = createApp(App) const app = createApp(App)
@@ -20,4 +17,3 @@ app.use(createPinia())
app.use(router) app.use(router)
app.mount('#app') app.mount('#app')
+7 -5
View File
@@ -12,7 +12,7 @@ export const useSocketStore = defineStore('websocket', () => {
const lastError = ref(null) const lastError = ref(null)
const currentGameId = 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 = () => { const connect = () => {
if (socket.value?.connected) return if (socket.value?.connected) return
@@ -27,13 +27,15 @@ export const useSocketStore = defineStore('websocket', () => {
auth: { token: `Bearer ${token}` }, auth: { token: `Bearer ${token}` },
reconnection: true, reconnection: true,
reconnectionAttempts: 5, reconnectionAttempts: 5,
reconnectionDelay: 1000 reconnectionDelay: 1000,
}) })
console.log('[WebSocket] Attempting to connect to', WS_URL)
socket.value.on('connect', () => { socket.value.on('connect', () => {
if (currentGameId.value) { if (currentGameId.value) {
console.log("Reconnected to socket. Rejoining game..."); console.log('Reconnected to socket. Rejoining game...')
socket.emit("join-game", { gameId: currentGameId.value }); socket.emit('join-game', { gameId: currentGameId.value })
} }
connected.value = true connected.value = true
@@ -124,6 +126,6 @@ export const useSocketStore = defineStore('websocket', () => {
playCard, playCard,
surrender, surrender,
onTrickEnd, onTrickEnd,
onGameOver onGameOver,
} }
}) })
+2 -2
View File
@@ -1,6 +1,6 @@
GROUP := "dad-group-x" GROUP := "dad-group-46"
VERSION := "1.0.0" VERSION := "2.0.6"
kubectl-pods: kubectl-pods:
-2
View File
@@ -1,2 +0,0 @@
PORT=
API_URL=
+57 -21
View File
@@ -1,7 +1,7 @@
import BiscaGame from "../classes/BiscaGame.js"; import BiscaGame from "../classes/BiscaGame.js";
import axios from "axios"; 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 { class BiscaMatch {
constructor(apiData, emitStateCallback, token, autoPlayCallback) { constructor(apiData, emitStateCallback, token, autoPlayCallback) {
@@ -55,7 +55,7 @@ class BiscaMatch {
headers: { headers: {
Authorization: this.token, Authorization: this.token,
"Content-Type": "application/json", "Content-Type": "application/json",
"Accept": "application/json" Accept: "application/json",
}, },
}; };
} }
@@ -73,7 +73,11 @@ class BiscaMatch {
began_at: new Date().toISOString(), 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; const gameData = res.data.game || res.data.data || res.data;
newGameDbId = gameData.id; newGameDbId = gameData.id;
@@ -86,7 +90,9 @@ class BiscaMatch {
{ id: this.player1Id, name: p1Name }, { id: this.player1Id, name: p1Name },
{ id: this.player2Id, name: p2Name }, { id: this.player2Id, name: p2Name },
newGameDbId, newGameDbId,
(result) => { this.handleGameEnd(result); } (result) => {
this.handleGameEnd(result);
}
); );
this.currentGame.init(); this.currentGame.init();
@@ -107,7 +113,8 @@ class BiscaMatch {
if (this.currentGame && this.currentGame.dbId) { if (this.currentGame && this.currentGame.dbId) {
console.log(`[Match ${this.id}] Aborting Game #${this.currentGame.dbId}`); console.log(`[Match ${this.id}] Aborting Game #${this.currentGame.dbId}`);
try { try {
const winnerId = loserId == this.player1Id ? this.player2Id : this.player1Id; const winnerId =
loserId == this.player1Id ? this.player2Id : this.player1Id;
const payload = { const payload = {
status: "Ended", status: "Ended",
@@ -116,16 +123,24 @@ class BiscaMatch {
is_draw: false, is_draw: false,
ended_at: new Date().toISOString(), ended_at: new Date().toISOString(),
}; };
await axios.put(`${API_URL}/games/${this.currentGame.dbId}`, payload, this.getAuthHeaders()); await axios.put(
} catch(e) { console.error("Error aborting game:", e.message); } `${API_URL}/games/${this.currentGame.dbId}`,
payload,
this.getAuthHeaders()
);
} catch (e) {
console.error("Error aborting game:", e.message);
}
} }
} }
async handleGameEnd(result) { async handleGameEnd(result) {
console.log(`[Match ${this.id}] Round ended. Winner: ${result.winnerId}`); 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.player1_id] !== undefined)
if (this.points[result.player2_id] !== undefined) this.points[result.player2_id] += result.player2_points; 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) { if (this.currentGame && this.currentGame.dbId) {
try { try {
@@ -138,20 +153,30 @@ class BiscaMatch {
player2_points: result.player2_points, player2_points: result.player2_points,
ended_at: new Date().toISOString(), ended_at: new Date().toISOString(),
}; };
await axios.put(`${API_URL}/games/${this.currentGame.dbId}`, payload, this.getAuthHeaders()); await axios.put(
} catch (e) { console.error("DB Game Update Error:", e.message); } `${API_URL}/games/${this.currentGame.dbId}`,
payload,
this.getAuthHeaders()
);
} catch (e) {
console.error("DB Game Update Error:", e.message);
}
} }
let marksToAdd = 0; let marksToAdd = 0;
let roundWinnerId = result.winnerId; let roundWinnerId = result.winnerId;
if (roundWinnerId) { 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; if (winningScore === 120) marksToAdd = 4;
else if (winningScore > 90) marksToAdd = 2; else if (winningScore > 90) marksToAdd = 2;
else if (winningScore >= 60) marksToAdd = 1; 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) { if (this.emitStateCallback) {
@@ -162,13 +187,14 @@ class BiscaMatch {
p2Points: result.player2_points, p2Points: result.player2_points,
p1Marks: this.marks[this.player1Id], p1Marks: this.marks[this.player1Id],
p2Marks: this.marks[this.player2Id], p2Marks: this.marks[this.player2Id],
reason: result.reason || 'points' reason: result.reason || "points",
}); });
} }
if (this.marks[this.player1Id] >= 4 || this.marks[this.player2Id] >= 4) { if (this.marks[this.player1Id] >= 4 || this.marks[this.player2Id] >= 4) {
await this.finishMatch(); await this.finishMatch();
if (this.emitStateCallback) this.emitStateCallback("match:ended-signal", null); if (this.emitStateCallback)
this.emitStateCallback("match:ended-signal", null);
} else { } else {
setTimeout(() => { setTimeout(() => {
this.startNewGame(); this.startNewGame();
@@ -178,8 +204,10 @@ class BiscaMatch {
async finishMatch() { async finishMatch() {
this.status = "Ended"; this.status = "Ended";
const winnerId = this.marks[this.player1Id] >= 4 ? this.player1Id : this.player2Id; const winnerId =
const loserId = winnerId == this.player1Id ? this.player2Id : this.player1Id; this.marks[this.player1Id] >= 4 ? this.player1Id : this.player2Id;
const loserId =
winnerId == this.player1Id ? this.player2Id : this.player1Id;
const payload = { const payload = {
status: "Ended", status: "Ended",
@@ -192,7 +220,11 @@ class BiscaMatch {
}; };
try { 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.`); console.log(`[Match ${this.id}] Match Closed in DB.`);
} catch (e) { } catch (e) {
console.error(`Match Close Error: ${e.message}`); console.error(`Match Close Error: ${e.message}`);
@@ -204,7 +236,10 @@ class BiscaMatch {
const result = this.currentGame.playCard(userId, cardId); const result = this.currentGame.playCard(userId, cardId);
if (result && (result.action === 'next_turn' || result.action === 'trick_resolved')) { if (
result &&
(result.action === "next_turn" || result.action === "trick_resolved")
) {
this.currentGame.startTurnTimer((uid, cid) => { this.currentGame.startTurnTimer((uid, cid) => {
if (this.autoPlayCallback) this.autoPlayCallback(uid, cid); if (this.autoPlayCallback) this.autoPlayCallback(uid, cid);
}); });
@@ -215,7 +250,8 @@ class BiscaMatch {
getGameState(userId) { getGameState(userId) {
if (!this.currentGame) return null; 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; return null;
} }
@@ -226,7 +262,7 @@ class BiscaMatch {
marks: this.marks, marks: this.marks,
points: this.points, points: this.points,
player1: this.player1, player1: this.player1,
player2: this.player2 player2: this.player2,
}; };
} }
} }
+43 -21
View File
@@ -2,10 +2,21 @@ import axios from "axios";
import { getGame, createGame } from "../state/game.js"; import { getGame, createGame } from "../state/game.js";
import { getUser } from "../state/connection.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 getStrength = (rank) => {
const strengthMap = { 1: 10, 7: 9, 13: 8, 11: 7, 12: 6, 6: 5, 5: 4, 4: 3, 3: 2, 2: 1 }; 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; return strengthMap[rank] || 0;
}; };
@@ -39,13 +50,13 @@ const sanitizeState = (state, game) => {
id: state.opponent?.id, id: state.opponent?.id,
name: state.opponent?.name, name: state.opponent?.name,
points: state.opponent?.points, points: state.opponent?.points,
cardCount: state.opponent?.cardCount cardCount: state.opponent?.cardCount,
}, },
table: state.table, table: state.table,
trumpCard: state.trumpCard, trumpCard: state.trumpCard,
deckCount: game.deck ? game.deck.length : (state.deckCount || 0), deckCount: game.deck ? game.deck.length : state.deckCount || 0,
currentTurn: state.currentTurn, currentTurn: state.currentTurn,
turnStartedAt: state.turnStartedAt turnStartedAt: state.turnStartedAt,
}; };
}; };
@@ -64,7 +75,7 @@ const broadcastState = (io, gameId, game) => {
} }
} }
} }
} };
async function saveGameResult(gameId, result, token) { async function saveGameResult(gameId, result, token) {
try { try {
@@ -92,11 +103,13 @@ const performGameEnd = (io, game, gameId, winnerId, loserId, reason) => {
action: "game_ended", action: "game_ended",
winnerId: parseInt(winnerId), winnerId: parseInt(winnerId),
loserId: parseInt(loserId), loserId: parseInt(loserId),
totalTime: game.startTime ? Math.floor((Date.now() - game.startTime) / 1000) : 0, totalTime: game.startTime
? Math.floor((Date.now() - game.startTime) / 1000)
: 0,
isDraw: false, isDraw: false,
player1_points: game.players[Object.keys(game.players)[0]]?.points || 0, player1_points: game.players[Object.keys(game.players)[0]]?.points || 0,
player2_points: game.players[Object.keys(game.players)[1]]?.points || 0, player2_points: game.players[Object.keys(game.players)[1]]?.points || 0,
reason: reason reason: reason,
}; };
game.status = "ended"; game.status = "ended";
@@ -107,24 +120,24 @@ const performGameEnd = (io, game, gameId, winnerId, loserId, reason) => {
isDraw: result.isDraw, isDraw: result.isDraw,
p1Points: result.player1_points, p1Points: result.player1_points,
p2Points: result.player2_points, p2Points: result.player2_points,
message: reason === "surrender" ? "Opponent Surrendered!" : "Game Over" message: reason === "surrender" ? "Opponent Surrendered!" : "Game Over",
}); });
const anyId = Object.keys(game.players)[0]; const anyId = Object.keys(game.players)[0];
const token = game.players[anyId]?.token; const token = game.players[anyId]?.token;
if (token) saveGameResult(gameId, result, token); if (token) saveGameResult(gameId, result, token);
} };
const handleTimeout = (io, gameId, userId) => { const handleTimeout = (io, gameId, userId) => {
const game = getGame(gameId); 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.`); console.log(`[Timeout] User ${userId} auto-playing lowest card.`);
const player = game.players[userId]; const player = game.players[userId];
if (!player || !player.hand || player.hand.length === 0) return; 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 sortedHand = [...player.hand].sort((a, b) => {
const strengthA = getStrength(a.rank) + (a.suit === trumpSuit ? 100 : 0); const strengthA = getStrength(a.rank) + (a.suit === trumpSuit ? 100 : 0);
@@ -152,11 +165,14 @@ const handleGameMove = (io, gameId, userId, cardId) => {
setTimeout(() => { setTimeout(() => {
if (game.status !== "ended") { if (game.status !== "ended") {
const canDraw = (game.deck && game.deck.length > 0) || game.trumpCard !== null; const canDraw =
(game.deck && game.deck.length > 0) || game.trumpCard !== null;
if (canDraw) { if (canDraw) {
const winnerId = result.trickResult.winnerId; const winnerId = result.trickResult.winnerId;
const loserId = Object.keys(game.players).find(id => String(id) !== String(winnerId)); const loserId = Object.keys(game.players).find(
(id) => String(id) !== String(winnerId)
);
if (winnerId) drawCard(game, winnerId); if (winnerId) drawCard(game, winnerId);
if (loserId) drawCard(game, loserId); if (loserId) drawCard(game, loserId);
@@ -194,7 +210,9 @@ export default (io, socket) => {
headers: { Authorization: token }, headers: { Authorization: token },
}); });
gameData = response.data.data || response.data; gameData = response.data.data || response.data;
} catch (e) { console.error("DB Sync Failed"); } } catch (e) {
console.error("DB Sync Failed");
}
if (!game && gameData) { if (!game && gameData) {
const p1Name = gameData.player1?.nickname || "Player 1"; const p1Name = gameData.player1?.nickname || "Player 1";
@@ -206,7 +224,7 @@ export default (io, socket) => {
{ id: gameData.player1_user_id, name: p1Name }, { id: gameData.player1_user_id, name: p1Name },
{ id: gameData.player2_user_id, name: p2Name } { id: gameData.player2_user_id, name: p2Name }
); );
game.status = gameData.status === 'Playing' ? 'playing' : 'pending'; game.status = gameData.status === "Playing" ? "playing" : "pending";
} }
if (!game) { if (!game) {
@@ -215,7 +233,7 @@ export default (io, socket) => {
} }
const myId = user.id; 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; const amIDbPlayer2 = gameData && gameData.player2_user_id == myId;
if (!game.players[myId] && (ghostKey || amIDbPlayer2)) { if (!game.players[myId] && (ghostKey || amIDbPlayer2)) {
@@ -238,9 +256,11 @@ export default (io, socket) => {
token: socket.handshake.auth.token, token: socket.handshake.auth.token,
}; };
game.player2 = { id: myId, name: user.nickname }; game.player2 = { id: myId, name: user.nickname };
game.status = 'playing'; game.status = "playing";
if(!game.timer) { if (!game.timer) {
game.startTurnTimer((timeoutUserId) => handleTimeout(io, gameId, timeoutUserId)); game.startTurnTimer((timeoutUserId) =>
handleTimeout(io, gameId, timeoutUserId)
);
} }
} }
@@ -271,7 +291,9 @@ export default (io, socket) => {
console.log(`[Game] User ${user.nickname} surrendered.`); console.log(`[Game] User ${user.nickname} surrendered.`);
const winnerId = Object.keys(game.players).find(id => String(id) !== String(user.id)); const winnerId = Object.keys(game.players).find(
(id) => String(id) !== String(user.id)
);
performGameEnd(io, game, gameId, winnerId, user.id, "surrender"); performGameEnd(io, game, gameId, winnerId, user.id, "surrender");
}); });
}; };
+33 -19
View File
@@ -2,10 +2,9 @@ import { getMatch, addMatch } from "../state/match.js";
import BiscaMatch from "../classes/BiscaMatch.js"; import BiscaMatch from "../classes/BiscaMatch.js";
import axios from "axios"; 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) => { export default (io, socket) => {
const broadcastMatchUpdate = (matchId, match) => { const broadcastMatchUpdate = (matchId, match) => {
const roomName = `match_${matchId}`; const roomName = `match_${matchId}`;
const room = io.sockets.adapter.rooms.get(roomName); const room = io.sockets.adapter.rooms.get(roomName);
@@ -25,10 +24,13 @@ export default (io, socket) => {
const match = getMatch(matchId); const match = getMatch(matchId);
if (!match) return; if (!match) return;
if (eventName === 'match:new-round-start' || eventName === 'match:ended-signal') { if (
eventName === "match:new-round-start" ||
eventName === "match:ended-signal"
) {
broadcastMatchUpdate(matchId, match); broadcastMatchUpdate(matchId, match);
} else if (eventName === 'match:round-ended') { } else if (eventName === "match:round-ended") {
io.to(`match_${matchId}`).emit('match:round-ended', payload); io.to(`match_${matchId}`).emit("match:round-ended", payload);
} else { } else {
io.to(`match_${matchId}`).emit(eventName, payload); io.to(`match_${matchId}`).emit(eventName, payload);
} }
@@ -43,7 +45,9 @@ export default (io, socket) => {
if (result && result.action === "trick_resolved") { if (result && result.action === "trick_resolved") {
io.to(`match_${matchId}`).emit("game:trick-end", result.trickResult); io.to(`match_${matchId}`).emit("game:trick-end", result.trickResult);
setTimeout(() => { broadcastMatchUpdate(matchId, match); }, 1500); setTimeout(() => {
broadcastMatchUpdate(matchId, match);
}, 1500);
} else { } else {
broadcastMatchUpdate(matchId, match); broadcastMatchUpdate(matchId, match);
} }
@@ -51,7 +55,8 @@ export default (io, socket) => {
socket.on("match:enter", async (data) => { socket.on("match:enter", async (data) => {
const { matchId } = data; const { matchId } = data;
if (!socket.user || !socket.user.id) return socket.emit("error", { message: "Auth failed" }); if (!socket.user || !socket.user.id)
return socket.emit("error", { message: "Auth failed" });
const userId = socket.user.id; const userId = socket.user.id;
socket.activeMatchId = matchId; socket.activeMatchId = matchId;
@@ -61,7 +66,9 @@ export default (io, socket) => {
if (!match) { if (!match) {
try { try {
const res = await axios.get(`${API_URL}/matches/${matchId}`, { const res = await axios.get(`${API_URL}/matches/${matchId}`, {
headers: { Authorization: socket.token || socket.handshake.auth.token }, headers: {
Authorization: socket.token || socket.handshake.auth.token,
},
}); });
const matchData = res.data.data || res.data; const matchData = res.data.data || res.data;
@@ -77,13 +84,14 @@ export default (io, socket) => {
} }
} }
match.emitStateCallback = createMatchEmitter(matchId); match.emitStateCallback = createMatchEmitter(matchId);
if (userId !== match.player1Id && match.player2Id === 1) await match.joinPlayer(userId, socket.user); if (userId !== match.player1Id && match.player2Id === 1)
await match.joinPlayer(userId, socket.user);
socket.join(room); socket.join(room);
const publicState = match.getPublicState(); const publicState = match.getPublicState();
const gameState = match.getGameState(userId); const gameState = match.getGameState(userId);
socket.emit("match:update", { ...publicState, game: gameState }); socket.emit("match:update", { ...publicState, game: gameState });
if (match.status === 'Playing') broadcastMatchUpdate(matchId, match); if (match.status === "Playing") broadcastMatchUpdate(matchId, match);
}); });
socket.on("game:play-card", (data) => { socket.on("game:play-card", (data) => {
@@ -91,10 +99,13 @@ export default (io, socket) => {
const match = getMatch(matchId); const match = getMatch(matchId);
if (!match || match.status !== "Playing") return; if (!match || match.status !== "Playing") return;
const result = match.playCard(socket.user.id, cardId); const result = match.playCard(socket.user.id, cardId);
if (result && result.error) return socket.emit("error", { message: result.error }); if (result && result.error)
return socket.emit("error", { message: result.error });
if (result && result.action === "trick_resolved") { if (result && result.action === "trick_resolved") {
io.to(`match_${matchId}`).emit("game:trick-end", result.trickResult); io.to(`match_${matchId}`).emit("game:trick-end", result.trickResult);
setTimeout(() => { broadcastMatchUpdate(matchId, match); }, 1500); setTimeout(() => {
broadcastMatchUpdate(matchId, match);
}, 1500);
} else { } else {
broadcastMatchUpdate(matchId, match); broadcastMatchUpdate(matchId, match);
} }
@@ -102,10 +113,11 @@ export default (io, socket) => {
socket.on("game:surrender", async ({ matchId }) => { socket.on("game:surrender", async ({ matchId }) => {
const match = getMatch(matchId); const match = getMatch(matchId);
if(!match || match.status !== "Playing") return; if (!match || match.status !== "Playing") return;
const userId = socket.user.id; const userId = socket.user.id;
console.log(`[Match ${matchId}] User ${userId} surrendered ROUND.`); console.log(`[Match ${matchId}] User ${userId} surrendered ROUND.`);
const opponentId = match.player1Id == userId ? match.player2Id : match.player1Id; const opponentId =
match.player1Id == userId ? match.player2Id : match.player1Id;
const result = { const result = {
winnerId: opponentId, winnerId: opponentId,
loserId: userId, loserId: userId,
@@ -114,20 +126,21 @@ export default (io, socket) => {
player2_id: match.player2Id, player2_id: match.player2Id,
player1_points: match.player1Id == opponentId ? 91 : 0, player1_points: match.player1Id == opponentId ? 91 : 0,
player2_points: match.player2Id == opponentId ? 91 : 0, player2_points: match.player2Id == opponentId ? 91 : 0,
reason: 'surrender' reason: "surrender",
}; };
await match.handleGameEnd(result); await match.handleGameEnd(result);
}); });
socket.on("match:surrender", async ({ matchId }) => { socket.on("match:surrender", async ({ matchId }) => {
const match = getMatch(matchId); const match = getMatch(matchId);
if(!match || match.status !== "Playing") return; if (!match || match.status !== "Playing") return;
const userId = socket.user.id; const userId = socket.user.id;
await match.abortCurrentGame(userId); await match.abortCurrentGame(userId);
console.log(`[Match ${matchId}] User ${userId} surrendered MATCH.`); console.log(`[Match ${matchId}] User ${userId} surrendered MATCH.`);
const opponentId = match.player1Id == userId ? match.player2Id : match.player1Id; const opponentId =
match.player1Id == userId ? match.player2Id : match.player1Id;
match.marks[opponentId] = 4; match.marks[opponentId] = 4;
await match.finishMatch(); await match.finishMatch();
broadcastMatchUpdate(matchId, match); broadcastMatchUpdate(matchId, match);
@@ -136,14 +149,15 @@ export default (io, socket) => {
socket.on("disconnect", async () => { socket.on("disconnect", async () => {
if (socket.activeMatchId) { if (socket.activeMatchId) {
const match = getMatch(socket.activeMatchId); const match = getMatch(socket.activeMatchId);
if (match && match.status === 'Playing') { if (match && match.status === "Playing") {
const userId = socket.user?.id; const userId = socket.user?.id;
if (userId === match.player1Id || userId === match.player2Id) { if (userId === match.player1Id || userId === match.player2Id) {
console.log(`[Match ${match.id}] Player ${userId} disconnected.`); console.log(`[Match ${match.id}] Player ${userId} disconnected.`);
await match.abortCurrentGame(userId); await match.abortCurrentGame(userId);
const opponentId = match.player1Id == userId ? match.player2Id : match.player1Id; const opponentId =
match.player1Id == userId ? match.player2Id : match.player1Id;
match.marks[opponentId] = 4; match.marks[opponentId] = 4;
await match.finishMatch(); await match.finishMatch();
broadcastMatchUpdate(match.id, match); broadcastMatchUpdate(match.id, match);
+46 -13
View File
@@ -9,7 +9,7 @@ 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 disconnectTimers = new Map();
const RECONNECT_GRACE_PERIOD = 1 * 60 * 1000; const RECONNECT_GRACE_PERIOD = 1 * 60 * 1000;
@@ -23,6 +23,8 @@ export const serverStart = (port) => {
}, },
}); });
console.log(`[WebSocket] API_URL is set to ${API_URL}`);
server.io.use(async (socket, next) => { server.io.use(async (socket, next) => {
let token = socket.handshake.auth.token; let token = socket.handshake.auth.token;
@@ -38,7 +40,7 @@ export const serverStart = (port) => {
const response = await axios.get(`${API_URL}/users/me`, { const response = await axios.get(`${API_URL}/users/me`, {
headers: { headers: {
Authorization: token, Authorization: token,
Accept: "application/json" Accept: "application/json",
}, },
}); });
@@ -53,7 +55,9 @@ export const serverStart = (port) => {
socket.handshake.auth.token = token; socket.handshake.auth.token = token;
if (disconnectTimers.has(user.id)) { if (disconnectTimers.has(user.id)) {
console.log(`[Connection] User ${user.id} reconnected! Cancelling surrender timer.`); console.log(
`[Connection] User ${user.id} reconnected! Cancelling surrender timer.`
);
clearTimeout(disconnectTimers.get(user.id)); clearTimeout(disconnectTimers.get(user.id));
disconnectTimers.delete(user.id); disconnectTimers.delete(user.id);
} }
@@ -86,37 +90,66 @@ export const serverStart = (port) => {
}); });
socket.on("disconnect", () => { socket.on("disconnect", () => {
// Remove from active socket list
removeUser(socket.id); removeUser(socket.id);
if (socket.isVoluntaryDisconnect) { if (socket.isVoluntaryDisconnect) {
console.log(`[Disconnect] User ${userId} disconnected voluntarily. No surrender needed.`); console.log(
`[Disconnect] User ${userId} disconnected voluntarily. No surrender needed.`
);
return; return;
} }
if (userId) { if (userId) {
console.log(`[Disconnect] User ${userId} disconnected. Waiting ${RECONNECT_GRACE_PERIOD / 1000}s...`); console.log(
const timer = setTimeout(async () => { `[Disconnect] User ${userId} disconnected. Waiting ${
console.log(`[Timeout] User ${userId} did not return. Forcing surrender.`); 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; const gameId = socket.activeGameId;
if (gameId) { if (gameId) {
try { try {
await axios.post(`${API_URL}/games/${gameId}/resign`, {}, { // 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: { headers: {
Authorization: socket.handshake.auth.token, Authorization: socket.handshake.auth.token,
Accept: "application/json" 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", { server.io.to(gameId).emit("game_over", {
winner: "opponent", winner: "opponent",
reason: "disconnect" reason: "disconnect",
}); });
console.log(`[Timeout] Successfully resigned game ${gameId} for user ${userId}`); console.log(
`[Timeout] Successfully resigned game ${gameId} for user ${userId}`
);
} catch (err) { } catch (err) {
console.error(`[Timeout] Failed to resign game for user ${userId}:`, err.message); console.error(
`[Timeout] Failed to resign game for user ${userId}:`,
err.message
);
} }
} }