Skip to content

Instantly share code, notes, and snippets.

@xtpor
Last active February 6, 2017 10:02
Show Gist options
  • Save xtpor/89e0c595934b0b70c83d136c45ef1d95 to your computer and use it in GitHub Desktop.
Save xtpor/89e0c595934b0b70c83d136c45ef1d95 to your computer and use it in GitHub Desktop.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TicTacToeFrame extends JFrame implements ActionListener {
private JButton newGameButton = new JButton("New Game");
private JButton exitButton = new JButton("Exit");
private JButton[][] buttons = new JButton[3][3];
private JLabel statusLabel = new JLabel();
private String[] symbol = { " ", "O", "X" };
private final int AI = 1;
private final int PLAYER = 0;
private boolean isWin;
private int count;
private int depth;
private int turn;
private TicTacToeMain main;
public TicTacToeFrame(TicTacToeMain main) {
this.main = main;
JPanel aPanel = new JPanel();
aPanel.add(newGameButton);
aPanel.add(exitButton);
newGameButton.addActionListener(this);
exitButton.addActionListener(this);
JPanel boardPanel = new JPanel();
boardPanel.setLayout(new GridLayout(3, 3));
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[0].length; j++) {
buttons[i][j] = new JButton();
buttons[i][j].addActionListener(this);
boardPanel.add(buttons[i][j]);
}
}
add(aPanel, BorderLayout.NORTH);
add(boardPanel, BorderLayout.CENTER);
add(statusLabel, BorderLayout.SOUTH);
// TicTacToeMain.newGame();
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
}
/* public void newGame() {
statusLabel.setText("Status: Player" + turn);
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[0].length; j++) {
buttons[i][j].setText(" ");
}
}
}*/
public void updateBoard(int[][] board) {
for (int i = 0; i < buttons.length; i++) {
for (int j = 0; j < buttons[0].length; j++) {
buttons[i][j].setText(symbol[board[i][j]]);
}
}
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == exitButton) {
System.exit(0);
}
if (event.getSource() == newGameButton) {
main.newGame();
} else {
}
}
}
/**
* TicTacToeMain
*/
public class TicTacToeMain {
private int[][] board = new int[3][3];
private TicTacToeFrame frame;
public TicTacToeMain() {
frame = new TicTacToeFrame(this);
frame.setVisible(true);
}
public void newGame() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = 0;
}
}
frame.updateBoard(board);
}
public static void main(String[] args) {
new TicTacToeMain();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment