這個程序的想法是玩一個Nim遊戲。我們爲這個堆產生一個隨機數。計算機隨機設置爲智能,使用算法從堆中取出,或從隨機取出的正常模式中取出。誰先走了也是隨機決定的。所以我做了三個更小的函數,它們在一個while循環中調用轉向序列,直到我們的棧處於1爲止。我測試了它的運行情況,並且我只獲得顯示計算機是否處於智能模式的輸出,是。在我加入這個計劃之前,我需要知道我出錯的地方。爲什麼它不起作用?編程一個Nim遊戲
編輯:智能模式的算法是2減1的冪,IE 2^4 = 16-1 = 15,但是我不知道如何用pileSize數學地工作,所以我只用了很多的if語句。
void Nim();
int PlayerTurn(int);
int ComputerTurn(int);
int SmartComputer(int);
int main()
{
srand(time(NULL));
Nim();
return 0;
}
int PlayerTurn(int pileSize)
{
int userInput = 0;
bool flag = true;
while(flag == true)
{
cout << "There are " << pileSize << " in the pile" << endl;
cout << "How many do you want to take? ";
cin >> userInput;
if (userInput > 1 && userInput < (pileSize/2))
{
pileSize = pileSize - userInput;
flag = false;
}
else
{
cout << "Error, that's not a valid move." << endl;
}
}
return pileSize;
}
int ComputerTurn(int pileSize)
{
cout << "The computer will take from the pile. " << endl;
pileSize = pileSize - rand() % (pileSize/2);
return pileSize;
}
int SmartComputer(int pileSize)
{
cout << "The computer will take from the pile. " << endl;
if (pileSize>63)
{
pileSize = 63;
}
else if (pileSize>31&&pileSize<63)
{
pileSize = 31;
}
else if (pileSize>15&&pileSize<31)
{
pileSize = 15;
}
else if (pileSize>7&&pileSize<15)
{
pileSize = 7;
}
else if (pileSize>3&&pileSize<7)
{
pileSize = 3;
}
else
{
pileSize = pileSize - rand() % (pileSize/2);
}
return pileSize;
}
void Nim()
{
int pileSize = rand()% (100-10) + 10;
bool smartOrStupid = rand() % 2;
if (smartOrStupid == true)
{
cout << "The computer is in smart mode." << endl;
}
bool turn = rand() % 2;
if (turn = true)
{
cout << "The computer will got first. " << endl;
}
else
{
cout << "The player will go first. " << endl;
}
while(pileSize!=1);
{
if (turn = true)
{
if (smartOrStupid = true)
{
pileSize = SmartComputer(pileSize);
cout << pileSize;
}
else
{
pileSize = ComputerTurn(pileSize);
cout << pileSize;
}
}
else
{
pileSize = PlayerTurn(pileSize);
cout << pileSize;
}
}
}
我注意到的一件事是'if(turn = true)'應該是'if(turn == true)'。這就是爲什麼我總是把常數放在左邊。 –
啊,是的。我總是犯這樣的愚蠢錯誤。謝謝。我仍然錯過了前兩個輸出之外的任何東西,但我會繼續尋找。 – Santa
另外,在'while(pileSize!= 1);' –