Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package tictactoe;
- import java.awt.Dimension;
- import java.awt.FlowLayout;
- import java.awt.Font;
- import java.awt.GridLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JOptionPane;
- public class TicTacToe extends JFrame implements ActionListener {
- private JButton[] cells;
- private final String PLAYER1 = "X";
- private final String PLAYER2 = "O";
- private String currentPlayer = PLAYER1;
- private boolean isGameOver = false;
- public TicTacToe() {
- setLayout(new GridLayout(3, 3));
- cells = new JButton[9];
- for (int i = 0; i < cells.length; i++) {
- cells[i] = new JButton();
- cells[i].setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 50));
- cells[i].setPreferredSize(new Dimension(100, 100));
- cells[i].addActionListener(this);
- add(cells[i]);
- }
- pack();
- }
- public static void main(String[] args) {
- TicTacToe ttt = new TicTacToe();
- ttt.setVisible(true);
- ttt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
- @Override
- public void actionPerformed(ActionEvent e) {
- if (isGameOver) {
- return;
- }
- JButton currentCell = (JButton) e.getSource();
- if (currentCell.getText().length() > 0) {
- return;
- }
- currentCell.setText(currentPlayer);
- if (hasWon(currentPlayer)) {
- isGameOver = true;
- JOptionPane.showMessageDialog(this, currentPlayer + "has won");
- return;
- }
- currentPlayer = currentPlayer.equals(PLAYER1) ? PLAYER2 : PLAYER1;
- }
- public boolean hasWon(String player) {
- if (player.equals(cells[0].getText())
- && player.equals(cells[1].getText())
- && player.equals(cells[2].getText())) {
- return true;
- }
- if (player.equals(cells[3].getText())
- && player.equals(cells[4].getText())
- && player.equals(cells[5].getText())) {
- return true;
- }
- if (player.equals(cells[6].getText())
- && player.equals(cells[7].getText())
- && player.equals(cells[8].getText())) {
- return true;
- }
- if (player.equals(cells[0].getText())
- && player.equals(cells[3].getText())
- && player.equals(cells[6].getText())) {
- return true;
- }
- if (player.equals(cells[1].getText())
- && player.equals(cells[4].getText())
- && player.equals(cells[7].getText())) {
- return true;
- }
- if (player.equals(cells[3].getText())
- && player.equals(cells[5].getText())
- && player.equals(cells[8].getText())) {
- return true;
- }
- if (player.equals(cells[0].getText())
- && player.equals(cells[4].getText())
- && player.equals(cells[8].getText())) {
- return true;
- }
- if (player.equals(cells[2].getText())
- && player.equals(cells[4].getText())
- && player.equals(cells[6].getText())) {
- return true;
- }
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement