56 lines
1.5 KiB
JavaScript
56 lines
1.5 KiB
JavaScript
window.addEventListener('load', function() {
|
|
var ws = new WebSocket('ws://' + window.location.hostname + '/play/');
|
|
var sessionKey = null;
|
|
var lib = Lib(ws);
|
|
var room = Room(document.getElementById('room'), lib);
|
|
var login = Login(document.getElementById('login'), lib);
|
|
var debug = document.getElementById('debug');
|
|
setTimeout(ping, 20000);
|
|
|
|
ws.addEventListener('message', function(event) {
|
|
var o = JSON.parse(event.data);
|
|
switch(o.tag) {
|
|
case "Welcome":
|
|
sessionKey = o.key;
|
|
room.populate(o.room, sessionKey);
|
|
break;
|
|
case "Pong":
|
|
setTimeout(ping, 10000);
|
|
break;
|
|
case "Relay":
|
|
relayedMessage(o)
|
|
break;
|
|
default:
|
|
debug.textContent = event.data;
|
|
}
|
|
});
|
|
|
|
function relayedMessage(o) {
|
|
switch(o.message.tag) {
|
|
case "LogIn":
|
|
room.enter(o.from, o.message.name);
|
|
if(o.from == sessionKey) {
|
|
login.on(o.from);
|
|
}
|
|
break;
|
|
case "LogOut":
|
|
room.leave(o.from);
|
|
if(o.from == sessionKey) {
|
|
login.off(o.from);
|
|
}
|
|
break;
|
|
case "Invitation":
|
|
var name = room.name(o.from);
|
|
var accept = false;
|
|
// invitations should come only from known players, in doubt say «no»
|
|
if(name) {
|
|
accept = confirm(name + " has invited you to a game");
|
|
}
|
|
lib.send({tag: "Answer", accept: accept});
|
|
}
|
|
}
|
|
|
|
function ping() {
|
|
lib.send({tag: "Ping"});
|
|
}
|
|
});
|