while (p3.Alive || p2.Alive)
{
Random rnd = new Random();
int victim = rnd.Next(1, 3);
switch (victim)
{
case 1:
p1.Attack(p2, 2);
break;
case 2:
p1.Attack(p3, 2);
break;
}
Thread.Sleep(2000);
}
p2和p3以及Person类的对象。他们将被凶手p1随机杀死。但是,当我看着它时,我觉得可能会有更好的解决方案,因为如果我准备杀死1000个类Person的对象怎么办?我只是似乎无法让p2和p3成为易于编程的变量。
while循环是相同的。如果我有1000个对象怎么办。甚至只有10个。我该如何写成这样的条件:“除了杀手之外,还有其他人还活着”,以及攻击随机rnd选择的任何人的“如果”或“开关”?
该问题在主题中写得不好。我不知道如何将所有这些总结为一个简短的问题。如果有人有好的建议,我将对其进行编辑。谢谢。
答案 0 :(得分:3)
这似乎本质上是一次掷硬币,有2个结果。可以使用“条件”运算符对2个结果进行建模:
var target = rnd.Next(0,2) == 0 ? p2 : p3;
pi.Attack(target);
对于较大的组,将可能的目标放在列表或数组中可能会很有用;那么您基本上可以做到:
var target = list[rnd.Next(list.Count)];
或者在C#8中,“开关表达式”可能会有用:
var target = rnd.Next(4) switch (
case 0: p1,
case 1: p2,
case 2: p3,
case 3: p4,
case _: default
);
答案 1 :(得分:3)
解决所有问题:
using System.Collections.Generic; // provides the List type
Random rnd = new Random();
var opponents = new List<Player> { p2, p3 }; // add more as needed
while (true)
{
opponents.RemoveAll(x => !x.Alive); // only keep live enemies (efficient: does not create new List)
if (opponents.Count == 0) // if nobody left --> exit loop
break;
int victim = rnd.Next(0, opponents.Count);
p1.Attack(opponents[victim]);
Thread.Sleep(2000);
}