Skip to content

Commit

Permalink
Added New backend
Browse files Browse the repository at this point in the history
  • Loading branch information
prathamtechops committed Sep 24, 2024
1 parent f356b83 commit 410d154
Show file tree
Hide file tree
Showing 3 changed files with 185 additions and 97 deletions.
137 changes: 103 additions & 34 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,44 @@ const io = new Server(server, {
transports: ["websocket"],
});

const port = process.env.PORT || 3000;
const port = process.env.PORT || 8000;
const rooms = new Map();

app.get("/", (req, res) => {
res.send("Hello World!");
});
// Utility function to sanitize room data
function sanitizeRoom(room) {
return {
roomId: room.roomId,
players: room.players.map(
({ id, username, avatar, orientation, remainingTime }) => ({
id,
username,
avatar,
orientation,
remainingTime,
})
),
currentTurn: room.currentTurn,
};
}

const GAME_TIME = 600; // 10 minutes in seconds

io.on("connection", (socket) => {
// Correcting the room join logic
socket.on("joinRoom", async ({ username, roomId, avatar, user_id }) => {
console.log(`Username received: ${username}, Room ID: ${roomId}`); // Corrected log
socket.data.username = username;
socket.data.user_id = user_id;

if (!rooms.has(roomId)) {
rooms.set(roomId, { roomId, players: [] });
rooms.set(roomId, {
roomId,
players: [],
currentTurn: null,
timer: null,
});
}

const room = rooms.get(roomId);

// Assign orientation based on the number of players in the room
if (!room.players.some((player) => player.id === user_id)) {
const playerOrientation =
room.players.length === 0
Expand All @@ -47,76 +64,128 @@ io.on("connection", (socket) => {
username,
avatar,
orientation: playerOrientation,
remainingTime: GAME_TIME,
});
room.currentTurn = room.players[0].id;
rooms.set(roomId, room);
}
rooms.set(roomId, room);
}

await socket.join(roomId);

if (room.players.length === 2) {
io.to(roomId).emit("startGame", room); // Ensuring both players are ready before starting
io.to(roomId).emit("startGame", sanitizeRoom(room));
startTimer(roomId);
}
});

socket.on("requestPlayAgain", ({ room }) => {
socket.to(room).emit("playAgainRequest"); // Notify the other player
socket.on("move", (data) => {
const room = rooms.get(data.room);
if (!room || room.players.length < 2) return;

const currentPlayer = room.players.find((p) => p.id === room.currentTurn);
if (!currentPlayer) return;

// Switch turn
room.currentTurn = room.players.find((p) => p.id !== room.currentTurn).id;
rooms.set(data.room, room);

// Emit move to opponent
socket.to(data.room).emit("move", data.move);

// Reset timer
resetTimer(data.room);
});

// Handle accepting play again request
socket.on("acceptPlayAgain", ({ room }) => {
io.to(room).emit("playAgainAccepted"); // Restart game for both players
socket.on("requestPlayAgain", ({ room }) => {
socket.to(room).emit("playAgainRequest");
});

socket.on("move", (data) => {
socket.to(data.room).emit("move", data.move);
socket.on("acceptPlayAgain", ({ room }) => {
const roomData = rooms.get(room);
if (roomData) {
roomData.players.forEach((player) => (player.remainingTime = GAME_TIME));
roomData.currentTurn = roomData.players[0].id;
rooms.set(room, roomData);
io.to(room).emit("playAgainAccepted", sanitizeRoom(roomData));
resetTimer(room);
}
});

socket.on("disconnect", () => {
const gameRooms = Array.from(rooms.values());

gameRooms.forEach((room) => {
rooms.forEach((room, roomId) => {
const playerIndex = room.players.findIndex(
(player) => player.id === socket.data.user_id
);

// Remove player from room if found
if (playerIndex !== -1) {
room.players.splice(playerIndex, 1);
rooms.set(roomId, room);
}

// Remove room if no players are left
if (room.players.length === 0) {
rooms.delete(room.roomId);
clearInterval(room.timer);
rooms.delete(roomId);
} else {
// Notify other players of the disconnection
socket.to(room.roomId).emit("playerDisconnected", socket.data.username);
socket.to(roomId).emit("playerDisconnected", socket.data.username);
}
});
});

socket.on("closeRoom", async (data) => {
console.log(`Close room request received for room ID: ${data.roomId}`);
const room = rooms.get(data.roomId);

if (room) {
// Notify all clients in the room about the closure
socket.to(data.roomId).emit("closeRoom", data);

// Fetch all client sockets in the room and disconnect them
const clientSockets = await io.in(data.roomId).fetchSockets();
clientSockets.forEach((s) => {
s.leave(data.roomId);
console.log(`Socket left room: ${data.roomId}`);
});

// Remove room from the Map
clearInterval(room.timer);
rooms.delete(data.roomId);
console.log(`Room deleted: ${data.roomId}`);
}
});
});

// Timer Functions
function startTimer(roomId) {
const room = rooms.get(roomId);
if (!room) return;

if (room.timer) {
clearInterval(room.timer);
}

room.timer = setInterval(() => {
const currentPlayer = room.players.find((p) => p.id === room.currentTurn);
if (!currentPlayer) return;

currentPlayer.remainingTime -= 1;

io.to(roomId).emit("timeUpdate", {
playerId: currentPlayer.id,
remainingTime: currentPlayer.remainingTime,
});

if (currentPlayer.remainingTime <= 0) {
io.to(roomId).emit("gameOver", {
winner: room.players.find((p) => p.id !== currentPlayer.id).id,
reason: "time",
});
clearInterval(room.timer);
}
}, 1000);

rooms.set(roomId, room);
}

function resetTimer(roomId) {
const room = rooms.get(roomId);
if (room && room.timer) {
clearInterval(room.timer);
startTimer(roomId);
}
}

server.listen(port, () => {
console.log(`Listening on *:${port}`);
});
Loading

0 comments on commit 410d154

Please sign in to comment.