No older revisions available
No older revisions available
~cpp
package TicTacToe;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.JFrame;
public class TicTacToe extends JFrame {
private JFrame frame;
private int board[][];
private int x, y;
private boolean b;
private static final int __O = 1;
private static final int __X = -1;
private static final int __NONE = 0;
public TicTacToe() {
init();
}
private void init() {
board = new int[3][3];
for(int i=0; i<3; ++i) {
for(int j=0; j<3; ++j) {
board[i][j] = __NONE;
}
}
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
x = e.getX()/200;
y = e.getY()/200;
if( board[x][y] != __NONE )
return;
if( b )
board[x][y] = __O;
else
board[x][y] = __X;
b = !b;
repaint();
int result = someoneWin(x,y);
if( result != __NONE ) {
if( result == -3)
System.out.println("흑 승");
else if( result == 3)
System.out.println("백 승");
System.exit(1);
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,600);
show();
}
public int someoneWin(int x, int y) {
int checkPoint = 0;
for(int i=x,j=y; i<3 && j<3 && i>=0 && j>=0; --i, --j) {
checkPoint += board[i][j];
if( winLose(checkPoint) ) return checkPoint;
}
checkPoint = 0;
for(int i=x,j=y; i<3 && j<3 && i>=0 && j>=0; --i, ++j) {
checkPoint += board[i][j];
if( winLose(checkPoint) ) return checkPoint;
}
checkPoint = 0;
for(int i=x,j=y; i<3 && j<3 && i>=0 && j>=0; ++i, --j) {
checkPoint += board[i][j];
if( winLose(checkPoint) ) return checkPoint;
}
checkPoint = 0;
for(int i=x,j=y; i<3 && j<3 && i>=0 && j>=0; ++i, ++j) {
checkPoint += board[i][j];
if( winLose(checkPoint) ) return checkPoint;
}
checkPoint = 0;
for(int i=x,j=y; i<3 && j<3 && i>=0 && j>=0; ++i) {
checkPoint += board[i][j];
if( winLose(checkPoint) ) return checkPoint;
}
checkPoint = 0;
for(int i=x,j=y; i<3 && j<3 && i>=0 && j>=0; --i) {
checkPoint += board[i][j];
if( winLose(checkPoint) ) return checkPoint;
}
checkPoint = 0;
for(int i=x,j=y; i<3 && j<3 && i>=0 && j>=0; ++j) {
checkPoint += board[i][j];
if( winLose(checkPoint) ) return checkPoint;
}
checkPoint = 0;
for(int i=x,j=y; i<3 && j<3 && i>=0 && j>=0 ; --j) {
checkPoint += board[i][j];
if( winLose(checkPoint) ) return checkPoint;
}
return __NONE;
}
private boolean winLose(int cp) {
return ( cp==-3) || (cp==3);
}
public void paint(Graphics g) {
drawGrids(g);
drawChoices(g);
}
private void drawChoices(Graphics g) {
for(int i=0; i<3; ++i) {
for(int j=0; j<3; ++j) {
drawCell(g, i,j,board[i][j]);
}
}
}
private void drawGrids(Graphics g) {
// horizental
g.drawLine(0, 200, 600, 200);
g.drawLine(0, 400, 600, 400);
// vertical
g.drawLine(200, 0, 200, 600);
g.drawLine(400, 0, 400, 600);
}
private void drawCell(Graphics g, int i, int j, int choice) {
int ptX = i * 200 + 10;
int ptY = j * 200 + 20;
if( choice == __O ) {
g.drawOval(ptX, ptY, 180, 180);
//System.out.println(ptX + " " + ptX2);
}
else if( choice == __X ) {
g.fillOval(ptX, ptY, 180, 180);
}
}
public static void main(String[] args) {
new TicTacToe();
}
}