使用Java Swing(图形化界面),写一个功能齐全的拼图游戏

游戏主入口

主入口只需要一个登录界面即可

import com.qinghuiliyi.ui.Ui.LoginJFrame;

public class APP {
    //创建一个程序的主入口,作为项目的启动
    public static void main(String[] args) {
        //new GameJFrame();//用于检测代码bug
        new LoginJFrame();
        //new RegisterJFrame();//用于检测代码bug
    }
}

游戏主界面窗口

满足菜单功能的实现,还有拼图游戏的正常游玩

package com.qinghuiliyi.ui.Ui;

//导入界面包
import javax.swing.*;
import javax.swing.border.BevelBorder;
//导入随机数包
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;


//所有和游戏相关的代码
//需要继承一个键盘监听的接口,同时重写接口中的方法
public class GameJFrame extends JFrame implements KeyListener , ActionListener {
    //将二维数组定义在这个地方可以让下面使用方法时,不需要返回值和传参
    int[][] date = new int[4][4];
    //x,y为0在打乱后在二维数组中的位置
    int x = 0;
    int y = 0;
    //定义path为展示图片的地址
    String path = "Jigsaw_Game\\image\\animal\\animal6\\";
    //先定义一个win的二维数组,当date和wining相同时就代表胜利
    int[][] win = new int[][] {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,0}};
    //定义一个计数器count来记录所用步数
    int count = 0;
    //创建选项下面的条目内容
    JMenuItem repalyItem = new JMenuItem("重新游戏");
    JMenuItem reloginItem = new JMenuItem("重新登录");
    JMenuItem closeItem = new JMenuItem("关闭游戏");
    JMenuItem blogaddressItem = new JMenuItem("博客地址");
    //设置一个更换图片下面的条目
    JMenuItem animal = new JMenuItem("动物");
    JMenuItem girl = new JMenuItem("女孩");
    JMenuItem sport = new JMenuItem("运动");
    public GameJFrame() {
        //初始化界面
        initializeJFrame();

        //初始化菜单
        initializeJMenuBar();

        //初始化(打乱)数据
        initializedate();

        //初始化图片
        initializeImage();

        //界面显示
        this.setVisible(true);
    }

    //打乱数据
    private void initializedate() {
        //这种循环不便于进行打乱图片的操作
        /*
        将一组图片依次排在界面中
        int x = 0;
        int y = 0;
        //16的原因是需要加载一个空的图片格
        for (int i = 1; i <= 16; i++) {
            //每次i++,赋予的图片依次排序
            String imagePath = "A:\\code\\Jigsaw_Game\\image\\animal\\animal" +
                    "1" + "\\" + i + ".jpg";
            //创建一个图片ImageIcon的对象,创建一个JLabel对象,管理容器
            JLabel jLabel = new JLabel(new ImageIcon(imagePath));
            //指定图片地址
            jLabel.setBounds(x , y , 105, 105);
            if(x == 315){
                x = 0;
                y += 105;
            }else{
                x += 105;
            }
            //把管理容器添加到界面中;
            this.getContentPane().add(jLabel);
        }
        */
        //定义一个计数器来记录那张图片
        //将一个0-15的数组进行打乱操作
        //需要空出一个格子来进行游戏
        //创建随机数对象
        Random rand = new Random();
        int[] arr = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
        //当到0时,因为图片资料中没有为0的图片,就会出现一个空白格,后续的游戏操作是基于该空白格进行的
        for (int i = 0; i < arr.length; i++) {
            int temp = rand.nextInt(arr.length);
            int num = arr[temp];
            arr[temp] = arr[i];
            arr[i] = num;
        }
        //把数组中的数据放入二维数组中去
        for (int i = 0; i < arr.length; i++) {
            //要记录0的坐标值方便后续判断
            if(arr[i] == 0){
                //记录0的坐标
                x = i / 4;
                y = i % 4;
            }
            date[i / 4][i % 4] = arr[i];
        }
    }

    //初始化图片
    private void initializeImage() {
        //因为每次移动图片都需要加载该方法,所以在每次调用时需要清除容器中的图片
        this.getContentPane().removeAll();
        //先加载的图片在图层的上方!!
        //将步数显示出来
        JLabel counts = new JLabel("步数: " + count);
        counts.setBounds(50 ,30 ,100 ,20);
        this.getContentPane().add(counts);
        //进行比较,如果排序正确则出现胜利的图标
        if(Victory()){
            //当运行此代码时,Victory()返回true就代表,两个数组相同,拼图游戏已完成
            //需要将胜利图标添加进入游戏界面
            JLabel winjLabel = new JLabel(new ImageIcon("Jigsaw_Game\\image\\win.png"));
            winjLabel.setBounds(203 , 283 , 197 , 73);
            //把管理容器添加到界面中;
            this.getContentPane().add(winjLabel);
        }
        //进行换行操作
        for (int j = 0; j < 4; j++) {
            //在一行中添加图片
            for (int i = 0; i < 4; i++) {
                //简写前的路径A:\\code\\Jigsaw_Game\\image\\animal\\animal3" + "\\" + date[j][i] + ".jpg";
                String imagePath = path + date[j][i] + ".jpg";
                //创建一个图片ImageIcon的对象,创建一个JLabel对象,管理容器
                JLabel jLabel = new JLabel(new ImageIcon(imagePath));
                //指定图片地址
                jLabel.setBounds(105 * i + 83, 105 * j + 134, 105, 105);
                //对图片进行美化
                //可以使用BevelBorder中的常量来增加代码的可读性
                //其中0:BevelBorder.RAISED
                //1:BevelBorder.LOWERED
                jLabel.setBorder(new BevelBorder(BevelBorder.LOWERED));
                //把管理容器添加到界面中;
                this.getContentPane().add(jLabel);
            }
        }
        //用链式代码先创建一个JLabel管理容器,然后在括号里创建要添加的图片对象
        //可以使用简写路径,从项目开始找,这样只要文件结构相同就可以不需要更改直接使用
        JLabel background = new JLabel(new ImageIcon("Jigsaw_Game\\image\\background.png"));
        //指定图片地址
        background.setBounds(40, 40, 508, 560);
        //把管理容器添加到界面中
        this.getContentPane().add(background);
        //最后需要刷新界面
        this.getContentPane().repaint();
    }

    //初始化菜单
    private void initializeJMenuBar() {
        //初始化菜单
        JMenuBar jMenuBar = new JMenuBar();
        //创建菜单中的选项的对象,一个是功能,一个是关于作者
        JMenu functionJMenu = new JMenu("功能");
        JMenu aboutauthorJMenu = new JMenu("作者博客");
        JMenu choose = new JMenu("更换图片");

        //将新的条目添加到chooseItem中
        choose.add(animal);
        choose.add(girl);
        choose.add(sport);

        //将选项的条目添加到相应的条目下
        functionJMenu.add(repalyItem);
        functionJMenu.add(reloginItem);
        functionJMenu.add(choose);
        functionJMenu.add(closeItem);

        aboutauthorJMenu.add(blogaddressItem);

        //将菜单中的两个选项添加到菜单当中
        jMenuBar.add(functionJMenu);
        jMenuBar.add(aboutauthorJMenu);

        //给这些条目绑定鼠标监听
        reloginItem.addActionListener(this);
        repalyItem.addActionListener(this);
        closeItem.addActionListener(this);
        blogaddressItem.addActionListener(this);
        animal.addActionListener(this);
        girl.addActionListener(this);
        sport.addActionListener(this);

        //把界面的菜单设置为jMenuBar
        this.setJMenuBar(jMenuBar);
    }

    //初始化界面
    private void initializeJFrame() {
        //初始化游戏界面,这样调用该对象时默认宽高为这些
        this.setSize(603 , 680);
        //设置游戏界面的标题
        this.setTitle("拼图游戏 v1.0");
        //让游戏界面置顶
        this.setAlwaysOnTop(true);
        //设置界面居中
        this.setLocationRelativeTo(null);
        //设置游戏关闭,程序也关闭,使用界面的x关闭程序也关闭
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //取消默认的居中放置,如不取消后续的图片设置位置无效,且必须设置位置
        this.setLayout(null);
        //给界面 添加 键盘监听事件,当触发后执行重写的接口方法
        this.addKeyListener(this);
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    //按下不松手时执行该代码
    @Override
    public void keyPressed(KeyEvent e) {
        int key = e.getKeyCode();
        //System.out.println(key);a:65
        if (key == 65) {
            //因为每次移动图片都需要加载该方法,所以在每次调用时需要清除容器中的图片
            this.getContentPane().removeAll();
            //把完整图片添加到界面上
            JLabel all = new JLabel(new ImageIcon(path + "all.jpg"));
            //指定图片地址
            all.setBounds(83, 134, 420, 420);
            //把管理容器添加到界面中
            this.getContentPane().add(all);
            //添加背景图片
            JLabel background = new JLabel(new ImageIcon("Jigsaw_Game\\image\\background.png"));
            //指定图片地址
            background.setBounds(40, 40, 508, 560);
            //把管理容器添加到界面中
            this.getContentPane().add(background);
            //最后需要刷新界面
            this.getContentPane().repaint();
        }
    }

    //按下时,执行的代码
    @Override
    public void keyReleased(KeyEvent e) {
        //当拼图完成时,使用return中止该方法
        if(Victory()){
            return;
        }
        //对上下左右进行判断  左:37 上:38 右:39 下:40
        //将获得的值赋予key,只要将key打印就可以知道对应的值;白值为(x,y)
        int key = e.getKeyCode();
        //System.out.println(key);
        //移动代码的核心为二维数组中数值的交换
        if (key == 37) {
            //此时向左移动
            if(y == 3){
                System.out.println("右边没有方块,不能再向左边移动");
            }else{
                date[x][y] = date[x][y + 1];
                date[x][y + 1] = 0;
                y++;
                count++;
                initializeImage();
            }
        }else if(key == 38){
            if(x == 3){
                System.out.println("下边没有方块,不能再向上边移动");
            }else{
                date[x][y] = date[x + 1][y];
                date[x + 1][y] = 0;
                x++;
                count++;
                initializeImage();
            }
        }else if(key == 39){
            if(y == 0){
                System.out.println("左边没有方块,不能再向右边移动");
            }else{
                date[x][y] = date[x][y - 1];
                date[x][y - 1] = 0;
                y--;
                count++;
                initializeImage();
            }
        }else if(key == 40){
            if(x == 0){
                System.out.println("上面边没有方块,不能再向下边移动");
            }else{
                date[x][y] = date[x - 1][y];
                date[x - 1][y] = 0;
                x--;
                count++;
                initializeImage();
            }
        }else if(key == 65){
            initializeImage();
        }else if(key == 83){//s键
            int[][] temp = new int[][]{{1,2,3,4} ,{5,6,7,8}
                    ,{9,10,11,12} ,{13,14,15,0}};
            date = temp;
            count++;
            initializeImage();
        }
    }

    //判断date数组是否和win数组相同
    //完全相同返回true
    public boolean Victory(){
        for (int i = 0; i < 16; i++) {
            if(date[i / 4][i % 4] != win[i / 4][i % 4]){
                //如果有一项不相等,将直接return false
                return false;
            }
        }
        return true;
    }

    //监听鼠标
    @Override
    public void actionPerformed(ActionEvent e) {
        Random rand = new Random();
        //定义一个obj来接收
        Object source = e.getSource();
        //点击重新游戏
        if (source == repalyItem) {
            initializedate();
            //重新开始需要将计步器归零
            count = 0;
            initializeImage();
        }else if(source == reloginItem){
            //关闭当前界面
            this.setVisible(false);
            //打开登录界面
            new LoginJFrame();
        }else if(source == closeItem){
            System.exit(0);
        }else if(source == blogaddressItem){
            //创建一个弹框对象
            JDialog jDialog = new JDialog();
            //设置游戏界面的标题
            jDialog.setTitle("轻绘梨衣l的博客");
            //把博客图片加载
            JLabel aboutauthor = new JLabel(new ImageIcon("Jigsaw_Game\\image\\aboutauthor.png"));
            aboutauthor.setBounds(0 , 0 , 361 , 361);
            //把图片添加到弹框中;
            jDialog.getContentPane().add(aboutauthor);
            //设置弹框大小
            jDialog.setSize( 450, 450);
            //弹框置顶
            jDialog.setAlwaysOnTop(true);
            //弹框居中
            jDialog.setLocationRelativeTo(null);
            //弹框不关闭无法进行下面的操作
            jDialog.setModal(true);
            //让弹框显示
            jDialog.setVisible(true);
        }else if(source == animal){
            int temp = rand.nextInt(8) + 1;
            path = "Jigsaw_Game\\image\\animal\\animal" + temp + "\\";
            initializedate();
            //重新开始需要将计步器归零
            count = 0;
            initializeImage();
        }else if(source == girl){
            int temp = rand.nextInt(13) + 1;
            path = "Jigsaw_Game\\image\\girl\\girl" + temp + "\\";
            initializedate();
            //重新开始需要将计步器归零
            count = 0;
            initializeImage();
        }else if(source == sport){
            int temp = rand.nextInt(10) + 1;
            path = "Jigsaw_Game\\image\\sport\\sport" + temp + "\\";
            initializedate();
            //重新开始需要将计步器归零
            count = 0;
            initializeImage();
        }
    }
}

游戏的登陆界面

游戏登录界面创建前需要先创建用户对象来存储登录信息,还有用于生成验证码的工具类tool

创建用户对象

package com.qinghuiliyi.ui.Oriented;

public class User {
    private String name;
    private String password;

    //空参和带参
    public User() {}
    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

    //get和set方法
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

工具类tool的编写

用于生成验证码

package com.qinghuiliyi.ui.Tool;
import java.util.Random;
public class VerificationCode {

    public static String getCode(){
        ///创建对象
        Random rand = new Random();
        //创建随机的大小写字母的数字的范围字符串
        StringBuilder sb = new StringBuilder();
        //将大小写字母,放入sb中
        for (int i = 0; i < 26; i++) {
            char c1 = 'A';
            char c2 = 'a';
            sb.append((char) (c1 + i));
            sb.append((char) (c2 + i));
        }//AaBb.....
        //在字符串的末尾加入0-9
        for (int i = 0; i < 10; i++) {
            char c1 = '0';
            sb.append((char) (c1 + i));
        }

        //创建一个reuslt来存放验证码
        StringBuilder result = new StringBuilder();
        //生成随机的验证码
        for (int i = 0; i < 5; i++) {
            int num = rand.nextInt(sb.length());
            result.append(sb.charAt(num));
        }

        //随机出一个数字,随机替换result中的一个数据
        int temp = rand.nextInt(10) + 52;
        //用c记录sb中随机出的数字
        char c = sb.charAt(temp);
        //用随机数来决定替换哪一个
        int r = rand.nextInt(4);
        //截取在result中r索引前面和后面的字符
        //要截取需要先将result转化为字符串
        StringBuilder resultend = new StringBuilder();
        if (r == 0) {
            resultend.append(c);
            resultend.append(result.toString().substring(1));
        }else if (r == 4) {
            resultend.append(result.toString().substring(0,4));
            resultend.append(c);
        }else{
            resultend.append(result.toString().substring(0,r));
            resultend.append(c);
            resultend.append(result.toString().substring(r + 1));
        }
        String str = resultend.toString();
        return str;
    }
}

游戏登录界面的主体

package com.qinghuiliyi.ui.Ui;

//导入界面包
import com.qinghuiliyi.ui.Tool.VerificationCode;
import com.qinghuiliyi.ui.Oriented.User;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;

//所有和登录相关的代码
//使用继承将APP中的代码分开写,便于修改bug和版本迭代
//继承鼠标监听
public class LoginJFrame extends JFrame implements MouseListener {
    //创建一个集合存储正确的用户名和密码
    static ArrayList<User> list = new ArrayList<>();
    //定义初始账号
    static {
        list.add(new User("zhangsan","123"));
        list.add(new User("轻绘梨衣","root123"));
    }
    //定义登录按钮
    JButton login = new JButton();
    //定义注册按钮
    JButton register = new JButton();
    //定义一个记录验证码
    JLabel rightCode = new JLabel();
    //验证码的输入框
    JTextField code = new JTextField();
    //密码输入框
    JTextField password = new JTextField();
    //添加用户名输入框
    JTextField username = new JTextField();
    public LoginJFrame() {
        //初始化界面
        initJFrame();

        //在这个界面中添加内容
        initView();

        //让当前界面显示出来
        this.setVisible(true);
    }

    //在这个界面中添加内容
    public void initView() {
        //清除内容界面
        this.getContentPane().removeAll();
        //添加用户名文字
        JLabel usernameText = new JLabel(new ImageIcon("Jigsaw_Game\\image\\login\\用户名.png"));
        usernameText.setBounds(116, 135, 47, 17);
        this.getContentPane().add(usernameText);

        //添加用户名输入框
        username.setBounds(195, 134, 200, 30);
        this.getContentPane().add(username);

        //添加密码文字
        JLabel passwordText = new JLabel(new ImageIcon("Jigsaw_Game\\image\\login\\密码.png"));
        passwordText.setBounds(130, 195, 32, 16);
        this.getContentPane().add(passwordText);

        //密码的输入框的内容
        password.setBounds(195, 195, 200, 30);
        this.getContentPane().add(password);

        //验证码提示
        JLabel codeText = new JLabel(new ImageIcon("puzzlegame\\image\\login\\验证码.png"));
        codeText.setBounds(133, 256, 50, 30);
        this.getContentPane().add(codeText);
        //验证码的输入框
        code.setBounds(195, 256, 100, 30);
        this.getContentPane().add(code);
        String codeStr = VerificationCode.getCode();
        //设置内容
        rightCode.setText(codeStr);
        //绑定鼠标事件
        rightCode.addMouseListener(this);
        //位置和宽高
        rightCode.setBounds(300, 256, 50, 30);
        //添加到界面
        this.getContentPane().add(rightCode);

        //添加登录按钮
        login.setBounds(123, 310, 128, 47);
        login.setIcon(new ImageIcon("Jigsaw_Game\\image\\login\\登录按钮.png"));
        //去除按钮的默认边框
        login.setBorderPainted(false);
        //去除按钮的默认背景
        login.setContentAreaFilled(false);
        //给图片绑定按键
        login.addMouseListener(this);
        this.getContentPane().add(login);

        //添加注册按钮
        register.setBounds(256, 310, 128, 47);
        register.setIcon(new ImageIcon("Jigsaw_Game\\image\\login\\注册按钮.png"));
        //去除按钮的默认边框
        register.setBorderPainted(false);
        //去除按钮的默认背景
        register.setContentAreaFilled(false);
        //给图片绑定按键
        register.addMouseListener(this);
        this.getContentPane().add(register);

        //添加背景图片
        JLabel background = new JLabel(new ImageIcon("Jigsaw_Game\\image\\login\\background.png"));
        background.setBounds(0, 0, 470, 390);
        this.getContentPane().add(background);


        //给这两个图片绑定长按键

        //最后需要刷新界面
        this.getContentPane().repaint();
    }

    //初始化界面
    public void initJFrame() {
        this.setSize(488, 430);//设置宽高
        this.setTitle("拼图游戏 登录");//设置标题
        this.setDefaultCloseOperation(3);//设置关闭模式
        this.setLocationRelativeTo(null);//居中
        this.setAlwaysOnTop(true);//置顶
        this.setLayout(null);//取消内部默认布局
    }


    //用弹框展示用户名或密码错误
    public void showJDialog(String content) {
        //创建一个弹框对象
        JDialog jDialog = new JDialog();
        //给弹框设置大小
        jDialog.setSize(200, 150);
        //让弹框置顶
        jDialog.setAlwaysOnTop(true);
        //让弹框居中
        jDialog.setLocationRelativeTo(null);
        //弹框不关闭永远无法操作下面的界面
        jDialog.setModal(true);

        //创建Jlabel对象管理文字并添加到弹框当中
        JLabel warning = new JLabel(content);
        warning.setBounds(0, 0, 200, 150);
        jDialog.getContentPane().add(warning);

        //让弹框展示出来
        jDialog.setVisible(true);
    }

    //单击
    @Override
    public void mouseClicked(MouseEvent e) {
        //定义一个obj来接收
        Object source = e.getSource();
        if(source == register){
            //关闭当前界面
            this.setVisible(false);
            //打开注册界面
            new RegisterJFrame();
        }else if(source == login){
            if(username.getText().equals("") || password.getText().equals("")){
                //账号和密码都不能为空
                showJDialog("账号和密码都不能为空!");
            }else{
                if(compare(rightCode.getText() , code.getText())){
                    User user = new User(username.getText(), password.getText());
                    if(compare(list , user)){
                        //关闭当前界面
                        this.setVisible(false);
                        //打开游戏界面
                        new GameJFrame();
                    }else{
                        //账号或者密码错误也需要全部重新输入
                        showJDialog("账号或者密码错误!");
                        //更换一次验证码
                        String code = VerificationCode.getCode();
                        rightCode.setText(code);
                    }
                }else{
                    //验证码错误需要全部重新输入
                    showJDialog("验证码输入错误!");
                    //更换一次验证码
                    String code = VerificationCode.getCode();
                    rightCode.setText(code);
                }
            }
        }else if (e.getSource() == rightCode) {
            System.out.println("更换验证码");
            //获取一个新的验证码
            String code = VerificationCode.getCode();
            rightCode.setText(code);
        }
    }

    //按下不松
    @Override
    public void mousePressed(MouseEvent e) {
        if (e.getSource() == login) {
            login.setIcon(new ImageIcon("Jigsaw_Game\\image\\login\\登录按下.png"));
        } else if (e.getSource() == register) {
            register.setIcon(new ImageIcon("Jigsaw_Game\\image\\login\\注册按下.png"));
        }
    }

    //松开按钮
    @Override
    public void mouseReleased(MouseEvent e) {
        if (e.getSource() == login) {
            login.setIcon(new ImageIcon("Jigsaw_Game\\image\\login\\登录按钮.png"));
        } else if (e.getSource() == register) {
            register.setIcon(new ImageIcon("Jigsaw_Game\\image\\login\\注册按钮.png"));
        }
    }

    //鼠标划入
    @Override
    public void mouseEntered(MouseEvent e) {
    }
    //鼠标划出
    @Override
    public void mouseExited(MouseEvent e) {
    }

    //比较字符串的代码无视小写
    public boolean compare(String a , String b){
        //先判断长度
        if(a.length() != b.length()){
            return false;
        }
        //再判断每一个字符
        for (int i = 0; i < a.length(); i++) {
            char c;
            char d;
            if(a.charAt(i) >= 'A' && a.charAt(i) <= 'Z'){
                c = (char)(a.charAt(i) + 32);
            }else{
                c = a.charAt(i);
            }
            if(b.charAt(i) >= 'A' && b.charAt(i) <= 'Z'){
                d = (char)(b.charAt(i) + 32);
            }else{
                d = b.charAt(i);
            }
            if(c != d){
                return false;
            }
        }
        return true;
    }

    //比较在数组中也没有该元素的方法
    public boolean compare(ArrayList<User> list , User user){
        for (int i = 0; i < list.size(); i++) {
            User u = list.get(i);
            if(u.getName().equals(user.getName())){
                if(u.getPassword().equals(user.getPassword())){
                    return true;
                }
            }
        }
        return false;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值