在下面的代码中,我找不到错误,导致未考虑计算机的选择。在Nim游戏中考虑了用户的输入,但未减去计算机的碎片。
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
void printInstructions();
int getUserInput(int);
int randomRange(int,int);
int PlayerTurn(int);
int smartCompMove(int);
int dumbCompMove(int);
int main()
{
srand(time(NULL));
int pieceAmount = randomRange(12,24);
char smartCompOrDumb;
printf("Do you want to play a smart computer or a dumb one? Select 'S' or 'D'.");
scanf("%c",&smartCompOrDumb);
bool gameOver = false;
bool playerTurn = true;
printInstructions();
while(pieceAmount > 0 && gameOver == false)
{
if (playerTurn == false)
{
if(pieceAmount <= 4)
{
printf("\nThe Computer has won :P ");
gameOver = true;
exit(0);
}
if (smartCompOrDumb == 's' || smartCompOrDumb == 'S')
{
playerTurn = true;
pieceAmount = smartCompMove(pieceAmount);
printf("%d",pieceAmount);
}
else if (smartCompOrDumb == 'd' || smartCompOrDumb == 'D')
{
playerTurn = true;
pieceAmount = dumbCompMove(pieceAmount);
printf("%d",pieceAmount);
}
}
else
{
if(pieceAmount <= 4)
{
printf("\nYou have won :) ");
gameOver = true;
exit(0);
}
playerTurn = false;
pieceAmount = PlayerTurn(pieceAmount);
printf("%d",pieceAmount);
}
}
return 0;
}
void printInstructions()
{
printf("\nThis game is called Nim and it is thousands of years old.");
printf("\nTake turns picking one to three pieces from a pile and whomever picks the last piece wins.");
printf("\n__________________________________________________________________________________________");
}
int randomRange(int low,int high)
{
return rand()% (high - low) + low;
}
int PlayerTurn(int pieceAmount)
{
pieceAmount = getUserInput(pieceAmount);
return pieceAmount;
}
int getUserInput(int pieceAmount)
{
int userInput = 0;
bool flag = true;
while (flag == true)
{
if (pieceAmount > 4)
{
printf("\nThere are %d pieces remaining.\n",pieceAmount);
printf("\nHow many pieces do you want to select? ");
scanf("%d", &userInput);
if (userInput >= 1 && userInput < 5)
{
pieceAmount = pieceAmount - userInput;
flag = false;
}
else
{
printf("This is not a valid move so try again.");
}
}
}
return pieceAmount;
}
int dumbCompMove(int pieceAmount)
{
int dumbPick = rand() % 3 + 1;
printf("\nComputer will pick from the stack. \n");
pieceAmount = pieceAmount - dumbPick;
printf("\nComputer picked %d pieces. \n", dumbPick );
return pieceAmount;
}
int smartCompMove(int pieceAmount)
{
int smartPick = 1;
printf("\nThe computer will select their pieces. \n");
if (pieceAmount >= 15 && pieceAmount < 24)
{
smartPick = 2;
pieceAmount = pieceAmount - smartPick;
}
else if (pieceAmount >= 10 && pieceAmount < 15)
{
smartPick = 4;
pieceAmount = pieceAmount - smartPick;
}
else if (pieceAmount >= 6 && pieceAmount < 10)
{
smartPick = 1;
pieceAmount = pieceAmount -smartPick;
}
else
pieceAmount = 3;
printf("\nThe computer selected %d pieces. \n",smartPick);
return pieceAmount;
}
我早些时候可以使用此代码,但是我必须以某种方式更改了一些小改动,现在它无法正常运行。我正在使用Cloud9程序来运行它。