I'm creating a game for a university assignment and one of the criteria is that the program asks who goes first.
I'm having a little trouble with this as I have defined ComputerPlayer firstPlayer
and ComputerPlayer secondPlayer
initially as null
, to then set the value based on a button press, but I keep getting an error as the players are already previously defined.
Can anyone help me in re-wording this so it works? Thanks.
public static void main(String[] args){
JPanel panel = new JPanel();
JRadioButton button1 = new JRadioButton("Human");
JRadioButton button2 = new JRadioButton("Computer");
panel.add(new JLabel("Who Goes First?"));
panel.add(button1);
panel.add(button2);
ComputerPlayer firstPlayer = null;
ComputerPlayer secondPlayer = null;
JOptionPane.showMessageDialog(null, panel);
if(button1.isSelected()) {
ComputerPlayer firstPlayer = new HumanPlayer();
ComputerPlayer secondPlayer = new AIPlayer();
}
if(button2.isSelected()) {
ComputerPlayer firstPlayer = new AIPlayer();
ComputerPlayer secondPlayer = new HumanPlayer();
}
GameLogic logic = new GameLogic();
logic.addPlayer(firstPlayer);
logic.addPlayer(secondPlayer);
logic.startGame();
}
Delete "ComputerPlayer" in if blocks. You already create this object, so u don't need do it again.
if(button1.isSelected()) {
firstPlayer = new HumanPlayer();
secondPlayer = new AIPlayer();
}
if(button2.isSelected()) {
firstPlayer = new AIPlayer();
secondPlayer = new HumanPlayer();
}