首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >编写一个Nim游戏

编写一个Nim游戏
EN

Stack Overflow用户
提问于 2014-02-28 02:20:04
回答 1查看 8.9K关注 0票数 0

这个程序的想法是玩一个Nim游戏。我们为堆生成一个随机数。计算机被随机设置为smart,它使用算法从堆中取出,或者在正常模式下随机从堆中取出。谁先走也是随机决定的。所以我做了三个更小的函数,在while循环中调用turn序列,这个循环一直持续到堆栈为1。我测试了它的运行,我只得到了显示计算机是否处于智能模式以及它是谁的输出。在我把更多的精力放在这个程序上之前,我需要知道我哪里出错了。为什么它不工作?

编辑:智能模式的算法是2减1的幂,IE2^4=16-1=15,但我不知道如何用pileSize数学地解决这个问题,所以我只使用了很多if语句。

代码语言:javascript
复制
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;
        }
    }
}
EN

回答 1

Stack Overflow用户

发布于 2014-02-28 05:49:33

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

它创建了一个无限循环。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22077037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档