// Define the game object
const game = {
currentRoom: null,
rooms: {},
createRoom: function (name, description) {
this.rooms[name] = {
name: name,
description: description,
exits: {},
items: [],
};
},
createExit: function (sourceRoom, direction, destinationRoom) {
this.rooms[sourceRoom].exits[direction] = destinationRoom;
},
createItem: function (room, item) {
this.rooms[room].items.push(item);
},
init: function (startRoom) {
this.currentRoom = startRoom;
},
look: function () {
return this.rooms[this.currentRoom].description;
},
go: function (direction) {
const nextRoom = this.rooms[this.currentRoom].exits[direction];
if (nextRoom) {
this.currentRoom = nextRoom;
return "You are now in " + this.currentRoom + ".";
} else {
return "You can't go that way!";
}
},
take: function (item) {
const roomItems = this.rooms[this.currentRoom].items;
const index = roomItems.indexOf(item);
if (index !== -1) {
roomItems.splice(index, 1);
return "You take the " + item + ".";
} else {
return "There is no " + item + " here.";
}
},
};
// Create rooms
game.createRoom("start", "You are in a dark room. There is a door to the north.");
game.createRoom("hall", "You are in a long hallway. There are doors to the north and south.");
game.createRoom("end", "You are in a brightly lit room. There is a door to the south.");
// Create exits
game.createExit("start", "north", "hall");
game.createExit("hall", "north", "end");
game.createExit("hall", "south", "start");
// Create items
game.createItem("start", "key");
// Initialize the game
game.init("start");
// Example gameplay
console.log(game.look()); // You are in a dark room. There is a door to the north.
console.log(game.go("north")); // You are now in hall.
console.log(game.look()); // You are in a long hallway. There are doors to the north and south.
console.log(game.take("key")); // You take the key.
console.log(game.go("north")); // You are now in end.
console.log(game.look()); // You are in a brightly lit room. There is a door to the south.
console.log(game.go("south")); // You are now in hall.