五子棋总的来说和画图板类似,首先画一个有正方形网格的图形,充当五子棋的底板,绘制棋子则是用Graphics画实心圆形,但是其中需要注意的有几个方面:
1.怎么实现黑白棋的交替落子?
2.如果点不准格子中间,怎么进行校正?
3.如果下在棋盘外面怎么办?
结构:
- 界面类:
创建一个窗体
绘制一个网格棋盘
给窗体添加鼠标监听器
- 监听器类:
实现鼠标监听
鼠标按下时绘制棋子
实现交替颜色绘制
校准棋子的坐标
限制落子的范围
public class GoBangUI{
GoListener gl=new GoListener();
public void showUI(){
GoFrame gf=new GoFrame();
gf.setTitle("五子棋v1.0");
gf.setSize(850,900);
gf.setLocation(500,100);
gf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gf.setVisible(true);
gf.addMouseListener(gl);
gl.g=gf.getGraphics;
}
public static void main(String[]args){
GoBangUI goBangUI=new GoBangUI();
goBangUI.showUI();
}
}
public class GoFrame extends JFrame{
public void paint(Graphics g){//重写Paint方法
super.paint(g);
//绘制棋盘
GoUtils.drawChessPad(g);
}
}
public class GoUtils{
static final int X=50;
static final int Y=75;
static final int ROW=15;
static final int COL=15;
static final int SIZE=50;//间距
static int chessType=1;
//static 静态,程序一开始时就开始执行;final,常量,不可变
public static void drawChessPad(Graphics g){
Color color=new Color(194, 188, 126);//设置背景颜色
g.setColor(color);
g.fillRect(X-SIZE/2,Y-SIZE/2,(COL+1)*SIZE,(ROW+1)*SIZE);
g.setColor(Color.BLACK);
for(int i=0;i<=COL;i++){
g.drawLine(X+i*SIZE,Y,X+i*SIZE,Y+ROW*SIZE);
g.drawLine(X,Y+i*SIZE,X+COL*SIZE,Y+i*SIZE);
}
}
}
public class GoListener extends GoUtils implements MouseListener{
Graphics g;
//int chessType=1;//1:黑棋,2:白棋,0,不能落子
@Override
public void mousePressed(MouseEvent e) {
int x=e.getX();
int y=e.getY();
//换算行列值
int c=(x-X+SIZE/2)/SIZE;
int r=(y-Y+SIZE/2)/SIZE;
//交替落子
if (chessType == 1) {
g.setColor(Color.BLACK);
chessType = 2;
} else if (chessType == 2) {
g.setColor(Color.WHITE);
chessType = 1;
}
//还原标准坐标
int chessX=c*SIZE+X-SIZE/2;
int chessY=r*SIZE+Y-SIZE/2;
g.fillOval(chessX,chessY,SIZE,SIZE);
}
@Override
public void mouseClicked(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
}
标签:gf,int,void,五子棋,v1.0,static,绘制,public,SIZE
From: https://blog.csdn.net/lxyfight/article/details/144095073