0

I am creating a text-based game in C++. I am wondering, however, if there is a way to randomize a a response from a set amount of responses.

Say I had a question, and the player answered incorrectly, I want the game to reply with a set response with something along the lines of "Sorry, that is invalid".

However, this does not add much personality to the game, and because the computer in this case is an AI in this particular game, when you type something wrong I am going to have the computer say 'I do not understand', 'What are you talking about', and a few other responses.

Now my question is, how can I make it randomly select a reply out of those responses I have?

Halcyonixus
  • 103
  • 5
  • `char* getResponce(){return responceTable[rand()*numresponces];}` – ratchet freak Feb 19 '14 at 14:03
  • 1
    @ratchetfreak rand() yields a number between (inclusive) `0` and `RAND_MAX` and thus your code is almost universally invoking undefined behaviour. – Lars Viklund Feb 19 '14 at 14:26
  • @LarsViklund oops replace the `*` with `%` then :) – ratchet freak Feb 19 '14 at 14:29
  • Using `rand()` is generally not a good idea if you can help it, as depending on how many choices you have, the output will be unfairly weighted. – icabod Feb 19 '14 at 15:00
  • Unrelated note: Make sure that the error messages are clearly given for the same reason. Giving different responses for one action can be confusing (in my opinion.) Feedback is everything in a text-based game. –  Feb 19 '14 at 15:36

2 Answers2

2

Given an array of responses:

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

You can use <random>, here's setting up your random generator:

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

and somewhere in your code:

if(badresponse)
{
    int index = distributor(generator);
    std::cout << responses[index];
}
1

Here's another example, using srand with the current time as the seed:

#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;
}

Note: the quality of random numbers generated by 'rand' isn't as good as some other random number generators, but for such a simple example its probably OK.

RKG
  • 150
  • 2
  • 8