< Previous | Contents | Next >

Setting Up the Game

As always, I start off with some comments and include the necessary files.

// Guess My Number

// The classic number guessing game


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


using namespace std;

I include cstdlib because I plan to generate a random number. I include ctime

because I want to seed the random number generator with the current time.

Introducing Guess My Number 75


image

Figure 2.15

The game loop applied to Guess My Number.


Next, I start the main() function by picking a random number, setting the number of tries to 0, and establishing a variable for the players guess:

int main()

{

srand(static_cast<unsigned int>(time(0))); //seed random number generator


int secretNumber = rand() % 100 + 1; // random number between 1 and 100 int tries = 0;

int guess;


cout << "\tWelcome to Guess My Number\n\n";

76 Chapter 2 n Truth, Branching, and the Game Loop: Guess My Number