const Item = require("./item"); var nextId = 0; class Room { constructor(map) { this.id = nextId++; this.players = {}; // id => Player this.items = {}; // key => Item this.map = map; } addPlayer(p) { if (this.players[p] !== undefined) return false; this.players[p.id] = p; p.room = this; p.sendMessage("enter_room", {room_id:this.id, map:this.map, items:Object.values(this.items).map(i => i.getJSON())}); this.broadcastMessage("new_player", {player_id:p.id}); return true; } removePlayer(p) { if (this.players[p] === undefined) return false; delete this.players[p]; this.broadcastMessage("remove_player", {player_id:p.id}); return true; } getItem(playerId, itemId) { const key = playerId + "_" + itemId; if (this.items[key] === undefined) return null; return items[key]; } playerMessage(player, messageStr) { const message = JSON.parse(messageStr); switch (message.type) { case 'update_items': if (message.items !== undefined) { let toSend = []; for (var itemData of message.items) { if (itemData.item_id !== undefined) { const itemId = parseInt(itemData.item_id); let item = this.getItem(player.ID, itemId); if (item == null) { item = new Item(player.id, itemId); this.items[item.key] = item; } const { item_id, player_id, key, ...cleanDetails } = itemData; item.details = cleanDetails; toSend.push(item.getJSON()); } } console.log("ITEMS: "); console.log(this.items); console.log("TOSEND: "); console.log(toSend); this.broadcastMessage('update_items', {items:toSend}, player); } break; } } broadcastString(msg, skipPlayer = null) { for (var p of Object.values(this.playeres)) { if (p == skipPlayer) continue; p.socket.send(msg); } } broadcastMessage(type, details, skipPlayer = null) { const msg = JSON.stringify({...details, type:type}); for (var p of Object.values(this.players)) { if (p == skipPlayer) continue; p.socket.send(msg); } } } module.exports = Room;