To manage team assignments in a Colyseus server while utilizing the room state, we will modify the example to maintain the state of teams and players directly in the room's state. This way, it becomes easier to synchronize the state across connected clients and ensure that everyone has the updated view of the game.
Updated Server Code with Room State
In this version, we'll define a room state that tracks teams and players and updates it whenever a player joins or leaves.
Install Dependencies
First, ensure you have the necessary packages installed if you haven't done so already by running:
npm install colyseus @colyseus/monitor express body-parser
Complete Server Code
Here's the updated TypeScript server code that implements team management through room state:
import { Server } from "colyseus";
import { WebSocketServer } from "ws";
import express from "express";
import http from "http";
import { Room, Client } from "colyseus";
import bodyParser from "body-parser";
interface Player {
id: string;
name: string;
team?: string;
}
interface RoomState {
players: { [key: string]: Player }; // Maps player IDs to Player objects
teams: { [key: string]: Player[] }; // Maps team names to arrays of Player objects
}
// Define the TeamLobbyRoom
class TeamLobbyRoom extends Room<RoomState> {
onCreate(options: { numTeams: number }) {
console.log("Team Lobby Room created with options:", options);
// Initialize the state
this.setState({
players: {},
teams: this.initializeTeams(options.numTeams),
});
this.onMessage("joinTeam", (client: Client) => {
this.addPlayerToTeam(client);
});
this.onMessage("leaveTeam", (client: Client) => {
this.removePlayerFromTeam(client);
});
}
onJoin(client: Client, options: any) {
console.log(`Client ${client.sessionId} joined!`);
// Welcome message and current state to the new player
this.send(client, {
message: `Welcome to the lobby! Choose your team.`,
teams: this.state.teams,
});
}
onLeave(client: Client) {
console.log(`Client ${client.sessionId} left!`);
this.removePlayerFromTeam(client);
delete this.state.players[client.sessionId]; // Remove from players list
}
onDispose() {
console.log("Team Lobby Room disposed!");
}
private initializeTeams(numTeams: number) {
const teams: { [key: string]: Player[] } = {};
for (let i = 0; i < numTeams; i++) {
teams[`team${i + 1}`] = [];
}
return teams;
}
private addPlayerToTeam(client: Client) {
// Find the team with the least players
const teamKeys = Object.keys(this.state.teams);
const smallestTeam = teamKeys.reduce((smallest, key) =>
this.state.teams[smallest].length <= this.state.teams[key].length ? smallest : key
);
// Add the player to the team
const playerName = `Player ${client.sessionId}`; // Example player name
const player: Player = { id: client.sessionId, name: playerName, team: smallestTeam };
this.state.players[client.sessionId] = player;
this.state.teams[smallestTeam].push(player);
// Notify all players about the new team assignment
this.broadcast("playerJoinedTeam", {
player: player,
team: smallestTeam,
});
console.log(`${playerName} joined ${smallestTeam}`);
}
private removePlayerFromTeam(client: Client) {
const player = this.state.players[client.sessionId];
if (!player || !player.team) return;
// Remove player from their team
const teamPlayers = this.state.teams[player.team];
const index = teamPlayers.indexOf(player);
if (index !== -1) {
teamPlayers.splice(index, 1);
// Notify other players
this.broadcast("playerLeftTeam", {
player: player,
team: player.team,
});
console.log(`${player.name} left ${player.team}`);
}
}
}
// Create a Colyseus server
const app = express();
const server = http.createServer(app);
const gameServer = new Server({
transport: new WebSocketServer({ server }),
});
// Middleware to parse JSON bodies
app.use(bodyParser.json());
// Define the room with default options
gameServer.define("team_lobby", TeamLobbyRoom);
// Route for clients to join with game mode
app.post("/join-lobby", (req, res) => {
const { gameMode } = req.body;
// Define number of teams based on the selected game mode
let numTeams;
switch (gameMode) {
case "modeA":
numTeams = 2; // 2 teams for mode A
break;
case "modeB":
numTeams = 3; // 3 teams for mode B
break;
case "modeC":
numTeams = 4; // 4 teams for mode C
break;
default:
numTeams = 2; // Default to 2 teams
}
// Create a new room with the specified number of teams
const roomId = gameServer.create("team_lobby", { numTeams });
res.json({ roomId });
});
// Start the Colyseus server
const PORT = Number(process.env.PORT || 3000);
server.listen(PORT, () => {
console.log(`Listening on ws://localhost:${PORT}`);
});
Changes in the Server Code
-
Using Room State: The room state now contains a structure to manage players and their teams. Every time a player joins or leaves a team, the state is updated accordingly.
-
Player Management:
- The
players field tracks active players with their respective states, including team assignments.
- The
teams field tracks which players belong to which team.
-
Team Management Logic: When a player joins, they are assigned to the team with the fewest players. The addPlayerToTeam and removePlayerFromTeam methods handle updating the state directly.
Client Interaction
For the client, we will use a similar structure as before to connect to this server. Below is the simplified example of how the client could interact with the lobby:
Example Client Code (JavaScript)
async function joinLobby(gameMode) {
try {
const response = await fetch('/join-lobby', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ gameMode }),
});
const data = await response.json();
const roomId = data.roomId;
const client = new Colyseus.Client("ws://localhost:3000");
const room = await client.joinById(roomId);
console.log("Joined team lobby!");
room.onMessage("playerJoinedTeam", (data) => {
console.log(`${data.player.name} joined ${data.team}`);
});
room.onMessage("playerLeftTeam", (data) => {
console.log(`${data.player.name} left ${data.team}`);
});
// Optionally allow players to join a team
room.send("joinTeam");
} catch (error) {
console.error("Error while joining the lobby:", error);
}
}
// Call joinLobby with desired game mode
joinLobby("modeA"); // Replace with desired mode
Running Your Server
- Compile the Server Code:
tsc server.ts
- Run the Server:
node server.js
- Test the Client: Ensure your client connects to the
/join-lobby endpoint with an appropriate game mode.
Conclusion
With this updated setup, the Colyseus architecture efficiently manages team assignments and maintains the state of players and teams. This allows all clients to be in sync with the room's current state. If you have any further questions or require additional features, feel free to ask!