80 lines
No EOL
1.9 KiB
JavaScript
80 lines
No EOL
1.9 KiB
JavaScript
class Network{
|
|
constructor(adress){
|
|
this.adress = adress;
|
|
this.connected = false;
|
|
this.playerId = null;
|
|
}
|
|
|
|
message(data){
|
|
switch(data.type){
|
|
case 'connect':
|
|
this.playerId = data.data.playerId;
|
|
for (let i = 0; i<data.data.players.length; i++) {
|
|
let p = data.data.players[i];
|
|
if(p.id==this.playerId)
|
|
player=new Player(p.id,p.x,p.y,p.name,p.dir);
|
|
else
|
|
players.push(new Player(p.id,p.x,p.y,p.name,p.dir));
|
|
}
|
|
break;
|
|
|
|
case 'update':
|
|
updatePlayer(data.data);
|
|
break;
|
|
|
|
case "newplayer":
|
|
players.push(new Player(data.id, data.x, data.y, data.name, data.dir));
|
|
break;
|
|
|
|
case "removePlayer":
|
|
removePlayer(data.data.id);
|
|
break;
|
|
|
|
case "newBullet":
|
|
bullets.push(new Bullet(data.data.x,data.data.y,data.data.dx,data.data.dy,data.data.id, this.sound));
|
|
break;
|
|
|
|
case "died":
|
|
console.log("player",data.data.id,"was killed by",data.data.killerId);
|
|
addKill(data.data.id,data.data.killerId);
|
|
break;
|
|
|
|
case "message":
|
|
phone.addMessage(data.data);
|
|
|
|
default:
|
|
console.log("received unknown data:",data);
|
|
break;
|
|
}
|
|
}
|
|
|
|
connect(){ //create the WebSocket, initialize it and connect to the server
|
|
this.socket = new WebSocket(this.adress);
|
|
this.socket.addEventListener('open', (e)=>{
|
|
this.connected = true; //connected to server
|
|
});
|
|
this.socket.addEventListener('message', (e)=>{
|
|
this.message(JSON.parse(e.data));
|
|
})
|
|
}
|
|
|
|
died(id, killerId){
|
|
this.socket.send(JSON.stringify({type:"died",data:{id: id, killerId: killerId}}));
|
|
}
|
|
|
|
update(obj){ //send data to server in order to broadcast
|
|
this.socket.send(JSON.stringify({
|
|
type: "update",
|
|
data: obj
|
|
}));
|
|
}
|
|
|
|
newBullet(x,y,dx,dy,parentId)
|
|
{
|
|
this.socket.send(JSON.stringify({type:"newBullet",data:{x: x,y: y,dx: dx,dy: dy,id:parentId}}));
|
|
}
|
|
|
|
sendMessage(title, content){
|
|
this.socket.send(JSON.stringify({type: "message", data: {title: title, content: content}}));
|
|
}
|
|
} |