我有一个列举一些可能动作的枚举
internal enum Action
{
Stay,
MoveLeft,
MoveRight
}
和一个对象,其中包含有关此操作当前机率的信息
internal class ActionWithPossibility
{
public Action Action { get; }
public int ActionChancePercent { get; }
public ActionWithPossibility(Action action, int actionChancePercent)
{
Action = action;
ActionChancePercent = actionChancePercent;
}
}
机会从0变为100。有机会的动作的集合可能是
List<ActionWithPossibility> actionsWithPossibilities = new List<ActionWithPossibility>() {
new ActionWithPossibility(Action.Stay, 40),
new ActionWithPossibility(Action.MoveLeft, 30),
new ActionWithPossibility(Action.MoveRight, 30)
};
或
List<ActionWithPossibility> actionsWithPossibilities = new List<ActionWithPossibility>() {
new ActionWithPossibility(Action.Stay, 30),
new ActionWithPossibility(Action.MoveLeft, 10),
new ActionWithPossibility(Action.MoveRight, 60)
};
或
List<ActionWithPossibility> actionsWithPossibilities = new List<ActionWithPossibility>() {
new ActionWithPossibility(Action.Stay, 30),
new ActionWithPossibility(Action.MoveLeft, 60),
new ActionWithPossibility(Action.MoveRight, 10)
};
有2件重要的事情:
通过此方法调用随机动作时
public void NextAction(List<ActionWithPossibility> actionsWithPossibilities)
{
int randomNumber = random.Next(0, 100);
// ...
Action targetAction = null; // ?
}
是否有一种方法来计算操作(不使用ifs)?我考虑过这种设置:
我可以总结一下当前行动的前辈,并会得到结果
但是我不知道如何通过代码来计算动作。一些帮助会很棒。
这可能是
的重复项但是正如我之前提到的,可能采取的行动数量是未知的,所以我不能选择三个if语句。也许有一些技巧可以使用一些数学运算来完全避免if语句。
答案 0 :(得分:3)
Expected 2 arguments, but got 1.
答案 1 :(得分:0)
如果您的操作在列表中,并且想要将生成的随机数映射到正确的对象。您可以这样想:
LINQ:
actionsWithPossibilities
.OrderBy(x => x.actionChancePercent) // Sort probabilities in increasing order
.First(y => randomNumber <= y.actionChancePercent)
// Find the correct 'bracket' by checking when the
// random number passes the thresholds.