Skip to content

Commit

Permalink
Integrate Tic Tac Toe game logic into the server with player manageme…
Browse files Browse the repository at this point in the history
…nt and turn handling
  • Loading branch information
Xanthium7 committed Jan 1, 2025
1 parent e520e06 commit 6212b7f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
4 changes: 3 additions & 1 deletion server.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ require("dotenv").config({ path: ".env.local" });
const { createServer } = require("http");
const { Server } = require("socket.io");
const roomChat = require("./roomChat");
const { useAzureSocketIO } = require("@azure/web-pubsub-socket.io");
const ticTacToe = require("./ticTacToe");

const httpServer = createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
Expand Down Expand Up @@ -146,6 +146,8 @@ io.on("connection", (socket) => {

//* Chat message handling
roomChat(io, socket);
//* Tic-Tac-Toe handling
ticTacToe(io, socket);

socket.on("disconnect", () => {
console.log(`Player disconnected: ${socket.id}`);
Expand Down
19 changes: 10 additions & 9 deletions ticTacToe.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,30 +13,31 @@ module.exports = function (io, socket) {
winner: null,
};
}
const game = io.games[roomId];

//adding the player part
games.players[socket.id] = {
game.players[socket.id] = {
id: socket.id,
name: playername || "hehe",
symbol: null, // 'X' or 'O'
};

const playerCount = Object.keys(io.games.players).length;
const playerCount = Object.keys(game.players).length;
if (playerCount === 1) {
games.players[socket.id].symbol = "X";
games.currentTurn = socket.id;
game.players[socket.id].symbol = "X";
game.currentTurn = socket.id;
socket.emit("gameStart", {
symbol: "X",
board: games.board,
currentTurn: games.currentTurn,
board: game.board,
currentTurn: game.currentTurn,
});
} else if (playerCount === 2) {
games.players[socket.id].symbol = "O";
game.players[socket.id].symbol = "O";
// notify both players
io.to(roomId).emit("gameStart", {
symbol: "O",
board: games.board,
currentTurn: games.currentTurn,
board: game.board,
currentTurn: game.currentTurn,
});
} else {
socket.emit("gameFull");
Expand Down

0 comments on commit 6212b7f

Please sign in to comment.