server/www/connect.js

57 lines
1.5 KiB
JavaScript
Raw Normal View History

2018-04-11 13:25:24 +02:00
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);
2018-04-11 13:25:24 +02:00
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);
2018-04-11 13:25:24 +02:00
switch(o.tag) {
case "Welcome":
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:
debug.textContent = event.data;
2018-04-11 13:25:24 +02:00
}
});
2018-04-11 13:25:24 +02:00
function relayedMessage(o) {
switch(o.message.tag) {
case "LogIn":
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);
if(o.from == sessionKey) {
login.off(o.from);
}
2018-04-11 13:25:24 +02:00
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});
2018-04-11 13:25:24 +02:00
}
}
function ping() {
lib.send({tag: "Ping"});
}
});