如何随机化两个函数的结果

时间:2017-09-18 23:50:11

标签: c#

我正在创建战舰控制台应用程序。 我希望系统随机选择重击或轻微攻击,这样玩家就有机会获胜,系统也是如此。这是我的代码。

玩家和敌人的健康都被设置为' 30'

 public void eHeavyAttack()
    {
        Console.Clear();
        Random r = new Random();
        int rInt = r.Next(1, 7);
        Player_Health = Player_Health - rInt;
        Console.WriteLine("The enemy has dealt " + rInt + " damage!");
        Console.WriteLine("Your health is now at " + Player_Health + " health!");
        Console.ReadKey();
    }

    public void eMinorAttack()
    {
        Console.Clear();
        Random r = new Random();
        int rInt = r.Next(0, 4);
        Player_Health = Player_Health - rInt;
        Console.WriteLine("The enemy has dealt " + rInt + " damage!");
        Console.WriteLine("Your health is now at " + Player_Health + " health!");

    }

1 个答案:

答案 0 :(得分:3)

您可以使用Random类。

首先,创建并初始化一个实例:

Random rnd = new Random();

然后根据对Next的调用:

调用两种方法之一
if (rnd.Next(2) == 1) {
    eMinorAttack();
} else {
    eHeavyAttack();
}

如果要将概率倾向两种攻击类型中的一种,请生成一个更大的随机数,并以所需的百分比概率检查某个边界。例如,如果您希望大约五分之二的攻击很重,请按以下步骤更改上述代码:

if (rnd.Next(5) < 3) {
    eMinorAttack();
} else {
    eHeavyAttack();
}