server/www/room.js

80 lines
2 KiB
JavaScript
Raw Permalink Normal View History

function Room(modules) {
function Player(key, name, alone) {
this.key = key;
this.name = name;
this.alone = alone;
this.dom = modules.dom.make('li', {textContent: name});
this.position = null;
}
var players = {};
var sortedKeys = [];
var session = {
key: null,
loggedIn: false,
selected: null
};
modules.messaging.addEventListener(["Welcome"], function(o) {
for(var key in o.room) {
enter(parseInt(key), o.room[key]);
}
});
modules.messaging.addEventListener(["Update"], function(o) {
o.alone.forEach(function(key) {players[key].alone = true;});
o.paired.forEach(function(key) {players[key].alone = false;});
});
modules.messaging.addEventListener(["Relay", "LogIn"], function(o) {
enter(o.from, o.message);
});
modules.messaging.addEventListener(["Relay", "LogOut"], function(o) {
leave(o.from);
});
var compareKeysByLogin = modules.fun.map(function(key) {return players[key].name;}, modules.fun.defaultCompare);
return {
filter: filter,
enter: enter,
leave: leave,
name: name
};
function filter(name) {
if(modules.session.loggedIn()) {
var keep = function(player) {
return player.name.match(name) && !modules.session.is(player.key) && player.alone;
};
} else {
var keep = function(player) {return player.name.match(name);};
}
return modules.fun.mapFilter(modules.fun.of(players), keep)(sortedKeys);
}
function enter(key, obj) {
var name = obj.name || "anon";
var alone = obj.alone != undefined ? obj.alone : true;
var player = new Player(key, name, alone);
players[key] = player;
player.position = modules.fun.insert(key, sortedKeys, compareKeysByLogin);
sortedKeys.splice(player.position, 0, key);
}
2018-04-11 13:25:24 +02:00
function leave(key) {
var player = players[key];
if(player != undefined) {
sortedKeys.splice(player.position, 1);
delete players[key];
}
}
function name(key) {
player = players[key];
return player && player.name;
}
2018-04-11 13:25:24 +02:00
}