You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
88 lines
2.7 KiB
88 lines
2.7 KiB
//===== Constructor
|
|
|
|
const Connection = function() {
|
|
// Local event listeners
|
|
document.addEventListener('L-guess', (evt) => {
|
|
this.ws.send(JSON.stringify({ type: 'guess', rawBody: evt.detail }));
|
|
});
|
|
|
|
document.addEventListener('L-join', (evt) => {
|
|
this.connect();
|
|
});
|
|
|
|
document.addEventListener('L-robots', () => {
|
|
this.ws.send(JSON.stringify({ type: 'robots' }));
|
|
});
|
|
|
|
document.addEventListener('L-skip', () => {
|
|
this.ws.send(JSON.stringify({ type: 'skip' }));
|
|
});
|
|
|
|
document.addEventListener('L-start', () => {
|
|
this.ws.send(JSON.stringify({ type: 'start' }));
|
|
});
|
|
|
|
document.addEventListener('L-stop', () => {
|
|
this.ws.send(JSON.stringify({ type: 'stop' }));
|
|
});
|
|
|
|
document.addEventListener('L-walls', () => {
|
|
this.ws.send(JSON.stringify({ type: 'walls' }));
|
|
});
|
|
};
|
|
|
|
Connection.prototype.connect = function(){
|
|
const names = ["Biff", "Morty", "Herb", "Chester", "Lyle", "Cap", "Dale", "Ned", "Mindy", "Frankie", "Gabriel", "Mona", "Dolores",
|
|
"Sepulveda", "Venus", "Blingbing", "Cyrpt"]
|
|
const r = Math.floor(Math.random() * names.length);
|
|
const rawInput = names[r] //prompt("What is your name?");
|
|
|
|
this.ws = new WebSocket('ws://localhost:8080/ricochet?name=' + rawInput);
|
|
|
|
this.ws.addEventListener('open', this.onOpen.bind(this));
|
|
this.ws.addEventListener('error', this.onError.bind(this));
|
|
this.ws.addEventListener('message', this.onReceiveMessage.bind(this));
|
|
};
|
|
|
|
//===== Connection event handlers
|
|
|
|
Connection.prototype.onOpen = function(aaa) {
|
|
const evt = new Event('L-conn-open');
|
|
document.dispatchEvent(evt);
|
|
};
|
|
|
|
Connection.prototype.onError = function(err) {
|
|
console.error(err);
|
|
|
|
const evt = new CustomEvent('L-conn-error', { detail: err });
|
|
document.dispatchEvent(evt);
|
|
};
|
|
|
|
Connection.prototype.onReceiveMessage = function({ data }) {
|
|
const msg = JSON.parse(data);
|
|
console.warn(JSON.stringify(msg));
|
|
|
|
if (!msg.type) {
|
|
console.warn("Unprocessable message: ", msg)
|
|
return;
|
|
}
|
|
|
|
let eventName;
|
|
|
|
switch (msg.type) {
|
|
case 'connected': eventName = 'G-connected'; break;
|
|
case 'guess': eventName = 'G-guess'; break;
|
|
case 'players': eventName = 'G-players'; break;
|
|
case 'robots': eventName = 'G-robots'; break;
|
|
case 'skip': eventName = 'G-skip'; break;
|
|
case 'solve': eventName = 'G-solve'; break;
|
|
case 'start': eventName = 'G-start'; break;
|
|
case 'stop': eventName = 'G-stop'; break;
|
|
case 'walls': eventName = 'G-walls'; break;
|
|
}
|
|
|
|
if (eventName) {
|
|
const evt = new CustomEvent(eventName, { detail: msg });
|
|
document.dispatchEvent(evt);
|
|
}
|
|
};
|