尼姆游戏-堆叠选择
Nim Game - Stack Selection
我们必须用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.";
}
}
一些类似的东西。
相关文章:
- 分段故障(堆芯转储)矢量
- 为什么会发生堆损坏
- 如何使用默认参数等选择模板专业化
- 释放错误后堆使用
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 函数中堆分配的效果与缺少堆分配的情况
- 选择要调用的构造函数
- C++选择排序算法中的逻辑错误
- QTreeView幻灯片多选后无法使用单击选择
- 在将变量声明为引用时,堆在释放后使用
- 无法获取菜单选择以运行函数.C++
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 在调用FreeLibrary后,释放动态链接到具有相同版本的CRT堆的DLL的内存
- 为什么我在leetcode上收到AddressSanitizer:地址0x602000000058上的堆缓冲区溢出错误
- 在C++中,如何通过几种类型从元组中选择多个元素
- 讨论 - 创建矩阵时的数组与向量的向量 - 什么是最实用的选择
- 对可变参数使用声明.如何选择正确的功能
- 使用堆查找第K个最大元素的时间复杂性
- 选择选举获胜者的程序
- 对于类中动态大小的数组,是否优先选择std::vector而不是堆数组