Nim
Nim is a two-player game in which players take turns removing objects from distinct heaps. On each turn, a player must remove at least one object. The player who take the last object loses.
#include <iostream>
using namespace std;
int computer(int max, int numMatches);
int human(int max, int numMatches);
int main ()
{
int numbMatches(0), maxMatches(0), temp(0);
cout << “Number of matches:”;
cin >> numbMatches;
cout << “Maximum matches to take:”;
cin >> maxMatches;
if( 2 == (rand() % 2 + 1) ){
cout << “Your turn to start. “;
temp = human(maxMatches, numbMatches);
numbMatches -= temp;
cout << “Matches left: ” << numbMatches <<”\n”;
if(numbMatches == 0 ){
cout << ” You lose, I win
“;
}
}else{
cout << “My turn to start. “;
}
while(numbMatches > 0 ){
temp = computer(maxMatches, numbMatches);
cout << “I take ” << temp << ” matches.”;
numbMatches -= temp;
cout << ” Matches left: ” << numbMatches <<”\n”;
if(numbMatches == 0 ){
cout << “I lose, you win”<<”\n”;
break;
}
temp = human(maxMatches, numbMatches);
numbMatches -= temp;
cout << “Matches left: ” << numbMatches <<”\n”;
if(numbMatches == 0 ){
cout << “You lose, I win
” <<”\n”;
}
}
return 0;
}
int computer(int max, int numMatches){
int temp = numMatches;
if(numMatches - max > 1){
while( temp % (max +1) != 0){
temp–;
}
temp = numMatches - temp-1;
}else{
temp= numMatches -1;
}
if(temp < 1){
return 1;
}
return temp;
}
int human(int max, int numMatches){
int temp(0);
cout << “Your turn: “;
cin >> temp;
while( temp > max || numMatches -temp < 0 || temp <= 0){
cout << “The number has to be less then ” << max << “.” “\n”;
cout << “Your turn: “;
cin >> temp;
}
return temp;
}
0 Responses to “Nim”
Leave a Response