0

我正在用 C++ 创建一个基于文本的游戏。但是,我想知道是否有办法从一组响应中随机化一个响应。

假设我有一个问题,而玩家回答不正确,我希望游戏以类似于“对不起,那是无效的”的方式回复。

然而,这并没有给游戏增加太多个性,因为在这种情况下,计算机是这个特定游戏中的人工智能,当你输入错误时,我会让计算机说“我不明白”,“什么是你在谈论',以及其他一些回应。

现在我的问题是,我怎样才能让它从我拥有的那些回复中随机选择一个回复?

4

2 回答 2

2

给定一系列响应:

int numResponses = 10;
std::string[] responses = { // fill responses }

你可以使用<random>,这里设置你的随机生成器:

std::random_device device;
std::mt19937 generator(device());
std::uniform_int_distribution<> distributor(0, numResponses - 1);

在您的代码中的某处:

if(badresponse)
{
    int index = distributor(generator);
    std::cout << responses[index];
}
于 2014-02-19T14:17:30.413 回答
1

这是另一个示例,使用 srand 和当前时间作为种子:

#include <cstdlib>
#include <iostream>
#include <ctime>
#include <string>
#include <vector>

using namespace std;

int main()
{
   // Use c++11 initializer list for vector
   vector<string> responses{"Response A", "Response B", "Response C"};

   // use current time as random seed
   srand(time(0));

   int r = rand() % responses.size();
   cout << responses[r] << endl;
}

注意:'rand' 生成的随机数的质量不如其他一些随机数生成器,但对于这样一个简单的示例,它可能还可以。

于 2014-02-19T15:33:23.863 回答