public interface Config {
//常量
public int X0=50,Y0=50,SIZE=50,LINE=15,CHESS=50;
}
public class GameUI {
//显示游戏界面
public void initUI(){
JFrame jf = new JFrame();
jf.setSize(900,900);
jf.setTitle("五子棋游戏");
jf.setLocationRelativeTo(null); //居中显示
jf.setDefaultCloseOperation(3); //退出进程
//用一个独立的面板对象绘制棋盘
//因为自定面板类才有绘制棋盘,棋子功能
MPanel chessPanel = new MPanel();
chessPanel.setBackground(Color.GREEN);
jf.add(chessPanel);
jf.setVisible(true);
//从窗体上获取画笔
Graphics g = chessPanel.getGraphics();
//给窗体添加鼠标监听器方法
GameListener listener = new GameListener();
chessPanel.addMouseListener(listener);
//传递画笔对象
listener.gr = g;
//把chessArr数组从GameListener中传递给MPanel类
chessPanel.chessArr = listener.chessArr;
}
public static void main(String[] args) {
GameUI ui = new GameUI();
ui.initUI();
}
}
public class GameListener extends MouseAdapter implements Config {
//引用传递
public Graphics gr; //保存传递过来的画笔对象
public int count=0; //棋子计数器
public int chessX,chessY; //保存当前棋子的交点值
public Color color; //保存当前棋子颜色
//保存棋子对象
public Chess[] chessArr = new Chess[200];
//构造方法:初始画笔
//鼠标点击
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
System.out.println("点击!");
//计算棋子交点值
if((x-X0)%SIZE > SIZE/2){
chessX = (x-X0)/SIZE + 1;
}else{
chessX = (x-X0)/SIZE;
}
if((y-Y0)%SIZE > SIZE/2){
chessY = (y-Y0)/SIZE + 1;
}else{
chessY = (y-Y0)/SIZE;
}
//取余 %
if(count%2 == 0){
color = Color.BLACK;
}else{
color = Color.WHITE;
}
System.out.println("chessX = "+chessX);
//创建Chess 对象,保存其数据,并绘制出来
//对象的数据类型就是前面的类名
Chess chess = new Chess(chessX,chessY,color);
chess.drawChess(gr);
//按顺序保存棋子对象
chessArr[count] = chess;
count++;
}
}
public class MPanel extends JPanel implements Config {
//引用传递
public Chess[] chessArr;
//重写paint方法
public void paint(Graphics g){
//1.保留绘制组件的功能
//super 表示当前类的父类对象
//this 表示本类对象
super.paint(g);
System.out.println("paint....");
//2.绘制棋盘,棋子
//硬编码
for(int i=0;i<LINE;i++) {
g.drawLine(X0, Y0+i*SIZE, (LINE-1)*SIZE+X0, Y0+i*SIZE);
g.drawLine(X0+i*SIZE, Y0, X0+i*SIZE, (LINE-1)*SIZE+Y0);
}
//重绘所有棋子数据
for(int i=0;i<chessArr.length;i++){
Chess c = chessArr[i];
if(c != null) {
c.drawChess(g);
}
}
}
}
public class Chess implements Config{
//属性
public int chessX,chessY; //交点值
public Color color; //当前棋子颜色
//方法
//构造方法:public 类名(参数类型 参数名,,){ 方法体...}
//作用:1.创建对象 2.同时给多个属性初始化
public Chess(int chessX,int chessY,Color color){
this.chessX = chessX;
this.chessY = chessY;
this.color = color;
}
//根据保存数据的还原图形
public void drawChess(Graphics g){
g.setColor(color);
g.fillOval(chessX*SIZE+X0-CHESS/2,chessY*SIZE+Y0-CHESS/2,CHESS,CHESS);
}
}
1万+

被折叠的 条评论
为什么被折叠?



