SyntaxSquad/DADProject#46 SyntaxSquad/DADProject#47 added sockets for game joining and card play

This commit is contained in:
2025-12-29 11:15:50 +00:00
committed by FernandoJVideira
parent d29e44c61c
commit c4078d9b82
7 changed files with 459 additions and 127 deletions
+76 -73
View File
@@ -1,105 +1,115 @@
const axios = require("axios");
const { getGame, createGame } = require("../state/game");
const { getUser } = require("../state/connection");
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";
module.exports = (io, socket) => {
// --- EVENTO: ENTRAR NO JOGO (Validado pela tabela GAMES) ---
async function saveGameResult(gameId, result, token) {
try {
const payload = {
status: "Ended",
is_draw: result.isDraw,
total_time: result.totalTime,
player1_points: result.player1_points,
player2_points: result.player2_points,
};
if (!result.isDraw && result.winnerId) {
payload.winner_user_id = result.winnerId;
payload.loser_user_id = result.loserId;
}
await axios.put(`${API_URL}/games/${gameId}`, payload, {
headers: { Authorization: token },
});
console.log(`[DB] Game ${gameId} saved.`);
} catch (error) {
console.error(`[DB Error] Game ${gameId}:`, error.message);
}
}
export default (io, socket) => {
socket.on("join-game", async ({ gameId }) => {
const user = getUser(socket.id);
if (!user) {
socket.emit("error", { message: "Não autenticado." });
socket.emit("error", { message: "Not authenticated." });
return;
}
console.log(`[Socket] User ${user.id} a tentar entrar no Game ${gameId}`);
// 1. Verificar se o jogo já está na memória do Node
let game = getGame(gameId);
// 2. Se NÃO existe na memória, vamos buscá-lo ao Laravel
if (!game) {
try {
// Token para autenticação no Laravel
const token = socket.handshake.auth.token;
// CHAMADA À API GAMES
const response = await axios.get(`${API_URL}/games/${gameId}`, {
headers: { Authorization: token },
});
const gameData = response.data.data;
const gameData = response.data.data || response.data;
if (gameData.status === "Ended") {
socket.emit("error", { message: "Game already finished." });
return;
}
// Validação: O user pertence a este jogo?
if (
gameData.player1_user_id != user.id &&
gameData.player2_user_id != user.id
gameData.player2_user_id != user.id &&
gameData.player2_user_id !== 1
) {
socket.emit("error", { message: "Não pertences a este jogo!" });
socket.emit("error", { message: "You are not in this game." });
return;
}
// Validação: O jogo já acabou?
if (gameData.status === "Ended") {
socket.emit("error", { message: "Este jogo já terminou." });
return;
}
console.log(`[Laravel] Game ${gameId} validado. A iniciar lógica...`);
// Preparar jogadores
// Nota: O endpoint 'games/{id}' deve retornar info básica dos users ou pelo menos os IDs.
// Se não vier o nome, usamos um placeholder ou o nome do user atual se coincidir.
const p1Name =
gameData.player1 && gameData.player1.name
? gameData.player1.name
: "Player 1";
const p2Name =
gameData.player2 && gameData.player2.name
? gameData.player2.name
: "Player 2";
const p1 = { id: gameData.player1_user_id, name: p1Name };
const p2 = { id: gameData.player2_user_id, name: p2Name };
// Tipo de jogo ('3' ou '9')
const p1Name = gameData.player1?.name || "Player 1";
const p2Name = gameData.player2?.name || "Player 2";
const type = gameData.type == "9" ? 9 : 3;
// CRIAR O JOGO NA MEMÓRIA
game = createGame(gameId, type, p1, p2);
} catch (error) {
console.error(
`[Erro Laravel] Falha ao buscar Game ${gameId}:`,
error.message
game = createGame(
gameId,
type,
{ id: gameData.player1_user_id, name: p1Name },
{ id: gameData.player2_user_id, name: p2Name }
);
// Dica: Se der 404, o jogo não existe na BD
socket.emit("error", { message: "Erro ao buscar dados do jogo." });
} catch (error) {
socket.emit("error", { message: "Failed to join game." });
return;
}
}
// 3. Juntar o socket à sala do jogo
const GHOST_ID = 1;
if (game && game.players) {
if (!game.players[user.id]) {
if (game.players[GHOST_ID]) {
delete game.players[GHOST_ID];
game.players[user.id] = {
id: user.id,
name: user.name,
hand: [],
points: 0,
tricks: 0,
};
}
}
}
socket.join(`game_${gameId}`);
// 4. Enviar o estado do jogo ao jogador
if (game.players[user.id]) {
// Envia apenas o que este jogador pode ver (esconde mão do adversário)
const gameState = game.getStateForPlayer(user.id);
socket.emit("game-state", gameState);
if (game && game.players[user.id]) {
socket.emit("game-state", game.getStateForPlayer(user.id));
console.log(`--> Estado enviado para User ${user.id}`);
} else {
socket.emit("error", { message: "Error joining game state." });
}
});
// --- EVENTO: JOGAR CARTA ---
socket.on("play-card", ({ gameId, cardId }) => {
const user = getUser(socket.id);
const game = getGame(gameId);
if (!game || !user) return;
// 1. Processar jogada
const result = game.playCard(user.id, cardId);
if (result.error) {
@@ -108,15 +118,10 @@ module.exports = (io, socket) => {
}
const roomName = `game_${gameId}`;
// 2. Atualizar estado visual (Solução rápida: Forçar refresh nos clientes)
// O ideal é iterar os sockets da sala e enviar 'game-state' personalizado a cada um
const socketsInRoom = io.sockets.adapter.rooms.get(roomName);
if (socketsInRoom) {
for (const socketId of socketsInRoom) {
const s = io.sockets.sockets.get(socketId);
// Precisamos saber qual User ID pertence a este socket para enviar o estado certo
// Assumindo que o teu getUser(socketId) funciona:
const u = getUser(socketId);
if (u && game.players[u.id]) {
s.emit("game-state", game.getStateForPlayer(u.id));
@@ -124,20 +129,18 @@ module.exports = (io, socket) => {
}
}
// 3. Eventos de Animação (Vaza / Fim de Jogo)
if (result.action === "trick_resolved") {
io.to(roomName).emit("trick-end", result.trickResult);
}
if (result.action === "game_ended") {
io.to(roomName).emit("game-over", { winnerId: result.winnerId });
// AQUI: Salvar o resultado na BD 'GAMES'
// axios.put(`${API_URL}/games/${gameId}`, {
// status: 'Ended',
// winner_user_id: result.winnerId,
// ...pontos...
// });
io.to(roomName).emit("game-over", {
winnerId: result.winnerId,
isDraw: result.isDraw,
p1Points: result.player1_points,
p2Points: result.player2_points,
});
saveGameResult(gameId, result, socket.handshake.auth.token);
}
});
};