GrandTabernacleAutoVI/public_html/js/network.js
2023-12-07 22:47:12 +01:00

108 lines
No EOL
2.8 KiB
JavaScript

class Network{
constructor(adress, bulletsound){
this.adress = adress;
this.connected = false;
this.playerId = null;
this.clientPlayer=null;
this.playersToAdd = [];
this.playersToRemove = [];
this.playersToUpdate = [];
this.bulletsToAdd = [];
this.deathToAdd = [];
this.sound=bulletsound;
}
message(data){
switch(data.type){
case 'connect':
this.playerId = data.data.playerId;
for (var i = data.data.players.length - 1; i >= 0; i--) {
if(data.data.players[i].id==this.playerId)
this.clientPlayer=new Player(data.data.players[i].id, data.data.players[i].x, data.data.players[i].y, data.data.players[i].name, data.data.players[i].dir);
else
this.playersToAdd.push(new Player(data.data.players[i].id, data.data.players[i].x, data.data.players[i].y, data.data.players[i].name, data.data.players[i].dir))
}
break;
case 'update':
this.playersToUpdate.push(data.data);
break;
case "newplayer":
this.playersToAdd.push(new Player(data.data.id, data.data.x, data.data.y, data.data.name, data.data.dir));
break;
case "removePlayer":
this.playersToRemove.push(data.data.id);
break;
case "newBullet":
this.bulletsToAdd.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);
this.deathToAdd.push(data.data);
break;
default:
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.deathToAdd.push({id:id,killerId: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}}));
}
getPlayersToAdd(){ //returns the list of new players
let tmp = this.playersToAdd;
this.playersToAdd = [];
return tmp;
}
getBulletsToAdd(){ //returns the list of new players
let tmp = this.bulletsToAdd;
this.bulletsToAdd = [];
return tmp;
}
getPlayersToRemove(){ //returns the list of player who have left the game
let tmp = this.playersToRemove;
this.playersToRemove = [];
return tmp;
}
getPlayersToUpdate(){ //return a list of all updates recieved from the server
let tmp = this.playersToUpdate;
this.playersToUpdate = [];
return tmp;
}
getDeathToAdd()
{
let tmp = this.deathToAdd;
this.deathToAdd=[];
return tmp;
}
}