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.
81 lines
2.1 KiB
81 lines
2.1 KiB
//===== Constructor
|
|
|
|
const Connection = function() {
|
|
// Local event listeners
|
|
document.addEventListener('L-robots', () => {
|
|
this.ws.send(JSON.stringify({ head: { type: 'reposition-robots' }}));
|
|
});
|
|
|
|
document.addEventListener('L-walls', () => {
|
|
this.ws.send(JSON.stringify({ head: { type: 'regenerate-walls' }}));
|
|
});
|
|
|
|
document.addEventListener('L-guess', (evt) => {
|
|
this.ws.send(JSON.stringify({ head: { type: 'guess' }, rawBody: evt.detail }));
|
|
});
|
|
|
|
document.addEventListener('L-join', (evt) => {
|
|
this.connect();
|
|
});
|
|
};
|
|
|
|
Connection.prototype.connect = function(){
|
|
const names = ["Biff", "Morty", "Herb", "Chester", "Lyle", "Cap", "Dale", "Ned", "Mindy"]
|
|
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() {
|
|
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(msg);
|
|
|
|
if (!msg.type) {
|
|
console.warn("Unprocessable message: ", msg)
|
|
return;
|
|
}
|
|
|
|
let eventName;
|
|
|
|
switch (msg.type) {
|
|
case 'players':
|
|
eventName = 'G-players';
|
|
break;
|
|
|
|
case 'robots':
|
|
eventName = 'G-robots';
|
|
break;
|
|
|
|
case 'walls':
|
|
eventName = 'G-walls';
|
|
break;
|
|
|
|
case 'guess':
|
|
eventName = 'G-guess';
|
|
break;
|
|
}
|
|
|
|
if (eventName) {
|
|
const evt = new CustomEvent(eventName, { detail: msg });
|
|
document.dispatchEvent(evt);
|
|
}
|
|
};
|