Here's a C++ text dungeon program with programming education elements:
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <random>
#include <chrono>
#include <thread>
#include <algorithm>
#include <sstream>
class Room {
public:
std::string name;
std::string description;
std::string programmingTip;
std::map<std::string, int> connections; // direction -> room_id
bool hasExit;
Room(const std::string& n, const std::string& desc, const std::string& tip, bool exit = false)
: name(n), description(desc), programmingTip(tip), hasExit(exit) {}
};
class NPC {
public:
std::string name;
int currentRoom;
std::chrono::steady_clock::time_point lastAction;
std::chrono::steady_clock::time_point lastMove;
std::vector<std::string> adviceList;
NPC(const std::string& n, int startRoom) : name(n), currentRoom(startRoom) {
lastAction = std::chrono::steady_clock::now();
lastMove = std::chrono::steady_clock::now();
adviceList = {
"Always comment your code - your future self will thank you!",
"Remember: premature optimization is the root of all evil.",
"Test early, test often. Bugs are easier to fix when they're fresh.",
"Keep your functions small and focused on a single task.",
"Use meaningful variable names - 'x' tells you nothing, 'playerHealth' tells you everything.",
"Version control is your friend. Commit often with clear messages.",
"Don't repeat yourself (DRY) - if you're copying code, consider making a function.",
"Learn to read error messages carefully - they're trying to help you!",
"Take breaks when debugging. Fresh eyes spot problems faster.",
"The best code is often the simplest code that works."
};
}
std::string getRandomAdvice() {
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, adviceList.size() - 1);
return adviceList[dis(gen)];
}
void performRandomAction() {
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 2);
switch(dis(gen)) {
case 0:
std::cout << "\n" << name << " coughs softly.\n";
break;
case 1:
std::cout << "\n" << name << " looks around thoughtfully.\n";
break;
case 2:
std::cout << "\n" << name << " adjusts their glasses.\n";
break;
}
}
};
class Dungeon {
private:
std::vector<Room> rooms;
int playerRoom;
NPC wanderer;
bool gameRunning;
std::chrono::steady_clock::time_point lastUpdate;
public:
Dungeon() : playerRoom(0), wanderer("Professor Code", 5), gameRunning(true) {
initializeRooms();
lastUpdate = std::chrono::steady_clock::now();
}
void initializeRooms() {
// Create 30 rooms with programming concepts
rooms.push_back(Room("Entry Hall",
"You stand in a dimly lit entry hall. Stone walls stretch upward into darkness. "
"On the eastern wall, glowing text appears to float in mid-air.",
"The glowing text reads: 'VARIABLES - Named storage locations in memory that hold data. "
"Like magical containers, they store values for later use.'"));
rooms.push_back(Room("Library of Loops",
"Dusty tomes line the walls of this ancient library. A terminal glows softly on a wooden desk. "
"The screen displays scrolling green text.",
"The terminal shows: 'LOOPS - Code structures that repeat instructions. "
"FOR loops run a specific number of times, WHILE loops continue until a condition is false.'"));
rooms.push_back(Room("Chamber of Arrays",
"Crystal formations jut from the walls, each containing a glowing number. "
"They seem to be arranged in a perfect sequence.",
"Etched below the crystals: 'ARRAYS - Collections of elements stored in contiguous memory. "
"Access any element instantly using its index, starting from 0.'"));
rooms.push_back(Room("Function Forge",
"A massive anvil sits in the center, surrounded by blueprints and diagrams. "
"The walls are covered with flowcharts drawn in chalk.",
"A sign reads: 'FUNCTIONS - Reusable blocks of code that perform specific tasks. "
"They take inputs (parameters), process them, and return outputs.'"));
rooms.push_back(Room("Recursion Mirror Hall",
"Mirrors line both walls, creating an infinite corridor of reflections. "
"Each reflection seems slightly smaller than the last.",
"Written in the dust: 'RECURSION - When a function calls itself. "
"Like these mirrors, it creates smaller versions until reaching a base case.'"));
rooms.push_back(Room("Pointer Plaza",
"Arrow symbols cover the floor, all pointing to different locations. "
"A holographic display shows memory addresses floating in the air.",
"The display explains: 'POINTERS - Variables that store memory addresses. "
"They point to where data lives, allowing indirect access and manipulation.'"));
rooms.push_back(Room("Class Constructor",
"Blueprints for various objects cover every surface. "
"A workbench holds half-assembled mechanical creatures.",
"A manual states: 'CLASSES - Blueprints for creating objects. "
"They bundle data (attributes) and functions (methods) into reusable templates.'"));
rooms.push_back(Room("Inheritance Tower",
"A spiral staircase winds upward, with family portraits on each level. "
"Each portrait shares features with those above and below.",
"A plaque reads: 'INHERITANCE - Classes can inherit properties from parent classes. "
"Like family traits passed down through generations.'"));
rooms.push_back(Room("Exception Trap Room",
"The floor is covered with carefully marked trap doors. "
"Signs warn of various dangers, but safe paths are clearly marked.",
"Warning sign: 'EXCEPTIONS - Unexpected events during program execution. "
"Try-catch blocks help programs handle errors gracefully instead of crashing.'"));
rooms.push_back(Room("Algorithm Amphitheater",
"Stone seats surround a central stage where mechanical figures act out sorting routines. "
"They continuously rearrange themselves in different patterns.",
"On the stage backdrop: 'ALGORITHMS - Step-by-step procedures for solving problems. "
"Like recipes, they transform inputs into desired outputs efficiently.'"));
rooms.push_back(Room("Binary Garden",
"Strange plants grow here, each with exactly two branches at every split. "
"Flowers bloom in patterns of open and closed petals.",
"Garden marker: 'BINARY - The language of computers using only 0s and 1s. "
"All data ultimately becomes these two states: on or off, true or false.'"));
rooms.push_back(Room("Stack Storage",
"Crates are piled high, with newer boxes always placed on top. "
"A sign indicates you can only access the topmost crate.",
"Storage rules: 'STACK - Last In, First Out (LIFO) data structure. "
"Like a stack of plates, you can only add or remove from the top.'"));
rooms.push_back(Room("Queue Corridor",
"A long hallway with a velvet rope line. "
"Ghostly figures wait patiently, moving forward one at a time.",
"Posted notice: 'QUEUE - First In, First Out (FIFO) data structure. "
"Like a line at a store, first to arrive is first to be served.'"));
rooms.push_back(Room("Debugging Den",
"Magnifying glasses and diagnostic tools cover the workbenches. "
"Broken code fragments lie scattered, waiting to be fixed.",
"Toolkit label: 'DEBUGGING - The art of finding and fixing errors. "
"Use print statements, debuggers, and logical thinking to track down bugs.'"));
rooms.push_back(Room("Constant Chamber",
"Everything here is frozen in time. "
"Numbers and symbols are carved permanently into unbreakable stone.",
"Carved in stone: 'CONSTANTS - Values that never change during program execution. "
"Use const or #define to prevent accidental modifications.'"));
rooms.push_back(Room("Exit Portal",
"A shimmering doorway fills the northern wall with bright light. "
"Fresh air flows through, carrying the scent of the outside world.",
"Above the door: 'PROGRAM TERMINATION - Every program must eventually end. "
"Return 0 indicates successful completion. Your journey ends here.'", true));
rooms.push_back(Room("Polymorphism Theater",
"Actors on stage seamlessly switch between different roles. "
"The same script produces different performances.",
"Program notes: 'POLYMORPHISM - Same interface, different implementations. "
"Objects of different types can be treated uniformly through common interfaces.'"));
rooms.push_back(Room("Memory Leak Swamp",
"Water drips constantly from unseen cracks. "
"Puddles grow larger, never seeming to drain away.",
"Warning sign: 'MEMORY LEAKS - Allocated memory that's never freed. "
"Always delete what you new, and free what you malloc!'"));
rooms.push_back(Room("Compiler Workshop",
"Machinery hums, transforming raw text into intricate patterns. "
"Input slots accept written code, output slots produce mysterious symbols.",
"Workshop manual: 'COMPILERS - Transform human-readable code into machine language. "
"They check syntax, optimize, and create executable programs.'"));
rooms.push_back(Room("Logic Gate Gallery",
"Mechanical gates open and close based on switch combinations. "
"AND, OR, and NOT gates create a complex puzzle of pathways.",
"Gallery guide: 'LOGIC GATES - Building blocks of digital circuits. "
"AND requires all inputs true, OR needs at least one, NOT inverts.'"));
rooms.push_back(Room("Hash Table Haven",
"Numbered buckets line the walls, each containing various treasures. "
"A mystical formula converts names into bucket numbers.",
"Instruction scroll: 'HASH TABLES - Fast lookup using key-value pairs. "
"Hash functions transform keys into array indices for O(1) access.'"));
rooms.push_back(Room("Scope Sanctuary",
"Nested chambers within chambers, each with its own locked contents. "
"Items in inner rooms can see out, but outer rooms cannot see in.",
"Sanctuary rules: 'SCOPE - Where variables can be accessed. "
"Local variables exist only within their defining blocks.'"));
rooms.push_back(Room("Type Casting Crucible",
"Alchemical equipment transforms materials from one form to another. "
"Lead becomes gold, water becomes ice, but some transformations fail.",
"Alchemist notes: 'TYPE CASTING - Converting data from one type to another. "
"Be careful - information can be lost in conversion!'"));
rooms.push_back(Room("Operator Overload Office",
"Mathematical symbols perform unexpected tasks. "
"Plus signs concatenate strings, asterisks repeat patterns.",
"Office memo: 'OPERATOR OVERLOADING - Giving new meanings to operators. "
"Make + work for your custom classes, but keep it intuitive!'"));
rooms.push_back(Room("Template Treasury",
"Blank forms await filling with specific types. "
"The same blueprint creates containers for numbers, strings, or anything.",
"Treasury guide: 'TEMPLATES - Generic programming for any data type. "
"Write once, use with int, float, string, or custom types.'"));
rooms.push_back(Room("Namespace Nexus",
"Different regions of the room contain similar items with different meanings. "
"Color-coded sections prevent confusion between duplicates.",
"Nexus map: 'NAMESPACES - Organize code to prevent naming conflicts. "
"std::cout and mycustom::cout can coexist peacefully.'"));
rooms.push_back(Room("Iterator Inn",
"A comfortable resting place with numbered seats. "
"Visitors move methodically from seat to seat, never skipping.",
"Inn register: 'ITERATORS - Objects that traverse containers. "
"Move through vectors, lists, or maps with begin() to end().'"));
rooms.push_back(Room("Virtual Vista",
"Windows show different views depending on who looks through them. "
"Each viewer's perspective creates a unique scene.",
"Vista plaque: 'VIRTUAL FUNCTIONS - Methods that can be overridden. "
"Base class pointers call derived class implementations dynamically.'"));
rooms.push_back(Room("Singleton Shrine",
"Only one sacred artifact exists here, heavily guarded. "
"All paths lead to the same central treasure.",
"Shrine inscription: 'SINGLETON PATTERN - Ensures only one instance exists. "
"Global access point to a single object throughout the program.'"));
rooms.push_back(Room("Magic Number Museum",
"Mysterious numbers float without explanation: 3.14159, 42, 255. "
"Their purposes remain unclear without context.",
"Museum warning: 'MAGIC NUMBERS - Unnamed constants in code. "
"Replace 3.14159 with PI, 60 with SECONDS_PER_MINUTE for clarity.'"));
// Set up connections (simplified grid layout)
setupConnections();
}
void setupConnections() {
// Create a 6x5 grid of rooms
for (int i = 0; i < 30; i++) {
int row = i / 6;
int col = i % 6;
// North
if (row > 0) rooms[i].connections["north"] = i - 6;
// South
if (row < 4) rooms[i].connections["south"] = i + 6;
// East
if (col < 5) rooms[i].connections["east"] = i + 1;
// West
if (col > 0) rooms[i].connections["west"] = i - 1;
}
}
void update() {
auto now = std::chrono::steady_clock::now();
auto timeSinceAction = std::chrono::duration_cast<std::chrono::seconds>(now - wanderer.lastAction).count();
auto timeSinceMove = std::chrono::duration_cast<std::chrono::seconds>(now - wanderer.lastMove).count();
// NPC random action
if (timeSinceAction > (rand() % 30 + 10)) {
if (wanderer.currentRoom == playerRoom) {
wanderer.performRandomAction();
}
wanderer.lastAction = now;
}
// NPC movement
if (timeSinceMove > 20) {
moveNPC();
wanderer.lastMove = now;
}
}
void moveNPC() {
std::vector<int> possibleRooms;
for (const auto& conn : rooms[wanderer.currentRoom].connections) {
possibleRooms.push_back(conn.second);
}
if (!possibleRooms.empty()) {
int oldRoom = wanderer.currentRoom;
wanderer.currentRoom = possibleRooms[rand() % possibleRooms.size()];
if (oldRoom == playerRoom) {
std::cout << "\n" << wanderer.name << " leaves the room.\n";
} else if (wanderer.currentRoom == playerRoom) {
std::cout << "\n" << wanderer.name << " enters the room.\n";
}
}
}
void look() {
const Room& current = rooms[playerRoom];
std::cout << "\n=== " << current.name << " ===\n";
std::cout << current.description << "\n\n";
std::cout << current.programmingTip << "\n";
if (current.hasExit) {
std::cout << "\nThe EXIT is here! Type 'exit' to leave the dungeon.\n";
}
std::cout << "\nExits: ";
for (const auto& conn : current.connections) {
std::cout << conn.first << " ";
}
std::cout << "\n";
if (wanderer.currentRoom == playerRoom) {
std::cout << "\n" << wanderer.name << " is here, looking thoughtful.\n";
}
}
void move(const std::string& direction) {
auto it = rooms[playerRoom].connections.find(direction);
if (it != rooms[playerRoom].connections.end()) {
playerRoom = it->second;
std::cout << "\nYou move " << direction << ".\n";
look();
} else {
std::cout << "\nYou can't go that way.\n";
}
}
void talkToNPC() {
if (wanderer.currentRoom == playerRoom) {
std::cout << "\n" << wanderer.name << " says: \"" << wanderer.getRandomAdvice() << "\"\n";
} else {
std::cout << "\nThere's no one here to talk to.\n";
}
}
void processCommand(const std::string& input) {
std::string command = input;
std::transform(command.begin(), command.end(), command.begin(), ::tolower);
if (command == "look" || command == "inspect" || command == "l") {
look();
} else if (command == "north" || command == "n") {
move("north");
} else if (command == "south" || command == "s") {
move("south");
} else if (command == "east" || command == "e") {
move("east");
} else if (command == "west" || command == "w") {
move("west");
} else if (command == "talk" || command == "speak" || command == "say") {
talkToNPC();
} else if (command == "exit" && rooms[playerRoom].hasExit) {
std::cout << "\nYou step through the shimmering portal and emerge into daylight.\n";
std::cout << "Congratulations! You've completed the Programming Dungeon!\n";
gameRunning = false;
} else if (command == "help") {
std::cout << "\nCommands: look, north/south/east/west (or n/s/e/w), talk, exit, quit\n";
} else if (command == "quit") {
gameRunning = false;
} else {
std::cout << "\nI don't understand that command. Type 'help' for options.\n";
}
}
void run() {
std::cout << "Welcome to the Programming Dungeon!\n";
std::cout << "Learn programming concepts as you explore 30 mysterious rooms.\n";
std::cout << "Type 'help' for commands.\n\n";
look();
std::string input;
while (gameRunning) {
std::cout << "\n> ";
std::getline(std::cin, input);
if (!input.empty()) {
processCommand(input);
}
update();
}
std::cout << "\nThanks for playing!\n";
}
};
int main() {
srand(time(nullptr));
Dungeon game;
game.run();
return 0;
}
This text dungeon game features:
- 30 unique rooms each with detailed descriptions and programming concepts
- Programming education integrated into room descriptions (variables, loops, arrays, functions, etc.)
- Professor Code - a wandering NPC who gives coding advice and performs timed actions
- Command system supporting look/inspect and movement
- Exit portal in room 15 to complete the game
- Timed NPC behaviors including random movements and actions
The game teaches fundamental programming concepts including:
- Variables and constants
- Loops and control structures
- Arrays and data structures
- Functions and recursion
- Object-oriented programming concepts
- Memory management
- Algorithms and logic
- Best practices (avoiding magic numbers, etc.)
Players explore the dungeon, learning programming concepts from room descriptions while occasionally encountering Professor Code for additional coding wisdom. The game provides an engaging way to reinforce programming knowledge through exploration and discovery.