Creating a game

#TC1017 #WSQ06

This time we had to create a simple game which basically generates a random number between 1 and 100 and it’s up to the user to try and guess what number the computer came up with. For this I created some if statements inside a do-while loop that keeps checking for an inequality between the random number and the user’s guess.

If the user doesn’t guess correctly, the programm checks whether the number guessed is inferior or superiror to the generated number, and thus informs the user. The code also keeps track of every guess and when guessed correctly displays the user how many tries he made.

wsq06.proof.PNG

This problem has been the most complex so far, since it requieres the implementation of some logic, but the tricky part was finding out how to generate a random number and keen the program running until the user guesses correctly.

I checked online how to generate a random number first, and it turned out you need to include some extra “files” into the code, as well as a specific function to generate te number and keep it between the given range.

For keeping the program running as along as the number isn’t guesses I asked Bauer for help and he instructed me to write an inequality as an argument for the while statement.

Once this was done all that was left was correcting the number of tires that were displayed to the user, since I didn’t count the very first try, so my programm was only showing one try. In the end, I decided to cheat a little and just add a +1 to the number os tries displayed. It works just fine 😛

Source code:

#include <iostream>
#include <cstdlib>
#include <ctime>

using namespace std;

int main (void){

srand (time(NULL)); //truly

numbers
int number = rand() % 99 +1; // % gives the residue: numbers from 0 to 99, the plus 1 is used to make it from 1 to 100
int guess;
int tries;

do
{

cout << “Please enter a number between 1 and 100:” << endl;
cin >> guess;
if (guess < number)
{
cout << guess << ” is too low, try again!” << endl;
cout << endl;
tries++;
}
else if (guess > number)
{
cout << guess << ” is too high, try again!” << endl;
cout << endl;
tries++;
}
else if (number == guess)
{
cout << ” You got it! You tried ” << 1 + tries << ” times.”<< endl; // 1+ gives accurate tries since the very first try has no counter
}
} while (guess != number);

{

}
}

——————–

Photo Credit: <a href=”https://www.flickr.com/photos/8749778@N06/8989251918/”>Eric Kilby</a> via <a href=”http://compfight.com”>Compfight</a&gt; <a href=”https://creativecommons.org/licenses/by-sa/2.0/”>cc</a

CC BY-SA 4.0 Creating a game by diegodamy is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.