Learning, for me, has never been about reading a textbook or sitting in on a lecture - it's been about experiencing and immersing myself in a hands-on challenge. This is particulary true for new programming languages. With GitLab Duo Code Suggestions, artificial intelligence (AI) becomes my interactive guide, providing an environment for trial, error, and growth. In this tutorial, we will build a text-based adventure game in C++ by using Code Suggestions to learn the programming language along the way.
You can use this table of contents to navigate into each section. It is recommended to read top-down for the best learning experience.
- Setup
- Getting started
- Setting the text adventure stage
- Defining the adventure: Variables
- Crafting the adventure: Making decisions with conditionals
- Structuring the narrative: Characters
- Structuring the narrative: Items
- Applying what we've learned at the Grand Library
- See you next time in the Dragon Realm
- Share your feedback
Download GitLab Ultimate for free for a 30-day trial of GitLab Duo Code Suggestions.
Setup
You can follow this tutorial in your preferred and supported IDE. Review the documentation to enable Code Suggestions for GitLab.com SaaS or GitLab self-managed instances.
These installation instructions are for macOS Ventura on M1 Silicon.
Installing VS Code
- Download and install VS Code.
- Alternatively, you can also install it as a Homebrew cask:
brew install --cask visual-studio-code
.
Installing Clang as a compiler
- On macOS, you'll need to install some developer tools. Open your terminal and type:
xcode-select --install
This will prompt you to install Xcode's command line tools, which include the Clang C++ compiler.
After the installation, you can check if clang++
is installed by typing:
clang++ --version
You should see an output that includes some information about the Clang version you have installed.
Setting up VS Code
- Launch VS Code.
- Install and configure the GitLab Workflow extension.
- Optionally, in VS Code, install the C/C++ Intellisense extension, which helps with debugging C/C++.
Getting started
Now, let's start building this magical adventure with C++. We'll start with a "Hello World" example.
Create a new project learn-ai-cpp-adventure
. In the project root, create adventure.cpp
. The first part of every C++ program is the main()
function. It's the entry point of the program.
When you start writing int main() {
, Code Suggestions will help autocomplete the function with some default parameters.
int main()
{
cout << "Hello World" << endl;
return 0;
}
While this is a good place to start, we need to add an include and update the output statement:
#include <iostream> // Include the I/O stream library for input and output
// Main function, the starting point of the program
int main()
{
// Print "Hello World!" to the console
std::cout << "Hello World!" << std::endl;
// Return 0 to indicate successful execution
return 0;
}
The program prints "Hello World!" to the console when executed.
-
#include <iostream>
: Because we are building a text-based adventure, we will rely on input from the player using input and output operations (I/O) in C++. This include is a preprocessor directive that tells our program to include theiostream
library, which provides facilities to use input and output streams, such asstd::cout
for output. -
You might find that Code Suggestions suggests
int main(int argc, char* argv[])
as the definition of our main function. The parameters(int argc, char* argv[])
are used to pass command-line arguments to the program. Code Suggestions added them as default parameters, but they are not needed if you're not using command-line arguments. In that case, we can also define the main function asint main()
. -
std::cout << "Hello World!" << std::endl;
: outputs "Hello World" to the console. The stream operator<<
is used to send the string to output.std::endl
is an end-line character. -
return 0;
: we usereturn 0;
to indicate the end of themain()
function and return a value of 0. In C++, it is good practice to return 0 to indicate the program has completed successfully.
Compiling and running your program
Now that we have some code, let's review how we'll compile and run this program.
- Open your terminal or use the terminal in VSCode (View -> Terminal).
- Navigate to your project directory.
- Compile your program by typing:
clang++ adventure.cpp -o adventure
This command tells the Clang++ compiler to compile adventure.cpp and create an executable named adventure. After this, run your program by typing:
./adventure
You should see "Hello World!" printed in the terminal.
Because our tutorial uses a single source file adventure.cpp
, we can use the compiler directly to build our program. In the future, if the program grows beyond a file, we'll set up additional configurations to handle compilation.
Setting the text adventure stage
Before we get into more code, let's set the stage for our text adventure.
For this text adventure, players will explore the Dragon Realm. The Dragon Realm is full of mountains, lakes, and magic. Our player will enter the Dragon Realm for the first time, explore different locations, meet new characters, collect magical items, and journal their adventure. At every location, they will be offered choices to decide the course of their journey.
To kick off our adventure into the Dragon Realm, let's update our adventure.cpp main()
function to be more specific. As you update the welcome message, you might find that Code Suggestions already knows we're building a game.
#include <iostream> // Include the I/O stream library for input and output
// Main function, the starting point of the program
int main()
{
// Print "Hello World!" to the console
std::cout << "Welcome to the Dragon Realm!" << std::endl;
// Return 0 to indicate successful execution
return 0;
}
Defining the adventure: Variables
A variable stores data that can be used throughout the program scope in the main()
function. A variable is defined by a type, which indicates the kind of data it can hold.
Let's create a variable to hold our player's name and give it the type string
. A string
is designed to hold a sequence of characters so it's perfect for storing our player's name.
#include <iostream> // Include the I/O stream library for input and output
// Main function, the starting point of the program
int main()
{
// Print "Hello World!" to the console
std::cout << "Welcome to the Dragon Realm!" << std::endl;
// Declare a string variable to hold the player's name
std::string playerName;
// Return 0 to indicate successful execution
return 0;
}
As you do this, you may notice that Code Suggestions knows what's coming next - prompting the user for their player's name.
We may be able to get more complete and specific Code Suggestions by providing comments about what we'd like to do with the name - personally welcome the player to the game. Start by adding our plan of action in comments.
// Declare a string variable to hold the player's name
std::string playerName;
// Prompt the user to enter their player name
// Display a personalized welcome message to the player with their name
To capture the player's name from input, we need to use the std::cin
object from the iostream
library to fetch input from the player using the extraction operator >>
. If you start typing std::
to start prompting the user, Code Suggestions will make some suggestions to help you gather user input and save it to our playerName
variable.
Next, to welcome our player personally to the game, we want to use std::cout
and the playerName
variable together:
// Declare a string variable to store the player name
std::string playerName;
// Prompt the user to enter their player name
std::cout << "Please enter your name: ";
std::cin >> playerName;
// Display a personalized welcome message to the player with their name
std::cout << "Welcome " << playerName << " to The Dragon Realm!" << std::endl;
Crafting the adventure: Making decisions with conditionals
It's time to introduce our player to the different locations in tbe Dragon Realm they can visit. To prompt our player with choices, we use conditionals. Conditionals allow programs to take different actions based on criteria, such as user input.
Let's offer the player a selection of locations to visit and capture their choice as an int
value that corresponds to the location they picked.
// Display a personalized welcome message to the player with their name
std::cout << "Welcome " << playerName << " to The Dragon Realm!" << std::endl;
// Declare an int variable to capture the user's choice
int choice;
Then, we want to offer the player the different locations that are possible for that choice. Let's start with a comment and prompt Code Suggestions with std::cout
to fill out the details for us.
As you accept the suggestions, Code Suggestions will help build out the output and ask the player for their input.
// Declare an int variable to capture the user's choice
int choice;
// Offer the player a choice of 3 locations: 1 for Moonlight Markets, 2 for Grand Library, and 3 for Shimmer Lake.
std::cout << "Where will " << playerName << " go?" << std::endl;
std::cout << "1. Moonlight Markets" << std::endl;
std::cout << "2. Grand Library" << std::endl;
std::cout << "3. Shimmer Lake" << std::endl;
std::cout << "Please enter your choice: ";
std::cin >> choice;
Once you start typing std::cin >>
or accept the prompt for asking the player for their choice, Code Suggestions might offer a suggestion for building out your conditional flow. AI is non-deterministic: One suggestion can involve if/else statements while another solution uses a switch statement.
To give Code Suggestions a nudge, we'll add a comment and start typing out an if statement: if (choice ==)
.
And if you keep accepting the subsequent suggestions, Code Suggestions will autocomplete the code using if/else statements.
// Check the user's choice and display the corresponding messages
if (choice == 1) {
std::cout << "You chose Moonlight Markets" << std::endl;
}
else if (choice == 2) {
std::cout << "You chose Grand Library" << std::endl;
}
else if (choice == 3) {
std::cout << "You chose Shimmer Lake" << std::endl;
}
else {
std::cout << "Invalid choice" << std::endl;
}
if/else
is a conditional statement that allows a program to execute code based on whether a condition, in this case the player's choice, is true or false. If the condition evaluates to true, the code inside the braces is executed.
if (condition)
: used to check if the condition is true.else if (another condition)
: if the previous condition isn't true, the programs checks this condition.else
: if none of the previous conditions are true.
Another way of managing multiple choices like this example is using a switch()
statement. A switch
statement allows our program to jump to different sections of code based on the value of an expression, which, in this case, is the value of choice
.
We are going to replace our if/else
statements with a switch
statement. You can comment out or delete the if/else
statements and prompt Code Suggestions starting with switch(choice) {
.
// Evaluate the player's decision
switch(choice) {
// If 'choice' is 1, this block is executed.
case 1:
std::cout << "You chose Moonlight Markets." << std::endl;
break;
// If 'choice' is 2, this block is executed.
case 2:
std::cout << "You chose Grand Library." << std::endl;
break;
// If 'choice' is 3, this block is executed.
case 3:
std::cout << "You chose Shimmer Lake." << std::endl;
break;
// If 'choice' is not 1, 2, or 3, this block is executed.
default:
std::cout << "You did not enter 1, 2, or 3." << std::endl;
}
Each case represents a potential value that the variable or expression being switched on (in this case, choice) could have. If a match is found, the code for that case is executed. We use the default
case to handle any input errors in case the player enters a value that isn't accounted for.
Let's build out what happens when our player visits the Shimmering Lake. I've added some comments after the player's arrival at Shimmering Lake to prompt Code Suggestions to help us build this out:
// If 'choice' is 3, this block is executed.
case 3:
std::cout << "You chose Shimmering Lake." << std::endl;
// The player arrives at Shimmering Lake. It is one of the most beautiful lakes the player has ever seen.
// The player hears a mysterious melody from the water.
// They can either 1. Stay quiet and listen, or 2. Sing along with the melody.
break;
Now, if you start writing std::cout
to begin offering the player this new decision point, Code Suggestions will help fill out the output code.
You might find that the code provided by Code Suggestions is very declarative. Once I've accepted the suggestion, I personalize the code as needed. For example in this case, including the melody the player heard and using the player's name instead of "you":
I also wanted Code Suggestions to offer suggestions in a specific format, so I added an end line:
Now, we'd like to offer our player a nested choice in this scenario. Before we can define the new choices, we need a variable to store this nested choice. Let's define a new variable int nestedChoice
in our main()
function, outside of the switch()
statement we set up. You can put it after our definition of the choice
variable.
// Declare an int variable to capture the user's choice
int choice;
// Declare an int variable to capture the user's nested choice
int nestedChoice;
Next, returning to the if/else
statement we were working on in case 3
, we want to prompt the player for their decision and save it in nestedChoice
.
As you can see, Code Suggestions wants to go ahead and handle the user's choice using another switch
statement. I would prefer to use an if/else
statement to handle this decision point.
First, let's add some comments to give context:
// Capture the user's nested choice
std::cin >> nestedChoice;
// If the player chooses 1 and remains silent, they hear whispers of the merfolk below, but nothing happens.
// If the player chooses 2 and sings along, a merfolk surfaces and gifts them a special blue gem as a token of appreciation for their voice.
// Evaluate the user's nestedChoice
Then, start typing if (nestedChoice == 1)
and Code Suggestions will start to offer suggestions:
If you tab to accept them, Code Suggestions will continue to fill out the rest of the nested if/else
statements.
Sometimes, while you're customizing the suggestions that Code Suggestions gives, you may even discover that it would like to make creative suggestions, too!
Here's the code for case 3
for the player's interaction at Shimmering Lake with the nested decision. I've updated some of the narrative dialogue player's name.
// Handle the Shimmering Lake scenario.
case 3:
std::cout << playerName << " arrives at Shimmering Lake. It is one of the most beautiful lakes that" << playerName << " has seen. They hear a mysterious melody from the water. They can either: " << std::endl;
std::cout << "1. Stay quiet and listen" << std::endl;
std::cout << "2. Sing along with the melody" << std::endl;
std::cout << "Please enter your choice: ";
// Capture the user's nested choice
std::cin >> nestedChoice;
// If the player chooses to remain silent
if (nestedChoice == 1)
{
std::cout << "Remaining silent, " << playerName << " hears whispers of the merfolk below, but nothing happens." << std::endl;
}
// If the player chooses to sing along with the melody
else if (nestedChoice == 2)
{
std::cout << "Singing along, a merfolk surfaces and gifts " << playerName
<< " a special blue gem as a token of appreciation for their voice."
<< std::endl;
}
break;
Our player isn't limited to just exploring Shimmering Lake. There's a whole realm to explore and they might want to go back and explore other locations.
To facilitate this, we can use a while
loop. A loop is a type of conditional that allows a specific section of code to be executed multiple times based on a condition. For the condition
that allows our while
loop to run multiple times, let's use a boolean
to initialize the loop condition.
// Initialize a flag to control the loop and signify the player's intent to explore.
bool exploring = true;
// As long as the player wishes to keep exploring, this loop will run.
while(exploring) {
// wrap the code for switch(choice)
}
We also need to move our location prompt inside the while
loop so that the player can visit more than one location at the time.
// Initialize a flag to control the loop and signify the player's intent to explore.
bool exploring = true;
// As long as the player wishes to keep exploring, this loop will run.
while(exploring) {
// If still exploring, ask the player where they want to go next
std::cout << "Where will " << playerName << " go next?" << std::endl;
std::cout << "1. Moonlight Markets" << std::endl;
std::cout << "2. Grand Library" << std::endl;
std::cout << "3. Shimmering Lake" << std::endl;
std::cout << "Please enter your choice: ";
// Update value of choice
std::cin >> choice;
// Respond based on the player's main choice
switch(choice) {
Our while
loop will keep running as long as exploring
is true
, so we need a way for the player to have the option to exit the game. Let's add a case 4 that allows the player to exit by setting exploring = false
. This will exit the loop and take the player back to the original choices.
// Option to exit the game
case 4:
exploring = false;
break;
Async exercise: Give the player the option to exit the game instead of exploring a new decision.
We also need to update the error handling for invalid inputs in the switch
statement. You can decide whether to end the program or use the continue
statement to start a new loop iteration.
default:
std::cout << "You did not enter a valid choice." << std::endl;
continue; // Errors continue with the next loop iteration
Using I/O and conditionals is at the core of text-based adventure games and helps make these games interactive. We can combine user input, display output, and implement our narrative into decision-making logic to create an engaging experience.
Here's what our adventure.cpp
looks like now with some comments:
#include <iostream> // Include the I/O stream library for input and output
// Main function, the starting point of the program
int main()
{
std::cout << "Welcome to the Dragon Realm!" << std::endl;
// Declare a string variable to store the player name
std::string playerName;
// Prompt the user to enter their player name
std::cout << "Please enter your name: ";
std::cin >> playerName;
// Display a personalized welcome message to the player with their name
std::cout << "Welcome " << playerName << " to The Dragon Realm!" << std::endl;
// Declare an int variable to capture the user's choice
int choice;
// Declare an int variable to capture the user's nested choice
int nestedChoice;
// Initialize a flag to control the loop and signify the player's intent to explore.
bool exploring = true;
// As long as the player wishes to keep exploring, this loop will run.
while(exploring) {
// If still exploring, ask the player where they want to go next
std::cout << "Where will " << playerName << " go next?" << std::endl;
std::cout << "1. Moonlight Markets" << std::endl;
std::cout << "2. Grand Library" << std::endl;
std::cout << "3. Shimmering Lake" << std::endl;
std::cout << "Please enter your choice: ";
// Update value of choice
std::cin >> choice;
// Respond based on the player's main choice
switch(choice) {
// Handle the Moonlight Markets scenario
case 1:
std::cout << "You chose Moonlight Markets." << std::endl;
break;
// Handle the Grand Library scenario.
case 2:
std::cout << "You chose Grand Library." << std::endl;
break;
// Handle the Shimmering Lake scenario.
case 3:
std::cout << playerName << " arrives at Shimmering Lake. It is one of the most beautiful lakes that" << playerName << " has seen. They hear a mysterious melody from the water. They can either: " << std::endl;
std::cout << "1. Stay quiet and listen" << std::endl;
std::cout << "2. Sing along with the melody" << std::endl;
std::cout << "Please enter your choice: ";
// Capture the user's nested choice
std::cin >> nestedChoice;
// If the player chooses to remain silent
if (nestedChoice == 1)
{
std::cout << "Remaining silent, " << playerName << " hears whispers of the merfolk below, but nothing happens." << std::endl;
}
// If the player chooses to sing along with the melody
else if (nestedChoice == 2)
{
std::cout << "Singing along, a merfolk surfaces and gifts " << playerName
<< " a special blue gem as a token of appreciation for their voice."
<< std::endl;
}
break;
// Option to exit the game
case 4:
exploring = false;
break;
// If 'choice' is not 1, 2, or 3, this block is executed.
default:
std::cout << "You did not enter a valid choice." << std::endl;
continue; // Errors continue with the next loop iteration
}
}
// Return 0 to indicate successful execution
return 0;
}
Here's what the build output looks like if we run adventure.cpp
and the player heads to the Shimmering Lake.
Structuring the narrative: Characters
Our player can now explore the world. Soon, our player will also be able to meet people and collect objects. Before we can do that, let's organize the things our player can do with creating some structure for the player character.
In C++, a struct
is used to group different data types. It's helpful in creating a group of items that belong together, such as our player's attributes and inventory, into a single unit. struct
objects are defined globally, which means at top the file, before the `main() function.
If you start typing struct Player {
, Code Suggestions will help you out with a sample definition of a player struct.
After accepting this suggestion, you might find that Code Suggestions is eager to define some functions to make this game more fun, such as hunting for treasure.
// Define a structure for a Player in the game.
struct Player{
std::string name; // The name of the player.
int health; // The current health of the player.
int xp; // Experience points gained by the player. Could be used for leveling up or other game mechanics.
};
Giving the player experience points was not in my original plan for this text adventure game, but Code Suggestions makes an interesting suggestion. We could use xp
for leveling up or for other game mechanics as our project grows.
struct Player
provides a blueprint for creating a player and details the attributes that make up a player. To use our player in our code, we must instantiate, or create, an object of the Player
struct within our main()
function. Objects in C++ are instances of structures that contain attributes. In our example, we're working with the Player
struct, which has attributes like name, health, and xp.
As you're creating a Player
object, you might find that Code Suggestions wants to name the player "John."
int main() {
// Create an instance of the Player struct
Player player;
player.health = 100; // Assign a default value for HP
Instead of naming our player "John" for everyone, we'll use the Player
object to set the attribute for name. When we want to interact with or manipulate an attribute of an object, we use the dot operator .
. The dot operator allows us to access specific members of the object. We can set the player's name using the dot operator with player.name
.
Note that we need to replace other mentions of playerName
the variable with player.name
, which allows us to access the player object's name directly.
- Search for all occurrences of the
playerName
variable, and replace it withplayer.name
. - Comment/Remove the unused
std::string playerName
variable after that.
What your adventure.cpp
will look like now:
#include <iostream> // Include the I/O stream library for input and output
// Define a structure for a Player in the game.
struct Player{
std::string name; // The name of the player.
int health; // The current health of the player.
int xp; // Experience points gained by the player. Could be used for leveling up or other game mechanics.
};
// Main function, the starting point of the program
int main()
{
std::cout << "Welcome to the Dragon Realm!" << std::endl;
// Create an instance of the Player struct
Player player;
player.health = 100; // Assign a default value for HP
// Prompt the user to enter their player name
std::cout << "Please enter your name: ";
std::cin >> player.name;
// Display a personalized welcome message to the player with their name
std::cout << "Welcome " << player.name << " to The Dragon Realm!" << std::endl;
// Declare an int variable to capture the user's choice
int choice;
// Declare an int variable to capture the user's nested choice
int nestedChoice;
// Initialize a flag to control the loop and signify the player's intent to explore.
bool exploring = true;
// As long as the player wishes to keep exploring, this loop will run.
while(exploring) {
// If still exploring, ask the player where they want to go next
std::cout << "Where will " << player.name << " go next?" << std::endl;
std::cout << "1. Moonlight Markets" << std::endl;
std::cout << "2. Grand Library" << std::endl;
std::cout << "3. Shimmering Lake" << std::endl;
std::cout << "Please enter your choice: ";
// Update value of choice
std::cin >> choice;
// Respond based on the player's main choice
switch(choice) {
// Handle the Moonlight Markets scenario
case 1:
std::cout << "You chose Moonlight Markets." << std::endl;
break;
// Handle the Grand Library scenario.
case 2:
std::cout << "You chose Grand Library." << std::endl;
break;
// Handle the Shimmering Lake scenario.
case 3:
std::cout << player.name << " arrives at Shimmering Lake. It is one of the most beautiful lakes that" << player.name << " has seen. They hear a mysterious melody from the water. They can either: " << std::endl;
std::cout << "1. Stay quiet and listen" << std::endl;
std::cout << "2. Sing along with the melody" << std::endl;
std::cout << "Please enter your choice: ";
// Capture the user's nested choice
std::cin >> nestedChoice;
// If the player chooses to remain silent
if (nestedChoice == 1)
{
std::cout << "Remaining silent, " << player.name << " hears whispers of the merfolk below, but nothing happens." << std::endl;
}
// If the player chooses to sing along with the melody
else if (nestedChoice == 2)
{
std::cout << "Singing along, a merfolk surfaces and gifts " << player.name
<< " a special blue gem as a token of appreciation for their voice."
<< std::endl;
}
break;
// Option to exit the game
case 4:
exploring = false;
break;
// If 'choice' is not 1, 2, or 3, this block is executed.
default:
std::cout << "You did not enter a valid choice." << std::endl;
continue; // Errors continue with the next loop iteration
}
}
// Return 0 to indicate successful execution
return 0;
}
Structuring the narrative: Items
An essential part of adventure games is a player's inventory - the collection of items they acquire and use during their journey. For example, at Shimmering Lake, the player acquired a blue gem.
Let's update our Player struct
to include an inventory using an array. In C++, an array
is a collection of elements of the same type that can be identified by an index. When creating an array, you need to specify its type and size. Start by adding std::string inventory
to the Player struct
:
You might find that Code Suggestions wants our player to be able to carry some gold, but we don't need that for now. Let's also add int inventoryCount;
to keep track of the number of items in our player's inventory.
// Define a structure for a Player in the game.
struct Player{
std::string name; // The name of the player.
int health; // The current health of the player.
int xp; // Experience points gained by the player. Could be used for leveling up or other game mechanics.
std::string inventory[10]; // An array of strings for the player's inventory.
int inventoryCount = 0; // The number of items in the player's inventory.
};
In our Player struct
, we have defined an array for our inventory that can hold the names of 10 items (type:string, size: 10). As the player progresses through our story, we can assign new items to the inventory array based on the player's actions using the array index.
Sometimes Code Suggestions gets ahead of me and tries to add more complexity to the game by suggesting that we need to create a struct
for some Monsters. Maybe later, Code Suggestions!
Back at the Shimmering Lake, the player received a special blue gem from the merfolk. Let's update the code in case 2
for the Shimmering Lake to add the gem to our player's inventory.
You can start by accessing the player's inventory with player.inventory
and Code Suggestions will help add the gem.
// If the player chooses to sing along with the melody
else if (nestedChoice == 2)
{
std::cout << "Singing along, a merfolk surfaces and gifts " << player.name
<< " a special blue gem as a token of appreciation for their voice."
<< std::endl;
player.inventory[player.inventoryCount] = "Blue Gem";
player.inventoryCount++;
}
player.inventory
: accesses the inventory attribute of the player objectplayer.inventoryCount
: accesses the integer that keeps track of how many items are currently in the player's inventory. This also represents the next available index in our inventory array where an item can be stored.player.inventoryCount++
: increments the value of inventoryCount by 1. This is a post-increment operation. We are adding “Blue Gem” to the next available slot in the inventory array and incrementing the array for the newly added item.
Once we've added something to our player's inventory, we may also want to be able to look at everything in the inventory. We can use a for
loop to iterate over the inventory array and display each item.
In C++, a for
loop allows code to be repeatedly executed a specific number of times. It's different from the while
loop we used earlier because the while
executes its body based on a condition, whereas a for
loop iterates over a sequence or range, usually with a known number of times.
After adding the gem to the player's inventory, let's display all the items it has. Try starting a for loop with for (
to display the player's inventory and Code Suggestions will help you with the syntax.
std::cout << player.name << "'s Inventory:" << std::endl;
// Loop through the player's inventory up to the count of items they have
for (int i = 0; i < player.inventoryCount; i++)
{
// Output the item in the inventory slot
std::cout << "- " << player.inventory[i] << std::endl;
}
A for
loop consists of 3 main parts:
int i = 0
: is the initialization where you set up your loop variable. Here, we start counting from 0.i < player.inventoryCount
: is the condition we're looping on, our loop checks ifi
, the current loop variable, is less than the number of items in our inventory. It will keep going until this is true.i++
: is the iteration. This updates the loop variable each time the loop runs.
To make sure that our loop doesn't encounter an error, let's add some error handling to make sure the inventory is not empty when we try to output it.
std::cout << player.name << "'s Inventory:" << std::endl;
// Loop through the player's inventory up to the count of items they have
for (int i = 0; i < player.inventoryCount; i++)
{
// Check if the inventory slot is not empty.
if (!player.inventory[i].empty())
{
// Output the item in the inventory slot
std::cout << "- " << player.inventory[i] << std::endl;
}
}
With our progress so far, we've successfully established a persistent while
loop for our adventure, handled decisions, crafted a struct
for our player, and implemented a simple inventory system. Now, let's dive into the next scenario, the Grand Library, applying the foundations we've learned.
Async exercise: Add more inventory items found in different locations.
Here's what we have for adventure.cpp
so far:
#include <iostream> // Include the I/O stream library for input and output
// Define a structure for a Player in the game.
struct Player{
std::string name; // The name of the player.
int health; // The current health of the player.
int xp; // Experience points gained by the player. Could be used for leveling up or other game mechanics.
std::string inventory[10]; // An array of strings for the player's inventory.
int inventoryCount = 0;
};
// Main function, the starting point of the program
int main()
{
std::cout << "Welcome to the Dragon Realm!" << std::endl;
// Create an instance of the Player struct
Player player;
player.health = 100; // Assign a default value for HP
// Prompt the user to enter their player name
std::cout << "Please enter your name: ";
std::cin >> player.name;
// Display a personalized welcome message to the player with their name
std::cout << "Welcome " << player.name << " to The Dragon Realm!" << std::endl;
// Declare an int variable to capture the user's choice
int choice;
// Declare an int variable to capture the user's nested choice
int nestedChoice;
// Initialize a flag to control the loop and signify the player's intent to explore.
bool exploring = true;
// As long as the player wishes to keep exploring, this loop will run.
while(exploring) {
// If still exploring, ask the player where they want to go next
std::cout << "--------------------------------------------------------" << std::endl;
std::cout << "Where will " << player.name << " go next?" << std::endl;
std::cout << "1. Moonlight Markets" << std::endl;
std::cout << "2. Grand Library" << std::endl;
std::cout << "3. Shimmering Lake" << std::endl;
std::cout << "Please enter your choice: ";
// Update value of choice
std::cin >> choice;
// Respond based on the player's main choice
switch(choice) {
// Handle the Moonlight Markets scenario
case 1:
std::cout << "You chose Moonlight Markets." << std::endl;
break;
// Handle the Grand Library scenario.
case 2:
std::cout << "You chose Grand Library." << std::endl;
break;
// Handle the Shimmering Lake scenario.
case 3:
std::cout << player.name << " arrives at Shimmering Lake. It is one of the most beautiful lakes that" << player.name << " has seen. They hear a mysterious melody from the water. They can either: " << std::endl;
std::cout << "1. Stay quiet and listen" << std::endl;
std::cout << "2. Sing along with the melody" << std::endl;
std::cout << "Please enter your choice: ";
// Capture the user's nested choice
std::cin >> nestedChoice;
// If the player chooses to remain silent
if (nestedChoice == 1)
{
std::cout << "Remaining silent, " << player.name << " hears whispers of the merfolk below, but nothing happens." << std::endl;
}
// If the player chooses to sing along with the melody
else if (nestedChoice == 2)
{
std::cout << "Singing along, a merfolk surfaces and gifts " << player.name
<< " a special blue gem as a token of appreciation for their voice."
<< std::endl;
player.inventory[player.inventoryCount] = "Blue Gem";
player.inventoryCount++;
std::cout << player.name << "'s Inventory:" << std::endl;
// Loop through the player's inventory up to the count of items they have
for (int i = 0; i < player.inventoryCount; i++)
{
// Check if the inventory slot is not empty.
if (!player.inventory[i].empty())
{
// Output the item in the inventory slot
std::cout << "- " << player.inventory[i] << std::endl;
}
}
}
break;
// Option to exit the game
case 4:
exploring = false;
break;
// If 'choice' is not 1, 2, or 3, this block is executed.
default:
std::cout << "You did not enter a valid choice." << std::endl;
continue; // Errors continue with the next loop iteration
}
}
// Return 0 to indicate successful execution
return 0;
}