2018-04-11 13:25:24 +02:00
|
|
|
window.addEventListener('load', function() {
|
2018-04-12 23:01:40 +02:00
|
|
|
var ws = new WebSocket('ws://' + window.location.hostname + '/play/');
|
|
|
|
var sessionKey = null;
|
|
|
|
var lib = Lib(ws);
|
|
|
|
var room = Room(document.getElementById('room'), lib);
|
2018-04-11 13:25:24 +02:00
|
|
|
var login = Login(document.getElementById('login'), lib);
|
|
|
|
var debug = document.getElementById('debug');
|
|
|
|
setTimeout(ping, 20000);
|
|
|
|
|
2018-04-12 23:01:40 +02:00
|
|
|
ws.addEventListener('message', function(event) {
|
|
|
|
var o = JSON.parse(event.data);
|
2018-04-11 13:25:24 +02:00
|
|
|
switch(o.tag) {
|
|
|
|
case "Welcome":
|
2018-04-12 23:01:40 +02:00
|
|
|
sessionKey = o.key;
|
|
|
|
room.populate(o.room, sessionKey);
|
2018-04-11 13:25:24 +02:00
|
|
|
break;
|
|
|
|
case "Pong":
|
|
|
|
setTimeout(ping, 10000);
|
|
|
|
break;
|
|
|
|
case "Relay":
|
|
|
|
relayedMessage(o)
|
|
|
|
break;
|
|
|
|
default:
|
2018-04-12 23:01:40 +02:00
|
|
|
debug.textContent = event.data;
|
2018-04-11 13:25:24 +02:00
|
|
|
}
|
2018-04-12 23:01:40 +02:00
|
|
|
});
|
2018-04-11 13:25:24 +02:00
|
|
|
|
|
|
|
function relayedMessage(o) {
|
|
|
|
switch(o.message.tag) {
|
|
|
|
case "LogIn":
|
2018-04-12 23:01:40 +02:00
|
|
|
room.enter(o.from, o.message.name);
|
|
|
|
if(o.from == sessionKey) {
|
|
|
|
login.on(o.from);
|
|
|
|
}
|
2018-04-11 13:25:24 +02:00
|
|
|
break;
|
|
|
|
case "LogOut":
|
|
|
|
room.leave(o.from);
|
2018-04-12 23:01:40 +02:00
|
|
|
if(o.from == sessionKey) {
|
|
|
|
login.off(o.from);
|
|
|
|
}
|
2018-04-11 13:25:24 +02:00
|
|
|
break;
|
2018-04-12 23:01:40 +02:00
|
|
|
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});
|
2018-04-11 13:25:24 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function ping() {
|
|
|
|
lib.send({tag: "Ping"});
|
|
|
|
}
|
|
|
|
});
|