/* The game of NIM - * a simple program introducing some * fundamental programming concepts. */ #include #include 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 if (num_objects == 2) { // stick a move in for a special case move = 1; } else { 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; }