1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/* The game of NIM -
 * a simple program introducing some
 * fundamental programming concepts.
 */

#include<iostream>
#include<cstdlib>

using namespace std;

int main() {     // main() starts the actual program

    // ------------------ Variable declarations ------------------------

    int num_objects = 23;
    int current_player = 1;
    int move;

    // ------------- Beginning of the main game loop -------------------

    do {			       // main game loop

        if (current_player == 1) {     // human player's move
 
            cout << "Player \"1\" enter your move (1-3): ";
            cin >> move;

                    // AND operator is &&, OR operator is this ||
            while (move < 1 || move > 3 || move > num_objects) {
                cout << "Illegal move. \nEnter a new move: ";
                cin >> move;
            }            // end of the WHILE loop
        } 		 // end of the IF statement (user's move)

	else { 		// computer's move

            do { 	// loop to make sure move is legal
                move = 1 + rand() % 3; // random computer move
            } while (move < 1 || move > 3 || move > num_objects);

            cout << "Computer removed " << move << endl;
        }		// end of the ELSE clause (computer's move)

        num_objects = num_objects - move; // implement the move
        cout << num_objects << " objects remaining.\n";
        current_player = (current_player + 1) % 2; // switch players

    } while (num_objects > 0);   	// end of the DO main game loop

    // -------------- end of the game loop -----------------------------

    cout << "Player " << current_player << " wins!!!\n";
    cin.ignore();
    cout << "\nPress enter to quit.\n";
    cin.ignore();
    return 0;

}