Add Lobby #43
1 changed files with 26 additions and 3 deletions
|
@ -34,6 +34,12 @@ function nextName(name: string): string {
|
|||
return name.substr(0, i) + (Number(name.slice(i)) + 1);
|
||||
}
|
||||
|
||||
function connectionOpen(conn: DataConnection): Promise<void> {
|
||||
return new Promise(resolve => {
|
||||
conn.on("open", () => resolve());
|
||||
});
|
||||
}
|
||||
|
||||
export class PeerServer extends EventEmitter {
|
||||
protected peer: Peer;
|
||||
private room: Room;
|
||||
|
@ -64,17 +70,21 @@ export class PeerServer extends EventEmitter {
|
|||
|
||||
// Setup peer
|
||||
this.peer = customPeer ? customPeer : new Peer();
|
||||
this.peer.on("open", function(id) {
|
||||
this.peer.on("open", id => {
|
||||
console.info("Peer ID assigned: %s", id);
|
||||
this.emit("open", id);
|
||||
});
|
||||
this.peer.on("connection", conn => {
|
||||
this._connection(conn);
|
||||
});
|
||||
}
|
||||
|
||||
private _connection(conn: DataConnection) {
|
||||
private async _connection(conn: DataConnection) {
|
||||
const metadata = conn.metadata as PeerMetadata;
|
||||
|
||||
// Wait for connection to be open
|
||||
await connectionOpen(conn);
|
||||
|
||||
let player: NetworkPlayer = {
|
||||
kind: "remote",
|
||||
name: metadata.name,
|
||||
|
@ -140,6 +150,12 @@ export class PeerServer extends EventEmitter {
|
|||
|
||||
private addPlayer(player: NetworkPlayer) {
|
||||
const playerName = player.name;
|
||||
|
||||
// Hacky: Give player list before this player was added, so join
|
||||
// message doesn't mess things up later
|
||||
const players = Object.keys(this.room.players);
|
||||
|
||||
// Add player to room
|
||||
this.room.players[playerName] = player;
|
||||
|
||||
// Start listening for new messages
|
||||
|
@ -148,6 +164,10 @@ export class PeerServer extends EventEmitter {
|
|||
this._received.bind(this, this.room.players[playerName])
|
||||
);
|
||||
|
||||
player.conn.on("error", err => {
|
||||
throw err;
|
||||
});
|
||||
|
||||
// Send the player info about the room
|
||||
this.send<RoomInfoMessage>(player, {
|
||||
kind: "room-info",
|
||||
|
@ -155,7 +175,7 @@ export class PeerServer extends EventEmitter {
|
|||
...this.room.info,
|
||||
password: ""
|
||||
},
|
||||
players: Object.keys(this.room.players)
|
||||
players
|
||||
});
|
||||
|
||||
// Notify other players
|
||||
|
@ -172,6 +192,9 @@ export class PeerServer extends EventEmitter {
|
|||
// Close connection with player
|
||||
player.conn.close();
|
||||
|
||||
// Remove player from player list
|
||||
delete this.room.players[player.name];
|
||||
|
||||
// Notify other players
|
||||
this.broadcast<LeaveMessage>({
|
||||
kind: "player-left",
|
||||
|
|
Loading…
Reference in a new issue