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.id] === undefined) return false; delete this.players[p.id]; this.broadcastMessage("remove_player", {player_id:p.id}); var toDelete = []; for (var item of Object.values(this.items)) { if (item.playerId == p.id && item.details.dod) //deleteOnDisconnect { item.details.__delete__ = true; toDelete.push(item); console.log("Deleting:"); console.log(item); delete this.items[item.key]; } } this.updateItems(toDelete); //console.log(this.items); return true; } getItem(playerId, itemId) { const key = playerId + "_" + itemId; if (this.items[key] === undefined) return null; return this.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; console.log("Inserting: (" + Object.values(this.items).length + ")"); console.log(item); } const { item_id, player_id, key, ...cleanDetails } = itemData; item.details = cleanDetails; toSend.push(item); } } //console.log("ITEMS: "); //console.log(this.items); this.updateItems(toSend, player); } break; } } updateItems(items, skipPlayer = null) { if (items.length > 0) { var toSend = items.map(i => i.getJSON()); //console.log("TOSEND: "); //console.log(toSend); this.broadcastMessage('update_items', {items:toSend}, skipPlayer); } } 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;