2014-02-27 98 views
0

这个程序的想法是玩一个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; 
     } 
    } 
} 
+2

我注意到的一件事是'if(turn = true)'应该是'if(turn == true)'。这就是为什么我总是把常数放在左边。 –

+0

啊,是的。我总是犯这样的愚蠢错误。谢谢。我仍然错过了前两个输出之外的任何东西,但我会继续寻找。 – Santa

+0

另外,在'while(pileSize!= 1);' –

回答

1

的问题是这里的分号while(pileSize != 1);

它创建了一个无限循环。

+0

Woot woot,我是Nate的第一张投票!欢迎来到SO! -缺口 –