我正在制作一个WP7应用程序,当用户点击图像时,会随机决定他们会得到什么。
现在,我有这个代码:
string firstdoor = "";
string seconddoor = "";
string thirddoor = "";
和
string prize1 = "vacation to Hawaii with all expenses covered";
string prize2 = "used glue stick";
string prize3 = "pile of dog dung";
string prize3 = "vacation to Europe with all expenses covered";
string prize3 = "million dollars";
string prize3 = "blank CD";
string prize3 = "temporary tattoo";
string prize3 = "nickel";
string prize3 = "dime";
和
我想要做的是将door
随机分配给prize
。
例如,当用户点按图片时,dime
被分配到thirddoor
,nickel
被分配到第一门,million dollars
被分配给secondoor
。
答案 0 :(得分:6)
这些步骤对我来说似乎最有意义(不会为你编写所有代码):
将所有奖品串放在一个数组中。
在0和最大奖金数之间生成三个随机数。
使用每个随机数从奖品阵列中为每个门分配奖品。
...
利润!
修改强>
实际上,这里有一些代码可以提供帮助:
var randomGenerator = new Random();
string[] prizes = { "vacation to Hawaii with all expenses covered",
"used glue stick",
"pile of dog dung",
"vacation to Europe with all expenses covered" };
string firstDoor = prizes[randomGenerator.Next(prizes.Length)];
string secondDoor = prizes[randomGenerator.Next(prizes.Length)];
string thirdDoor = prizes[randomGenerator.Next(prizes.Length)];
答案 1 :(得分:1)
假设您不想重复任何奖品,解决方案会稍微复杂一些,但您可以带一些Linq和一些随机玩的小技巧:
var prizes = new string[] {
"vacation to Hawaii with all expenses covered",
"used glue stick",
// etc
"dime"
};
var rand = new Random();
var result = (from prize in prizes
orderby rand.NextDouble()
select prize).Take(3).ToArray();
答案 2 :(得分:1)
贾斯汀,你的回答很好,但可能会导致2个门获得相同的奖金。我相信这可能会更好:
string[] prizes = new string[]
{
"Prize 1",
"Prize 2",
"Prize 3",
"Prize 4",
"Prize 5"
};
Random r = new Random();
var choices = prizes.OrderBy(x => r.Next()).Take(3).ToArray();
string firstDoor = choices[0];
string secondDoor = choices[1];
string thirdDoor = choices[2];