尼姆游戏-堆叠选择

Nim Game - Stack Selection

本文关键字:选择 -堆 游戏      更新时间:2023-10-16

我们必须用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]

此外,我强烈建议您在使用变量的函数中声明每个变量。将所有变量声明为全局变量是不可取的,因为这可能会在大型程序中引发严重问题。

您使用了两次变量名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.";
    }
}

一些类似的东西。