Austin Taylor
Austin Taylor

Reputation: 11

Generate random numbers without a specified range. Eg. random of 1, 6, 10, 12

An assignment for class has us recreating "Hunt The Wumpus." After an arrow is shot, I have the option to either leave the Wumpus where it is, or move the Wumpus to the room I am currently in, or to any of the three rooms adjacent to the room I am currently in.

adjacentRooms = new int[,]         
            {
               {1, 4, 7},   {0, 2, 9},   {1, 3, 11},   {2, 4, 13},    {0, 3, 5},
              {4, 6, 14},  {5, 7, 16},    {0, 6, 8},   {7, 9, 17},   {1, 8, 10},
             {9, 11, 18}, {2, 10, 12}, {11, 13, 19},  {3, 12, 14},  {5, 13, 15},
            {14, 16, 19}, {6, 15, 17},  {8, 16, 18}, {10, 17, 19}, {12, 15, 18}

Here is the array I have. For example, say I am in room 0 (index 0), and the wumpus is in room 15 (index 15). I shoot an arrow and miss. The Wumpus now has to move and his options are room 15, room 0, room 1, room 4, room 7. I have been trying random.Next to try and produce a random number between those 5 and have not had any luck. I'm assuming random.Next may not be the way to go. If anyone could give me some hints or help me out I would be extremely grateful!

Upvotes: 0

Views: 95

Answers (2)

Ergwun
Ergwun

Reputation: 12978

To pick a number randomly from a specified set of numbers:

// Prepare a random number generator
var rng = new Random();

// Get the set of options in a list.
var choices = new List<int> { 15, 0, 1, 4, 7 };

// Pick a random index into that list.
// Note that first parameter is inclusive, and second is exclusive.
var randomSelection = rng.Next(0, choices.Count);

// Take the option at that index
var chosen = choices[randomSelection];

Upvotes: 2

Steve Py
Steve Py

Reputation: 35073

The choices for the Wumpus would be an array of 5 elements consisting of: {same}, {mine}, and the 3x adjacent rooms based on where Wumpus is. Your random bounds would be 1-5 (or 0-4) for those above choices where you select the room # in the position of the array of those selections. So if the Wumpus is in Room 3, you are in room 1, and the 2, 4, and 13 you would have a choice of {3, 1, 2, 4, 13} If the Rnd # comes back as "3" (out of 0-4) then the Wumpus would move to Room #4.

Then the question would be what if you were in an adjacent room? For instance if Wumpus is in #3, and you are in #4. Does that mean {3, 4, 2, 4, 13} or do you just pick from 4 rooms. {3, 4, 2, 13} You'll need to structure your logic to one of those two solutions.

With simple random generation, ensure that you only initialize the random sequence once, not with each game loop since it is timer based and you will generate similar picks when run inside a loop. You can read up on better pseudo-random solutions for C# to get more random-like picks.

Upvotes: 3

Related Questions