我正在尝试制作一个RPG游戏,我在使用“玩家的健康”更新标签时遇到了一些问题。我有两种形式。第一个叫做“游戏”,它包含以下代码。
private void AttackTroll_Click(object sender, EventArgs e)
{
Game.wizard.DoBattle(troll); // Attacks a troll which has 40 return damage, and player health is 200.
MessageBox.Show(Game.wizard.Health.ToString()); // Shows that player health is now 160 (working fine).
Game newGame = new Game(); // Making a new form to get accses to the label I need (thats the only way I know).
newGame.HealthLabel.Text = Game.wizard.Health.ToString(); // This is suposed to update the label from 200 to 160, BUT IT STAYS AT 200.
newGame.Show(); // Help me, please.
}
该表单创建我的类并使用播放器的名称和运行状况填充名称和健康标签。当我单击按钮Battle时,它会创建一个新形式,我可以在其中与某些生物战斗。这是第二种形式
public class Die
{
private final int MAX = 6; // maximum face value
private int faceValue; // current value showing on the die
//-----------------------------------------------------------------
// Constructor: Sets the initial face value.
//-----------------------------------------------------------------
public Die()
{
faceValue = 1;
}
//-----------------------------------------------------------------
// Rolls the die and returns the result.
//-----------------------------------------------------------------
public int roll()
{
faceValue = (int)(Math.random() * MAX) + 1;
return faceValue;
}
//-----------------------------------------------------------------
// Face value mutator.
//-----------------------------------------------------------------
public void setFaceValue(int value)
{
faceValue = value;
}
//-----------------------------------------------------------------
// Face value accessor.
//-----------------------------------------------------------------
public int getVal()
{
return faceValue;
}
//-----------------------------------------------------------------
// Returns a string representation of this die.
//-----------------------------------------------------------------
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
此按钮攻击有伤害的生物。问题是我需要使用新值更新第一个表单中的“HealthLabel”,但我无法做到。提前谢谢。
答案 0 :(得分:2)
这是一个相当常见的混淆点。您正在实例化与原始Game
实例无关的第二个Game
表单。
相反,请修改您的Battle
表单,以便将Game
表单的引用传递给它:
public class Battle : Form
{
private Form game;
public Battle(Form game)
{
InitializeComponent();
this.game = game;
}
修改您的Game
表格,以便更新标签的方法:
public class Game : Form
{
public void UpdateHealth(string health)
{
HealthLabel.Text = health;
}
现在,您的Battle
类可以使用引用和公共方法,而您无需创建Game
的第二个实例。
game.UpdateHealth(Game.wizard.Health.ToString());