Get Programming with JavaScript - Listing 10.11

Listing 10.11 - A map with four locations

var Place = function (title, description) { this.title = title; this.exits = {}; this.addExit = function (direction, exit) { this.exits[direction] = exit; }; this.showExits = function () { console.log("Exits from " + this.title + ":"); Object.keys(this.exits).forEach(function (key) { console.log(key); }); }; }; var library = new Place("The Old Library"); var kitchen = new Place("The Kitchen"); var garden = new Place("The Kitchen Garden"); var cupboard = new Place("The Kitchen Cupboard"); library.addExit("north", kitchen); garden.addExit("east", kitchen); cupboard.addExit("west", kitchen); kitchen.addExit("south", library); kitchen.addExit("west", garden); kitchen.addExit("east", cupboard); library.showExits(); kitchen.showExits();

Further Adventures

Listing 10.11 - A map with four locations - Tasks 1 to 4

var Place = function (title, description) { this.title = title; this.exits = {}; this.items = []; this.addExit = function (direction, exit) { this.exits[direction] = exit; }; this.showExits = function () { console.log("Exits from " + this.title + ":"); Object.keys(this.exits).forEach(function (key) { console.log(key); }); }; this.addItem = function (item) { this.items.push(item); }; this.showItems = function () { console.log("Items in " + this.title + ":"); this.items.forEach(function (item) { console.log(" - " + item); }); }; }; var library = new Place("The Old Library"); var kitchen = new Place("The Kitchen"); var garden = new Place("The Kitchen Garden"); var cupboard = new Place("The Kitchen Cupboard"); library.addExit("north", kitchen); garden.addExit("east", kitchen); cupboard.addExit("west", kitchen); kitchen.addExit("south", library); kitchen.addExit("west", garden); kitchen.addExit("east", cupboard); library.showExits(); kitchen.showExits(); library.addItem("a rusty key"); kitchen.addItem("a smelly cheese"); kitchen.addItem("holy water"); library.showItems(); kitchen.showItems();