GrandTabernacleAutoVI/public_html/js/network.js
2023-12-12 13:53:55 +01:00

73 lines
No EOL
1.8 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,0,p.name,p.dir);
else
players.push(new Player(p.id,p.x,p.y,0,p.name,p.dir));
}
break;
case 'update':
updatePlayer(data.data);
break;
case "newplayer":
players.push(new Player(data.data.id, data.data.x, data.data.y, 0, data.data.name, data.data.dir));
break;
case "removePlayer":
removePlayer(data.data.id);
break;
case "newBullet":
bullets.push(new Bullet(data.data.x,data.data.y,data.z,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;
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,z,dx,dy,parentId)
{
this.socket.send(JSON.stringify({type:"newBullet",data:{x: x,y: y,z: z,dx: dx,dy: dy,id:parentId}}));
}
}