Game Development Reference
In-Depth Information
It's also good practice to use static _ cast when carrying out conversions to larger types (actually
called widening conversions) to make it clear and obvious to other programmers that we have used
the conversion on purpose and that it is not actually a mistake.
static _ cast is evaluated by the compiler at compile time and will cause a compilation error if we are
trying to convert between incompatible types.
A Simple Guessing Game
We'll use what you have learned about declaring and defining variables and integers to create a
simple guessing game. In the beginning the game will be basic; however, we will add to the game
throughout the remainder of this chapter to make the output more like a game.
For now we will ask the player to input a number and output that number and a random number
selected by the program. Listing 2-1 shows the program written to compile using C++ 4.7.3.
Listing 2-1. A Simple C++ Guessing Game
#include <ctime>
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
int main()
{
// Generate unique random numbers using the current time
srand(time(NULL));
// Get a random number between 0 and 99
unsigned int numberToGuess = rand() % 100;
cout << "Guess a number between 0 and 99" << endl;
unsigned int playersNumber {};
cin >> playersNumber;
cout << "You guessed: "
<< playersNumber
<< " The actual number was: "
<< numberToGuess
<< endl;
return 0;
}
Our guessing game source code begins by including the C++ header files necessary for the features
we use and declares that we will be using the std namespace.
 
Search WWH ::




Custom Search