GrandTabernacleAutoVI/js/network.js
2023-11-29 15:54:09 +01:00

51 lines
No EOL
1.3 KiB
JavaScript

class Network{
constructor(adress, Renderer){
this.adress = adress;
this.connected = false;
this.Renderer = Renderer
}
message(data){
switch(data.type){
case 'connect':
playerId = data.data.playerId;
for (var i = data.data.players.length - 1; i >= 0; i--) {
players.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))
this.Renderer.AddPlayer(players[players.length - 1])
}
break;
case 'update':
for (var i = players.length - 1; i >= 0; i--) {
if(players[i].id==data.data.id){
players[i].retrieveServerInfo(data.data.id, data.data.x, data.data.y, data.data.dir);
break;
}
}
break;
case "newplayer":
players.push(new Player(data.data.id, data.data.x, data.data.y, data.data.name, data.data.dir));
this.Renderer.AddPlayer(players[players.length - 1])
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));
})
}
update(obj){
this.socket.send(JSON.stringify({
type: "update",
data: obj
}))
}
}