一、实践目标:
1.掌握JavaGUI界面设计
2.掌握鼠标事件的监听(MouseListener,MouseMotionListener)
二、实践内容:
设计一个简单的五子棋程序,能够实现五子棋下棋过程。如下图所示
五子棋运行界面
1.五子棋棋盘类
package cn.edu.ouc.fiveChess;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RadialGradientPaint;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Ellipse2D;
import javax.swing.*;
/**
* 五子棋--棋盘类
*/
public class ChessBoard extends JPanel implements MouseListener {
public static final int MARGIN=30;//边距
public static final int GRID_SPAN=35;//网格间距
public static final int ROWS=15;//棋盘行数
public static final int COLS=15;//棋盘列数
Point[] chessList=new Point[(ROWS+1)*(COLS+1)];//初始每个数组元素为null
boolean isBlack=true;//默认开始是黑棋先
boolean gameOver=false;//游戏是否结束
int chessCount;//当前棋盘棋子的个数
int xIndex,yIndex;//当前刚下棋子的索引
Image img;
Image shadows;
Color colortemp;
public ChessBoard(){
// setBackground(Color.blue);//设置背景色为橘黄色
img=Toolkit.getDefaultToolkit().getImage("board.jpg");
shadows=Toolkit.getDefaultToolkit().getImage("shadows.jpg");
addMouseListener(this);
addMouseMotionListener(new MouseMotionListener(){
public void mouseDragged(MouseEvent e){
}
public void mouseMoved(MouseEvent e){
int x1=(e.getX()-MARGIN+GRID_SPAN/2)/GRID_SPAN;
//将鼠标点击的坐标位置转成网格索引
int y1=(e.getY()-MARGIN+GRID_SPAN/2)/GRID_SPAN;
//游戏已经结束不能下
//落在棋盘外不能下
//x,y位置已经有棋子存在,不能下
if(x1<0||x1>ROWS||y1<0||y1>COLS||gameOver||findChess(x1,y1))
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
//设置成默认状态
else setCursor(new Cursor(Cursor.HAND_CURSOR));
}
});
}
//绘制
public void paintComponent(Graphics g){
super.paintComponent(g);//画棋盘
int imgWidth= img.getWidth(this);
int imgHeight=img.getHeight(this);//获得图片的宽度与高度
int FWidth=getWidth();
int FHeight=getHeight();//获得窗口的宽度与高度
int x=(FWidth-imgWidth)/2;
int y=(FHeight-imgHeight)/2;
g.drawImage(img, x, y, null);
for(int i=0