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.
83 lines
2.5 KiB
83 lines
2.5 KiB
//===== Constructor
|
|
|
|
const Connection = function() {
|
|
// Local event listeners
|
|
document.addEventListener('L-join', (evt) => {
|
|
this.connect();
|
|
});
|
|
|
|
document.addEventListener('L-objective', () => {
|
|
this.ws.send(JSON.stringify({ type: 'objective' }));
|
|
});
|
|
|
|
document.addEventListener('L-robots', () => {
|
|
this.ws.send(JSON.stringify({ type: 'robots' }));
|
|
});
|
|
|
|
document.addEventListener('L-solve', (evt) => {
|
|
this.ws.send(JSON.stringify({ type: 'solve', rawBody: evt.detail }));
|
|
});
|
|
|
|
document.addEventListener('L-walls', () => {
|
|
this.ws.send(JSON.stringify({ type: 'walls' }));
|
|
});
|
|
|
|
document.addEventListener('L-skip', () => {
|
|
this.ws.send(JSON.stringify({ type: 'skip' }));
|
|
});
|
|
};
|
|
|
|
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]
|
|
// const rawInput = 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 'countdown': eventName = 'G-countdown'; break;
|
|
case 'objective': eventName = 'G-objective'; break;
|
|
case 'players': eventName = 'G-players'; break;
|
|
case 'robots': eventName = 'G-robots'; break;
|
|
case 'state': eventName = 'G-state'; break;
|
|
case 'walls': eventName = 'G-walls'; break;
|
|
}
|
|
|
|
if (eventName) {
|
|
const evt = new CustomEvent(eventName, { detail: msg });
|
|
document.dispatchEvent(evt);
|
|
}
|
|
};
|
|
|