Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Christian Ballard
- // COSC 1337 - 001
- // August 30th 2015
- // A simple game of NIM
- #include<iostream>
- #include<time.h>
- #include<Windows.h>
- using namespace std;
- const int HUMAN = 1;
- const int COMPUTER = 0;
- int getHumanMove(int);
- int getComputerMove(int);
- int playTheGame(int);
- int main()
- {
- int numMarbles = 0;
- char currentPlayer;
- cout << "Rules of the game: " << endl << endl;
- cout << "1. The game begins with 35 marbles in a jar." << endl;
- cout << "2. Each player must take between 1 and 5 marbles" << endl;
- cout << " from the jar when it's their turn." << endl;
- cout << "3. The player that takes the last marble wins the game." << endl << endl;
- cout << "Do you want to go first? (Y/N) ";
- do
- {
- cin >> currentPlayer;
- currentPlayer = toupper(currentPlayer);
- switch (currentPlayer)
- {
- case 'Y': playTheGame(HUMAN);
- break;
- case 'N': playTheGame(COMPUTER);
- break;
- default: cout << "Error: please enter Y or N." << endl;
- break;
- }
- } while (currentPlayer != 'Y' || currentPlayer != 'N');
- system("pause");
- return 0;
- }
- int getHumanMove(int numMarbles1)
- {
- int humanMarbTaken = 0;
- do
- {
- cout << "How many marbles would you like to take? (1 - 5)" << endl;
- cin >> humanMarbTaken;
- if (humanMarbTaken < 0 || humanMarbTaken > 5)
- {
- cout << "Please try again with a number 1 - 5" << endl;
- }
- } while (humanMarbTaken < 1 || humanMarbTaken > 5);
- return humanMarbTaken;
- }
- int getComputerMove(int numMarbles2)
- {
- int compMarbTaken = 0;
- //int modMarb = numMarbles2 % 6;
- srand((unsigned)time(NULL));
- int min = 0, max = 5;
- if (numMarbles2 <= 5)
- {
- numMarbles2 -= numMarbles2;
- }
- else
- {
- compMarbTaken = rand() % 5 + 1;
- numMarbles2 = numMarbles2 - compMarbTaken;
- }
- cout << "The computer took " << compMarbTaken << " marbles from the jar."
- << endl << endl;
- return compMarbTaken;
- }
- int playTheGame(int player)
- {
- int numMarbles = 35, currentMove = 0;
- while (numMarbles != 0)
- {
- if (player == HUMAN && numMarbles != 0)
- {
- cout << "There are " << numMarbles << " marbles left in the jar." << endl;
- numMarbles -= getHumanMove(numMarbles);
- player = COMPUTER;
- if (numMarbles == 0){
- cout << "Congrats! You won!" << endl;
- }
- }
- else if (player == COMPUTER && numMarbles != 0)
- {
- cout << "There are " << numMarbles << " marbles left in the jar." << endl;
- numMarbles -= getComputerMove(numMarbles);
- player = HUMAN;
- if (numMarbles == 0){
- cout << "Congrats! The computer won!" << endl;
- }
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment