나는 TicTacToe의 간단한 게임을 만들었지 만 게임이 끝날 때마다 그리고 다시 시작 버튼을 클릭 할 때마다 게임을 다시 시작해야했습니다. 방금 첫 번째 수평 버튼을했습니다. 당신이 그 (것)들을 누를 때 창은 팝업하고 우승자가다는 것을 당신에게 말한다. 방금 테스트 해 봤어. 하지만 재시작을 누를 때 게임을 다시 시작하려면 어떻게해야합니까? 저는 자바를 처음 접했고 게임을 개선하기 위해 스스로 노력하고 있습니다. 당신이 가지고있는 유일한 상태는 버튼에 텍스트 것 같다게임 다시 시작
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!");
}
}
처음 게임을 실행할 때와 마찬가지로 모든 게임 상태, 변수 등을 초기화해야합니다. – nullpotent
배열을 배우고 사용하면 코드를 크게 단순화하고 문제를 훨씬 쉽게 해결할 수 있습니다. –
메모 해 주셔서 감사합니다. 나는 배열에 익숙하지 않았지만 여전히 그것에 대해 연구 중이다. – ickyrr