How would I make a win condition to my tic-tac-toe game? I need to also make it so when the player is done, that it will ask them if they want to play again. If you figure out a way, can you please tell me why that is so. Here is my code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
@SuppressWarnings("serial")
public class game extends JFrame{
JFrame gameWindow = new JFrame("Tic-Tac-Toe");
private JButton buttons[] = new JButton[9];
private String mark = "";
private int count = 0;
public static void main(String[] args){
new game();
}
public game(){
HandlerClass handler = new HandlerClass();
// Sets buttons on the screen
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(mark);
buttons[i].addActionListener(handler);
gameWindow.add(buttons[i]);
}
// Sets the looks of the window
gameWindow.setLayout(new GridLayout(3,3));
gameWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gameWindow.setSize(300,300);
gameWindow.setVisible(true);
}
private class HandlerClass implements ActionListener{
@Override
public void actionPerformed(ActionEvent event) {
JButton click = (JButton) event.getSource();
if(count % 2 == 0){
mark = "X";
click.setBackground(Color.YELLOW);
}else{
mark = "O";
click.setBackground(Color.CYAN);
}
click.setText(mark);
click.setEnabled(false);
System.out.println(count + "\n" + (count % 2));
count++;
}
}
}