Generate a short program of a small, simple text dungeon in C++
- User
Generate a short program of a small, simple text dungeon in C++
Assistant
Sure! Below is a simple text-based dungeon game in C++. This program will allow the player to navigate through a small dungeon with a few rooms and a simple objective.
#include <iostream> #include <string> using namespace std; class Room { public: string description; Room* north; Room* south; Room* east; Room* west; bool hasTreasure; Room(string desc, bool treasure = false) : description(desc), hasTreasure(treasure) { north = south = east = west = nullptr; } }; void displayRoom(Room* currentRoom) { cout << "You are in a " << currentRoom->description << ".\n"; if (currentRoom->hasTreasure) { cout << "You found the treasure! Congratulations!\n"; } } int main() { // Create rooms Room start("start room", false); Room northRoom("north room", false); Room eastRoom("east room", false); Room treasureRoom("treasure room", true); // Connect rooms start.north = &northRoom; northRoom.south = &start; start.east = &eastRoom; eastRoom.west = &start; northRoom.east = &treasureRoom; treasureRoom.west = &northRoom; // Start the game Room* currentRoom = &start; string command; bool gameOver = false; while (!gameOver) { displayRoom(currentRoom); cout << "Enter a command (north, south, east, west, quit): "; cin >> command; if (command == "north" && currentRoom->north != nullptr) { currentRoom = currentRoom->north; } else if (command == "south" && currentRoom->south != nullptr) { currentRoom = currentRoom->south; } else if (command == "east" && currentRoom->east != nullptr) { currentRoom = currentRoom->east; } else if (command == "west" && currentRoom->west != nullptr) { currentRoom = currentRoom->west; } else if (command == "quit") { gameOver = true; } else { cout << "You can't go that way.\n"; } } cout << "Thanks for playing!\n"; return 0; }Explanation:
- Room Class: This class represents a room in the dungeon. Each room has a description, pointers to adjacent rooms (north, south, east, west), and a boolean to indicate if the room contains the treasure.
- displayRoom Function: This function prints the description of the current room and checks if the room contains the treasure.
- Main Function: This is the main game loop. It creates the rooms, connects them, and allows the player to navigate through the dungeon using simple commands (north, south, east, west, quit).
To run this program, you need a C++ compiler. Save the code to a file (e.g.,
dungeon.cpp) and compile it using a command likeg++ dungeon.cpp -o dungeon. Then, run the executable with./dungeon.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.