75 lines
No EOL
2 KiB
JavaScript
75 lines
No EOL
2 KiB
JavaScript
class Network{
|
|
constructor(adress){
|
|
this.adress = adress;
|
|
this.connected = false;
|
|
|
|
this.playerId = null;
|
|
this.clientPlayer=null;
|
|
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--) {
|
|
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;
|
|
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));
|
|
})
|
|
}
|
|
|
|
update(obj){ //send data to server in order to broadcast
|
|
this.socket.send(JSON.stringify({
|
|
type: "update",
|
|
data: obj
|
|
}))
|
|
}
|
|
|
|
getPlayersToAdd(){ //returns the list of new players
|
|
let tmp = this.playersToAdd;
|
|
this.playersToAdd = [];
|
|
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;
|
|
}
|
|
} |