Text Adventure: Lesson 1
Setting up, using scanf & writing our first game loop
Resources:
The code for this episode.
Some common locations for the vcvarsall.bat file you need to run in order to run the compiler from the command line.
Some more info on printf
Welcome our first real project & our first game! Let's dive straight in. We're going to start by adding our main entry point to our program. As we know it looks like this:
}
This is where our program starts running. We then use the printf function to output our first prompt to the user:
As you can see, we're adding the newline character '\n' at the end, so the text looks nicer. The next function we are going to use is the scanf function. This is the opposite of printf, instead of outputting text to the command line, it's going to read in text from the command line. This allows us to read in what the user wants to do. This might be: 'take potion', 'attack wolf' or 'quit'. In order to use the scanf function we need to pass in a char array to be filled in. Remember, char arrays are the equavilant of Strings in C. Just a list of characters. So we create an array of characters on the stack that will store our user's response.
Note since we are declaring it on the stack, we don't have to allocate it. Now that we have it, we can pass it to scanf to fill out.
Now when scanf is hit in the code. It will pause the program and allow the user to type in their response. Once they do & press ENTER, the program will carry on. We can even see what the user wrote by printing out the array to the command line.
printf("%s\n", userResponse);
Quick Quiz:
What is the function we used to print text in the command prompt & what header file did we have to #include to use it? Click to see
The function is printf, and the header file we had to #include was
What is the function we used to get input from the user?Click to see
scanf
What header file did we have to #include to use the boolean data type (written as bool in C & C++)?Click to see
What was the while loop we used to keep the program going commonly called?Click to see
The game loop.
How do you know when you reach the end of a string in the C language?Click to see
You reach the null terminating character '\0'
What did we have to watch out for when writing our string match function?Click to see
That two words could start the same, but be different lengths. For example: "quit" & "quita" are the same for the length of the first word, but our function should return false since they aren't the same.