This could have many applications, such as Enjay mentions here.
Ok, so here's my idea:Enjay wrote:I had a level where the player returned repeatedly to a single point in the map to be given a key by an NPC. There were 6 areas in the map and the access to each was controlled by one of the 6 keys. The areas could be completed in any order so, to mix it up, I wanted the keys to be given in a random order so that the game could play differently each time the player tackled the map. And that's where my difficulty came: I needed the player to be given a different key six times in a single play of the map. The keys needed to be given at random but once a key had been given it should never be given again.
Code: Select all
int list[6] = {1,2,3,4,5,6};
int last = 5; // this will be used later on
Code: Select all
int max = 5; // (size of array - 1)
Code: Select all
int choice;
choice = list[Random(0,max)];
Code: Select all
int temp;
temp = list[choice];
list[choice] = list[last]; // this is where we need the "last" variable.
list[last] = temp; // it represents the last element of the full sized array
max--;
So in this example, the array would now look like this: {1,2,4,5,6,3}
When Random() is called again with Random(0,max), it will have access to {1,2,4,5,6}, thus allowing for another random choice to be made, and making it easy to keep track of the remaining possible values in the list.
The script can be made to continue in this fashion, moving selected numbers to the end of the list and decreasing the upper bound by 1, until all possibilities have been selected.
I hope this helps anyone who has needed a situation like this but had difficulty creating one. May it help you in your future projects.