尼姆游戏 - 堆栈选择

时间:2014-10-09 16:53:14

标签: c++ arrays

我们必须为Uni开发一个Nim in C ++的游戏,我正在努力解决它只是我遇到了一个问题,当玩家选择一个堆栈时,它在数组编号而不是数字上的数字屏幕。我很确定它在某个地方只是一个“-1”但是我无法找到它,在我试图放置“-1”的任何地方它最终都会占用最终的计数器数。

以下代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <string>
#include <iomanip>


char star = '*';
const int HEAPS = 3;
int heaps[HEAPS];
int heapNumber[] = {1,2,3};
int playerHeapChoice;
int playerCounterChoice;

int playerTurn()
{
    std::cout << "Which stack would you like to take counters from?";
    std::cin >> playerHeapChoice;
    std::cout << "How many counters would you like to take from the heap?";
    std::cin >> playerCounterChoice;

    heaps[playerHeapChoice] = heaps[playerHeapChoice] - playerCounterChoice;
    std::cout << "There are " << heaps[playerHeapChoice] << " counters left in this stack.";

    return heaps[playerHeapChoice];
}

int main()
{   
    srand(time(NULL));

    for (int i = 0; i < HEAPS; i++)
    {
        heaps[i] = (rand() % 20) + 1;
    }

    std::cout << "Stack" << std::setw(8) << "  Number" << std::setw(8) << "   Counters" <<     std::endl;
    for (int count = 0; count < HEAPS; count++)
    {
         std::cout << heapNumber[count] << std::setw(8) << heaps[count] << std::setw(8);
         for (int count = 0; count < heaps[count]; count++)
        {
            std::cout << star;
        }
        std::cout << std::endl;
    }

    playerTurn();

    _getch();
    return 0;
}

2 个答案:

答案 0 :(得分:1)

您使用变量名称int count两次。

进入第一个for循环,一个进入第二个循环。我很惊讶编译。但我确信这会引起问题。

for (int count = 0; count < HEAPS; count++)
{
    for (int count = 0; count < heaps[count]; count++)
    {
    }
}

至于你的问题,很难理解这个问题?是你要求玩家从哪个堆栈中获取并且他们输入的数字是获取数组索引而不是具有该数量的实际堆栈?

如果是这样,因为您正在通过他们键入的索引直接访问数组。您需要在数组中找到值。 Psuedo代码:

for(int i = 0; i < heaps[count]; ++count)
{
    if(heaps[i] == playerHeapChoice)
    {
        std::cout << "There are " << heaps[i] << " counters left in this stack.";
    }
}

这些方面的东西。

答案 1 :(得分:1)

请注意,而不是

std::cout << heapNumber[count]

你可以做到

std::cout << (count + 1)

同样,您的部分问题是

heaps[playerHeapChoice]

应该是

heaps[playerHeapChoice - 1]

另外,我强烈建议您在函数内部声明每个变量。将所有变量声明为全局变量是不受欢迎的,因为它可能会在较大的程序中引起严重问题。