相同的随机生成的整数在 c# 中的 while 循环中重复

时间:2021-01-10 15:53:24

标签: c# random

我正在创建一个基于文本的游戏,在游戏中,当敌人击中你时,造成的伤害量是随机生成的,但是,在 while 循环中,它会重复生成的数字。

预期结果

Okay, lets fight him!
The monster has a health of 25! What do you wish to do?
[Press 0 to attack.]
0
The monster's health went down by 2. Their health is now 23
The monster attacks! Your health went down by 9. Your health is now 41
The monster has a health of 23! What do you wish to do?
[Press 0 to attack.]
0
The monster's health went down by 2. Their health is now 21
The monster attacks! Your health went down by 10. Your health is now 31
The monster has a health of 21! What do you wish to do?
[Press 0 to attack.]

输出

Okay, lets fight him!
The monster has a health of 25! What do you wish to do?
[Press 0 to attack.]
0
The monster's health went down by 2. Their health is now 23
The monster attacks! Your health went down by 3. Your health is now 47
The monster has a health of 23! What do you wish to do?
[Press 0 to attack.]
0
The monster's health went down by 2. Their health is now 21
The monster attacks! Your health went down by 3. Your health is now 44
The monster has a health of 21! What do you wish to do?
[Press 0 to attack.]

你可以看到在输出中敌人造成的伤害量是重复的。为什么会这样,我该如何解决?

代码:

using System;
using Game;

public class Zero
{
    public static void G1()
    {

        while (Player.HP > 0&&Enemy.h > 0)
        {
            Console.WriteLine($"The monster has a health of {Enemy.h}! What do you wish to do?");
            Console.WriteLine("[Press 0 to attack.]");
            string read_action = Console.ReadLine();
            if (read_action == "0")
            {
                Enemy.h = Enemy.h - Player.At;
                Player.HP = Player.HP - Enemy.at;
                Console.WriteLine($"The monster's health went down by {Player.At}. Their health is now {Enemy.h}");
                Console.WriteLine($"The monster attacks! Your health went down by {Enemy.at}. Your health is now {Player.HP}");

            }
        }



    }
}

另一个文件中的变量:

 public static Random numGen = new Random();
 public static int at = numGen.Next(1, 11); //this is the enemy's attack function

2 个答案:

答案 0 :(得分:4)

静态“at”变量只计算一次,这意味着它被分配了一次随机值,然后再也不会改变。

您能否提供有关此变量所在位置的更多上下文?您可能希望将其移动到另一个类中,并且不使用静态变量,而是使用计算属性。

编辑:

根据您的说明,我认为您可以在实际的 Enemy 类中使​​用方法或计算属性。这里有一个计算属性的例子:

public class Enemy {
   Random numGen = new Random();
   int minAttack = 1;
   int maxAttack = 11;

   public int Attack => numGen.Next(minAttack, maxAttack);
}

每次访问都会重新评估敌方实例的 Attack 属性。

答案 1 :(得分:1)

at 变量正在使用 .Next(1, 11) 函数的返回值进行初始化,因此如果它返回 8,它将存储值 8 并保留该值。

您可以去掉 at 变量并使用此行直接从 numGen 变量中获取随机数。

Player.HP = Player.HP - Enemy.numGen.Next(1, 11);

或者您可以编写一个函数来处理获取新的攻击值并将其存储在 at 变量中,例如:

public int GetEnemyAttack()
{
    at = numGen.Next(1, 11);
    return at;
}

然后从计算玩家新HP的那一行调用它

Player.HP = Player.HP - Enemy.GetEnemyAttack();
相关问题