Games and More Games
Now that we know how to write functions and generate random numbers, it’s possible to enhance some game programs.
The Subtraction Game example at the end of Chapter 2 can be improved. Right now, when the user plays optimal strategy, the computer responds by choosing 1. We can make this more interesting by randomizing the computer’s response in these situations. The following program makes the necessary changes, putting altered lines in bold:
nim2.cpp
#include <iostream> #include <cmath> #include <ctime> #include <cstdlib> using namespace std; int rand_0toN1(int n); int main() { int total, n; srand(time(NULL)); // Set seed for random numbers. cout << "Welcome to NIM. Pick a starting total: "; cin >> total; while (true) { // Pick best response and print results. if ((total % 3) == 2) { total = total - 2; cout << "I am subtracting 2." << endl; } else if ((total % 3) == 1) { total--; cout << "I am subtracting 1." << endl; } else { n = 1 + rand_0toN1(2); // n = 1 or 2. total = total - n; cout << "I am subtracting "; cout << n << "." << endl; } cout << "New total is " << total << endl; if (total == 0) { cout << "I win!" << endl; break; } // Get user's response; must be 1 or 2. cout << "Enter num to subtract (1 or 2): "; cin >> n; while (n < 1 || n > 2) { cout << "Input must be 1 or 2." << endl; cout << "Re-enter: "; cin >> n; } total = total - n; cout << "New total is " << total << endl; if (total == 0) { cout << "You win!" << endl; break; } } system("PAUSE"); return 0; } int rand_0toN1(int n) { return rand() % n; }
Chapter 2 presented an exercise: Alter this program so that it permits any number from 1 to N to be subtracted each time, where N is set at the beginning. That problem is left as an exercise for this version as well. (You can even prompt the end user for this value before the game starts. As always, the computer should win whenever the user does not play perfect strategy.)
The last full example in Chapter 10 presents a game of Rock, Paper, Scissors that can be programmed even with C++ compilers that are not fully C++0x compliant. To use the example in Chapter 10 (Example 10.3) with weak, rather than strong, enumerations, replace this line in Chapter 10:
enum class Choice { rock, paper, scissors };
with this:
enum Choice { rock, paper, scissors };
Also, remove the using statement:
using namespace Choice;