U E D R , A S I H C RSS

Tic Tac Toe/노수민

~cpp 
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class TicTacToe extends JFrame {

    private static final int O = 1; 
    private static final int X = 2; 
    
    int board[][];
	int turn = 1;
	Image notImage;
	Image crossImage;
	boolean exit = false;

	public TicTacToe() {
		board = new int[3][3];
		setBounds(10, 10, 800, 600);
		setBackground(Color.white);
		show();

		addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (exit)
					JOptionPane.showMessageDialog(
						null,
						"Player" + turn + "Win!");
				else {
					int row, col;
					if (100 <= e.getX()
						&& e.getX() <= 400
						&& 100 <= e.getY()
						&& e.getY() <= 400) {
						row = (int) ((e.getX() - 100) / 100);
						col = (int) ((e.getY() - 100) / 100);
						if (!checkBoard(row, col)) {
							board[row][col] = turn;
							if (turn == O)
								turn = X;
							else
								turn = O;
						}

					}

					repaint();
					if (checkWin()) {
						if (turn == 1)
							turn = 2;
						else
							turn = 1;
						JOptionPane.showMessageDialog(
							null,
							"Player" + turn + "Win!");
					}
				}

			}
		});
	}
	public boolean checkBoard(int r, int c) {
		if (board[r][c] != 0)
			return true;
		else
			return false;

	}
	public boolean checkWin() {
		for (int i = 0; i < 3; i++) {
			if ((board[i][0] == O && board[i][1] == O && board[i][2] == O)
				|| (board[i][0] == X && board[i][1] == X && board[i][2] == X)
				|| (board[0][i] == O && board[1][i] == O && board[2][i] == O)
				|| (board[0][i] == X && board[1][i] == X && board[2][i] == X)) {
				exit = true;
				return true;
			}
		}
		if ((board[0][0] == O && board[1][1] == O && board[2][2] == O)
			|| (board[0][0] == X && board[1][1] == X && board[2][2] == X)
			|| (board[0][2] == O && board[1][1] == O && board[2][0] == O)
			|| (board[0][2] == X && board[1][1] == X && board[2][0] == X))
		{
			exit = true;
			return true;
		}
		return false;
	}
	public static void main(String args[]) {
		TicTacToe ttt = new TicTacToe();
		ttt.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	public void paint(Graphics g) {
		setTitle("Player " + turn + " 차례");
		for (int i = 0; i <= 3; i++) {
			g.drawLine(100, 100 + 100 * i, 400, 100 + 100 * i);
			g.drawLine(100 + 100 * i, 100, 100 + 100 * i, 400);
		}
		for (int i = 0; i <= 2; i++)
			for (int j = 0; j <= 2; j++)
				if (board[i][j] == 1)
					g.drawOval(100 + 100 * i, 100 + 100 * j, 100, 100);
				else if (board[i][j] == 2) {
					g.drawLine(
						100 + 100 * i,
						100 + 100 * j,
						200 + 100 * i,
						200 + 100 * j);
					g.drawLine(
						100 + 100 * i,
						200 + 100 * j,
						200 + 100 * i,
						100 + 100 * j);
				}
	}

}
Valid XHTML 1.0! Valid CSS! powered by MoniWiki
last modified 2021-02-07 05:28:14
Processing time 0.0187 sec