我正在制作一个具有主类、战斗类、怪物类、玩家类等的 Java 游戏……我在主类框架上显示了统计信息。按下按钮会创建一个新的战斗框架,其中还会显示统计数据。战斗结束后,统计数据有所不同(例如,玩家的生命值低于被怪物击中前的值)。我需要这些统计数据的变化在战斗框架消失后反映在主框架上。
告诉主要班级战斗结束并刷新统计数据的最佳方式是什么?代码如下。显然,这是一项正在进行的工作,还有一些其他不相关的类。
开始战斗的主类的一部分(即,创建一个新的战斗对象,它是一个 JFrame):
public class DarkWorld extends JFrame implements ActionListener
{
...
public DarkWorld()
{
...
public void createInfoLabel()
{
infoLabel.setText("<html>Player: " + DarkWorld.user.getPlayerName()
+ "<br>Health: " + DarkWorld.user.getHealth()
+ "<br>Attack Damage: " + DarkWorld.user.getAttackDamage()
+ "<br>Level: " + DarkWorld.user.getLevel()
+ "<br>Experience: " + DarkWorld.user.getExperience());
}
...
if(source == monsterButton)
{
BattleFrame battle = new BattleFrame();
final int WIDTH = 700;
final int HEIGHT = 500;
battle.setSize(WIDTH, HEIGHT);
battle.setVisible(true);
}
...
}
战斗课的部分:
...
public class BattleFrame extends JFrame implements ActionListener
{
Monster newMonster = new Monster();
...
public BattleFrame()
...
public void displayStats()
{
monsterLabel.setText("<html>Type: " + newMonster.getMonsterName()
+ "<br>Health: " + newMonster.getHealth()
+ "<br>Attack: " + newMonster.getAttackName()
+ "<br>Attack Damage: " + newMonster.getAttackDamage());
playerLabel.setText("<html>Player: " + DarkWorld.user.getPlayerName()
+ "<br>Health: " + DarkWorld.user.getHealth()
+ "<br>Attack Damage: " + DarkWorld.user.getAttackDamage()
+ "<br>Level: " + DarkWorld.user.getLevel()
+ "<br>Experience: " + DarkWorld.user.getExperience());
}
...
if(newMonster.getHealth() <= 0)
{
...
JOptionPane.showMessageDialog(null, "You killed the monster! You found a " + newItem.getItemName()
+ ". It has been added to your inventory.");
dispose();
}
if(DarkWorld.user.getHealth() <= 0)
{
//if player dies (health reaches zero), the game is over - need to make game end
displayStats();
JOptionPane.showMessageDialog(null, "The monster killed you!");
dispose();
}
}
...
}
编辑:试图在这里简化代码,以便更清楚我在问什么。