c++ - 使用随机数生成器选择数组值
问题描述
它是一个基于文本的垄断游戏,我需要骰子从数组中选择数字,就像在棋盘上一样。我有数字生成器,但我需要做的是,当值出现时,它会在数组上加上它以获得匹配的数字,例如,如果玩家掷出 6,则 6 + 数组 0 = 数组值 6 这将是街道的名称,但这意味着玩家知道他们在组成的棋盘上的哪个位置。这是我用来尝试这样做的编码,但我一直在获取 006ff65。我怎样才能得到它来显示数字,因为稍后将添加名称。
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
解决方案
很基本。你要么打错了几个字,要么需要学习数组是如何工作的(以及程序流程和子例程,但也许这是为了以后的课程。)
首先,您将数组查找的结果分配回您的随机数:rnum = values[rnum];
这没什么大不了的,除非您稍后使用该变量并且它不再包含您可能认为的内容。它实际上包含您正在寻找的价值!
其次,变量values是指向数组头部的指针,因此您将使用这一行输出 values 数组的地址:这里根本没有发生数组查找。奇怪的是,您错过了这一点,因为您在之前替换随机数值时确实正确引用了数组内容。cout << "# You move to grid "<< values << endl;
推荐阅读
- python - 使用 Django 用户模型自定义登录
- typescript - 如何编写模拟Gaxios错误的类?
- c# - OBD2 模拟器:无法发送 AT 命令
- php - 致命错误:未捕获错误:在初始化之前不得访问类型化属性
- java - 如何独立于布局文件 colorPrimary 更改按钮颜色?
- c# - 如何模拟由多个类实现单个接口的对象
- javascript - 在随机歌曲结束时,用另一首重新开始
- python - 如何修复conda环境中的pip安装错误权限被拒绝
- javascript - React Native,更改按钮颜色并呈现不同的文本
- r - 在 R 中第一次出现连字符或下划线之前删除字符串中的单词