GrandTabernacleAutoVI/js/network.js
Killian Marty 0e6a41a259 dying
2023-12-07 09:07:06 +01:00

97 lines
No EOL
2.5 KiB
JavaScript

class Network{
constructor(adress){
this.adress = adress;
this.connected = false;
this.playerId = null;
this.clientPlayer=null;
this.playersToAdd = [];
this.playersToRemove = [];
this.playersToUpdate = [];
this.bulletsToAdd = [];
}
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));
break;
case "died":
console.log(data.data);
console.log("someone died");
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){
this.socket.send(JSON.stringify({type:"died",data:{id: id}}));
}
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;
}
}