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