colyseus io typescript server side custom lobby example
Assistant
User
same but redestribute players in teams
Assistant
User
same but number oof teams depends on options
Assistant
Certainly! Colyseus is a popular multiplayer game framework that allows you to create real-time multiplayer games easily. Below is a simple example of a TypeScript-based Colyseus server implementation that demonstrates how to create a custom lobby.
Setting Up Your Colyseus Server
Install Packages:
To get started, you need to install the necessary packages. Assuming you have Node.js and npm installed, you can create a new directory for your project and run the following commands:
Create Server Files:
Create a directory called src and within it, create the following files:
lobbyRoom.ts: This will be the implementation of the lobby room.
index.ts: This will be the entry point of your server.
Implementation of lobbyRoom.ts
Create a file named lobbyRoom.ts under the src directory:
typescript
import { Room, Client } from "colyseus";
interface Player {
id: string;
name: string;
}
export class LobbyRoom extends Room {
private players: Player[] = [];
onCreate(options: any) {
console.log("Lobby Room created!");
// Setting up the message handlers
this.onMessage("join", (client: Client, message: { name: string }) => {
const player: Player = { id: client.sessionId, name: message.name };
this.players.push(player);
// Notify all clients about the new player
this.broadcast("player_joined", player);
});
this.onMessage("leave", (client: Client) => {
this.players = this.players.filter(player => player.id !== client.sessionId);
this.broadcast("player_left", { id: client.sessionId });
});
}
onJoin(client: Client) {
console.log(`Client ${client.sessionId} joined the lobby`);
}
onLeave(client: Client) {
console.log(`Client ${client.sessionId} left the lobby`);
this.players = this.players.filter(player => player.id !== client.sessionId);
// Optionally, notify others
this.broadcast("player_left", { id: client.sessionId });
}
onDispose() {
console.log("Lobby Room disposed.");
}
}
Implementation of index.ts
Now, create a file named index.ts in the src directory:
typescript
import { Server } from "colyseus";
import { createServer } from "http";
import express from "express";
import { LobbyRoom } from "./lobbyRoom";
const app = express();
const server = createServer(app);
const gameServer = new Server({
server
});
// Register the room
gameServer.define("lobby", LobbyRoom);
app.get("/", (req, res) => {
res.send("Welcome to Colyseus Lobby Server!");
});
const PORT = process.env.PORT || 2567;
gameServer.listen(PORT, () => {
console.log(`Listening on ws://localhost:${PORT}`);
});
Starting the Server
To run the server, add a script to your package.json:
json
"scripts": {
"start": "ts-node src/index.ts"
}
Then, you can start your server with:
bash
npm start
Client Side
You would need a compatible client to interact with the server. Colyseus provides a JavaScript client that you can use to connect to the server. Below is a sample client code:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Colyseus Lobby Client</title>
<script src="https://unpkg.com/colyseus.js"></script>
</head>
<body>
<script>
const client = new Colyseus.Client('ws://localhost:2567');
// Join the lobby
client.join("lobby").then(room => {
console.log("You joined room:", room);
room.onMessage("player_joined", (player) => {
console.log("Player joined:", player);
});
room.onMessage("player_left", (data) => {
console.log("Player left:", data.id);
});
// Example of sending a message to join with a name
room.send("join", { name: "Player1" });
// Leave room when window unloads
window.addEventListener('beforeunload', () => {
room.send("leave");
room.leave();
});
}).catch(e => {
console.error("Join error", e);
});
</script>
</body>
</html>
This simple example shows how to create a lobby room using Colyseus in TypeScript. You can expand upon this with more complex logic, user authentication, and various game-related features.
Sure! To manage teams in the lobby, we need to extend the earlier example to distribute players into teams automatically. We'll create a simple logic that divides players into two teams whenever someone joins.
Updated LobbyRoom.ts
Let's modify the LobbyRoom class in lobbyRoom.ts to include team management:
typescript
import { Room, Client } from "colyseus";
interface Player {
id: string;
name: string;
team: number; // 0 for Team A, 1 for Team B
}
export class LobbyRoom extends Room {
private players: Player[] = [];
private teamA: Player[] = [];
private teamB: Player[] = [];
onCreate(options: any) {
console.log("Lobby Room created!");
this.onMessage("join", (client: Client, message: { name: string }) => {
const team = this.assignTeam(); // Assign a team
const player: Player = { id: client.sessionId, name: message.name, team };
this.players.push(player);
// Notify all clients about the new player
this.broadcast("player_joined", player);
this.broadcast("teams_update", this.getTeams());
});
this.onMessage("leave", (client: Client) => {
this.players = this.players.filter(player => player.id !== client.sessionId);
this.broadcast("player_left", { id: client.sessionId });
this.updateTeams();
});
}
onJoin(client: Client) {
console.log(`Client ${client.sessionId} joined the lobby`);
}
onLeave(client: Client) {
console.log(`Client ${client.sessionId} left the lobby`);
this.players = this.players.filter(player => player.id !== client.sessionId);
this.updateTeams();
// Optionally, notify others
this.broadcast("player_left", { id: client.sessionId });
}
onDispose() {
console.log("Lobby Room disposed.");
}
private assignTeam(): number {
// Assign players to Team A (0) or Team B (1)
return this.teamA.length <= this.teamB.length ? 0 : 1;
}
private updateTeams() {
this.teamA = this.players.filter(player => player.team === 0);
this.teamB = this.players.filter(player => player.team === 1);
this.broadcast("teams_update", this.getTeams());
}
private getTeams() {
return {
teamA: this.teamA,
teamB: this.teamB,
};
}
}
Updated index.ts file
No changes are needed in the index.ts file, but just to clarify, we will maintain the server setup as before.
Client-side Updates
Now you’ll also want to update your client-side script to handle the new team updates. Here’s an updated version of the client HTML code that listens for team updates and displays the players in each team:
Team Management: We added team management logic to the LobbyRoom. A player is assigned to Team A (0) or Team B (1) based on the current distribution of players.
Updating Teams: Whenever a player joins or leaves, the teams are updated, and the new state of the teams is broadcasted to all clients.
Client Updates: The client listens to the "teams_update" message and updates the displayed information about players and teams accordingly.
Running the Server and Client
Start your server as before:
bash
npm start
Open your HTML client in multiple browser tabs or windows to see how players are distributed between the teams when they join the lobby.
This example demonstrates a simplified lobby system with basic team assignment features. You can further enhance it by adding functionalities like team balancing, team-specific actions, or visual representation of teams in a game setting.
To implement a dynamic number of teams based on provided options, we can modify the server-side code to accept an options parameter specifying how many teams to create. Then, we can assign players to these teams in a round-robin fashion.
Updated lobbyRoom.ts
Let’s modify the lobbyRoom.ts file to support dynamic team creation:
typescript
import { Room, Client } from "colyseus";
interface Player {
id: string;
name: string;
team: number;
}
export class LobbyRoom extends Room {
private players: Player[] = [];
private teams: Player[][] = [];
onCreate(options: { numTeams: number }) {
console.log(`Lobby Room created with ${options.numTeams} teams!`);
// Initialize teams based on the number of teams specified
this.teams = Array.from({ length: options.numTeams }, () => []);
// Setting up message handlers
this.onMessage("join", (client: Client, message: { name: string }) => {
const teamIndex = this.assignTeam(); // Assign a team index
const player: Player = { id: client.sessionId, name: message.name, team: teamIndex };
this.players.push(player);
// Add player to the appropriate team
this.teams[teamIndex].push(player);
// Notify all clients about the new player
this.broadcast("player_joined", player);
this.broadcast("teams_update", this.getTeams());
});
this.onMessage("leave", (client: Client) => {
// Remove player from players list
this.players = this.players.filter(player => player.id !== client.sessionId);
this.updateTeams();
this.broadcast("player_left", { id: client.sessionId });
});
}
onJoin(client: Client) {
console.log(`Client ${client.sessionId} joined the lobby`);
}
onLeave(client: Client) {
console.log(`Client ${client.sessionId} left the lobby`);
this.players = this.players.filter(player => player.id !== client.sessionId);
this.updateTeams();
// Optionally, notify others
this.broadcast("player_left", { id: client.sessionId });
}
onDispose() {
console.log("Lobby Room disposed.");
}
private assignTeam(): number {
// Choose the team with the least number of players
const smallestTeamIndex = this.teams.reduce((smallestIndex, team, index) => {
return team.length < this.teams[smallestIndex].length ? index : smallestIndex;
}, 0);
return smallestTeamIndex;
}
private updateTeams() {
this.teams.forEach((team) => {
// Remove players from the team
team.filter(player => this.players.some(p => p.id === player.id));
});
this.broadcast("teams_update", this.getTeams());
}
private getTeams() {
return this.teams.map((team, index) => ({
teamIndex: index,
players: team,
}));
}
}
Updated index.ts
You will need to modify the room creation options in index.ts to pass the number of teams you want:
typescript
import { Server } from "colyseus";
import { createServer } from "http";
import express from "express";
import { LobbyRoom } from "./lobbyRoom";
const app = express();
const server = createServer(app);
const gameServer = new Server({ server });
// Allow setting the number of teams via room options
const numTeams = 3; // Change this to your desired number of teams
gameServer.define("lobby", LobbyRoom, { numTeams });
app.get("/", (req, res) => {
res.send("Welcome to Colyseus Lobby Server!");
});
const PORT = process.env.PORT || 2567;
gameServer.listen(PORT, () => {
console.log(`Listening on ws://localhost:${PORT}`);
});
Updated Client-side Code
The client-side code doesn't need to change much from the previous version; it can still listen for player join/leave and team updates. Here’s an example client code that utilizes the implementation:
Dynamic Team Creation: The number of teams is now passed from the index.ts file to the LobbyRoom based on the numTeams option. You can adjust this variable to create as many teams as you need.
Team Assignment Logic: Players are assigned to the team with the fewest members to achieve a balanced distribution.
Client Team Display: The client code has been updated to display the players under their respective teams dynamically.
Testing
Make sure to adjust the numTeams value in index.ts according to your requirements.
Start the server with npm start and open the provided HTML file in multiple tabs to see how players are dynamically assigned to teams.
This implementation allows you to specify the number of teams based on options and automatically distributes incoming players into those teams dynamically.