I am working on an assignment in which I wrote the function tortoisePick(int )and need to find a way to be able to have the player chose if they want to go first. The computer is the tortoise and should pick a number (if I wrote the function correctly. How would I go about selecting a person? Please just hints, I would really like to figure this out on my own.
#include <iostream>
usingnamespace::std;
int tortoisePick(int numberOfEggs);
// Use of a flag to control the game
// The program plays the role of the "Judge" for the game
// - program asks for a valid selection
// - program determines if the game is over
// - program declares the winner (last one to take eggs)
void main()
{
bool gameOver = false; // flag
int numberEggs = 13;
int player = 1; // 1 for Tortoise , 2 for Hare
int selected;
while( !gameOver )
{
cout << "Number of eggs remaining is " << numberEggs << endl;
cout << "Enter your selection (1, 2 or 3) "
<< (player==1 ? "Tortoise":"Hare") << " ";
cin >> selected;
// If move is legal: 1 to 3 eggs and no more than numEggs remaining
if ( selected >=1 && selected <= 3 && selected <= numberEggs ) // student supplies code
{
// adjust numberEggs // student supplies code
numberEggs -=selected;
if ( numberEggs > 0) // student supplies code
{
// change players // student supplies code
player= (player==1) ? 2 : 1;
}
else
{
gameOver = true;
}
}
else // not a valid selection
{
cout <<"Not a valid egg selection, try again\n";
}
} // end while
//declare the winner (Tortoise or Hare) // student supplies code
cout<< "The Winner: "<< ( player==1 ? "tortoise" : "hare") << endl;
return;
} // end main
int tortoisePick(int numberOfEggs)
{
int result;
if( (numberOfEggs %4) !=0 )
result = (numberOfEggs%4);
else
result = 1;
return result;
}
fluppe,
Finally got it! For some reason I had a hard time visualizing where the function needed to be called. On line 11, where I switch players, is there a better way to have player 1 and 2 switch? Or is this the most efficient?
Thanks again!
void main()
{
bool gameOver = false; // flag
int numberEggs = 13;
int player = 0; // 1 for Tortoise , 2 for Hare
int selected;
cout << "Would you like to go first or second? " << endl;
cin >> player;
if (player==1)
player = 2;
else
player = 1;
while( !gameOver )
{
cout << "Number of eggs remaining is " << numberEggs << endl;
if (player == 2){
cout << "Enter your selection (1, 2 or 3) "
<< (player==1 ? "Tortoise":"Hare") << " ";
cin >> selected;
}
else{
selected = tortoisePick(numberEggs);
cout << "The computer picked: " << selected << endl;
}