我们必须在 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/