Skip to content

Commit

Permalink
feat(socket): add script 2/3
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastianjnuwu committed Jan 5, 2025
1 parent 252c64c commit 87b0d15
Show file tree
Hide file tree
Showing 17 changed files with 331 additions and 26 deletions.
2 changes: 2 additions & 0 deletions socket/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules/
package-lock.json
6 changes: 6 additions & 0 deletions socket/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"type": "module",
"dependencies": {
"socket.io": "^4.8.1"
}
}
11 changes: 11 additions & 0 deletions socket/src/functions/functions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
let roomIdCounter = 0;

export function $generate_uuid() {
roomIdCounter += 1;
return roomIdCounter;
}

// code
export function $generate_code() {
return Math.random().toString(36).substring(2, 8).toUpperCase();
};
186 changes: 186 additions & 0 deletions socket/src/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import { Server } from 'socket.io';
import {
$generate_code,
$generate_uuid
} from './functions/functions.js';

const io = new Server();
const ROOMS = {};

io.on("connection", (socket) => {

// room
socket.on("room", ({ room_code, room_time, room_player }) => {

// Gera um código para a sala, se necessário
if (!room_code) {
const new_room_code = $generate_code(); // Certifique-se de que $generate_code está definida
room_code = new_room_code;
ROOMS[room_code] = {
code: room_code,
date: new Date(),
players: [],
owner: room_player,
time: room_time,
state: "waiting"
};
}

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

// Verifica se a sala existe
if (!room) {
console.log(`O "${room_player}" tentou entrar em uma sala "${room_code}" que não existe!`);
return;
}

// Verifica se a sala está no estado "waiting"
if (room.state !== "waiting") {
console.log(`O "${room_player}" tentou entrar em uma sala "${room_code}" que está com status: ${room.state}`);
return;
}

// Verifica se já existe um jogador com o mesmo nickname na sala
const existingPlayer = room.players.find(player => player.room_player === room_player);
if (existingPlayer) {
console.log("Já existe um jogador com este nick na sala!");
return;
}

// Adiciona o socket à sala
socket.join(room_code);

// Registra o jogador na sala
room.players.push({
id: $generate_uuid(), // Certifique-se de que $generate_uuid está definida
date: new Date(),
socket: socket.id,
player_date: {
cps: 0,
cookies: 0
},
room_player
});

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

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

// leave_room
socket.on("leave_room", ({ room_code, room_player }) => {

const room = ROOMS[room_code];

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

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

// Se a sala ficar vazia, remove-a
if (room.players.length === 0) {
delete ROOMS[room_code];
console.log(`Sala ${room_code} foi deletada.`);
} else if (room.owner === room_player) {
// Atualiza o dono da sala, se necessário
room.owner = room.players[0]?.room_player || null;
console.log(`Novo dono da sala ${room_code}: ${room.owner}`);
}

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

// Envia uma atualização para todos os membros restantes da sala
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}`);

console.log(room);

});

// rejoin_room
socket.on('rejoin_room', ({
room_player, room_code
}) => {

// select code room
const room = ROOMS[room_code];

if (!room) return;

// trocar o socket id
room.players.forEach(x => {
if (x.room_player === room_player) {
x.socket = socket.id;
};
});

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

// send the update to room.
io.to(room_code).emit("update_room", { room_player, room });

console.log(room);

});

socket.on("start_game", ({ room_code }) => {

const room = ROOMS[room_code];
room.state = "in_game";

let countdown = 3; // Contagem regressiva de 10 segundos
const countdownInterval = setInterval(() => {
io.to(room_code).emit("count_down", { countdown });

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

// Envia o início do jogo
io.to(room_code).emit("game_start");

// Inicia o temporizador do jogo
let time_game = room.time * 1; // Converte minutos em segundos (60 ta em 1 para teste)

const gameInterval = setInterval(() => {
time_game--;

// Atualiza o tempo restante
io.to(room_code).emit("timer", { time_game });

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

// Finaliza o jogo e envia 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
}));

// Atualiza o estado da sala e envia o ranking
room.state = "finished";
io.to(room_code).emit("game_end", { ranking });

console.log(`Jogo na sala ${room_code} finalizado! Ranking:`, ranking);
}
}, 1000); // Atualiza a cada segundo
}

countdown--;
}, 1000); // Atualiza a cada segundo
});

});

io.listen(3000);
52 changes: 32 additions & 20 deletions www/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>Cookie</title>
<link rel="shortcut icon" href="https://i.imgur.com/dGKQOJf.png" type="image/png">
<link rel="shortcut icon" href="./src/img/icon.webp" type="image/webp">
<link rel="stylesheet" href="./src/styles/css/ui.css">
<script src="https://cdn.jsdelivr.net/npm/js[email protected]/dist/js.cookie.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.8.1/socket.io.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="./src/js/modules/js.cookie.min.js"></script>
<script src="./src/js/modules/socket.io.min.js"></script>
<script src="./src/js/modules/jquery.min.js"></script>
<script type="module" src="./src/js/socket.js"></script>
<script type="module" src="./main.ts"></script>
</head>
Expand All @@ -22,12 +22,12 @@

<!--- sound of button clicks --->
<audio id="click" preload="auto">
<source src="https://github.com/sebastianjnuwu/sebastianjnuwu/raw/refs/heads/main/CDN/start.mp3">
<source src="https://github.com/sebastianjnuwu/sebastianjnuwu/raw/refs/heads/main/CDN/click.mp3">
</audio>

<!--- (splash-screen) --->
<div id="splash-screen">
<img src="https://i.imgur.com/dGKQOJf.png" alt="splash-screen" class="icon mb-5">
<img src="./src/img/icon.webp" alt="splash-screen" class="icon mb-5">
<h1>Click...</h1>
</div>
<!--- (splash-screen) --->
Expand All @@ -41,31 +41,35 @@ <h1 class="title">
<button id="start-playing" data-bs-toggle="modal" data-bs-target="#gameModal">
<i class="fas fa-gamepad"></i> Jogar
</button>
<button id="game-settings">
<!-- <button id="game-settings">
<i class="fas fa-cog"></i> Configurações
</button>
<button id="exit-app">
<i class="fas fa-sign-out-alt"></i> Sair
</button>
</button> -->
</div>
</div>
<!--- (splash-screen) --->

<ui style="display: none;">

<div class="room-code position-fixed top-0 start-50 translate-middle-x mt-4">
<div class="room-code position-fixed top-0 start-50 translate-middle-x mt-4">
<h3><i class="fas fa-key"></i> Código da Sala:</h3>
<p id="current_code">
<i class="fas fa-wifi"></i>
</p>
</div>

<div style="display: none !important;" id="countdown-container" class="countdown-overlay d-flex justify-content-center align-items-center">
<div id="ranking" style="display: none;">
<h2>Ranking Final</h2>
<ul id="ranking-list"></ul>
</div>

<div id="countdown-container" class="countdown-overlay d-flex justify-content-center align-items-center" style="display: none !important;">
<h1 id="countdown" class="countdown-text">3</h1>
</div>


<div class="waiting-room">
<div class="waiting-room">
<h1><i class="fas fa-cookie-bite"></i> Aguardando...</h1>
<p>
<i class="fas fa-users"></i> <x id="online">1</x>/1
Expand All @@ -81,9 +85,9 @@ <h1><i class="fas fa-cookie-bite"></i> Aguardando...</h1>

</div>


<div style="display: none;" class="game">
<table class="statistic position-relative">
<div style="display: none !important;" class="game d-flex flex-column justify-content-center align-items-center">
<table class="statistic position-relative">
<tbody>
<tr>
<th><i class="fas fa-cookie-bite"></i> Cookies</th>
Expand All @@ -95,14 +99,21 @@ <h1><i class="fas fa-cookie-bite"></i> Aguardando...</h1>
</tr>
</tbody>
</table>
</div>

<cookie style="display: none;" class="cookie position-relative game">
<img src="https://raw.githubusercontent.com/sebastianjnuwu/sebastianjnuwu/refs/heads/main/website/7_Sem_Titulo_20241227172134.png" alt="cookie" class="icon mb-4">
<cookie class="cookie position-relative game">
<img src="./src/img/cookie.webp" alt="cookie" class="icon mb-4">
</cookie>

</div>

<div class="game-time position-fixed bottom-0 start-50 translate-middle-x mb-4" style="display: none;">
<h3><i class="fas fa-stopwatch"> Tempo: </i> <span id="timer">0:00</span></h3>
</div>


</ui>


<div class="modal fade" id="gameModal" tabindex="-1" aria-labelledby="gameModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
Expand Down Expand Up @@ -167,10 +178,11 @@ <h5 class="modal-title" id="gameModalLabel">
</div>
</div>

<!--- (script) --->
<script type="module" src="./src/js/main.js" defer></script>
<script type="module" src="./src/js/cookie/game.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-I7E8VVD/ismYTF4hNIPjVp/Zjvgyol6VFvRkX/vR+Vc4jQkC+hVqc2pM8ODewa9r" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-0pUGZvbkm6XF6gxjEnlmuGrJXVbNuzT9qBBavbLwCsOGabYfZo0T0to5eqruptLy" crossorigin="anonymous"></script>
<script src="./src/js/modules/bootstrap.min.js"></script>
<!--- (script) --->

</body>
</html>
Binary file removed www/src/audio/click.mp3
Binary file not shown.
Binary file removed www/src/audio/start.mp3
Binary file not shown.
Binary file added www/src/img/cookie.webp
Binary file not shown.
Binary file added www/src/img/icon.webp
Binary file not shown.
2 changes: 1 addition & 1 deletion www/src/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ $(() => {
}, 1000);
});

$("start-screen button").on("click", () => $("#click")[0].play());
$("#start-screen button").on("click", () => $("#click")[0].play());

$('input[name="option_game"]').on('change', () => {
if ($('#room_join').is(':checked')) {
Expand Down
7 changes: 7 additions & 0 deletions www/src/js/modules/bootstrap.min.js

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions www/src/js/modules/jquery.min.js

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions www/src/js/modules/js.cookie.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions www/src/js/modules/socket.io.min.js

Large diffs are not rendered by default.

36 changes: 35 additions & 1 deletion www/src/js/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ socket.on("count_down", ({ countdown }) => {
$(".room-code").show();
$countdown.remove();
$(".game").show();
$(".game-time ").show();
}, 1000);
}

Expand All @@ -94,6 +95,39 @@ $("#start_game").on("click", () => {
socket.emit("start_game", {
room_code: Cookies.get('code'),
});


});

socket.on("timer", ({ time_game }) => {
return $("#timer").text(time_game);
});

// Evento recebido do servidor com o ranking final
socket.on("game_end", ({ ranking }) => {

console.log(ranking);

$(".room-code").hide();
$(".game").remove();
$(".game-time").hide();

const $rankingContainer = $("#ranking");
const $rankingList = $("#ranking-list");

// Limpa a lista antes de adicionar novos jogadores
$rankingList.empty();

// Adiciona cada jogador ao ranking
ranking.forEach((player, index) => {
const isNewClass = index === 0 ? "new" : ""; // Destaque para o primeiro lugar
$rankingList.append(`
<li class="${isNewClass}">
<span><b>#${player.rank}</b> ${player.room_player} - ${player.cookies} </span>
</li>
`);
});

// Mostra o ranking
$rankingContainer.fadeIn();

});
Loading

0 comments on commit 87b0d15

Please sign in to comment.