我正在创建一个简单的井字游戏,但是每当游戏结束和单击重新启动按钮时,我都会陷入重新启动游戏的困境。我刚刚做了第一个水平按钮。当您按下它们时,会弹出一个窗口并告诉您有赢家。我只是为了测试而做的。但是当我按下重新启动时如何重新启动游戏?我只是java新手,我正在尝试自己制作游戏以进行改进。以下是我的代码的一些部分:
public class TicTacToe extends javax.swing.JFrame implements ActionListener{
int i=0;
boolean win = false;
String player[]={"You","Comp"};
/**
* Creates new form TicTacToe
*/
public TicTacToe() {
super("TicTacToe (LeeMinHu-bag)");
initComponents();
setResizable(false);
setLocationRelativeTo(null);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
}
//If a button is pressed, its text will become "X"
public void actionPerformed(ActionEvent e){
if(e.getSource() == b1){
b1.setText("X");
b1.setEnabled(false);
}else if(e.getSource() == b2){
b2.setText("X");
b2.setEnabled(false);
}else if(e.getSource() == b3){
b3.setText("X");
b3.setEnabled(false);
}else if(e.getSource() == b4){
b4.setText("X");
b4.setEnabled(false);
}else if(e.getSource() == b5){
b5.setText("X");
b5.setEnabled(false);
}else if(e.getSource() == b6){
b6.setText("X");
b6.setEnabled(false);
}else if(e.getSource() == b7){
b7.setText("X");
b7.setEnabled(false);
}else if(e.getSource() == b8){
b8.setText("X");
b8.setEnabled(false);
}else if(e.getSource() == b9){
b9.setText("X");
b9.setEnabled(false);
}
i++;
System.out.println(i);
if(i%2==0){
turn.setText(player[0]);
}else{
turn.setText(player[1]);
}
checkIfWin();
}
//check to see if there is a winner
public void checkIfWin(){
if(b1.getText()==b2.getText() && b2.getText()==b3.getText() && b1.getText()!=""){
win = true;
}else if(i==9 && win==false){
JOptionPane.showMessageDialog(null,"Tie!","Game Over",JOptionPane.INFORMATION_MESSAGE);
}else{
win=false;
}
ifWin(win);
}
//if there is a winner
public void ifWin(boolean w){
if(w==true){
JOptionPane.showMessageDialog(null,"WIN!","Game Over",JOptionPane.INFORMATION_MESSAGE);
TicTacToe restart = new TicTacToe();
restart.validate();
}else{
System.out.println("The game is still on!");
}
}