开发者

choosing items based on random numbers

开发者 https://www.devze.com 2023-03-03 23:11 出处:网络
I am working on a small game where prizes are awarded based on a random number.So when a mission is completed and the reward has to be handed out, I want to randomly generate the prize.Currently I am

I am working on a small game where prizes are awarded based on a random number. So when a mission is completed and the reward has to be handed out, I want to randomly generate the prize. Currently I am getting a random number between 1 and 500 and th开发者_如何学Cen using a giant nested if-else statement to assign the prize based on the result. It is obvious to me that this is the wrong way to do this, however I am not sure what other way this may be done.

Any suggestions?


You can just use a prize array to hold your prices, use the random value as index into the array to pick a prize.

var prizes = new Prize[500];
//fill prizes
//randomly select index within prize array

If there are gaps or only a few numbers win anything, use a dictionary mapping from an integer to a prize ( or nothing if they key doesn't exist) instead.


There are many things you could do. For example, you could use an array to store the prizes and use the random number as the index of the array. The prize would then be whatever was stored in the array at that index. You could do the same with a List if you wanted more control.


Use a list where each item has a unique "minimum value" and information about the associated prize. Then find the item on the list that has the highest value, but is still below your random number. Or vice-versa.

The minimum value allows you to give different probabilities to prizes without using a giant array that has an entry for all numbers. The probabilities are defined by the distances of the values between different prizes.


In this example I assume that your prizes are strings (but this works with objects too). Create a list and add all of your prizes to it, in the following way:

//using System.Collections.Generic;
var prices = new List<string>();
//Add all of your prices here
var random = new Random();
var price = prices[random.Next(0,prices.Count)];
0

精彩评论

暂无评论...
验证码 换一张
取 消