Last active
October 23, 2021 22:44
-
-
Save mobyjames/cfd2e9584e8681822fa231a40bb2f2cd to your computer and use it in GitHub Desktop.
Colyseus Bot Template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class BotClient { | |
client: Client; | |
room: Room<GameState>; | |
player: Player; | |
sessionId: string; | |
constructor(server: string | Client) { | |
this.client = server instanceof Client ? server : new Client(server); | |
} | |
dispose() { | |
// clean up here | |
} | |
async joinRoom(roodId: string) { | |
this.room = await this.client.joinById<GameState>( | |
roomId, | |
{ | |
bot: true, | |
}, | |
GameState | |
); | |
this.begin(); | |
} | |
// useful if you want to integrate with loadtest | |
attachToRoom(room: Room) { | |
this.room = room; | |
this.begin(); | |
} | |
leave() { | |
this.room?.leave(true); | |
} | |
private begin() { | |
this.sessionId = this.room.sessionId; | |
// attach message handlers, e.g... | |
this.room.onMessage<string>('ping', (message) => { | |
this.room.send('pong', { message }); | |
}); | |
// listen for state changes | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class GameRoom extends Room<GameState> { | |
bots: Map<string, BotClient> | null = new Map<string, BotClient>(); | |
async addBot() { | |
const bot = new BotClient(SERVER_URL); | |
await bot.joinRoom(this.roomId); | |
this.bots.set(bot.sessionId, bot); | |
} | |
onLeave(client: Client, consented: boolean) { | |
const player = this.state.playerWithClient(client); | |
if (player.bot) { | |
const bot: BotClient = this.bots[client.sessionId]; | |
if (bot) { | |
this.bots.delete(client.sessionId); | |
bot.dispose(); | |
} | |
} | |
// remaining leave actions... | |
} | |
onDispose() { | |
this.bots.forEach((bot) => { | |
bot.dispose(); | |
}); | |
this.bots = null; | |
// remaining dispose actions... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment