📄 tictactoe.java
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TicTacToe extends JPanel
{ public TicTacToe(Image o,Image x)
{ init(o,x);}
protected void init(Image o,Image x)
{ if(board==null)
{ board=new TicBoard(o,x,Color.white,this);
game=new TicGame(board,this);
}
setLayout(new BorderLayout());
add(board,BorderLayout.CENTER);
board.setGame(game);
board.addMouseListener(new MouseHandler());
newGame();
}
protected void newGame()
{ game.reset();
if(first)
{ game.move(1,4,TicGame.PLAYER_O);
}
first=!first;
board.repaint();
/* gameBegin();*/
}
public void userMove(int sou,int tar)
{ if(game.ended())
{ newGame();
return;
}
if(!move(sou,tar,TicGame.PLAYER_X)) invalidMove();
else if(!game.ended())
{
int t=game.generateMove();
if(t!=TicGame.NOMOVE) move(source,target,TicGame.PLAYER_O);
}
source=-1;
}
protected boolean move(int sou,int tar,boolean player)
{ int status=game.move(sou,tar,player);
if(status==TicGame.NOMOVE) return false;
board.repaint();
if(status==TicGame.WIN_X||status==TicGame.WIN_O) winner();
return true;
}
protected void winner() {}
protected void invalidMove() { target=source=-1;}
class MouseHandler extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{ if(source>=0)
{ int c=board.col(e.getX());
int r=board.row(e.getY());
target=c+r*3;
userMove(source,target);
}
else
validateSourcePoint(e.getX(),e.getY());
}
}
protected void validateSourcePoint(int mouseX,int mouseY)
{ int i=0,count=3;
int c=board.col(mouseX);
int r=board.row(mouseY);
source=c+r*3;
int x=game.getCrossValue();
while(count>0)
{
if((x&1)!=0)
{ count--;
if(i==source) return;
}
i++;x>>=1;
}
source=-1;
}
public void setMove(int s,int t)
{
source=s;
target=t;
}
protected TicBoard board=null;
protected TicGame game=null;
protected boolean first=false;
protected int source=-1,target=-1;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -