GrandTabernacleAutoVI/js/network.js

75 lines
1.6 KiB
JavaScript
Raw Normal View History

2023-11-17 19:25:26 +01:00
class Network{
2023-11-29 16:12:00 +01:00
constructor(adress){
2023-11-17 19:25:26 +01:00
this.adress = adress;
this.connected = false;
2023-11-29 16:12:00 +01:00
2023-11-29 16:20:47 +01:00
this.playerId = null;
2023-11-29 17:25:40 +01:00
this.clientPlayer=null;
2023-11-29 16:12:00 +01:00
this.playersToAdd = [];
this.playersToRemove = [];
this.playersToUpdate = [];
2023-11-17 19:25:26 +01:00
}
message(data){
switch(data.type){
case 'connect':
2023-11-29 16:12:00 +01:00
this.playerId = data.data.playerId;
2023-11-19 18:38:27 +01:00
for (var i = data.data.players.length - 1; i >= 0; i--) {
2023-11-29 17:25:40 +01:00
if(data.data.players[i].id==this.playerId)
this.clientPlayer=data.data.players[i];
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))
2023-11-18 13:38:29 +01:00
}
2023-11-17 19:25:26 +01:00
break;
case 'update':
2023-11-29 16:12:00 +01:00
this.playersToUpdate.push(data.data);
2023-11-18 13:38:29 +01:00
break;
case "newplayer":
2023-11-29 16:12:00 +01:00
this.playersToAdd.push(new Player(data.data.id, data.data.x, data.data.y, data.data.name, data.data.dir));
2023-11-17 19:25:26 +01:00
break;
}
}
connect(){
this.socket = new WebSocket(this.adress);
this.socket.addEventListener('open', (e)=>{
//connected to server
this.connected = true;
});
this.socket.addEventListener('message', (e)=>{
this.message(JSON.parse(e.data));
})
}
2023-11-19 19:56:29 +01:00
2023-11-29 16:20:47 +01:00
getPlayerId(){
while(this.playerId==null){
//waiting for connection
};
return this.playerId;
}
2023-11-19 19:56:29 +01:00
update(obj){
this.socket.send(JSON.stringify({
type: "update",
data: obj
}))
}
2023-11-29 16:12:00 +01:00
getPlayersToAdd(){
let tmp = this.playersToAdd;
this.playersToAdd = [];
return tmp;
}
getPlayersToRemove(){
let tmp = this.playersToRemove;
this.playersToRemove = [];
return tmp;
}
getPlayersToUpdate(){
let tmp = this.playersToUpdate;
this.playersToUpdate = [];
return tmp;
}
2023-11-17 19:25:26 +01:00
}