我是Java的新手,已经建立了我的第一个基本角色对战游戏,但我不知道如何扩展它。如果我的目标是练习面向对象和课程,那么您的重点是什么?我很感激任何建议!
我目前最大的问题是当有人点击游戏时,我无法找到简化退出游戏的方法。按钮。我目前已单独编码每个出口,但我希望有任何方法可以随时退出任何' x'被按下了?甚至只是一种更清洁的方式来处理它。
public class GameFile extends JFrame
{
public static void main(String[] args)
{
String name;
int clicked, playAgain = 0;
while (playAgain == 0)
{
name = JOptionPane.showInputDialog("Welcome! What is your name?");
if (name != null)
{
GameCharacter player = new GameCharacter(10, name, CharacterType.PLAYER);
GameCharacter enemy = new GameCharacter(10, "the Evil Wizard", CharacterType.ENEMY);
clicked = JOptionPane.showConfirmDialog(null,
"Hi " + player.getName() + "! Get ready to battle you opponent!", " ",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
if (clicked == 0)
{
do
{
String[] moveChoices = { "Attack", "Use Potion(" + player.getPotions() + ")" };
int choice = JOptionPane.showOptionDialog(null, "What would you like to do?", " ",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE, null, moveChoices,
moveChoices[0]);
if (choice == 0)
{
player.attack(enemy);
if (JOptionPane.showConfirmDialog(null,
"You attacked " + enemy.getName() + "! They have " + enemy.getHealthPoints()
+ " health left.",
" ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != 0)
{
System.exit(0);
}
}
else if (choice == 1)
{
player.usePotion();
if (JOptionPane.showConfirmDialog(null,
"You used a potion! You have " + player.getHealthPoints() + " health.", " ",
JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != 0)
{
System.exit(0);
}
}
else
{
System.exit(0);
}
if (enemy.getHealthPoints() > 0)
{
if ((enemy.getHealthPoints() < 10) && (enemy.getPotions() > 0))
{
enemy.usePotion();
if (JOptionPane.showConfirmDialog(null,
enemy.getName() + " used a potion! They have " + enemy.getHealthPoints()
+ " health.",
" ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != 0)
{
System.exit(0);
}
}
else
{
enemy.attack(player);
if (JOptionPane.showConfirmDialog(null,
enemy.getName() + " attacked you! You have " + player.getHealthPoints()
+ " health left.",
" ", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE) != 0)
{
System.exit(0);
}
}
}
} while (player.getHealthPoints() > 0 && enemy.getHealthPoints() > 0);
if (player.getHealthPoints() <= 0)
{
JOptionPane.showMessageDialog(null, "Sorry, you lose!");
}
else
{
JOptionPane.showMessageDialog(null, "Great job " + player.getName() + ", you win!");
}
}
else
{
System.exit(0);
}
}
else
{
System.exit(0);
}
playAgain = JOptionPane.showConfirmDialog(null, "Would you like to play again?", " ",
JOptionPane.YES_NO_OPTION);
}
}
}
答案 0 :(得分:0)
上下文是你似乎在while
循环中拥有主游戏控制逻辑,为用户提供再次播放的选择。但是你似乎在许多地方都在呼叫System.exit
......如果你这样做,用户就无法再次播放。
我想......也许......你不应该&#34;退出&#34;一点都不当然,如果你想让玩家玩另一个游戏,那就不是了。所以,也许你真正要问的问题是如何在不退出计划的情况下放弃当前的游戏。例如,您可以从(内部)循环中断,或者您可以重构代码,以便每个游戏都是方法调用。
简而言之: