GrandTabernacleAutoVI/js/network.js

51 lines
1.3 KiB
JavaScript
Raw Normal View History

2023-11-17 19:25:26 +01:00
class Network{
2023-11-29 15:53:35 +01:00
constructor(adress, Renderer){
2023-11-17 19:25:26 +01:00
this.adress = adress;
this.connected = false;
2023-11-29 15:53:35 +01:00
this.Renderer = Renderer
2023-11-17 19:25:26 +01:00
}
message(data){
switch(data.type){
case 'connect':
2023-11-18 13:38:29 +01:00
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-19 18:55:21 +01:00
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))
2023-11-19 18:38:27 +01:00
2023-11-29 15:53:35 +01:00
this.Renderer.AddPlayer(players[players.length - 1])
2023-11-18 13:38:29 +01:00
}
2023-11-17 19:25:26 +01:00
break;
case 'update':
2023-11-18 13:38:29 +01:00
for (var i = players.length - 1; i >= 0; i--) {
if(players[i].id==data.data.id){
2023-11-19 19:56:29 +01:00
players[i].retrieveServerInfo(data.data.id, data.data.x, data.data.y, data.data.dir);
2023-11-18 13:38:29 +01:00
break;
}
}
break;
case "newplayer":
2023-11-19 18:55:21 +01:00
players.push(new Player(data.data.id, data.data.x, data.data.y, data.data.name, data.data.dir));
2023-11-29 15:53:35 +01:00
this.Renderer.AddPlayer(players[players.length - 1])
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
update(obj){
this.socket.send(JSON.stringify({
type: "update",
data: obj
}))
}
2023-11-17 19:25:26 +01:00
}