SyntaxSquad/DADProject#16 fix: i forgot this
This commit is contained in:
+117
-153
@@ -4,9 +4,11 @@ import axios from "axios";
|
||||
const API_URL = "http://localhost:8000/api/v1";
|
||||
|
||||
class BiscaMatch {
|
||||
constructor(apiData, emitStateCallback, token) {
|
||||
// FIX: Added autoPlayCallback parameter
|
||||
constructor(apiData, emitStateCallback, token, autoPlayCallback) {
|
||||
this.id = apiData.id;
|
||||
this.emitStateCallback = emitStateCallback;
|
||||
this.autoPlayCallback = autoPlayCallback;
|
||||
this.token = token;
|
||||
this.stake = apiData.stake;
|
||||
this.type = apiData.type;
|
||||
@@ -14,6 +16,8 @@ class BiscaMatch {
|
||||
|
||||
this.player1Id = apiData.player1_user_id;
|
||||
this.player2Id = apiData.player2_user_id;
|
||||
this.player1 = apiData.player1;
|
||||
this.player2 = apiData.player2;
|
||||
|
||||
this.marks = {
|
||||
[this.player1Id]: apiData.player1_marks || 0,
|
||||
@@ -33,11 +37,12 @@ class BiscaMatch {
|
||||
}
|
||||
}
|
||||
|
||||
async joinPlayer(userId) {
|
||||
async joinPlayer(userId, user) {
|
||||
if (this.player2Id !== this.GHOST_ID) return false;
|
||||
if (userId === this.player1Id) return false;
|
||||
|
||||
this.player2Id = userId;
|
||||
this.player2 = user;
|
||||
this.marks[userId] = 0;
|
||||
this.points[userId] = 0;
|
||||
this.status = "Playing";
|
||||
@@ -48,226 +53,185 @@ class BiscaMatch {
|
||||
|
||||
getAuthHeaders() {
|
||||
return {
|
||||
headers: { Authorization: this.token },
|
||||
headers: {
|
||||
Authorization: this.token,
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async startNewGame() {
|
||||
console.log(`[Match ${this.id}] A iniciar nova mão (Game DB)...`);
|
||||
|
||||
console.log(`[Match ${this.id}] Starting new round...`);
|
||||
let newGameDbId = null;
|
||||
|
||||
try {
|
||||
let payloadP1 = this.player1Id;
|
||||
let payloadP2 = this.player2Id;
|
||||
|
||||
if (this.player2Id !== this.GHOST_ID) {
|
||||
console.log(
|
||||
"🔄 Multiplayer detetado: Trocando ordem para satisfazer a API..."
|
||||
);
|
||||
payloadP1 = this.player2Id;
|
||||
payloadP2 = this.player1Id;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
type: this.type,
|
||||
player1_user_id: payloadP1,
|
||||
player2_user_id: payloadP2,
|
||||
player1_user_id: this.player1Id,
|
||||
player2_user_id: this.player2Id,
|
||||
match_id: this.id,
|
||||
status: "Playing",
|
||||
began_at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
console.log("📤 [Payload Adaptado]:", JSON.stringify(payload, null, 2));
|
||||
|
||||
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;
|
||||
|
||||
console.log(`[Match ${this.id}] Game DB criado: #${newGameDbId}`);
|
||||
|
||||
const apiP1 = gameData.player1_user_id;
|
||||
const apiP2 = gameData.player2_user_id;
|
||||
|
||||
const p1 = { id: apiP1, name: `User ${apiP1}` };
|
||||
const p2 = { id: apiP2, name: `User ${apiP2}` };
|
||||
const p1Name = this.player1?.nickname || `User ${this.player1Id}`;
|
||||
const p2Name = this.player2?.nickname || `User ${this.player2Id}`;
|
||||
|
||||
this.currentGame = new BiscaGame(
|
||||
this.id,
|
||||
this.type,
|
||||
p1,
|
||||
p2,
|
||||
{ id: this.player1Id, name: p1Name },
|
||||
{ id: this.player2Id, name: p2Name },
|
||||
newGameDbId,
|
||||
(result) => {
|
||||
this.handleGameEnd(result);
|
||||
}
|
||||
(result) => { this.handleGameEnd(result); }
|
||||
);
|
||||
|
||||
this.currentGame.init();
|
||||
|
||||
// FIX: Start Timer & Connect Callback
|
||||
this.currentGame.startTurnTimer((uid, cid) => {
|
||||
if (this.autoPlayCallback) this.autoPlayCallback(uid, cid);
|
||||
});
|
||||
|
||||
if (this.emitStateCallback) {
|
||||
this.emitStateCallback("match:new-round", this.getState());
|
||||
this.emitStateCallback("match:new-round-start", null);
|
||||
}
|
||||
} catch (e) {
|
||||
if (e.response) {
|
||||
console.error(
|
||||
`❌ Erro API (${e.response.status}):`,
|
||||
JSON.stringify(e.response.data)
|
||||
);
|
||||
} else {
|
||||
console.error(`❌ Erro Código: ${e.message}`);
|
||||
}
|
||||
console.error(`❌ Start Game Error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async handleGameEnd(result) {
|
||||
console.log(
|
||||
`[Match ${this.id}] Mão terminada. Vencedor: ${result.winnerId}`
|
||||
);
|
||||
// --- FIX: Close DB Game row on surrender ---
|
||||
async abortCurrentGame(loserId) {
|
||||
if (this.currentGame && this.currentGame.dbId) {
|
||||
console.log(`[Match ${this.id}] Aborting Game #${this.currentGame.dbId}`);
|
||||
try {
|
||||
// Determine winner for the DB record based on who DIDN'T lose
|
||||
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); }
|
||||
}
|
||||
}
|
||||
|
||||
this.points[result.player1_id] += result.player1_points;
|
||||
this.points[result.player2_id] += result.player2_points;
|
||||
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.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(),
|
||||
};
|
||||
|
||||
console.log(
|
||||
`📤 A enviar update para Game #${this.currentGame.dbId}...`
|
||||
);
|
||||
|
||||
// --- CORREÇÃO IMPORTANTE: Forçar o header aqui ---
|
||||
const config = {
|
||||
headers: {
|
||||
Authorization: this.token,
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
};
|
||||
|
||||
await axios.put(
|
||||
`${API_URL}/games/${this.currentGame.dbId}`,
|
||||
payload,
|
||||
config
|
||||
);
|
||||
|
||||
console.log(
|
||||
`✅ Game #${this.currentGame.dbId} atualizado com sucesso.`
|
||||
);
|
||||
} catch (e) {
|
||||
// --- LOG DETALHADO PARA VER O MOTIVO DO 403 ---
|
||||
if (e.response) {
|
||||
console.error(`❌ ERRO CRÍTICO API (${e.response.status}):`);
|
||||
// Isto vai imprimir o JSON exato que o Laravel devolve
|
||||
console.error(JSON.stringify(e.response.data, null, 2));
|
||||
} else {
|
||||
console.error("Erro Axios:", e.message);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.warn("⚠️ Ignorado: Não há ID de jogo na DB para atualizar.");
|
||||
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); }
|
||||
}
|
||||
|
||||
// ... (resto da lógica de atribuir marcas e finishMatch mantém-se igual)
|
||||
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;
|
||||
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'
|
||||
});
|
||||
}
|
||||
|
||||
if (this.marks[this.player1Id] >= 4 || this.marks[this.player2Id] >= 4) {
|
||||
await this.finishMatch();
|
||||
if (this.emitStateCallback) {
|
||||
this.emitStateCallback("match:ended", this.getState());
|
||||
}
|
||||
if (this.emitStateCallback) this.emitStateCallback("match:ended-signal", null);
|
||||
} else {
|
||||
console.log(`[Match ${this.id}] Ninguém ganhou 4 marcas. A baralhar...`);
|
||||
await this.startNewGame();
|
||||
setTimeout(() => {
|
||||
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",
|
||||
winner_user_id: winnerId,
|
||||
loser_user_id: loserId,
|
||||
player1_marks: this.marks[this.player1Id],
|
||||
player2_marks: this.marks[this.player2Id],
|
||||
player1_points: this.points[this.player1Id],
|
||||
player2_points: this.points[this.player2Id],
|
||||
};
|
||||
|
||||
try {
|
||||
await axios.put(
|
||||
`${API_URL}/matches/${this.id}`,
|
||||
{
|
||||
status: "Ended",
|
||||
winner_user_id: winnerId,
|
||||
loser_user_id: loserId,
|
||||
player1_marks: this.marks[this.player1Id],
|
||||
player2_marks: this.marks[this.player2Id],
|
||||
player1_points: this.points[this.player1Id],
|
||||
player2_points: this.points[this.player2Id],
|
||||
},
|
||||
this.getAuthHeaders()
|
||||
);
|
||||
console.log(`[Match ${this.id}] Encerrado com sucesso na API.`);
|
||||
await axios.put(`${API_URL}/matches/${this.id}`, payload, this.getAuthHeaders());
|
||||
console.log(`[Match ${this.id}] Match Closed in DB.`);
|
||||
} catch (e) {
|
||||
console.error(`Erro ao fechar Match API: ${e.message}`);
|
||||
console.error(`Match Close Error: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
playCard(userId, cardId) {
|
||||
if (!this.currentGame || this.status !== "Playing") return;
|
||||
return this.currentGame.playCard(userId, cardId);
|
||||
|
||||
const result = this.currentGame.playCard(userId, cardId);
|
||||
|
||||
// FIX: Restart timer if game continues
|
||||
if (result && (result.action === 'next_turn' || result.action === 'trick_resolved')) {
|
||||
this.currentGame.startTurnTimer((uid, cid) => {
|
||||
if (this.autoPlayCallback) this.autoPlayCallback(uid, cid);
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
getState() {
|
||||
let gameState = null;
|
||||
|
||||
if (this.currentGame) {
|
||||
const p1Id = this.player1Id;
|
||||
const p2Id = this.player2Id;
|
||||
|
||||
if (this.currentGame.players && this.currentGame.players[p1Id]) {
|
||||
gameState = this.currentGame.getStateForPlayer(p1Id);
|
||||
} else if (this.currentGame.players && this.currentGame.players[p2Id]) {
|
||||
gameState = this.currentGame.getStateForPlayer(p2Id);
|
||||
} else if (this.currentGame.players) {
|
||||
const availableIds = Object.keys(this.currentGame.players);
|
||||
if (availableIds.length > 0) {
|
||||
console.warn(
|
||||
`⚠️ [Match ${this.id}] IDs desalinhados! A usar vista do user ${availableIds[0]}`
|
||||
);
|
||||
gameState = this.currentGame.getStateForPlayer(availableIds[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
getGameState(userId) {
|
||||
if (!this.currentGame) return null;
|
||||
if (this.currentGame.players[userId]) return this.currentGame.getStateForPlayer(userId);
|
||||
return null;
|
||||
}
|
||||
|
||||
getPublicState() {
|
||||
return {
|
||||
matchId: this.id,
|
||||
status: this.status,
|
||||
marks: this.marks,
|
||||
points: this.points,
|
||||
game: gameState,
|
||||
player1: this.player1,
|
||||
player2: this.player2
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user