gamelobby
ES6 JS classes for Game Lobbies with friend lobbies, heartbeats and disconnect handlers
Installation
npm install gamelobby --save
Usage
This is a Game Lobby implementation I made for http://x64projects.tk/WikiRace
Main features:
- Friend lobbies by generating uuidv4 hashes for lobby names.
- Disconnect handlers for BOTH timeouts and players closing the page due to the heartbeats.
- Object-oriented design for overriding methods.
- Event-based callbacks for game lobbies
- Websocket based (using SailsJS, but can be overridden) for maximum speed.
LobbyManager inherits from node's EventEmitter, and thus allows you to subscribe/publish events
of your own choosing as well as add hooks to the existing ones.
class LobbyManager extends EventEmitter {
constructor (LobbyClass=Lobby) {
...
this.EVENTS = {
LOBBY_DESTROYED: this._onLobbyDestroy,
GAME_START: this._onLobbyGameStart,
};
...
};
Incorporate gamelobby into a web app or networked application by creating lobbies and adding players.
const gamelobby = require('gamelobby');
const lobbyManager = new gamelobby.LobbyManager();
let lobbyConfig = { mode: "BATTLE" };
let lobby = lobbyManager.getFirstOpenLobbyWithCriteria(lobbyConfig);
if (!lobby) {
lobby = lobbyManager.createOpenLobby(lobbyConfig);
}
let playerConfig = { username: "billy", userId: 4, character: "turtle" };
lobby.addPlayer(req.socket, playerConfig);
lobbyManager.on("GAME_START", (lobby) => {
lobby.lobbyConfig['levelStage'] = "opening_level";
lobby.playerList.forEach(p => p.playerConfig.team = "BLUE");
});
lobbyManager.on("GAME_OVER", (lobby) => {
lobby.playerList.forEach((player, index) => {
let didWin = player.getWinStatus() == gamelobby.Player.WIN;
let didLose = player.getWinStatus() == gamelobby.Player.LOST ? 1 : 0),
let didDisconnect = player.getConnectionStatus() == gamelobby.Player.DISCONNECTED;
await SomeDatabase.update(player.playerConfig.username, { win: didWin, loss: didLose, disconnects: didDisconnect });
});
lobby.destroyLobby();
});
Lobbies automatically check for disconnections by receiving heartbeats every few seconds.
Have your web app send heartbeats to another endpoint and update the lobby.
Timeouts result in USER_DISCONNECT being emitted.
let lobby = lobbyManager.getLobbyBySocket(req.socket);
if (!lobby) {
return res.json({error: "NO_LOBBY_FOUND_FOR_HEARTBEAT"});
}
lobby.updateClientHeartbeat(req.socket, new Date().getTime());
Used in tandem with my LobbyClient.js on the front end (to be released in future) helps a lot.
More features available, read the code to suit your needs.
TODO:
Add easier Redis support, maybe as a subclass.
Credits
http://x64projects.tk/