c++ - Nim 游戏 - 堆栈选择

标签 c++ arrays

我们必须在 C++ 中为 Uni 开发一个 Nim 游戏,我正在很好地完成它,只是我遇到了一个问题,当玩家选择一个堆栈时,它以数组数字而不是数字屏幕。我很确定它只是某个地方的“-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;
}

最佳答案

注意不是

std::cout << heapNumber[count]

你可以做到

std::cout << (count + 1)

同样,您的部分问题在于

heaps[playerHeapChoice]

应该是

heaps[playerHeapChoice - 1]

此外,我强烈建议您在使用变量的函数内声明每个变量。将所有变量声明为全局变量是不受欢迎的,因为它会在较大的程序中导致严重的问题。

关于c++ - Nim 游戏 - 堆栈选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26283892/

相关文章:

c++ - 是否可以隐藏具有 boost 范围的底层容器?

c++ - 在一个声明语句中定义一个函数和一个变量

c++ - 如何创建具有电视效果的图像?

c++ - 如何通过id获取线程对象?

c - 在 C 中使用数组计算分数

javascript - 如何使用变量引用对象

c++ - 在没有地址的函数中使用指针

php - 如何在 PostgreSQL array_append() 中使用数组变量?

javascript - IE 7 和 8 在使用 indexOf 和数组时遇到问题

python - 如何将列表 [a, b, c] 转换为 python slice index[ :a, :b :c]?