2012-04-06 132 views
-2

编辑(4/3/2017):对不起,当时我是一个noob。Java:基于回合的战斗系统(与gui)

我正在尝试做一个基于回合的战斗系统,玩家点击轮到他的按钮。但我似乎无法找到如何编码它。以下是我所做的代码。

这里应该发生的事情是,当我点击攻击按钮时(例如),下一回合将是怪兽轮回,但是当我点击按钮时,playerTurn变量不会改变。 playerTurn总是如此。你能帮我解决这个问题吗?这是一个回合制战斗系统。

public class BattleFrame extends JFrame implements ActionListener, Runnable { 

    private JButton atkButton = new JButton("Attack"); 
    private JButton runButton = new JButton("Run"); 
    private JButton itemButton = new JButton("Item"); 
    private JButton magicButton = new JButton("Magic"); 

    private JPanel panelButtons = new JPanel(); 

private Random rand = new Random(); 
private Boolean playerTurn; 
private Thread t; 

public BattleFrame() { 
    setSize(480, 390); 
    setLayout(null); 

      // I have not included the code with the setting of the JButtons 
    initPanel(); // initialize the panel with buttons 

    setResizable(false); 
    setVisible(true); 
    playerTurn = true; 
    t = new Thread(this); 
    t.start(); 
} 

// I'm not so familiar with 'synchronized' but I tried it here but it doesn't change anything 
public void actionPerformed(ActionEvent e) { 
    Object src = e.getSource(); 

    if(src.equals(atkButton) && playerTurn) { 
      System.out.println("Attack!"); 
     playerTurn = false; 
} 
else if(src.equals(runButton) && playerTurn) { 
     System.out.println("Run!"); 
     playerTurn = false; 
} 

else if(src.equals(itemButton) && playerTurn) { 
     System.out.println("Item"); 
     playerTurn = false; 
} 

else if(src.equals(magicButton) && playerTurn) { 
     System.out.println("Magic"); 
     playerTurn = false; 
} 

} 

public void run() { 
    while(true) { 
     if(playerTurn == false) { 
      System.out.println("Monster's turn!"); // just printing whose turn it is 
      playerTurn = true; 
     } 
     else System.out.println("player's turn!"); 
    } 

} 

public static void main(String[] args) { 
    new BattleFrame(); 

    } 
} 
+0

你的问题是如此之广。尝试更多,并尝试提出点问题的详细问题 – kommradHomer 2012-04-06 12:45:34

+0

你怎么知道变量不会改变?也许你因为输出的速度而无法看到变化? – maialithar 2012-04-06 12:46:46

+0

因为当你点击按钮变量应该改变,但从来没有我已经得到它,我宣布一个布尔值不布尔,并且我正在使用a == b而不是a.equals(b),所以我改变布尔值为布尔值 – Zik 2012-04-06 13:51:46

回答

2

布尔是一个对象,因此通过身份而不是值进行比较。

assert new Boolean (true) == new Boolean(true); 

上面将失败,因为这两种不同的布尔对象是不一样的物件。

对于一般用途,请使用基本类型布尔值,而不是标准库类布尔值。您应该使用布尔值的情况非常罕见:这是存在更多对称性的事情之一,而不是任何实际的理由。如果你使用它,你需要使用a.equals(b)而不是== b。

有关详细信息,请参阅:

http://www.java-samples.com/showtutorial.php?tutorialid=221

+0

oooohhhh所以这就是为什么它不工作!谢谢! – Zik 2012-04-06 12:54:08