Write a C++ program for a text dungeon. The dungeon should include 30 rooms, each with a…
- User
Write a C++ program for a text dungeon. The dungeon should include 30 rooms, each with a novel, detailed description when the user uses the command look or inspect. Each room should contain a piece of information about general programming, either by being written on the walls, in a computer terminal, or maybe a detailed NPC in the room, and each piece of information will say what a loop is or what magic numbers are, etc. Be sure to put in an NPC that will travel randomly through the rooms that can interact with the player if the players says something to them, usually giving good coding advice from a list of say ten different responses. Install an exit somewhere in the dungeon, say an open doorway. NPCs should perform small details on a timed based, say coughing at random intervals no more than 40 seconds apart or looking around.
- Assistant
Below is a C++ program for a text-based dungeon game that meets your requirements. The program includes 30 rooms with detailed descriptions, programming-related information in each room, a wandering NPC with random interactions, and timed NPC actions. The game uses basic input parsing for commands like "look," "inspect," "talk," and "move," and includes an exit in one of the rooms.
To keep the code manageable and readable, I'll provide a structured implementation with comments. Note that this is a console-based program, and for timed NPC actions, we'll use simple threading (via
<thread>and<chrono>). If you're using an older compiler, you may need to enable C++11 or later (e.g., compile with-std=c++11).C++ Program: Text Dungeon
#include <iostream> #include <string> #include <vector> #include <map> #include <random> #include <thread> #include <chrono> #include <algorithm> #include <cctype> using namespace std; // Constants const int NUM_ROOMS = 30; const int EXIT_ROOM = 25; // Room 25 contains the exit const int NPC_COUGH_INTERVAL = 40; // Max seconds between NPC actions // Room structure to hold description and programming info struct Room { string description; string programmingInfo; vector<int> exits; // Connected rooms (indices) }; // NPC structure struct NPC { string name = "Wandering Coder"; int currentRoom = 0; // Start in room 0 vector<string> advice = { "Always comment your code to make it readable for others—and your future self!", "Avoid magic numbers; use named constants instead for clarity.", "When writing loops, ensure they have a clear exit condition to avoid infinite loops.", "Use version control systems like Git to track changes in your codebase.", "Refactor your code regularly to improve its structure and readability.", "Test your code with edge cases to ensure robustness.", "Prefer meaningful variable names over short, cryptic ones.", "Learn to use debugging tools to step through your code and find bugs.", "Keep functions small and focused on a single task.", "Remember that premature optimization can lead to complex, unmaintainable code." }; bool isActive = true; // For NPC thread }; // Game state struct GameState { int playerRoom = 0; // Start in room 0 bool gameRunning = true; NPC wanderingCoder; }; // Function to generate a random number int getRandom(int min, int max) { static random_device rd; static mt19937 gen(rd()); uniform_int_distribution<> dis(min, max); return dis(gen); } // Function to convert string to lowercase for case-insensitive input string toLower(string str) { transform(str.begin(), str.end(), str.begin(), ::tolower); return str; } // Function to initialize rooms with descriptions and programming info vector<Room> initializeRooms() { vector<Room> rooms(NUM_ROOMS); // Room 0 rooms[0].description = "You stand in a dimly lit chamber with moss-covered stone walls. A rusty sword lies in the corner, and a faint hum echoes from a dusty computer terminal."; rooms[0].programmingInfo = "A note on the terminal reads: 'A loop is a programming construct that repeats a block of code until a condition is met, such as a for or while loop.'"; rooms[0].exits = {1, 2}; // Room 1 rooms[1].description = "This room is filled with glowing crystals embedded in the walls, casting eerie blue light. A skeleton sits at a desk, clutching a book."; rooms[1].programmingInfo = "The book is open to a page that says: 'Magic numbers are hard-coded values in your code; replace them with named constants for better readability.'"; rooms[1].exits = {0, 3}; // Room 2 rooms[2].description = "A cavernous room with stalactites hanging from the ceiling. A small stream runs through, and a glowing tablet lies on a pedestal."; rooms[2].programmingInfo = "The tablet displays: 'An array is a data structure that holds a fixed-size sequence of elements of the same type.'"; rooms[2].exits = {0, 4}; // Room 3 rooms[3].description = "This room smells of burnt metal. A charred workbench holds remnants of a failed experiment, and a screen flickers with static."; rooms[3].programmingInfo = "The screen flashes: 'A function is a reusable block of code that performs a specific task, often taking parameters and returning a value.'"; rooms[3].exits = {1, 5}; // Room 4 rooms[4].description = "A room with walls covered in ancient runes. A glowing orb floats in the center, pulsating with energy."; rooms[4].programmingInfo = "The orb whispers: 'A pointer is a variable that stores the memory address of another variable.'"; rooms[4].exits = {2, 6}; // Room 5 rooms[5].description = "This room is a library, with shelves of dusty tomes stretching to the ceiling. A single candle burns on a table."; rooms[5].programmingInfo = "A book on the table reads: 'A class is a blueprint for creating objects, encapsulating data and behavior.'"; rooms[5].exits = {3, 7}; // Room 6 rooms[6].description = "A room filled with mirrors, reflecting your image infinitely. A small console sits in the corner."; rooms[6].programmingInfo = "The console displays: 'A conditional statement, like if-else, allows your program to make decisions based on conditions.'"; rooms[6].exits = {4, 8}; // Room 7 rooms[7].description = "This room is a workshop, with tools scattered across a workbench. A robot arm twitches in the corner."; rooms[7].programmingInfo = "A sign on the wall reads: 'A variable is a named storage location in memory that holds a value.'"; rooms[7].exits = {5, 9}; // Room 8 rooms[8].description = "A room with a floor of polished obsidian, reflecting the flickering torchlight. A stone tablet lies in the center."; rooms[8].programmingInfo = "The tablet is engraved with: 'A stack is a data structure that follows the Last In, First Out (LIFO) principle.'"; rooms[8].exits = {6, 10}; // Room 9 rooms[9].description = "This room is a garden, with glowing mushrooms and bioluminescent vines. A small pond reflects the light."; rooms[9].programmingInfo = "A sign by the pond reads: 'A queue is a data structure that follows the First In, First Out (FIFO) principle.'"; rooms[9].exits = {7, 11}; // Room 10 rooms[10].description = "A room with walls of ice, chilling the air. A frozen knight stands in the corner, holding a scroll."; rooms[10].programmingInfo = "The scroll reads: 'A linked list is a data structure where each element points to the next.'"; rooms[10].exits = {8, 12}; // Room 11 rooms[11].description = "This room is a forge, with a blazing fire in the center. An anvil is covered in soot."; rooms[11].programmingInfo = "A hammer is engraved with: 'A binary tree is a data structure where each node has at most two children.'"; rooms[11].exits = {9, 13}; // Room 12 rooms[12].description = "A room with a ceiling of stars, twinkling in an artificial sky. A telescope stands in the corner."; rooms[12].programmingInfo = "The telescope lens is etched with: 'A hash table is a data structure that maps keys to values for efficient lookup.'"; rooms[12].exits = {10, 14}; // Room 13 rooms[13].description = "This room is a prison, with rusted chains hanging from the walls. A skeleton clutches a diary."; rooms[13].programmingInfo = "The diary reads: 'A recursive function is a function that calls itself to solve a problem.'"; rooms[13].exits = {11, 15}; // Room 14 rooms[14].description = "A room with walls of living vines, pulsing with energy. A stone altar holds a glowing gem."; rooms[14].programmingInfo = "The gem projects: 'A graph is a data structure consisting of nodes connected by edges.'"; rooms[14].exits = {12, 16}; // Room 15 rooms[15].description = "This room is a laboratory, with bubbling potions and sparking machines. A whiteboard is covered in equations."; rooms[15].programmingInfo = "The whiteboard reads: 'A sorting algorithm arranges elements in a specific order, like bubble sort or quicksort.'"; rooms[15].exits = {13, 17}; // Room 16 rooms[16].description = "A room with a floor of glass, revealing a swirling void below. A pedestal holds a glowing book."; rooms[16].programmingInfo = "The book reads: 'A searching algorithm finds a specific element in a data structure, like binary search.'"; rooms[16].exits = {14, 18}; // Room 17 rooms[17].description = "This room is a throne room, with a golden chair atop a dais. A crown lies discarded on the floor."; rooms[17].programmingInfo = "The crown is engraved with: 'A design pattern is a reusable solution to a common software design problem.'"; rooms[17].exits = {15, 19}; // Room 18 rooms[18].description = "A room with walls of fire, yet the air is cool. A stone tablet floats in the center."; rooms[18].programmingInfo = "The tablet reads: 'A thread is a unit of execution within a process, enabling parallelism.'"; rooms[18].exits = {16, 20}; // Room 19 rooms[19].description = "This room is a maze of mirrors, distorting your reflection. A small console blinks in the corner."; rooms[19].programmingInfo = "The console displays: 'A mutex is a synchronization primitive used to prevent race conditions in multithreaded programs.'"; rooms[19].exits = {17, 21}; // Room 20 rooms[20].description = "A room with a ceiling of gears, clicking and whirring. A mechanical bird perches on a stand."; rooms[20].programmingInfo = "The bird chirps: 'A compiler translates high-level code into machine code for execution.'"; rooms[20].exits = {18, 22}; // Room 21 rooms[21].description = "This room is a greenhouse, with exotic plants glowing in the dark. A notebook lies on a bench."; rooms[21].programmingInfo = "The notebook reads: 'An interpreter executes code line by line without compiling it first.'"; rooms[21].exits = {19, 23}; // Room 22 rooms[22].description = "A room with walls of water, held back by invisible barriers. A coral-encrusted chest sits in the center."; rooms[22].programmingInfo = "The chest contains a scroll that reads: 'A virtual function allows derived classes to override a base class method.'"; rooms[22].exits = {20, 24}; // Room 23 rooms[23].description = "This room is a cathedral, with stained glass windows depicting code snippets. A podium holds a book."; rooms[23].programmingInfo = "The book reads: 'An abstract class cannot be instantiated and is used as a base for other classes.'"; rooms[23].exits = {21, 25}; // Room 24 rooms[24].description = "A room with a floor of lava, crossed by a narrow stone bridge. A glowing orb hovers at the end."; rooms[24].programmingInfo = "The orb whispers: 'A template is a C++ feature that allows functions and classes to operate with generic types.'"; rooms[24].exits = {22, 26}; // Room 25 (Exit Room) rooms[25].description = "This room is bathed in golden light, with an open doorway leading to freedom. A sign above the door reads 'Exit.'"; rooms[25].programmingInfo = "A plaque on the wall reads: 'A namespace is a way to group related code to avoid naming conflicts.'"; rooms[25].exits = {23, 27}; // Room 26 rooms[26].description = "A room with walls of shifting sand, forming patterns and symbols. A stone tablet lies half-buried."; rooms[26].programmingInfo = "The tablet reads: 'A lambda function is an anonymous function defined inline, often used in functional programming.'"; rooms[26].exits = {24, 28}; // Room 27 rooms[27].description = "This room is a void, with floating platforms connected by glowing bridges. A console blinks in the distance."; rooms[27].programmingInfo = "The console displays: 'A smart pointer automatically manages memory, preventing memory leaks.'"; rooms[27].exits = {25, 29}; // Room 28 rooms[28].description = "A room with walls of crystal, refracting light into rainbows. A pedestal holds a glowing gem."; rooms[28].programmingInfo = "The gem projects: 'A container is a data structure that holds multiple elements, like vectors or maps.'"; rooms[28].exits = {26}; // Room 29 rooms[29].description = "This room is a clock tower, with gears and pendulums swinging in harmony. A book lies on a ledge."; rooms[29].programmingInfo = "The book reads: 'A destructor is a special member function called when an object goes out of scope.'"; rooms[29].exits = {27}; return rooms; } // Function to handle NPC movement and actions void npcBehavior(GameState& state, const vector<Room>& rooms) { while (state.gameRunning && state.wanderingCoder.isActive) { // Move NPC to a random adjacent room if (!rooms[state.wanderingCoder.currentRoom].exits.empty()) { int newRoom = rooms[state.wanderingCoder.currentRoom].exits[getRandom(0, rooms[state.wanderingCoder.currentRoom].exits.size() - 1)]; state.wanderingCoder.currentRoom = newRoom; } // Random NPC action (cough or look around) int action = getRandom(0, 1); if (state.wanderingCoder.currentRoom == state.playerRoom) { if (action == 0) { cout << state.wanderingCoder.name << " coughs softly, adjusting their glasses.\n"; } else { cout << state.wanderingCoder.name << " looks around the room, muttering about code efficiency.\n"; } } // Wait for a random interval up to NPC_COUGH_INTERVAL seconds this_thread::sleep_for(chrono::seconds(getRandom(10, NPC_COUGH_INTERVAL))); } } // Function to display room information void displayRoom(const GameState& state, const vector<Room>& rooms) { const Room& room = rooms[state.playerRoom]; cout << "\n--- Room " << state.playerRoom << " ---\n"; cout << room.description << "\n"; if (state.wanderingCoder.currentRoom == state.playerRoom) { cout << state.wanderingCoder.name << " is here, scribbling notes on a clipboard.\n"; } cout << "Exits lead to rooms: "; for (int exit : room.exits) { cout << exit << " "; } cout << "\n"; if (state.playerRoom == EXIT_ROOM) { cout << "You see an open doorway leading to freedom. Type 'exit' to leave the dungeon.\n"; } } // Function to handle player input void handleInput(GameState& state, const vector<Room>& rooms) { string input; cout << "\nWhat do you do? (look, inspect, talk, move <room>, exit, quit): "; getline(cin, input); input = toLower(input); if (input == "look" || input == "inspect") { const Room& room = rooms[state.playerRoom]; cout << room.description << "\n"; cout << room.programmingInfo << "\n"; } else if (input == "talk") { if (state.wanderingCoder.currentRoom == state.playerRoom) { int adviceIndex = getRandom(0, state.wanderingCoder.advice.size() - 1); cout << state.wanderingCoder.name << " says: \"" << state.wanderingCoder.advice[adviceIndex] << "\"\n"; } else { cout << "There's no one here to talk to.\n"; } } else if (input.substr(0, 5) == "move ") { try { int targetRoom = stoi(input.substr(5)); const Room& currentRoom = rooms[state.playerRoom]; if (find(currentRoom.exits.begin(), currentRoom.exits.end(), targetRoom) != currentRoom.exits.end()) { state.playerRoom = targetRoom; displayRoom(state, rooms); } else { cout << "You can't go to room " << targetRoom << " from here.\n"; } } catch (...) { cout << "Invalid room number. Use 'move <room number>'.\n"; } } else if (input == "exit" && state.playerRoom == EXIT_ROOM) { cout << "You step through the open doorway and escape the dungeon. Congratulations!\n"; state.gameRunning = false; } else if (input == "quit") { cout << "You abandon your quest. Goodbye!\n"; state.gameRunning = false; } else { cout << "Unknown command. Try 'look', 'inspect', 'talk', 'move <room>', 'exit', or 'quit'.\n"; } } int main() { cout << "Welcome to the Dungeon of Code!\n"; cout << "Explore rooms, learn programming concepts, and find the exit.\n"; cout << "Commands: look, inspect, talk, move <room>, exit, quit\n\n"; // Initialize game state and rooms GameState state; vector<Room> rooms = initializeRooms(); // Start NPC behavior in a separate thread thread npcThread(npcBehavior, ref(state), ref(rooms)); // Display starting room displayRoom(state, rooms); // Main game loop while (state.gameRunning) { handleInput(state, rooms); } // Clean up NPC thread state.wanderingCoder.isActive = false; if (npcThread.joinable()) { npcThread.join(); } return 0; }Explanation of the Program
-
Room Structure:
- Each room has a
description,programmingInfo, and a list ofexits(adjacent rooms). - The rooms are initialized with unique descriptions and programming-related information, covering topics like loops, magic numbers, data structures, and more.
- Each room has a
-
NPC Behavior:
- The NPC, named "Wandering Coder," moves randomly between rooms using a separate thread.
- The NPC performs random actions (coughing or looking around) at intervals up to 40 seconds, but only if they are in the same room as the player.
- The NPC provides random coding advice from a list of 10 responses when the player uses the "talk" command.
-
Game Mechanics:
- The player starts in room 0 and can move to adjacent rooms using the "move " command.
- The "look" or "inspect" command displays the room's description and programming info.
- The "talk" command interacts with the NPC if present.
- Room 25 contains an exit, and the player can type "exit" to win the game.
- The "quit" command ends the game at any time.
-
Timed Actions:
- The NPC's actions are handled in a separate thread using
<thread>and<chrono>. - The NPC thread is properly cleaned up when the game ends.
- The NPC's actions are handled in a separate thread using
-
Input Handling:
- Input is case-insensitive, and invalid commands are handled gracefully.
- The program uses string parsing to handle commands like "move ".
How to Compile and Run
To compile and run this program, you'll need a C++ compiler that supports C++11 or later. For example, using
g++:g++ -std=c++11 dungeon.cpp -o dungeon ./dungeonOn Windows, you may need to link the threading library explicitly if using MinGW:
g++ -std=c++11 dungeon.cpp -o dungeon -lpthread dungeon.exeSample Gameplay
Welcome to the Dungeon of Code! Explore rooms, learn programming concepts, and find the exit. Commands: look, inspect, talk, move <room>, exit, quit --- Room 0 --- You stand in a dimly lit chamber with moss-covered stone walls. A rusty sword lies in the corner, and a faint hum echoes from a dusty computer terminal. Exits lead to rooms: 1 2 What do you do? (look, inspect, talk, move <room>, exit, quit): look You stand in a dimly lit chamber with moss-covered stone walls. A rusty sword lies in the corner, and a faint hum echoes from a dusty computer terminal. A note on the terminal reads: 'A loop is a programming construct that repeats a block of code until a condition is met, such as a for or while loop.' What do you do? (look, inspect, talk, move <room>, exit, quit): move 1 --- Room 1 --- This room is filled with glowing crystals embedded in the walls, casting eerie blue light. A skeleton sits at a desk, clutching a book. Exits lead to rooms: 0 3 What do you do? (look, inspect, talk, move <room>, exit, quit): inspect This room is filled with glowing crystals embedded in the walls, casting eerie blue light. A skeleton sits at a desk, clutching a book. The book is open to a page that says: 'Magic numbers are hard-coded values in your code; replace them with named constants for better readability.' [Wandering Coder is here, scribbling notes on a clipboard.] What do you do? (look, inspect, talk, move <room>, exit, quit): talk Wandering Coder says: "Always comment your code to make it readable for others—and your future self!" [Wandering Coder coughs softly, adjusting their glasses.] What do you do? (look, inspect, talk, move <room>, exit, quit): move 3 ...Notes
- The dungeon layout is a simple linear graph with some branching, but you can modify the
exitsininitializeRooms()to create a more complex maze. - The NPC's movement is random, so they may not always be easy to find. You could add a command to locate the NPC if desired.
- The timed NPC actions are basic; you could expand them to include more varied behaviors.
- For a more polished game, consider adding items, puzzles, or combat, but this version focuses on exploration and learning.
Enjoy your dungeon adventure, and happy coding!
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.