【发布时间】:2021-01-11 05:06:06
【问题描述】:
我正在创建一个基于文本的游戏,并且在游戏中当敌人击中你时,造成的伤害量是随机生成的,但是,在 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
【问题讨论】:
-
at是静态的,只初始化一次 -
注意
Random是静态的是正确的 -
我意识到并改变了它。我会编辑帖子