Text-Based Adventure Game C++, Python
👤 Sharing: AI
Okay, here's a text-based adventure game example in both C++ and Python, along with explanations to help you understand the code. I've focused on a simple structure that you can easily expand upon.
**C++ Version**
```cpp
#include <iostream>
#include <string>
#include <limits> // Required for std::numeric_limits
using namespace std;
// Function declarations
void display_location(string location);
string get_player_input();
void process_command(string command, string& current_location);
int main() {
string current_location = "forest"; // Starting location
bool game_over = false;
cout << "Welcome to the Text Adventure Game!\n";
while (!game_over) {
display_location(current_location);
string command = get_player_input();
process_command(command, current_location);
if (current_location == "treasure_room") {
cout << "\nYou found the treasure! You win!\n";
game_over = true;
} else if (current_location == "lost") {
cout << "\nYou are hopelessly lost. Game Over.\n";
game_over = true;
}
}
cout << "Thanks for playing!\n";
return 0;
}
void display_location(string location) {
if (location == "forest") {
cout << "\nYou are in a dense forest. Sunlight filters through the trees.\n";
cout << "To the north, you see a dark cave. To the east, there's a small clearing.\n";
} else if (location == "cave") {
cout << "\nYou are in a dark, damp cave. You hear water dripping.\n";
cout << "There's a narrow passage leading deeper into the cave to the west. The forest is to the south.\n";
} else if (location == "clearing") {
cout << "\nYou are in a small clearing. There's a strange symbol etched into a stone.\n";
cout << "The forest is to the west, and a path leads north.\n";
} else if (location == "treasure_room") {
cout << "\nYou are in a room filled with gold and jewels!\n";
} else {
cout << "\nYou are lost in the wilderness. There's nothing here.\n";
}
}
string get_player_input() {
cout << "\nWhat do you do? > ";
string input;
getline(cin, input); // Use getline to handle spaces in input
return input;
}
void process_command(string command, string& current_location) {
if (command == "north") {
if (current_location == "forest") {
current_location = "cave";
} else if (current_location == "clearing") {
current_location = "treasure_room";
} else {
cout << "You can't go that way.\n";
}
} else if (command == "south") {
if (current_location == "cave") {
current_location = "forest";
} else {
cout << "You can't go that way.\n";
}
} else if (command == "east") {
if (current_location == "forest") {
current_location = "clearing";
} else {
cout << "You can't go that way.\n";
}
} else if (command == "west") {
if (current_location == "clearing") {
current_location = "forest";
} else if (current_location == "cave") {
current_location = "lost";
} else {
cout << "You can't go that way.\n";
}
} else if (command == "look") {
display_location(current_location); // Redisplay the current location
} else if (command == "quit") {
current_location = "quit"; // A signal to end the game (not used in C++'s main loop, but could be)
}
else {
cout << "I don't understand that command.\n";
}
}
```
**C++ Explanation:**
1. **Headers:**
* `iostream`: For input and output (e.g., `cout`, `cin`).
* `string`: To use the `string` data type for text.
* `limits`: Used for clearing the input buffer after an invalid input.
2. **`main()` Function:**
* `current_location`: A string variable that stores the player's current location. It starts at "forest".
* `game_over`: A boolean variable to track if the game is over.
* The `while` loop continues as long as `game_over` is `false`.
* Inside the loop:
* `display_location()`: Prints a description of the current location.
* `get_player_input()`: Gets the player's command from the console.
* `process_command()`: Parses the command and updates the `current_location` accordingly.
* Checks for win or lose conditions based on `current_location`.
3. **`display_location()` Function:**
* Takes the `location` as input (a string).
* Uses `if` / `else if` statements to display different descriptions based on the location. You can easily add more locations here.
4. **`get_player_input()` Function:**
* Prompts the player for input using `cout`.
* Uses `getline(cin, input)` to read the entire line of input, including spaces. This is important because a command might be "get sword" instead of just "north".
* Returns the player's input as a string.
5. **`process_command()` Function:**
* Takes the `command` (string) and the `current_location` (string, passed by *reference* so it can be modified).
* Uses `if` / `else if` statements to check the command.
* If the command is a movement command (north, south, east, west), it updates the `current_location` based on the current location.
* If the command is "look", it calls `display_location()` to redisplay the description.
* If the command is "quit", you can set a variable to end the game (the C++ version here doesn't *use* the quit functionality, but I've added it for completeness).
* If the command is not recognized, it prints an error message.
**Python Version**
```python
def display_location(location):
"""Displays the description of the current location."""
if location == "forest":
print("\nYou are in a dense forest. Sunlight filters through the trees.")
print("To the north, you see a dark cave. To the east, there's a small clearing.")
elif location == "cave":
print("\nYou are in a dark, damp cave. You hear water dripping.")
print("There's a narrow passage leading deeper into the cave to the west. The forest is to the south.")
elif location == "clearing":
print("\nYou are in a small clearing. There's a strange symbol etched into a stone.")
print("The forest is to the west, and a path leads north.")
elif location == "treasure_room":
print("\nYou are in a room filled with gold and jewels!")
else:
print("\nYou are lost in the wilderness. There's nothing here.")
def get_player_input():
"""Gets the player's command."""
return input("\nWhat do you do? > ").lower() # Convert to lowercase for easier comparison
def process_command(command, current_location):
"""Processes the player's command and updates the game state."""
new_location = current_location # Assume the location doesn't change
if command == "north":
if current_location == "forest":
new_location = "cave"
elif current_location == "clearing":
new_location = "treasure_room"
else:
print("You can't go that way.")
elif command == "south":
if current_location == "cave":
new_location = "forest"
else:
print("You can't go that way.")
elif command == "east":
if current_location == "forest":
new_location = "clearing"
else:
print("You can't go that way.")
elif command == "west":
if current_location == "clearing":
new_location = "forest"
elif current_location == "cave":
new_location = "lost"
else:
print("You can't go that way.")
elif command == "look":
display_location(current_location)
elif command == "quit":
return "quit" # Signal to end the game
else:
print("I don't understand that command.")
return new_location # Return the potentially updated location
# Main game loop
def main():
current_location = "forest"
game_over = False
print("Welcome to the Text Adventure Game!\n")
while not game_over:
display_location(current_location)
command = get_player_input()
new_location = process_command(command, current_location)
if new_location == "quit":
game_over = True
else:
current_location = new_location
if current_location == "treasure_room":
print("\nYou found the treasure! You win!\n")
game_over = True
elif current_location == "lost":
print("\nYou are hopelessly lost. Game Over.\n")
game_over = True
print("Thanks for playing!")
if __name__ == "__main__":
main()
```
**Python Explanation:**
1. **Functions:** The code is organized into functions to make it more readable and maintainable.
* `display_location(location)`: Displays the description of the current location based on the `location` string.
* `get_player_input()`: Prompts the player for a command and returns it as a string, converted to lowercase using `.lower()` for easier comparison.
* `process_command(command, current_location)`: Takes the player's `command` and the `current_location` as input. It determines the new location based on the command and the current location, and returns the new location. If the command is "quit", it returns "quit" to signal the main loop to end the game.
2. **`main()` Function:**
* Sets the `current_location` to "forest" and `game_over` to `False`.
* The `while` loop runs as long as `game_over` is `False`.
* Inside the loop:
* `display_location()`: Prints the description of the current location.
* `command = get_player_input()`: Gets the player's input.
* `new_location = process_command()`: Processes the command and updates `current_location`.
* Checks for win or lose conditions.
3. **`if __name__ == "__main__":`**
* This is a standard Python idiom. It ensures that the `main()` function is only called when the script is run directly (not when it's imported as a module into another script).
**Key Improvements and Differences between C++ and Python**
* **String Handling:** Python's string handling is much simpler than C++. You don't need to worry about manual memory management.
* **Input:** Python's `input()` function is more straightforward than `cin` (and especially `getline`) in C++. The `.lower()` method makes command processing easier.
* **Readability:** Python's syntax (whitespace, etc.) makes the code generally more readable.
* **No explicit types**: Python doesn't require you to declare the type of a variable like C++ does. This can speed up development, but it also means that you need to be careful about type errors.
* **Return values**: Python returns the new location and that new location is assigned to the current location.
**How to Run the Code**
* **C++:**
1. Save the code as a `.cpp` file (e.g., `adventure.cpp`).
2. Compile the code using a C++ compiler (like g++): `g++ adventure.cpp -o adventure`
3. Run the compiled executable: `./adventure`
* **Python:**
1. Save the code as a `.py` file (e.g., `adventure.py`).
2. Run the script from the command line: `python adventure.py`
**How to Extend the Game**
1. **More Locations:** Add more `else if` (in C++) or `elif` (in Python) blocks to the `display_location()` function and the `process_command()` function to create new locations and paths between them.
2. **Items:** Introduce items that the player can pick up and use. You'll need a way to store the player's inventory (e.g., a list or vector).
3. **Puzzles:** Add puzzles that the player must solve to progress.
4. **Enemies:** Add enemies that the player must fight. This will require adding some combat mechanics.
5. **More Complex Commands:** Instead of just single-word commands, you could allow commands like "take sword" or "use key on door". You'll need to parse the player's input to extract the verb and the object.
6. **Game Over Conditions:** Add more ways for the player to lose the game.
7. **Score:** Keep track of the player's score based on their actions.
This example provides a solid foundation for building a more complex and engaging text-based adventure game. Remember to break down the problem into smaller, manageable tasks and test your code frequently. Good luck!
👁️ Viewed: 6
Comments