Skip to content

Commit

Permalink
update socket/src/main.js
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastianjnuwu committed Jan 8, 2025
1 parent 0b9c0cd commit cc15b76
Showing 1 changed file with 119 additions and 99 deletions.
218 changes: 119 additions & 99 deletions socket/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,56 +4,66 @@ import { $generate_code, $generate_uuid } from "./functions/functions.js";
const io = new Server();
const ROOMS = {};

/**
* Event listener for a new connection from a client.
*/
io.on("connection", (socket) => {
// room

/**
* Handles room creation or joining a room.
* @param {Object} data - The data for the room.
* @param {string} data.room_code - The code of the room.
* @param {number} data.room_time - The time duration for the room in minutes.
* @param {string} data.room_player - The name of the player joining the room.
*/
socket.on("room", ({ room_code, room_time, room_player }) => {
// Gera um código para a sala, se necessário
// Generate a room code if not provided
if (!room_code) {
const new_room_code = $generate_code(); // Certifique-se de que $generate_code está definida
const new_room_code = $generate_code(); // Ensure $generate_code is defined
room_code = new_room_code;
ROOMS[room_code] = {
code: room_code,
date: new Date(),
players: [],
owner: room_player,
time: room_time || 1,
time: room_time || 11, // Default to 11 seconds if no time is provided
state: "waiting",
};
}

// Seleciona a sala pelo código
// Select the room by its code
const room = ROOMS[room_code];

// Verifica se a sala existe
// Check if the room exists
if (!room) {
socket.emit("err_socket", {
message: `O "${room_player}" tentou entrar em uma sala "${room_code}" que não existe!`,
message: `The room "${room_code}" doesn't exist!`,
});
return;
}

// Verifica se a sala está no estado "waiting"
// Check if the room is in "waiting" state
if (room.state !== "waiting") {
socket.emit("err_socket", {
message: `O "${room_player}" tentou entrar em uma sala "${room_code}" que está com status: ${room.state}`,
message: `The room "${room_code}" is currently in "${room.state}" state.`,
});
return;
}

// Verifica se já existe um jogador com o mesmo nickname na sala
// Check if the player with the same nickname is already in the room
if (room.players.find((player) => player.room_player === room_player)) {
socket.emit("err_socket", {
message: `Ja existe um jogador com este nickname (${room_player}) na sala`,
message: `A player with the nickname "${room_player}" already exists in the room.`,
});
return;
}

// Adiciona o socket à sala
// Add the player to the room
socket.join(room_code);

// Registra o jogador na sala
// Register the player in the room
room.players.push({
id: $generate_uuid(), // Certifique-se de que $generate_uuid está definida
id: $generate_uuid(), // Ensure $generate_uuid is defined
date: new Date(),
socket: socket.id,
player_date: {
Expand All @@ -62,177 +72,187 @@ io.on("connection", (socket) => {
room_player,
});

// Envia uma atualização da sala para todos os jogadores
// Send room update to all players
io.to(room_code).emit("update_room", { room_player, room });

// Log para depuração
console.log(
`Jogador "${room_player}" entrou na sala "${room_code}". Estado da sala:`,
room,
`Player "${room_player}" joined room "${room_code}". Room state:`,
room
);
});

// leave_room
/**
* Handles player leaving a room.
* @param {Object} data - The data for leaving the room.
* @param {string} data.room_code - The code of the room.
* @param {string} data.room_player - The name of the player leaving the room.
*/
socket.on("leave_room", ({ room_code, room_player }) => {
const room = ROOMS[room_code];

// Verifica se a sala existe
// Check if the room exists
if (!room) return;

// Remove o jogador da sala
// Remove the player from the room
room.players = room.players.filter(
(player) => player.room_player !== room_player,
(player) => player.room_player !== room_player
);

// Se a sala ficar vazia, remove-a
// Delete the room if it is empty
if (room.players.length === 0) {
delete ROOMS[room_code];
console.log(`Sala ${room_code} foi deletada.`);
console.log(`Room ${room_code} has been deleted.`);
} else if (room.owner === room_player) {
// Atualiza o dono da sala, se necessário
// Update the owner if necessary
room.owner = room.players[0]?.room_player || null;
console.log(`Novo dono da sala ${room_code}: ${room.owner}`);
console.log(`New owner of room ${room_code}: ${room.owner}`);
}

// Remove o socket da sala
// Remove the socket from the room
socket.leave(room_code);

// Envia uma atualização para todos os membros restantes da sala
// Send updated room state to all players
io.to(room_code).emit("update_room", { room_player, room });

// Log para fins de depuração
console.log(
`Socket ${socket.id} (${room_player}) saiu da sala ${room_code}`,
`Socket ${socket.id} (${room_player}) left room ${room_code}`
);
});

// rejoin_room
/**
* Handles player rejoining a room.
* @param {Object} data - The data for rejoining the room.
* @param {string} data.room_player - The name of the player rejoining the room.
* @param {string} data.room_code - The code of the room.
*/
socket.on("rejoin_room", ({ room_player, room_code }) => {
// select code room
const room = ROOMS[room_code];

if (!room) return;
if (room.state === "finished") return;

// trocar o socket id
// Trocar o socket id
// Update the socket ID for the player
for (const player of room.players) {
if (player.room_player === room_player) {
player.socket = socket.id;
break; // Se só um jogador precisa ser atualizado, encerra o loop
break; // Exit the loop after updating the player's socket
}
}

// enter the code room
// Player joins the room again
socket.join(room_code);

// send the update to room.
// Send updated room state to all players
io.to(room_code).emit("update_room", { room_player, room });
});

/**
* Starts the game in a room.
* @param {Object} data - The data for starting the game.
* @param {string} data.room_code - The code of the room.
*/
socket.on("start_game", ({ room_code }) => {
const room = ROOMS[room_code];
const room = ROOMS[room_code];

// Verifica se a sala existe
if (!room) {
socket.emit("err_socket", {
message: `Sala ${room_code} não encontrada.`,
});
return;
}
// Check if the room exists
if (!room) {
socket.emit("err_socket", {
message: `Room ${room_code} not found.`,
});
return;
}

// Altera o estado da sala para "in_game"
room.state = "in_game";
// Change the room state to "in_game"
room.state = "in_game";

let countdown = 3; // Contagem regressiva de 3 segundos
const countdownInterval = setInterval(() => {
// Envia o valor atual do countdown para a sala
io.to(room_code).emit("count_down", { countdown });
let countdown = 3; // Countdown for 3 seconds
const countdownInterval = setInterval(() => {
// Send the current countdown to the room
io.to(room_code).emit("count_down", { countdown });

if (countdown <= 0) {
clearInterval(countdownInterval);
if (countdown <= 0) {
clearInterval(countdownInterval);

// Envia o evento de início do jogo
io.to(room_code).emit("game_start");
// Start the game
io.to(room_code).emit("game_start");

// Define o tempo de jogo em segundos
let time_game = room.time * 1; // <fix> Multiplica os minutos por 60 para converter para segundos
let time_game = room.time * 1; // Convert time from minutes to seconds

const gameInterval = setInterval(() => {
// Envia o tempo restante para a sala
io.to(room_code).emit("timer", { time_game });
const gameInterval = setInterval(() => {
// Send the remaining game time to the room
io.to(room_code).emit("timer", { time_game });

if (time_game <= 0) {
clearInterval(gameInterval);
if (time_game <= 0) {
clearInterval(gameInterval);

// Finaliza o jogo e gera o ranking
const ranking = room.players
.sort((a, b) => b.player_date.cookies - a.player_date.cookies) // Ordena por cookies
.map((player, index) => ({
rank: index + 1,
room_player: player.room_player,
cookies: player.player_date.cookies,
}));
// End the game and generate the ranking
const ranking = room.players
.sort((a, b) => b.player_date.cookies - a.player_date.cookies) // Sort by cookies
.map((player, index) => ({
rank: index + 1,
room_player: player.room_player,
cookies: player.player_date.cookies,
}));

// Atualiza o estado da sala
room.state = "finished";
room.state = "finished";

// Envia o evento de fim do jogo com o ranking
io.to(room_code).emit("game_end", { ranking });
// Send the game end event with the ranking
io.to(room_code).emit("game_end", { ranking });

if (room.state === "finished") {
delete ROOMS[room_code];
console.log(`Sala ${room_code} foi deletada.`);
}
if (room.state === "finished") {
delete ROOMS[room_code];
console.log(`Room ${room_code} has been deleted.`);
}

console.log(
`Jogo na sala ${room_code} finalizado! Ranking:`,
ranking
);
console.log(`Game in room ${room_code} finished! Ranking:`, ranking);

return; // Evita que qualquer execução adicional ocorra
}
return; // Prevent further execution
}

time_game--; // Decrementa o tempo após enviar o valor atual
}, 1000); // Atualiza a cada segundo
}
time_game--; // Decrement the game time
}, 1000); // Update every second
}

countdown--; // Decrementa o countdown após enviar o valor atual
}, 1000); // Atualiza a cada segundo
});
countdown--; // Decrement the countdown
}, 1000); // Update every second
});

/**
* Updates the number of cookies for a player in the room.
* @param {Object} data - The data for updating cookies.
* @param {string} data.room_player - The name of the player.
* @param {string} data.room_code - The code of the room.
* @param {number} data.cookies - The number of cookies to update.
*/
socket.on("update_cookies", ({ room_player, room_code, cookies }) => {
// Valida se o número de cookies recebido é válido
if (typeof cookies !== "number" || cookies < 0) {
console.error("Dados inválidos recebidos no evento update_cookies.");
console.error("Invalid cookie data received.");
return;
}

// Busca a sala diretamente pelo código
const room = ROOMS[room_code];

if (!room) {
console.error(`Sala ${room_code} não encontrada.`);
console.error(`Room ${room_code} not found.`);
return;
}

// Busca o jogador dentro da sala
const player = room.players.find(
(player) => player.room_player === room_player,
(player) => player.room_player === room_player
);

// Verifica se o jogador existe e atualiza os cookies
if (player) {
player.player_date.cookies = cookies;
console.log(
`Jogador ${room_player} na sala ${room_code} atualizou cookies para ${cookies}.`,
`Player ${room_player} in room ${room_code} updated cookies to ${cookies}.`
);
} else {
console.error(
`Jogador ${room_player} não encontrado na sala ${room_code}.`,
`Player ${room_player} not found in room ${room_code}.`
);
}
});
});

// Start listening on port 3000
io.listen(3000);

0 comments on commit cc15b76

Please sign in to comment.