65 lines
No EOL
1.4 KiB
JavaScript
65 lines
No EOL
1.4 KiB
JavaScript
class Network{
|
|
constructor(adress){
|
|
this.adress = adress;
|
|
this.connected = false;
|
|
|
|
this.playerId;
|
|
this.playersToAdd = [];
|
|
this.playersToRemove = [];
|
|
this.playersToUpdate = [];
|
|
}
|
|
|
|
message(data){
|
|
switch(data.type){
|
|
case 'connect':
|
|
this.playerId = data.data.playerId;
|
|
for (var i = data.data.players.length - 1; i >= 0; i--) {
|
|
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;
|
|
}
|
|
|
|
}
|
|
|
|
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
|
|
}))
|
|
}
|
|
|
|
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;
|
|
}
|
|
} |