教你用Java做出一个五子棋小游戏

7,844 阅读6分钟

「本文已参与好文召集令活动,点击查看:后端、大前端双赛道投稿,2万元奖池等你挑战!」

让我先来从注册到登陆再到玩一局演示一下(本来想录制个GIF,但是录制出来的动图太大了,有几百兆,想想还是录视频,但是掘金目前还没有开发出传视频的功能,我就传在哔哩哔哩了)代码可以通过文章末尾方式获取

www.bilibili.com/video/BV1hU…

五子棋.gif这个也有点大,四十多兆,能不能加载出来随缘

🎯一、用户注册类

类名就叫做 Register.java

image.png

这里我们用到了JFrame,窗口。JFrame 是一个可以独立显示的组件,一个窗口通常包含有标题、图标、操作按钮(关闭、最小化、最大化),还可以为窗口添加菜单栏、工具栏等。一个进程中可以创建多个窗口,并可在适当时候进行显示、隐藏 或 销毁。

控制用户注册的类主要代码

这里只放主要代码,不然太长不利于阅读

public class Register extends JFrame{

/*
 * 用户注册
 */
final JLabel welcomeRegisterLabel = new JLabel("欢迎注册开心五子棋!");
final JLabel userLabel = new JLabel("用户名:");
final JTextField userjt = new JTextField(14);
final JLabel passwordLabel = new JLabel("密码:");
final JPasswordField passwordjp = new JPasswordField(14);
final JLabel confirmPasswordLabel = new JLabel("确认密码:");
final JPasswordField confirmPasswordjp = new JPasswordField(14);
final JLabel yanzhengmajl = new JLabel("验证码:");
final JTextField yanzhengmajt = new JTextField("请输入验证码", 7);
final JLabel yanzhengmaUpdate = new JLabel("看不清?换一张");
final JButton register = new JButton("               注  册               ");
final JLabel back = new JLabel("返回");
final JLabel tipUserAlreadyRegistered = new JLabel("该账号已经注册!");
final JLabel tipUserNameEmpty = new JLabel("用户名为空!");
final JLabel tipUserNameLessThan5Char = new JLabel("账号少于5个字符!");
final JLabel tipPasswordEmpty = new JLabel("密码不能为空!");
final JLabel tipPasswordLessThan6Char = new JLabel("密码少于6个字符!");
final JLabel tipPasswordInconfirmity = new JLabel("两次密码不一致!");
final JLabel tipConfirmPasswordqualified = new JLabel("重复密码正确!");
final JLabel tipyanzhengmaerror = new JLabel("验证码输入不正确!");
final DrawYZM drawyzm = new DrawYZM();
final Random r = new Random();
static String userName = new String();
static String password = new String();
final FileOperation read = new FileOperation();
String repeatPassword = new String();
String yanzhengma = new String();
String yzm = new String();
int flagUserName = 0;
int flagPassword = 0;
int flagConfirmedPassword = 0;
int flagyanzhengma = 0;
char[] YZM = new char[62];{
        for(int i = 0; i < 26; i++) {
                YZM[i] = (char) ('A' + i);
        }
        for(int i = 26; i< 52; i++) {
                YZM[i] = (char) ('a' + i - 26);
        }
        for(char i = 52; i < 62; i++) {
                YZM[i] = (char) (i - 4);
        }
}
SpringLayout springLayout = new SpringLayout();//使用弹簧布局管理器


}

注册时需要的验证码类

class DrawYZM extends JPanel{
        /*
         *验证码类
         */
        public void paint(Graphics g) {
                setBounds(269, 269, 100, 60);
                int R = r.nextInt(255);
                int G = r.nextInt(255);
                int B = r.nextInt(255);
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
            int n = 0;
            yzm = "";
                for(int i = 0; i < 4; i++) {
                        n = r.nextInt(62);
                        yzm += YZM[n];
                        int flag = r.nextInt(2);
                        Color color = new Color(r.nextInt(200) + 20, r.nextInt(200) + 20, r.nextInt(200) + 20);
                        g2.setColor(color);
                        Graphics2D g2d = (Graphics2D)g;
                        AffineTransform trans = new AffineTransform();//将文字旋转指定角度
                        if(flag == 0) {
                                trans.rotate(- r.nextInt(45) * 3.14 / 180, 275 + i * 25, 307);
                        }else {
                                trans.rotate(r.nextInt(45) * 3.14 / 180, 275 + i * 25, 307);
                        }
                        g2d.setTransform(trans);
                        g2.setFont(new Font("微软雅黑", 1, 24));
                        g2.drawString(YZM[n] + "", 277 + i * 22, 307);
                }

        }
}

🍺二、文件操作类

类名就叫做 FileOperation.java

首先我们需要创建excel文件

包括了编号,用户名,密码,分数,等级,胜利场数,总场数,是否记住密码,是否自动登录,以及注册时间

public void creatExcel(String path) {
        String data[] = { "Num","userName", "password", "points", "class", 
                        "winNum", "totalNum", "RememberPassword", "AutoLogin", "date"};
        try {  
    File file = new File(path);
    WritableWorkbook book = Workbook.createWorkbook(file); 
    WritableSheet sheet = book.createSheet("用户信息", 0); 
    for(int i = 0; i < data.length; i++) {//将信息写入xls文件中
        Label label = new Label(i, 0, data[i]);
        sheet.addCell(label);
    }
    book.write();  
    book.close();  

} catch (Exception e) {  
    System.out.println(e);  
}  
} 

下面的方法用于判断账号是否存在

public boolean readData(String path, String userName) {
        File file = new File(path);
        if(!file.exists()) {//如果文件不存在
                creatExcel("user.xls");//创建文件
        }
        Workbook workbook = null;
        Sheet sheet = null;
        Cell cell = null;
        boolean flag = false;
        try {
                workbook = Workbook.getWorkbook(file);
                sheet = workbook.getSheet(0);
                for(int i = 0; i < sheet.getRows(); i ++) {
                        cell = sheet.getCell(1, i);
                        String content = cell.getContents();//获取内容
                        if(content.equals(userName)) {
                                flag = true;
                                break;
                        }
                }
                workbook.close();
        }catch(Exception e) {
                e.printStackTrace();
        }
        return flag;
}

将用户将信息写入文件中

public void writeData(String path, String userName, String keyword, String data) {
		File file = new File(path);//创建文件对象
		if(!file.exists()) {//如果文件不存在
			creatExcel("user.xls");//创建文件
		}
	    Workbook workbook = null;  
        WritableWorkbook wtbook = null;  
        WritableSheet wtsheet = null;  
        WritableCell wtcell = null; 
        int flagx = 0; 
        int flagy = 0;
        try {
            workbook = Workbook.getWorkbook(file);  
            wtbook = Workbook.createWorkbook(file, workbook);  
            wtsheet = wtbook.getSheet(0);//获取第一张表格  
            for(int i = 0; i < wtsheet.getColumns(); i++) {//查找列
            	wtcell = wtsheet.getWritableCell(i, 0);
            	if(wtcell.getType() == CellType.LABEL) {
            		String cell = ((Label)wtcell).getContents();
		            if(cell.equals(keyword)) {//定位到关键词的那一行
		            	flagx = i;
		            	break;
		            }
            	}     
            }
            if(keyword.equals("userName")) {//如果写入用户名
            	flagy = wtsheet.getRows();
            }else {//写入其他
            	for(int i = 0; i < wtsheet.getRows(); i++) {//查找行
            		wtcell = wtsheet.getWritableCell(1, i);
	        		String cell = ((Label)wtcell).getContents();
	        		if(cell.equals(userName)) {
	        			flagy = i;
	        			break;
	        		}
	            }
            }
	        Label label = new Label(flagx, flagy, data);
	        wtsheet.addCell(label);
	        wtsheet.addCell(new Label(0, flagy, String.valueOf((wtsheet.getRows() - 1))));
	        
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                wtbook.write();  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
            try {  
                wtbook.close();  
            } catch (WriteException | IOException e) {  
                e.printStackTrace();  
            }  
            workbook.close();  
        }  
}

返回对应用户的对应信息

public String backData(String path, String userName, String keyword) {
        File file = new File(path);
        if(!file.exists()) {//如果文件不存在
                creatExcel("user.xls");//创建文件
        }
        Workbook workbook = null;
        Sheet sheet = null;
        Cell cell = null;
        int flagx = 0; 
        int flagy = 0;
        try {
                workbook = Workbook.getWorkbook(file);
                sheet = workbook.getSheet(0);
                for(int i = 0; i < sheet.getColumns(); i++) {//找到用户名所在行
                        cell = sheet.getCell(i, 0);
                        String s = cell.getContents();

                        if(s.equals(keyword)) {
                                flagx = i;
                                break;
                        }
                }
                for(int i = 0; i < sheet.getRows(); i++) {
                        cell = sheet.getCell(1, i);
                        String s = cell.getContents();
                        if(s.equals(userName)) {
                                flagy = i;
                                break;
                        }
                }
                workbook.close();
        }catch(Exception e) {
                e.printStackTrace();
        }
        try {
                cell = Workbook.getWorkbook(file).getSheet(0).getCell(flagx, flagy);
        }catch(Exception e) {
                e.printStackTrace();
        }
        String s = cell.getContents();
        return s;
}

✨三、棋盘页面类

棋盘页面类名 Chessboard.java

为棋色选择添加事件监听器

whiteChessLabel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
                if(chessboardEmpty == 0) {//只有棋盘为空的时候才能选择棋子颜色
                    whiteChessjr.setSelected(true);
                }
        }
});
blackChessLabel.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
                if(chessboardEmpty == 0) {//只有棋盘为空的时候才能选择棋子颜色
                    blackChessjr.setSelected(true);
                }
        }
});

为新局按钮添加事件监听器

newRound.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                for(int i = 0; i < map.length; i++) {//将map数组置0
                        for(int j = 0; j < map[i].length; j++) {
                                map[i][j] = 0;
                                mapflag[i][j] = 0;
                        }
                }
                for(int j = 0; j < 225; j++) {//将悔棋标记数组置为0
                        imapflag[j] = 0;
                        jmapflag[j] = 0;
                }
                flag = 0;//行列标记数组下表置0
                winFLAG = 0;//输赢标记置0
                playerColor = -1;//玩家棋色标记置-1
                computerColor = -1;//电脑棋色标记为-1
                chessboardEmpty = 0;//棋盘标记为空
                player = 1;//玩家先下棋
                computer = 0;//电脑后下
                newchessX = 0;//新棋子标记置0
                newchessY = 0;
                depth = 0;
                repaint();
        }
});

为悔棋添加事件监听器

back.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

                if(flag - 1 >= 0) {//棋盘上面有棋子的时候, 点击一次棋盘上面少两颗棋子,一颗是自己的,另一颗是电脑的
                        for(int i = flag - 1; i > flag - 3; i--) {
                                map[imapflag[i]][jmapflag[i]] = 0;
                                mapflag[imapflag[i]][jmapflag[i]] = 0;
                                imapflag[i] = 0;//将坐标存放在悔棋标记数组中
                                jmapflag[i] = 0;
                        }
                        flag = flag - 2;//表示每次悔棋棋盘上双方均少一颗子
                        winFLAG = 0;
                        if(flag - 1 >= 0) {
                                newchessX = imapflag[flag - 1];
                                newchessY = jmapflag[flag - 1];
                        }
                        if(flag == 0) {//表示棋盘为空
                                chessboardEmpty = 0;//棋盘为空
                                playerColor = -1;//玩家和电脑棋子颜色置0
                                computerColor = -1;
                                depth = 0;
                        }
                        repaint();
                }else {
                        ;
                }

        }
});

返回按钮添加事件监听器

returnback.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                dispose();
                new Main();
        }
});

退出按钮事件监听器

exit.addActionListener(new ActionListener() {//点击退出按钮退出程序
        public void actionPerformed(ActionEvent e) {
                System.exit(0);
        }
});

鼠标进入棋盘区域内,用于显示提示方框,表示点击之后可以在哪个区域内下棋

addMouseMotionListener(new MouseMotionListener() {
        public void mouseMoved(MouseEvent e) {
                // TODO 自动生成的方法存根
                x = e.getX();
                y = e.getY();
                if(x >= 247 && x <= 951 && y >=77 && y <= 781) {//如果鼠标点击的点在棋盘内或者边上一点
                        double m = (x - 270.0)/47.0;//判断点击位置最靠近的哪个交叉点
                        double n = (y - 100.0)/47.0;
                        int p = (x - 270)/47;
                        int q = (y - 100)/47;
                        int i, j;
                        if(m - p >= 0.5 || m - p <= -0.5) {
                                i = p + 1;
                        }else {
                                i = p;
                        }
                        if(n - q >= 0.5 || n - q <= -0.5) {
                                j = q + 1;
                        }else {
                                j = q;
                        }
                        if(i >=0 && i <= 15 && j >= 0 && j <= 15) {//识别到的区域为棋盘之内
                                if(mapflag[i][j] == 0 && winFLAG == 0 && player == 1) {//表示这个地方没有棋子,并且还没有赢
                                        promptBoxFlag[i][j] = 1;
                                        repaint();
                                }
                        }
                }		
        }
        public void mouseDragged(MouseEvent e) {}
});

电脑下棋函数

	private void tuntoComputer() {//电脑下棋
		// TODO 自动生成的方法存根
		if(depth >= 7) {
			depth = 6;
		}
		position = Algorithm.evalute(map, depth, computerColor);//调用估值函数
		map[position[0]][position[1]] = computerColor;
		imapflag[flag] = position[0];//将坐标存放在悔棋标记数组中
		jmapflag[flag] = position[1];
		newchessX = position[0];//新棋子标记记录坐标
		newchessY = position[1];
		int a = Math.max(Math.abs(position[0] - 7), Math.abs(position[1] - 7));//计算该点到中心的最大的距离
		depth = Math.max(depth, a);//不断更新depth的值
		flag ++;
		chessboardEmpty = 1;//棋盘标记为有棋子
		player = 1;//玩家下棋标志置0
		computer = 0;//电脑下棋标志为1
		judgeFlag = 1;
		repaint();
	}

绘制棋盘

    for(int i = 0; i < 15; i++) {//横线
            g2.drawLine(261, i * 47 + 63, 919, i * 47 + 63);
    }
    for(int j = 0; j < 15; j++) {//竖线
            g2.drawLine(j * 47 + 261, 64, j * 47 + 261, 721);
    }

绘制棋子

for(int i = 0; i < map.length; i++) {
        for(int j = 0; j < map[i].length; j++) {
                //白棋
                if(map[i][j] == 1) {
                        g2.drawImage(white, i * 47 + 241, j * 47 + 43, 40, 40, this);
                        mapflag[i][j] = 1;//标记位置表示这个地方已经有棋子
                }
                //黑棋
                if(map[i][j] == 2) {
                        g2.drawImage(black, i * 47 + 241, j * 47 + 43, 40, 40, this);
                        mapflag[i][j] = 1;
                }	
        }
}

判断棋子是否连成五个

if(judgeFlag == 1) {
        judge();
        judgeFlag = 0;
}

绘制新棋子红点标记

if(chessboardEmpty != 0) {
        g2.setColor(Color.red);
    g2.fillOval(newchessX * 47 + 254, newchessY * 47 + 55, 15, 15);
}

绘制鼠标移动方框

for(int i = 0; i < 15; i++) {
        for(int j = 0; j < 15; j++) {
                if(promptBoxFlag[i][j] == 1) {
                        g2.setColor(Color.RED);
                        g2.setStroke(new BasicStroke(2.5f));//设置线条大小
                        g2.drawLine(238 + i * 47, 40 + j * 47, 248 + i * 47, 40 + j * 47);//上左横线
                        g2.drawLine(275 + i * 47, 40 + j * 47, 285 + i * 47, 40 + j * 47);//上右横线
                        g2.drawLine(238 + i * 47, 40 + j * 47, 238 + i * 47, 50 + j * 47);//左上竖线
                        g2.drawLine(285 + i * 47, 40 + j * 47, 285 + i * 47, 50 + j * 47);//右上竖线
                        g2.drawLine(238 + i * 47, 77 + j * 47, 238 + i * 47, 87 + j * 47);//左下竖线
                        g2.drawLine(285 + i * 47, 77 + j * 47, 285 + i * 47, 87 + j * 47);//右下竖线
                        g2.drawLine(238 + i * 47, 87 + j * 47, 248 + i * 47, 87 + j * 47);//下左横线
                        g2.drawLine(275 + i * 47, 87 + j * 47, 285 + i * 47, 87 + j * 47);//下右横线
                        promptBoxFlag[i][j] = 0;
                }
        }
}
for(int i = 0; i < 5; i++) {//右上角星星
        g2.drawImage(happy, 711 + i * 47, 20, 40, 40, null);
}

解决第一次不能显示输赢标志的问题

g2.drawImage(win, 0, 0, 1, 1, null);
g2.drawImage(lose, 0, 0, 1, 1, null);

if(winFLAG == 0 && player == 0) {//表示还未分出胜负并且玩家下了,调用电脑下棋
        tuntoComputer();
}

设置下拉框和单选按钮在棋盘不为空的是否不能进行选择

设置棋子颜色单选框可用状态

if(chessboardEmpty == 1) {//棋盘不为空
        difficulityClass.setEnabled(false);//设置下拉框不可用
        if(whiteChessjr.isSelected()) {//白棋子单选框被选中
                blackChessjr.setEnabled(false);
                whiteChessjr.setEnabled(true);
        }else {//黑棋子单选框被选中
                blackChessjr.setEnabled(true);
                whiteChessjr.setEnabled(false);
        }
}else {//棋盘为空
        blackChessjr.setEnabled(true);//释放两个单选框
        whiteChessjr.setEnabled(true);
        difficulityClass.setEnabled(true);//释放下拉框
}

重绘积分,等级,胜率

classNum = (int)((int)(pointsNum /100 * 0.4 + gamewinNum * 0.4 + gameNum * 0.2) * 0.8);
sunNum = (int) (classNum / 100);
moonNum = (int)(classNum - sunNum * 100) / 50;
starNum = (int)(classNum - sunNum * 100 - moonNum * 50) / 10;
for(t = 0; t < sunNum; t++) {//绘画太阳
        g2.drawImage(sun, 75 + t * 30, 538, 30, 30, null);
}
for(t = sunNum ; t < moonNum + sunNum; t++) {//绘画月亮
        g2.drawImage(moon, 75 + t * 30, 540, 25, 25, null);
}
if(moonNum > 0 || sunNum > 0) {//绘画星星
        for(t = moonNum + sunNum ; t < starNum + moonNum + sunNum; t ++) {
            g2.drawImage(star, 75 + t * 30, 540, 25, 25, null);
    }
}else {
        for(t = moonNum ; t < starNum + 1; t ++) {
            g2.drawImage(star, 75 + t * 30, 538, 30, 30, null);
    }
}

判断棋子是否连成五个

public void judge() {
        for(t = newchessX,s = newchessY,count = 0; t >=0 && s >= 0 && count <= 4; t--,s--,count++) {
                comeX = t;
                comeY = s;
        }
        for(t = newchessX, s = newchessY, count = 0; t <=14 && s >= 0 && count <= 4; t++, s--, count++) {
                toX = t;
                toY = s;
        }
        if(winFLAG == 0) {
                for(int ch = 1; ch <=2; ch++) {
                        CHESSCOLOR = ch;
                        //判断横向棋子
                        for(s = (newchessX - 4) >=0 ? (newchessX - 4) : 0 ; s <= newchessX; s++) {//表示玩家获胜
                            t = newchessY;
                                if(map[s][t] == CHESSCOLOR && s < 11) {//行棋子数量计算
                                        if(map[s + 1][t] == CHESSCOLOR) {
                                                if(map[s + 2][t] == CHESSCOLOR) {
                                                        if(map[s + 3][t] == CHESSCOLOR) {
                                                                if(map[s + 4][t] == CHESSCOLOR) {
                                                                        winX = s;
                                                                        winY = t;
                                                                        winWay = 1;
                                                                        if(CHESSCOLOR == 1) {//白棋
                                                                                winFLAG = 1;
                                                                        }else {//黑棋
                                                                                winFLAG = 2;
                                                                        }
                                                                        break;
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                        if(winFLAG != 0) {//如果某一方赢了就直接退出
                                break;
                        }
                //判断列项棋子
                        for(t = (newchessY - 4) >=0 ? (newchessY - 4) : 0 ; t <= newchessY; t ++) {
                                s = newchessX;
                                if(map[s][t] == CHESSCOLOR && t < 11) {//列棋子数量计算
                                        if(map[s][t + 1] == CHESSCOLOR) {
                                                if(map[s][t + 2] == CHESSCOLOR) {
                                                        if(map[s][t + 3] == CHESSCOLOR) {
                                                                if(map[s][t + 4] == CHESSCOLOR) {
                                                                        winX = s;
                                                                        winY = t;
                                                                        winWay = 2;
                                                                        if(CHESSCOLOR == 1) {//白棋
                                                                                winFLAG = 1;
                                                                        }else {//黑棋
                                                                                winFLAG = 2;
                                                                        }
                                                                        break;
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                        if(winFLAG != 0) {//如果某一方赢了就直接退出
                                break;
                        }
                //判断左上到右下棋子
                        for(s = comeX, t = comeY; s <= newchessX && t <= newchessY; s ++, t++) {
                                if(map[s][t] == CHESSCOLOR && s < 11 && t < 11) {//斜下棋子数量计算
                                        if(map[s + 1][t + 1] == CHESSCOLOR) {
                                                if(map[s + 2][t + 2] == CHESSCOLOR) {
                                                        if(map[s + 3][t + 3] == CHESSCOLOR) {
                                                                if(map[s + 4][t + 4] == CHESSCOLOR) {
                                                                        winX = s;
                                                                        winY = t;
                                                                        winWay = 3;
                                                                        if(CHESSCOLOR == 1) {//白棋
                                                                                winFLAG = 1;
                                                                        }else {//黑棋
                                                                                winFLAG = 2;
                                                                        }
                                                                        break;
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                        if(winFLAG != 0) {//如果某一方赢了就直接退出
                                break;
                        }
                //判断右上到左下棋子
                        for(s = toX, t = toY; s >= newchessX && t <= newchessY; s --, t++) {
                                if(map[s][t] == CHESSCOLOR && s >= 4 && t < 11) {//斜上棋子数量计算
                                        if(map[s - 1][t + 1] == CHESSCOLOR) {
                                                if(map[s - 2][t + 2] == CHESSCOLOR) {
                                                        if(map[s - 3][t + 3] == CHESSCOLOR) {
                                                                if(map[s - 4][t + 4] == CHESSCOLOR) {
                                                                        winX = s;
                                                                        winY = t;
                                                                        winWay = 4;
                                                                        if(CHESSCOLOR == 1) {//白棋
                                                                                winFLAG = 1;
                                                                        }else {//黑棋
                                                                                winFLAG = 2;
                                                                        }
                                                                        break;
                                                                }
                                                        }
                                                }
                                        }
                                }
                        }
                        if(winFLAG != 0) {//如果某一方赢了就直接退出
                                break;
                        }
                }
        }
}

💌四、主函数 Main.java

基本布局设置

setTitle("开心五子棋");
setBounds(200, 200, 500, 500);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
SpringLayout springLayout = new SpringLayout();//使用弹簧布局管理器
Container c = getContentPane();//创建容器
c.setBackground(new Color(255, 218, 185));
c.setLayout(springLayout);

userjt.setFont(new Font("微软雅黑", 0, 18 ));
userjt.setText(Register.userName);
passwordjt.setFont(new Font("微软雅黑", 0, 18));
passwordjt.setText(Register.password);
logoLabel.setFont(new Font("微软雅黑", 1, 48));
logoLabel.setForeground(Color.pink);
ImageIcon logoimage = new ImageIcon(Main.class.getResource("/image/logo5.jpg"));
logoimage.setImage(logoimage.getImage().getScaledInstance(260, 130, Image.SCALE_DEFAULT));
logo.setIcon(logoimage);
userLabel.setFont(new Font("微软雅黑", 1, 20));
passwordLabel.setFont(new Font("微软雅黑", 1, 20));
rememberPasswordjl.setFont(new Font("微软雅黑", 0, 14));
rememberPasswordjl.setForeground(Color.gray);
automaticLoginjl.setFont(new Font("微软雅黑", 0, 14));
automaticLoginjl.setForeground(Color.gray);
loginButton.setFont(new Font("微软雅黑", 1, 16));
registerLabel.setFont(new Font("微软雅黑", 1, 13));
registerLabel.setForeground(Color.gray);
promptPasswordFalse.setFont(new Font("微软雅黑", 0, 13));
promptPasswordFalse.setForeground(Color.red);
promptUserNameEmpty.setFont(new Font("微软雅黑", 0, 13));
promptUserNameEmpty.setForeground(Color.red);
prompPasswordEmpty.setFont(new Font("微软雅黑", 0, 13));
prompPasswordEmpty.setForeground(Color.red);
promptRegister.setFont(new Font("微软雅黑", 0, 13));
promptRegister.setForeground(Color.red);
rememberPasswordjcb.setBackground(new Color(255, 218, 185));
automaticLoginjcb.setBackground(new Color(255, 218, 185));

首页图标

c.add(logo);//首页图标
springLayout.putConstraint(springLayout.NORTH, logo, 40, springLayout.NORTH, c);
springLayout.putConstraint(springLayout.WEST, logo, 115, springLayout.WEST, c);
    c.add(logoLabel);//标题“开心五子棋”
    springLayout.putConstraint(springLayout.NORTH, logoLabel, 100, springLayout.NORTH, c);
    springLayout.putConstraint(springLayout.WEST, logoLabel, 120, springLayout.WEST, c);
    logoLabel.setVisible(false);

用户名

c.add(userLabel);//用户名
springLayout.putConstraint(springLayout.NORTH, userLabel, 35, springLayout.SOUTH, logoLabel);
springLayout.putConstraint(springLayout.WEST, userLabel, 110, springLayout.WEST, c);
c.add(userjt);
springLayout.putConstraint(springLayout.NORTH, userjt, 35, springLayout.SOUTH, logoLabel);
springLayout.putConstraint(springLayout.WEST, userjt, 10, springLayout.EAST, userLabel);

密码

c.add(passwordLabel);//密码
springLayout.putConstraint(springLayout.NORTH, passwordLabel, 10, springLayout.SOUTH, userLabel);
springLayout.putConstraint(springLayout.WEST, passwordLabel, 110, springLayout.WEST, c);
c.add(passwordjt);
springLayout.putConstraint(springLayout.NORTH, passwordjt, 10, springLayout.SOUTH, userjt);
springLayout.putConstraint(springLayout.WEST, passwordjt, 10, springLayout.EAST, passwordLabel);

复选框

c.add(rememberPasswordjcb);//复选框
springLayout.putConstraint(springLayout.NORTH, rememberPasswordjcb, 10, springLayout.SOUTH, passwordLabel);
springLayout.putConstraint(springLayout.WEST, rememberPasswordjcb, 175, springLayout.WEST, c);
c.add(rememberPasswordjl);
springLayout.putConstraint(springLayout.NORTH, rememberPasswordjl, 10, springLayout.SOUTH, passwordjt);
springLayout.putConstraint(springLayout.WEST, rememberPasswordjl, 5, springLayout.EAST, rememberPasswordjcb);
c.add(automaticLoginjcb);
springLayout.putConstraint(springLayout.NORTH, automaticLoginjcb, 10, springLayout.SOUTH, passwordjt);
springLayout.putConstraint(springLayout.WEST, automaticLoginjcb, 30, springLayout.EAST, rememberPasswordjl);
c.add(automaticLoginjl);
springLayout.putConstraint(springLayout.NORTH, automaticLoginjl, 10, springLayout.SOUTH, passwordjt);
springLayout.putConstraint(springLayout.WEST, automaticLoginjl, 5, springLayout.EAST, automaticLoginjcb);

登陆和注册按钮

c.add(loginButton);//登陆按钮
springLayout.putConstraint(springLayout.NORTH, loginButton, 20, springLayout.SOUTH, rememberPasswordjl);
springLayout.putConstraint(springLayout.WEST, loginButton, 110, springLayout.WEST, c);
c.add(registerLabel);//注册按钮
springLayout.putConstraint(springLayout.NORTH, registerLabel, 5, springLayout.SOUTH, loginButton);
springLayout.putConstraint(springLayout.WEST, registerLabel, 320, springLayout.WEST, c);

账号未注册提示

c.add(promptRegister);//账号未注册提示
promptRegister.setVisible(false);
springLayout.putConstraint(springLayout.NORTH, promptRegister, 41, springLayout.SOUTH, logoLabel);
springLayout.putConstraint(springLayout.WEST, promptRegister, 5, springLayout.EAST, userjt);
c.add(promptUserNameEmpty);//请输入账号
promptUserNameEmpty.setVisible(false);
springLayout.putConstraint(springLayout.NORTH, promptUserNameEmpty, 41, springLayout.SOUTH, logoLabel);
springLayout.putConstraint(springLayout.WEST, promptUserNameEmpty, 5, springLayout.EAST, userjt);

密码错误提示

c.add(promptPasswordFalse);
promptPasswordFalse.setVisible(false);
springLayout.putConstraint(springLayout.NORTH, promptPasswordFalse, 20, springLayout.SOUTH, promptRegister);
springLayout.putConstraint(springLayout.WEST, promptPasswordFalse, 5, springLayout.EAST, passwordjt);

密码为空提示

c.add(prompPasswordEmpty);
prompPasswordEmpty.setVisible(false);
springLayout.putConstraint(springLayout.NORTH, prompPasswordEmpty, 20, springLayout.SOUTH, promptRegister);
springLayout.putConstraint(springLayout.WEST, prompPasswordEmpty, 5, springLayout.EAST, passwordjt);

设置文本框鼠标点击事件

userjt.addMouseListener(new MouseAdapter() {//文本框
        public void mouseClicked(MouseEvent e) {
                userjt.setText("");
        }
});
passwordjt.addMouseListener(new MouseAdapter() {//密码框
        public void mouseClicked(MouseEvent e) {
                passwordjt.setText("");
        }
});

设置登陆按钮单击事件

loginButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
                String userName = userjt.getText().trim();//获取用户输入的账号和密码
                String Password = new String(passwordjt.getPassword()).trim();
                //判断账号和密码
            if(userName.length() != 0) {//用户名不为空
                promptUserNameEmpty.setVisible(false);//关闭账号为空显示
                if(Password.length() != 0) {//密码不为空
                        if(f.readData("user.xls", userName) && Password.equals(f.backData("user.xls", userName, "password"))) {//用户输入的账号和密码正确
                                        promptRegister.setVisible(false);//隐藏提示信息
                                        promptPasswordFalse.setVisible(false);
                                        prompPasswordEmpty.setVisible(false);
                                        loginButton.setText("                登 陆 中...               ");
                                        new Chessboard();//跳转到五子棋棋盘页面
                                        dispose();//销毁当前页面
                                }
                        else if( f.readData("user.xls", userName) && !Password.equals(f.backData("user.xls", userName, "password"))) {//用户输入密码错误
                                        promptPasswordFalse.setVisible(true);//显示密码错误提示
                                        promptRegister.setVisible(false);
                                        prompPasswordEmpty.setVisible(false);
                                        passwordjt.setText("");//密码框清空
                                        passwordjt.requestFocus();//光标定位到密码框
                                }else {//账号还未注册
                                        promptRegister.setVisible(true);
                                promptPasswordFalse.setVisible(false);
                                        prompPasswordEmpty.setVisible(false);
                                }
                }
                else {//密码为空
                        if(userName.equals("admin")) {//用户名已经注册, 提示输入密码
                                prompPasswordEmpty.setVisible(true);
                                promptUserNameEmpty.setVisible(false);
                                promptRegister.setVisible(false);
                                promptPasswordFalse.setVisible(false);
                        }else {//用户名未注册
                                prompPasswordEmpty.setVisible(false);
                                promptUserNameEmpty.setVisible(false);
                                promptRegister.setVisible(true);
                                promptPasswordFalse.setVisible(false);
                        }

                }
            }else {//用户名为空
                promptUserNameEmpty.setVisible(true);//提示输入账号
                promptRegister.setVisible(false);
                promptPasswordFalse.setVisible(false);
                prompPasswordEmpty.setVisible(false);
                passwordjt.setText("");//将密码框置为空
                if(Password.length() == 0) {//密码为空
                        prompPasswordEmpty.setVisible(true);
                        promptRegister.setVisible(false);
                        promptPasswordFalse.setVisible(false);
                }
            }
        }
});

注册标签监听器

registerLabel.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent e) {
dispose();
                new Register();
        }
        public void mouseEntered(MouseEvent e) {
                registerLabel.setForeground(Color.red);;
        }
        public void mouseExited(MouseEvent e) {
            registerLabel.setForeground(Color.black);
        }
        public void mousePressed(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
});

🎖五、算法类 Algorithm.java

计算左边棋子数量

for(int i = X - 1; i >=0; i--) {
        if(map[i][Y] == color) {
                upcount[0]++;
        }else if(map[i][Y] != 0 && map[i][Y] != color) {//表示有对方棋子
                upflag[0] = -1;
                break;
        }else {//表示为空
                upflag[0] = 1;
                if(i - 1 >= 0 && map[i][Y] == 0) {
                        upflag[0] = 2;//表示两个空格
                }else {
                        break;
                }
                if(i - 2 >= 0 && map[i][Y] == 0) {
                        upflag[0] = 3;//表示有三个空格
                }else {
                        break;
                }
                break;
        }
}

计算右边棋子数量

for(int j = X + 1; j <= 14; j++) {
        if(map[j][Y] == color) {
                downcount[0]++;
        }else if(map[j][Y] != 0 && map[j][Y] != color) {
                downflag[0] = -1;
                break;
        }else {//表示为空
                downflag[0] = 1;
                if(j + 1 <= 14 && map[j][Y] == 0) {
                        downflag[0] = 2;
                }else {
                        break;
                }
                if(j + 2 <= 14 && map[j][Y] == 0) {
                        downflag[0] = 3;
                }else {
                        break;
                }
                break;
        }
}

计算方向向上

for(int i = Y - 1; i >= 0; i--) {
        if(map[X][i] == color) {
                upcount[1]++;
        }else if(map[X][i] != 0 && map[X][i] != color) {//表示该点是对方棋子
                upflag[1] = -1;
                break;
        }else {//表示为空
                upflag[1] = 1;
                if(i - 1 >= 0 && map[X][i] == 0) {
                        upflag[1] = 2;
                }else {
                        break;
                }
                if(i - 2 >= 0 && map[X][i] == 0) {
                    upflag[1] = 3;
                }else {
                        break;
                }
                break;
        }
}

计算方向向下

for(int j = Y + 1; j <= 14; j++) {
        if(map[X][j] == color) {
                downcount[1]++;
        }else if(map[X][j] != 0 && map[X][j] != color) {//表示该点是对方棋子
                downflag[1] = -1;
                break;
        }else {//表示为空
                downflag[1] = 1;
                if(j + 1 >= 0 && map[X][j] == 0) {
                        downflag[1] = 2;
                }else {
                        break;
                }
                if(j + 2 >= 0 && map[X][j] == 0) {
                    downflag[1] = 3;
                }else {
                        break;
                }
                break;
        }
}

计算斜向上

int i = 0;
int j = 0;
for(i = X - 1, j = Y - 1; i >= 0 && j >= 0; i--, j--) {
        if(map[i][j] == color) {
                upcount[2]++;
        }else if(map[i][j] != 0 && map[i][j] != color) {
                upflag[2] = -1;
                break;
        }else {//为空
                upflag[2] = 1;
                if(i - 1 >= 0 && j - 1 >= 0 && map[i][j] == 0) {
                        upflag[2] = 2;
                }else {
                        break;
                }
                if(i - 2 >= 0 && j - 2 >= 0 && map[i][j] == 0) {
                        upflag[2] = 3;
                }else {
                        break;
                }
                break;
        }
}

计算斜向下

for(i = X + 1, j = Y + 1; i <= 14 && j <= 14; i++, j++) {
        if(map[i][j] == color) {
                downcount[2]++;
        }else if(map[i][j] != 0 && map[i][j] != color) {
                downflag[2] = -1;
                break;
        }else {//为空
                downflag[2] = 1;
                if(i + 1 <= 14 && j + 1 <= 14 && map[i][j] == 0) {
                        downflag[2] = 2;
                }else {
                        break;
                }
                if(i + 2 <= 14 && j + 2 <= 14 && map[i][j] == 0) {
                        downflag[2] = 3;
                }else {
                        break;
                }
                break;
        }
}

估值算法,返回一个数组,用于记录坐标

public static int[] evalute(int map[][], int depth, int computerColor) {
        int maxscore = 0;
        Random r = new Random();
        int pos[][] = new int[10][2];{
                for(int i = 0; i < pos.length; i++) {
                        for(int j = 0; j < pos[i].length; j++) {
                                pos[i][j] = 0;
                        }
                }
        }
        int FLAG = 0;
        int score[][] = new int[15][15];{//初始化计分数组
                for(int i = 0; i < 15; i++) {
                        for(int j = 0; j < 15; j++) {
                                score[i][j] = 0;
                        }
                }
        }
        int position[] = new int[]{0, 0};//初始化位置坐标数组
        for(int i = 6 - depth; i <= 8 + depth && i <= 14; i++) {//搜索横坐标
                for(int j = 6 - depth; j <= 8 + depth && j <= 14; j++) {//搜索纵坐标
                        if(map[i][j] == 0) {//表示该点在棋盘上面为空
                                score[i][j] = countScore(map, i, j, computerColor);
                                if(maxscore < score[i][j]) {
                                        maxscore = score[i][j];//记录当前棋盘分数的最大值
                                }
                        }
                }
        }
        for(int i = 6 - depth; i <= 8 + depth && i <= 14; i++) {
                for(int j = 6 - depth; j <= 8 + depth && j <= 14; j++) {
                        if(score[i][j] == maxscore) {
                                pos[FLAG][0] = i;
                                pos[FLAG++][1] = j;
                        }
                }
        }
        int m = r.nextInt(FLAG);
        position[0] = pos[m][0];
        position[1] = pos[m][1];
        return position;
}

项目目录

image.png

Java文件

image.png

其他所需文件

图片: image.png

jar包:jxl.jar

五子棋小.gif

代码下载:

关注作者同名公众号【海拥】回复【java五子棋小游戏】

蓝色格子背景几何图形卡通公众号二维码 - 副本.png

相关文章:

【Java练习题】Java程序的输出 | 第一套(含解析)

【Java练习题】Java程序的输出 | 第二套(含解析)

【Java练习题】Java程序的输出 | 第三套(含解析)

【Java练习题】Java程序的输出 | 第四套(含解析)

【Java练习题】Java程序的输出 | 第五套(含解析)

【Java练习题】Java程序的输出 | 第六套(含解析)

【Java练习题】Java程序的输出 | 第七套(含解析)

【Java练习题】Java程序的输出 | 第八套(含解析)

我已经写了很长一段时间的技术博客,这是我的一篇技术文章/教程。希望你们会喜欢!这里汇总了我的全部原创及作品源码:GitHubGitee

如果你真的从这篇文章中学到了一些新东西,喜欢它,收藏它并与你的小伙伴分享。🤗最后,不要忘了❤或📑支持一下哦