Java小项目|拼图小游戏|黑马

news/2024/5/18 12:07:06 标签: java, windows, 游戏程序, 开源

项目技术需求

Java基础

  • 基本if、for
  • io流
  • File
  • 集合
  • JFrame【看得懂就行】

项目素材以及打包exe:

链接:https://pan.baidu.com/s/1rPazJezTwS9O6e8BoYNIYA?pwd=6666 

项目运行截图

 

 项目来源

哔哩哔哩-黑马程序员上

哔哩哔哩-黑马程序员下

项目介绍:

项目分为三个部分

  • 登录
  • 注册
  • 游戏

登录

业务逻辑分析:

  • 查询改账号是否存在
  • 比对用户信息是否正确
  • 随机验证码处理

 注册

业务逻辑分析

  • 查询用户信息是否存在
  • 比对俩次密码是否一致
  • 添加新用户数据
  • 数据存入本地文件

 游戏

业务逻辑分析

  • 游戏块上下移动功能
  • 成功判定
  • 图片随机出现位置确定
  • 步数统计
  • 游戏读档存档,更换图片,重新游戏

 打包文件

  •  将代码打包成jar
  • 将jar转换为exe文件
  • 将exe与文件素材打包为安装包

代码实现

登录代码:

java">package com.itheima.ui;

import com.itheima.domain.Data;
import com.itheima.domain.User;
import com.itheima.util.CodeUtil;

import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class LoginJFrame extends JFrame implements MouseListener {
    ArrayList<Data> list = new ArrayList<>();
    JButton login = new JButton();
    JButton register = new JButton();
    JTextField username = new JTextField();
    //JTextField password = new JTextField();
    JPasswordField password = new JPasswordField();
    JTextField code = new JTextField();

    //正确的验证码
    JLabel rightCode = new JLabel();

    public LoginJFrame() throws IOException {
        //获取本地数据
        data();
        //初始化界面
        initJFrame();
        //在这个界面中添加内容
        initView();
        //让当前界面显示出来
        this.setVisible(true);
    }
    public void data() throws IOException {
        File file = new File("data.txt");
        file.createNewFile();

        BufferedReader br = new BufferedReader(new FileReader("data.txt"));
        String str;

        while ((str = br.readLine()) != null){
            String[] data = str.split("&");
            //name
            String name = data[0].split("=")[1];
            //password
            String password = data[1].split("=")[1];
            list.add(new Data(name,password));
        }
        br.close();
    }

    public void initView() {
        //1. 添加用户名文字
        JLabel usernameText = new JLabel(new ImageIcon("src\\image\\login\\用户名.png"));
        usernameText.setBounds(116, 135, 47, 17);
        this.getContentPane().add(usernameText);

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

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

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

        //验证码提示
        JLabel codeText = new JLabel(new ImageIcon("src\\image\\login\\验证码.png"));
        codeText.setBounds(133, 256, 50, 30);
        this.getContentPane().add(codeText);

        //验证码的输入框
        code.setBounds(195, 256, 100, 30);

        code.addMouseListener(this);
        this.getContentPane().add(code);


        String codeStr = CodeUtil.getCode();
        //设置内容
        rightCode.setText(codeStr);
        //绑定鼠标事件
        rightCode.addMouseListener(this);
        //位置和宽高
        rightCode.setBounds(300, 256, 50, 30);
        //添加到界面
        this.getContentPane().add(rightCode);

        //5.添加登录按钮
        login.setBounds(123, 310, 128, 47);
        login.setIcon(new ImageIcon("src\\image\\login\\登录按钮.png"));
        //去除按钮的边框
        login.setBorderPainted(false);
        //去除按钮的背景
        login.setContentAreaFilled(false);
        //给登录按钮绑定鼠标事件
        login.addMouseListener(this);
        this.getContentPane().add(login);

        //6.添加注册按钮
        register.setBounds(256, 310, 128, 47);
        register.setIcon(new ImageIcon("src\\image\\register\\注册按钮.png"));
        //去除按钮的边框
        register.setBorderPainted(false);
        //去除按钮的背景
        register.setContentAreaFilled(false);
        //给注册按钮绑定鼠标事件
        register.addMouseListener(this);
        this.getContentPane().add(register);
        //7.添加背景图片
        JLabel background = new JLabel(new ImageIcon("src\\image\\register\\background.png"));
        background.setBounds(0, 0, 470, 390);
        this.getContentPane().add(background);

    }


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



    //点击
    @Override
    public void mouseClicked(MouseEvent e) {
        if (e.getSource() == login) {
            System.out.println("点击了登录按钮");
            //获取两个文本输入框中的内容
            String usernameInput = username.getText();
            String passwordInput = password.getText();
            //获取用户输入的验证码
            String codeInput = code.getText();

            //创建一个User对象
            User userInfo = new User(usernameInput, passwordInput);
            System.out.println("用户输入的用户名为" + usernameInput);
            System.out.println("用户输入的密码为" + passwordInput);

            if (codeInput.length() == 0) {
                showJDialog("验证码不能为空");
                //刷新验证码
                String code = CodeUtil.getCode();
                rightCode.setText(code);
            } else if (usernameInput.length() == 0 || passwordInput.length() == 0) {
                //校验用户名和密码是否为空
                System.out.println("用户名或者密码为空");
                //调用showJDialog方法并展示弹框
                showJDialog("用户名或者密码为空");
                //清空验证码
                code.setText("");
                //刷新验证码
                String code = CodeUtil.getCode();
                rightCode.setText(code);
            } else if (!codeInput.equalsIgnoreCase(rightCode.getText())) {
                showJDialog("验证码输入错误");
                //清空验证码输入框
                code.setText("");
                //验证码刷新
                String code = CodeUtil.getCode();
                rightCode.setText(code);
            } else if (contains(userInfo,list)) {
                System.out.println("用户名和密码正确可以开始玩游戏了");
                //打开游戏的主界面
                //需要把当前登录的用户名传递给游戏界面
                new GameJFrame();
                //关闭当前登录界面
                this.setVisible(false);

            } else {
                System.out.println("用户名或密码错误");
                showJDialog("用户名或密码错误");
                //清空密码和验证码
                password.setText("");
                code.setText("");
                //更换验证码
                String code = CodeUtil.getCode();
                rightCode.setText(code);
            }
        } else if (e.getSource() == register) {
            System.out.println("点击了注册按钮");
            try {
                new RegisterJFrame();
                this.setVisible(false);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else if (e.getSource() == rightCode) {
            System.out.println("更换验证码");
            //获取一个新的验证码
            String code = CodeUtil.getCode();
            rightCode.setText(code);
        }
    }


    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 mousePressed(MouseEvent e) {
        if (e.getSource() == login) {
            login.setIcon(new ImageIcon("src\\image\\login\\登录按下.png"));
        } else if (e.getSource() == register) {
            register.setIcon(new ImageIcon("src\\image\\register\\注册按下.png"));
        }
    }


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

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

    }

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

    }

    //判断用户在集合中是否存在
    public boolean contains(User userInput,ArrayList<Data> data){
        for (int i = 0; i < data.size(); i++) {
            Data rightUser = data.get(i);
            if(userInput.getUsername().equals(rightUser.getName()) && userInput.getPassword().equals(rightUser.getPassword())){
                //有相同的代表存在,返回true,后面的不需要再比了
                return true;
            }
        }
        //循环结束之后还没有找到就表示不存在
        return false;
    }


}

注册代码:

java">package com.itheima.ui;

import com.itheima.domain.Data;

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

public class RegisterJFrame extends JFrame implements MouseListener {
    ArrayList<Data> list = new ArrayList<>();
    //提升三个输入框的变量的作用范围,让这三个变量可以在本类中所有方法里面可以使用。
    JTextField username = new JTextField();
    JTextField password = new JTextField();
    JTextField rePassword = new JTextField();

    //提升两个按钮变量的作用范围,让这两个变量可以在本类中所有方法里面可以使用。
    JButton submit = new JButton();
    JButton reset = new JButton();


    public RegisterJFrame() throws IOException {
        data();
        initFrame();
        initView();
        setVisible(true);
    }
    public void data() throws IOException {
        File file = new File("data.txt");
        file.createNewFile();
        BufferedReader br = new BufferedReader(new FileReader("data.txt"));
        String str;
        while ((str = br.readLine()) != null) {
            String[] data = str.split("&");
            //name
            String name = data[0].split("=")[1];
            //password
            String password = data[1].split("=")[1];
            list.add(new Data(name, password));
        }
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        //获取输入框中的内容
        String userNameStr = username.getText();
        String passWordStr = password.getText();
        String rePasswordText = rePassword.getText();

        if (e.getSource() == submit){//注册
            System.out.println("注册");
            //判断输入框是否有空
            if ((userNameStr.length() == 0) || (passWordStr.length() == 0) || (rePasswordText.length() == 0)){
                showDialog("账号或密码不能为空");
                //清空密码
                password.setText("");
                rePassword.setText("");
            } else if (!passWordStr.equals(rePasswordText)) {
                showDialog("密码不一致");
                //清空密码
                rePassword.setText("");
            } else if (!tfUsername(userNameStr)) { //账户已存在
                showDialog("账号已存在");
            } else {
                try {
                    //将数据存入本地文件中
                    Data(userNameStr,passWordStr);
                    showDialog("注册成功");
                    this.setVisible(false);
                    new LoginJFrame();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }


            //
        }else if(e.getSource() == reset){//重置
            System.out.println("重置");
            password.setText("");
            rePassword.setText("");
            username.setText("");
        }
    }
    /*
    * 将数据账号数据存入本地文件中
    * 参数1:账号 参数2:密码
    * */
    private void Data(String name , String password) throws IOException {
        String data = "name="+name+"&password="+password;
        BufferedWriter bw = new BufferedWriter(new FileWriter("data.txt",true));
        bw.write(data);
        bw.newLine();
        bw.close();
    }


    /*
    * 检测账号是否存在
    * 返回值 boolean
    * 传入 username
    * */
    private boolean tfUsername(String userName){
        for (Data data : list) {
            if(data.getName().equals(userName))
                return false;
        }
        return true;
    }



    @Override
    public void mousePressed(MouseEvent e) {
        if (e.getSource() == submit) {
            submit.setIcon(new ImageIcon("src\\image\\register\\注册按下.png"));
        } else if (e.getSource() == reset) {
            reset.setIcon(new ImageIcon("src\\image\\register\\重置按下.png"));
        }
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (e.getSource() == submit) {
            submit.setIcon(new ImageIcon("src\\image\\register\\注册按钮.png"));
        } else if (e.getSource() == reset) {
            reset.setIcon(new ImageIcon("src\\image\\register\\重置按钮.png"));
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {

    }

    @Override
    public void mouseExited(MouseEvent e) {

    }

    private void initView() {
        //添加注册用户名的文本
        JLabel usernameText = new JLabel(new ImageIcon("src\\image\\register\\注册用户名.png"));
        usernameText.setBounds(85, 135, 80, 20);

        //添加注册用户名的输入框
        username.setBounds(195, 134, 200, 30);

        //添加注册密码的文本
        JLabel passwordText = new JLabel(new ImageIcon("src\\image\\register\\注册密码.png"));
        passwordText.setBounds(97, 193, 70, 20);

        //添加密码输入框
        password.setBounds(195, 195, 200, 30);

        //添加再次输入密码的文本
        JLabel rePasswordText = new JLabel(new ImageIcon("src\\image\\register\\再次输入密码.png"));
        rePasswordText.setBounds(64, 255, 95, 20);

        //添加再次输入密码的输入框
        rePassword.setBounds(195, 255, 200, 30);

        //注册的按钮
        submit.setIcon(new ImageIcon("src\\image\\register\\注册按钮.png"));
        submit.setBounds(123, 310, 128, 47);
        submit.setBorderPainted(false);
        submit.setContentAreaFilled(false);
        submit.addMouseListener(this);

        //重置的按钮
        reset.setIcon(new ImageIcon("src\\image\\register\\重置按钮.png"));
        reset.setBounds(256, 310, 128, 47);
        reset.setBorderPainted(false);
        reset.setContentAreaFilled(false);
        reset.addMouseListener(this);

        //背景图片
        JLabel background = new JLabel(new ImageIcon("src\\image\\background.png"));
        background.setBounds(0, 0, 470, 390);

        this.getContentPane().add(usernameText);
        this.getContentPane().add(passwordText);
        this.getContentPane().add(rePasswordText);
        this.getContentPane().add(username);
        this.getContentPane().add(password);
        this.getContentPane().add(rePassword);
        this.getContentPane().add(submit);
        this.getContentPane().add(reset);
        this.getContentPane().add(background);
    }

    private void initFrame() {
        //对自己的界面做一些设置。
        //设置宽高
        setSize(488, 430);
        //设置标题
        setTitle("拼图游戏 V1.0注册");
        //取消内部默认布局
        setLayout(null);
        //设置关闭模式
        setDefaultCloseOperation(3);
        //设置居中
        setLocationRelativeTo(null);
        //设置置顶
        setAlwaysOnTop(true);
    }

    //只创建一个弹框对象
    JDialog jDialog = new JDialog();
    //因为展示弹框的代码,会被运行多次
    //所以,我们把展示弹框的代码,抽取到一个方法中。以后用到的时候,就不需要写了
    //直接调用就可以了。
    public void showDialog(String content){
        if(!jDialog.isVisible()){
            //把弹框中原来的文字给清空掉。
            jDialog.getContentPane().removeAll();
            JLabel jLabel = new JLabel(content);
            jLabel.setBounds(0,0,200,150);
            jDialog.add(jLabel);
            //给弹框设置大小
            jDialog.setSize(200, 150);
            //要把弹框在设置为顶层 -- 置顶效果
            jDialog.setAlwaysOnTop(true);
            //要让jDialog居中
            jDialog.setLocationRelativeTo(null);
            //让弹框
            jDialog.setModal(true);
            //让jDialog显示出来
            jDialog.setVisible(true);
        }
    }
}

游戏代码:

java">package com.itheima.ui;

import com.itheima.domain.GameInfo;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.event.*;
import java.io.*;
import java.util.Properties;
import java.util.Random;

public class GameJFrame extends JFrame implements KeyListener, ActionListener {
    //读档
    JMenuItem du1;
    JMenuItem du2;
    JMenuItem du3;
    JMenuItem du4;
    JMenuItem du0;
    //存档
    JMenuItem cun1;
    JMenuItem cun2;
    JMenuItem cun3;
    JMenuItem cun4;
    JMenuItem cun0;

    JMenu cunDang;
    JMenu duDang;


    //JFrame 界面,窗体
    //子类呢?也表示界面,窗体
    //规定:GameJFrame这个界面表示的就是游戏的主界面
    //以后跟游戏相关的所有逻辑都写在这个类中

    //创建一个二维数组
    //目的:用来管理数据
    //加载图片的时候,会根据二维数组中的数据进行加载
    int[][] data = new int[4][4];

    //记录空白方块在二维数组中的位置
    int x = 0;
    int y = 0;

    //定义一个变量,记录当前展示图片的路径
    String path = "src\\image\\animal\\animal3\\";

    //定义一个二维数组,存储正确的数据
    int[][] win = {
            {1, 2, 3, 4},
            {5, 6, 7, 8},
            {9, 10, 11, 12},
            {13, 14, 15, 0}
    };

    //定义变量用来统计步数
    int step = 0;


    //创建选项下面的条目对象
    JMenuItem girl = new JMenuItem("美女");
    JMenuItem animal = new JMenuItem("动物");
    JMenuItem sport = new JMenuItem("运动");
    JMenuItem replayItem = new JMenuItem("重新游戏");
    JMenuItem reLoginItem = new JMenuItem("重新登录");
    JMenuItem closeItem = new JMenuItem("关闭游戏");
    JMenuItem accountItem = new JMenuItem("公众号");


    //创建随机对象
    Random r = new Random();


    public GameJFrame() {
        //初始化界面
        initJFrame();

        //初始化菜单
        initJMenuBar();


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

        //初始化图片(根据打乱之后的结果去加载图片)
        initImage();

        //让界面显示出来,建议写在最后
        this.setVisible(true);

    }


    //初始化数据(打乱)
    private void initData() {
        //1.定义一个一维数组
        int[] tempArr = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
        //2.打乱数组中的数据的顺序
        //遍历数组,得到每一个元素,拿着每一个元素跟随机索引上的数据进行交换
        Random r = new Random();
        for (int i = 0; i < tempArr.length; i++) {
            //获取到随机索引
            int index = r.nextInt(tempArr.length);
            //拿着遍历到的每一个数据,跟随机索引上的数据进行交换
            int temp = tempArr[i];
            tempArr[i] = tempArr[index];
            tempArr[index] = temp;
        }

        /*
         *
         *           5   6   8   9
         *           10  11  15  1
         *           4   7   12  13
         *           2   3   0  14
         *
         *           5   6   8   9   10  11  15  1   4   7   12  13  2   3   0   14
         * */

        //4.给二维数组添加数据
        //遍历一维数组tempArr得到每一个元素,把每一个元素依次添加到二维数组当中
        for (int i = 0; i < tempArr.length; i++) {
            if (tempArr[i] == 0) {
                x = i / 4;
                y = i % 4;
            }
            data[i / 4][i % 4] = tempArr[i];
        }
    }

    //初始化图片
    //添加图片的时候,就需要按照二维数组中管理的数据添加图片
    private void initImage() {

        //清空原本已经出现的所有图片
        this.getContentPane().removeAll();

        if (victory()) {
            //显示胜利的图标
            JLabel winJLabel = new JLabel(new ImageIcon("src\\image\\win.png"));
            winJLabel.setBounds(203, 283, 197, 73);
            this.getContentPane().add(winJLabel);
        }


        JLabel stepCount = new JLabel("步数:" + step);
        stepCount.setBounds(50, 30, 100, 20);
        this.getContentPane().add(stepCount);


        //路径分为两种:
        //绝对路径:一定是从盘符开始的。C:\  D:\
        //相对路径:不是从盘符开始的
        //相对路径相对当前项目而言的。 aaa\\bbb
        //在当前项目下,去找aaa文件夹,里面再找bbb文件夹。

        //细节:
        //先加载的图片在上方,后加载的图片塞在下面。
        //外循环 --- 把内循环重复执行了4次。
        for (int i = 0; i < 4; i++) {
            //内循环 --- 表示在一行添加4张图片
            for (int j = 0; j < 4; j++) {
                //获取当前要加载图片的序号
                int num = data[i][j];
                //创建一个JLabel的对象(管理容器)
                JLabel jLabel = new JLabel(new ImageIcon(path + num + ".jpg"));
                //指定图片位置
                jLabel.setBounds(105 * j + 83, 105 * i + 134, 105, 105);
                //给图片添加边框
                //0:表示让图片凸起来
                //1:表示让图片凹下去
                jLabel.setBorder(new BevelBorder(BevelBorder.LOWERED));
                //把管理容器添加到界面中
                this.getContentPane().add(jLabel);
            }
        }


        //添加背景图片
        JLabel background = new JLabel(new ImageIcon("src\\image\\background.png"));
        background.setBounds(40, 40, 508, 560);
        //把背景图片添加到界面当中
        this.getContentPane().add(background);

        //刷新一下界面
        this.getContentPane().repaint();


    }

    private void initJMenuBar() {
        //创建整个的菜单对象
        JMenuBar jMenuBar = new JMenuBar();
        //创建菜单上面的两个选项的对象 (功能  关于我们)
        JMenu functionJMenu = new JMenu("功能");
        JMenu aboutJMenu = new JMenu("关于我们");
        JMenu changeImage = new JMenu("更换图片");

        cunDang = new JMenu("存档");
        duDang = new JMenu("读档");

        //把美女,动物,运动添加到更换图片当中
        changeImage.add(girl);
        changeImage.add(animal);
        changeImage.add(sport);

        //读档
        du0 = new JMenuItem("读档0(空)");
        du1 = new JMenuItem("读档1(空)");
        du2 = new JMenuItem("读档2(空)");
        du3 = new JMenuItem("读档3(空)");
        du4 = new JMenuItem("读档4(空)");
        cun0 = new JMenuItem("存档0(空)");
        cun1 = new JMenuItem("存档1(空)");
        cun2 = new JMenuItem("存档2(空)");
        cun3 = new JMenuItem("存档3(空)");
        cun4 = new JMenuItem("存档4(空)");
        //添加到存档读档中
        cunDang.add(cun0);
        cunDang.add(cun1);
        cunDang.add(cun2);
        cunDang.add(cun3);
        cunDang.add(cun4);

        duDang.add(du0);
        duDang.add(du1);
        duDang.add(du2);
        duDang.add(du3);
        duDang.add(du4);

        //将更换图片,重新游戏,重新登录,关闭游戏添加到“功能”选项当中
        functionJMenu.add(changeImage);
        functionJMenu.add(replayItem);
        functionJMenu.add(reLoginItem);
        functionJMenu.add(closeItem);
        functionJMenu.add(cunDang);
        functionJMenu.add(duDang);

        //将公众号添加到关于我们当中
        aboutJMenu.add(accountItem);

        //绑定点击事件
        girl.addActionListener(this);
        animal.addActionListener(this);
        sport.addActionListener(this);
        replayItem.addActionListener(this);
        reLoginItem.addActionListener(this);
        closeItem.addActionListener(this);
        accountItem.addActionListener(this);
        du0.addActionListener(this);
        du1.addActionListener(this);
        du2.addActionListener(this);
        du3.addActionListener(this);
        du4.addActionListener(this);
        cun0.addActionListener(this);
        cun1.addActionListener(this);
        cun2.addActionListener(this);
        cun3.addActionListener(this);
        cun4.addActionListener(this);


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

        getGameInfo();

        //给整个界面设置菜单
        this.setJMenuBar(jMenuBar);
    }
    /*实现实时数据
    *
    *
    * */
    private void getGameInfo(){
        //所有File对象表示存档的文件夹
        File file = new File("save");
        //获取里面的所存档信息
        File[] files = file.listFiles();
        //遍历数组获取每一个存档文件
        for (File f : files) {
            //f:表示每一个存档文件
            //获取每一个存档文件中的步数
            GameInfo o = null;
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
                o = (GameInfo) ois.readObject();
                ois.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

            //步数
            int step = o.getStep();
            //文件名
            String name = f.getName();
            System.out.println(name);
            int index = name.charAt(4) - '0'; //存档的序号

            //修改存档读档
            duDang.getItem(index).setText("读档"+index+"("+step+")步");
            cunDang.getItem(index).setText("读档"+index+"("+step+")步");

        }
    }






    private void initJFrame() {
        //设置界面的宽高
        this.setSize(603, 680);
        //设置界面的标题
        this.setTitle("拼图单机版 v1.0");
        //设置界面置顶
        this.setAlwaysOnTop(true);
        //设置界面居中
        this.setLocationRelativeTo(null);
        //设置关闭模式
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //取消默认的居中放置,只有取消了才会按照XY轴的形式添加组件
        this.setLayout(null);
        //给整个界面添加键盘监听事件
        this.addKeyListener(this);

    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    //按下不松时会调用这个方法
    @Override
    public void keyPressed(KeyEvent e) {
        int code = e.getKeyCode();
        if (code == 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("src\\image\\background.png"));
            background.setBounds(40, 40, 508, 560);
            //把背景图片添加到界面当中
            this.getContentPane().add(background);
            //刷新界面
            this.getContentPane().repaint();


        }
    }

    //松开按键的时候会调用这个方法
    @Override
    public void keyReleased(KeyEvent e) {
        //判断游戏是否胜利,如果胜利,此方法需要直接结束,不能再执行下面的移动代码了
        if (victory()) {
            //结束方法
            return;
        }
        //对上,下,左,右进行判断
        //左:37 上:38 右:39 下:40
        int code = e.getKeyCode();
        System.out.println(code);
        if (code == 37) {
            System.out.println("向左移动");
            if (y == 3) {
                return;
            }
            //逻辑:
            //把空白方块右方的数字往左移动
            data[x][y] = data[x][y + 1];
            data[x][y + 1] = 0;
            y++;
            //每移动一次,计数器就自增一次。
            step++;
            //调用方法按照最新的数字加载图片
            initImage();

        } else if (code == 38) {
            System.out.println("向上移动");
            if (x == 3) {
                //表示空白方块已经在最下方了,他的下面没有图片再能移动了
                return;
            }
            //逻辑:
            //把空白方块下方的数字往上移动
            //x,y  表示空白方块
            //x + 1, y 表示空白方块下方的数字
            //把空白方块下方的数字赋值给空白方块
            data[x][y] = data[x + 1][y];
            data[x + 1][y] = 0;
            x++;
            //每移动一次,计数器就自增一次。
            step++;
            //调用方法按照最新的数字加载图片
            initImage();
        } else if (code == 39) {
            System.out.println("向右移动");
            if (y == 0) {
                return;
            }
            //逻辑:
            //把空白方块左方的数字往右移动
            data[x][y] = data[x][y - 1];
            data[x][y - 1] = 0;
            y--;
            //每移动一次,计数器就自增一次。
            step++;
            //调用方法按照最新的数字加载图片
            initImage();
        } else if (code == 40) {
            System.out.println("向下移动");
            if (x == 0) {
                return;
            }
            //逻辑:
            //把空白方块上方的数字往下移动
            data[x][y] = data[x - 1][y];
            data[x - 1][y] = 0;
            x--;
            //每移动一次,计数器就自增一次。
            step++;
            //调用方法按照最新的数字加载图片
            initImage();
        } else if (code == 65) {
            initImage();
        } else if (code == 87) {
            data = new int[][]{
                    {1, 2, 3, 4},
                    {5, 6, 7, 8},
                    {9, 10, 11, 12},
                    {13, 14, 15, 0}
            };
            initImage();
        }
    }


    //判断data数组中的数据是否跟win数组中相同
    //如果全部相同,返回true。否则返回false
    public boolean victory() {
        for (int i = 0; i < data.length; i++) {
            //i : 依次表示二维数组 data里面的索引
            //data[i]:依次表示每一个一维数组
            for (int j = 0; j < data[i].length; j++) {
                if (data[i][j] != win[i][j]) {
                    //只要有一个数据不一样,则返回false
                    return false;
                }
            }
        }
        //循环结束表示数组遍历比较完毕,全都一样返回true
        return true;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //获取当前被点击的条目对象
        Object obj = e.getSource();
        //判断
        if (obj == replayItem) {
            System.out.println("重新游戏");
            //计步器清零
            step = 0;
            //再次打乱二维数组中的数据
            initData();
            //重新加载图片
            initImage();
        } else if (obj == reLoginItem) {
            System.out.println("重新登录");
            //关闭当前的游戏界面
            this.setVisible(false);
            //打开登录界面
            try {
                new LoginJFrame();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else if (obj == closeItem) {
            System.out.println("关闭游戏");
            //直接关闭虚拟机即可
            System.exit(0);
        } else if (obj == accountItem) {
            System.out.println("公众号");
            //创建一个弹框对象
            Properties prop = new Properties();
            try {
                FileInputStream fis = new FileInputStream("game.properties");
                prop.load(fis);
                fis.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            String path =(String) prop.get("account");
            System.out.println(path);
            showJDialog(path);

        } else if (obj == girl) {
            System.out.println("girl");
            //下列代码重复了,自己思考一下,能否抽取成一个方法呢?
            int number = r.nextInt(13) + 1;
            path = "src\\image\\girl\\girl" + number + "\\";
            //计步器清零
            step = 0;
            //再次打乱二维数组中的数据
            initData();
            //重新加载图片
            initImage();
        } else if (obj == animal) {
            System.out.println("animal");
            //下列代码重复了,自己思考一下,能否抽取成一个方法呢?
            int number = r.nextInt(8) + 1;
            path = "src\\image\\animal\\animal" + number + "\\";
            //计步器清零
            step = 0;
            //再次打乱二维数组中的数据
            initData();
            //重新加载图片
            initImage();
        } else if (obj == sport) {
            System.out.println("sport");
            //下列代码重复了,自己思考一下,能否抽取成一个方法呢?
            int number = r.nextInt(10) + 1;
            path = "src\\image\\sport\\sport" + number + "\\";
            //计步器清零
            step = 0;
            //再次打乱二维数组中的数据
            initData();
            //重新加载图片
            initImage();
        } else if (obj == du0 || obj == du2 || obj == du3 || obj == du4 || obj == du1) {
            System.out.println("读档");
            //直接把游戏数据写到本地文件中
            JMenuItem item = (JMenuItem) obj;
            int num = Integer.parseInt(item.getText().substring(2, 3));
            System.out.println(num);
            GameInfo gi = null;
            try {
                ObjectInputStream ois = new ObjectInputStream(new FileInputStream("save\\save" + num + ".data"));
                gi = (GameInfo) ois.readObject();
                ois.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            } catch (ClassNotFoundException ex) {
                throw new RuntimeException(ex);
            }
            data = gi.getData();
            path = gi.getPath();
            step = gi.getStep();
            x = gi.getX();
            y = gi.getY();

            initImage();

        } else if (obj == cun1 || obj == cun2 || obj == cun3 || obj == cun4 || obj == cun0) {
            System.out.println("存档");
            JMenuItem item = (JMenuItem) obj;
            int num = Integer.parseInt(item.getText().substring(2, 3));
            try {
                ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("save\\save" + num + ".data"));
                GameInfo gi = new GameInfo(data, x, y, path, step);
                oos.writeObject(gi);
                oos.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            //修改展示信息
            //存档
            item.setText("存档" + num + "(" + step + ")步");
            //读档
            duDang.getItem(num).setText("读档" + num + "(" + step + ")步");
        }
    }

    private void showJDialog(String filepath) {
        JDialog jDialog = new JDialog();
        //创建一个管理图片的容器对象JLabel
        JLabel jLabel = new JLabel(new ImageIcon(filepath));
        //设置位置和宽高
        jLabel.setBounds(0, 0, 258, 258);
        //把图片添加到弹框当中
        jDialog.getContentPane().add(jLabel);
        //给弹框设置大小
        jDialog.setSize(344, 344);
        //让弹框置顶
        jDialog.setAlwaysOnTop(true);
        //让弹框居中
        jDialog.setLocationRelativeTo(null);
        //弹框不关闭则无法操作下面的界面
        jDialog.setModal(true);
        //让弹框显示出来
        jDialog.setVisible(true);
    }
}


http://www.niftyadmin.cn/n/4978503.html

相关文章

Linux系统编程系列之进程间通信(IPC)-信号

一、什么是信号 信号是进程间通信的一种方式&#xff0c;它是异步通信的。而异步的意思就是不同步&#xff0c;事件的发生和处理没有协同。 二、信号的特性 Linux/Unix系统下&#xff0c;信号总共分成两大类&#xff0c;一类是最常用的标准信号&#xff0c;另一类是后面的引入…

javaee spring jdbcTemplate的使用

依赖 <?xml version"1.0" encoding"UTF-8"?><project xmlns"http://maven.apache.org/POM/4.0.0" xmlns:xsi"http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation"http://maven.apache.org/POM/4.0.0 htt…

Linux知识点 -- Linux多线程(四)

Linux知识点 – Linux多线程&#xff08;四&#xff09; 文章目录 Linux知识点 -- Linux多线程&#xff08;四&#xff09;一、线程池1.概念2.实现3.单例模式的线程池 二、STL、智能指针和线程安全1.STL的容器是否是线程安全的2.智能指针是否是线程安全的 三、其他常见的各种锁…

ast在python架构中的使用

AST学习 AST简介&#xff1a; AST(Abstract syntac tree)是编译原理中的概念&#xff0c;是对源代码语法结构的一种抽象表示&#xff0c;它以树的形式表现编程语言的语法结构&#xff0c;树上的每个节点都表示源代码中的一种结构。 下面的代码展示了以demo.py中的ast语法&…

c++冒泡排序的动画演示+程序实现

冒泡排序&#xff08;Bubble Sort&#xff09;是一种计算机科学领域的较简单的排序算法。 它重复地走访过要排序的元素列&#xff0c;依次比较两个相邻的元素&#xff0c;如果顺序&#xff08;如从大到小、首字母从Z到A&#xff09;错误就把他们交换过来。走访元素的工作是重复…

1018 Public Bike Management 结题记录(dfs剪枝)

个人觉得直接放入代码是最管用的。 其他方法类似&#xff0c;题意请参考其他博主。 #include <bits/stdc.h> using namespace std; const int N 1e4 50;int maxn 2000000000; int c, n, ed, s[N], m, minlen, needn, backn, pre[N]; bool flag, book[N]; vector<p…

第十一章 CUDA的NMS算子实战篇(下篇)

cuda教程目录 第一章 指针篇 第二章 CUDA原理篇 第三章 CUDA编译器环境配置篇 第四章 kernel函数基础篇 第五章 kernel索引(index)篇 第六章 kenel矩阵计算实战篇 第七章 kenel实战强化篇 第八章 CUDA内存应用与性能优化篇 第九章 CUDA原子(atomic)实战篇 第十章 CUDA流(strea…

C++,多态练习

一、定义基类Animals&#xff0c;以及多个派生类&#xff0c;基类中至少包含虚函数perform() #include <iostream>using namespace std;class Aniamls { private:string cry; public:Aniamls() {}Aniamls(string cry):cry(cry) {}virtual void perform() 0; //纯虚函数…