Swing+Mybatis+Maven实现拼图游戏

前言

        这是基于b站阿玮老师的拼图游戏进行扩展,集成mybatis和maven,把注册的玩家信息基于mybatis存储到mysql中,登录是也是从mysql中提取,还有实现更换图片功能,并且添加了排行榜功能。

一、环境装配

文件目录

1.maven搭建

Maven环境还是比较简单的,装一个mysql,mybatis,lombok就可以了,

         
<dependencies>
 <!-- 驱动类-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
</dependencies>

2.mybatis环境配置

        1.xml文件设置

        mybatis制作一个mapper.xml映射文件和它的接口,两个名字尽量一致(包名也尽量一致),还有一个config.xml文件(代码包里面有)。

      2.连接数据库

        idea中是自带数据库的,输入账号和密码连接就可

二、主要技术介绍

        1.数据库实现及mappper实现

        表有两个,一个是登录注册用户表,一个是排行榜所需的表

//用户注册表
create table gameuser
(
    username varchar(20) primary key,//用户名
    password varchar(20) //密码
);

//排行榜数据
create table date
(
    username varchar(20) primary key ,//用户名
    step     int         null,//步数
    date     varchar(50) null //游戏完成时间(用char类型,有点儿业余)
);

      mapper代码实现(sql语句较为简单,用的注解方式)

//用户接口
public interface GameuserMapper{
     //添加用户
    @Insert("insert into gameuser values(#{username},#{password})")
    void insertAll(Gameuser gameuser);
     //根据用户名查询密码
    @Select("select password from gameuser where username=#{username}")
    String selectByName(String username);

}
//排行榜接口
public interface DateMapper {
     //添加排行榜信息
    @Insert("insert into date values(#{username},#{step},#{date})")
    void insertAll(Date date);
     //查询排行榜数据,根据步数升序排列
    @Select("select * from date order by step asc")
    List<Date> selectAll();
}

          2.注册实现

注册就是给数据库中存储用户,如果满足一定的条件就存储到数据库中

package com.example.ui;

import com.example.util.Sql;
import com.example.mapper.GameuserMapper;
import com.example.pojo.Gameuser;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Objects;

//继承JFrame,实现事件
public class RegisterJFrame extends JFrame implements ActionListener {

    JTextField jTextField,jTextField1,jTextField2;
    JButton jButton,jButton1;
    public RegisterJFrame(){
        //初始化界面
        intiJFrame();
        //初始化菜单
        initJMenuBar();
        this.setVisible(true);

    }
    private void intiJFrame() {
        //设置界面大小
        this.setSize(488,430);
        //设置界面的主题
        this.setTitle("登录界面");
        //设置界面置顶
        this.setAlwaysOnTop(true);
        //设置界面居中
        this.setLocationRelativeTo(null);
        //设置关闭模式
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //设置窗口的拉伸
        this.setResizable(false);
        //取消默认的居中放置
        this.setLayout(null);
        //打开界面
        this.setVisible(true);
    }
    private void initJMenuBar() {
        //清空原本的图片
        this.getContentPane().removeAll();
        //定义注册主界面
        JLabel zhuti = new JLabel();
        zhuti.setBounds(0,0,470,390);
        //以下添加了三个图片
        JLabel jLabel = new JLabel(new ImageIcon("image/register/注册用户名.png"));
        jLabel.setBounds(100,140,90,20);//定义位置大小
        this.getContentPane().add(jLabel);//添加到主界面(以下操作一样)

        JLabel jLabel1 = new JLabel(new ImageIcon("image/register/注册密码.png"));
        jLabel1.setBounds(110,200,90,20);
        this.getContentPane().add(jLabel1);

        JLabel jLabel2 = new JLabel(new ImageIcon("image/register/再次输入密码.png"));
        jLabel2.setBounds(90,260,100,20);
        this.getContentPane().add(jLabel2);

        //定义用户名输入框
        jTextField = new JTextField();
        jTextField.setBounds(195,134,200,30);
        this.getContentPane().add(jTextField);
        //定义密码输入框
        jTextField1 = new JTextField();
        jTextField1.setBounds(195,195,200,30);
        this.getContentPane().add(jTextField1);
        //定义确认密码输入框
        jTextField2 = new JTextField();
        jTextField2.setBounds(195,255,200,30);
        this.getContentPane().add(jTextField2);
        //定义注册按钮
        jButton = new JButton("注册");
        jButton.setBounds(100,300,105,40);
        jButton.addActionListener(this);//添加到点击事件中
        //用图片覆盖按钮(好看)
        jButton.setIcon(new ImageIcon("image/register/注册按钮.png"));
        this.getContentPane().add(jButton);
        //定义重置按钮
        jButton1 = new JButton("重置");
        jButton1.setBounds(250,300,105,40);
        jButton1.addActionListener(this);

        jButton1.setIcon(new ImageIcon("image/register/重置按钮.png"));
        this.getContentPane().add(jButton1);

        //添加背景图片
        JLabel label = new JLabel(new ImageIcon("image/register/background.png"));
        label.setBounds(-59,-47,592,490);
        //把背景图片添加到界面中
        this.getContentPane().add(label);
        //刷新一下界面
        this.getContentPane().repaint();

    }

    //没连接数据库之前用文件存储信息,已弃用
    public void file(String a,String b) throws IOException {
        FileWriter writer = new FileWriter("user.txt",true);
        writer.write(a);
        writer.write("&");
        writer.write(b);
        writer.write("\r\n");
        writer.close();

    }
    //事件处理
    @Override
    public void actionPerformed(ActionEvent e) {
        //打印按钮名称
        System.out.println(e.getActionCommand());
        //点击注册按钮
        if(Objects.equals(e.getActionCommand(), "注册")){
            //如果用户名为空,则提示用户名为空
            if(Objects.equals(jTextField.getText(),"")){
                JOptionPane.showMessageDialog(this, "用户名为空!");
            } else if(!Objects.equals(jTextField1.getText(), jTextField2.getText())|| Objects.equals(jTextField1.getText(), "")) {
                //如果两次密码输入不一致,则提示
                JOptionPane.showMessageDialog(this, "两次密码输入不一致!");
            } else {
                //符合注册条件
                //输入框信息
                System.out.println(jTextField.getText());
                System.out.println(jTextField1.getText());
                System.out.println(jTextField2.getText());
                //定义用户接口
                GameuserMapper mapper;
                try {
                    //接口实现(写的一个接口调用,代码中有)
                    mapper = new Sql().sql().getMapper(GameuserMapper.class);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                //定义用户
                Gameuser gameuser = new Gameuser();
                gameuser.setUsername(jTextField.getText());
                gameuser.setPassword(jTextField1.getText());
                //调用mapper中注册sql
                mapper.insertAll(gameuser);
                //设置按下按钮样式
                jButton.setIcon(new ImageIcon("image/register/注册按下.png"));
                //提示注册成功
                JOptionPane.showMessageDialog(this, "注册成功!");
                //调用登录面板
                new LoginJFrame();

            }
            //点击登录按钮
        } else if (Objects.equals(e.getActionCommand(), "重置")) {
            //使三个输入框为空
            jTextField.setText("");
            jTextField1.setText("");
            jTextField2.setText("");
            //定义按下样式
            jButton1.setIcon(new ImageIcon("image/register/重置按下.png"));
            
            try {
                //定义0.2秒后恢复样式
                Thread.sleep(200);
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }
            jButton1.setIcon(new ImageIcon("image/register/重置按钮.png"));

        }
    }
}

3.登录实现

原理就是根据输入的用户名从数据库中获取密码与输入密码的进行对比判断状态

        和注册页面相似的代码没有做注释

package com.example.ui;

import com.example.util.Sql;
import com.example.mapper.GameuserMapper;


import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class LoginJFrame extends JFrame implements ActionListener {

    public static  String username;
    JTextField jTextField,jTextField1;
    JButton jButton;
    public LoginJFrame(){
        //初始化界面
        intiJFrame();
        //初始化菜单
        initJMenuBar();
        this.setVisible(true);

    }
    private void initJMenuBar() {
        this.getContentPane().removeAll();

        JLabel zhuti = new JLabel();
        zhuti.setBounds(0,0,470,390);

        JLabel jLabel = new JLabel(new ImageIcon("image/login/用户名.png"));
        jLabel.setBounds(116,135,51,19);
        this.getContentPane().add(jLabel);

        JLabel jLabel1 = new JLabel(new ImageIcon("image/login/密码.png"));
        jLabel1.setBounds(130,195,51,19);
        this.getContentPane().add(jLabel1);

        JButton jLabel2 = new JButton("去注册");
        jLabel2.setBounds(300,267,80,30);
        jLabel2.setForeground(Color.gray);
        jLabel2.addActionListener(this);
        this.getContentPane().add(jLabel2);


        jTextField = new JTextField();
        jTextField.setBounds(195,134,200,30);
        this.getContentPane().add(jTextField);

        jTextField1 = new JTextField();
        jTextField1.setBounds(195,195,200,30);
        this.getContentPane().add(jTextField1);

        jButton = new JButton("Login");
        jButton.setBounds(183,260,105,40);
        jButton.addActionListener(this);

        jButton.setIcon(new ImageIcon("image/login/登录按钮.png"));
        this.getContentPane().add(jButton);
        //添加背景图片
        JLabel label = new JLabel(new ImageIcon("image/login/background.png"));
        label.setBounds(-59,-47,592,490);
//        把背景图片添加到界面中
        this.getContentPane().add(label);
//        刷新一下界面
        this.getContentPane().repaint();

    }

    private void intiJFrame() {
        this.setSize(488,430);
        //设置界面的主题
        this.setTitle("登录界面");
        //设置界面置顶
        this.setAlwaysOnTop(true);
        //设置界面居中
        this.setLocationRelativeTo(null);
        //设置关闭模式
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setResizable(false);//设置窗口的拉伸
        //取消默认的居中放置
        this.setLayout(null);
        this.setVisible(true);
    }
    //文件获取用户信息,已弃用
    public Map<String,String> file() throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("user.txt"));
        String user;
        Map<String,String> map = new HashMap<>();
        while (true) {
            user = reader.readLine();
            if(user!=null) {
                System.out.println(user.split("&")[0]);
                System.out.println(user.split("&")[1].split("\r\n")[0]);
                map.put(user.split("&")[0], user.split("&")[1]);
            }else {
                break;
            }
        }
        reader.close();
        return map;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        //点击去注册按钮,没账号可以跳转注册页面
        if (Objects.equals(e.getActionCommand(), "去注册")){
            System.out.println("asdf");
            new RegisterJFrame();
            //点击登录按钮
        } else if (Objects.equals(e.getActionCommand(), "Login")){
            System.out.println("点击Login");
            System.out.println(jTextField.getText());
            System.out.println(jTextField1.getText());
            GameuserMapper mapper;
            try {
                mapper = new Sql().sql().getMapper(GameuserMapper.class);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            //用用户名获取密码
            String gameuser = mapper.selectByName(jTextField.getText());
            //用户名获取密码为空,判定用户不存在
            if (gameuser==null) {
                jButton.setIcon(new ImageIcon("image/login/登录按下.png"));
                JOptionPane.showMessageDialog(this, "该用户未注册!");
                jButton.setIcon(new ImageIcon("image/login/登录按钮.png"));
                //用户名获取密码等于输入框密码
            } else if (Objects.equals(gameuser, jTextField1.getText())) {
                //登录按钮按下样式
                jButton.setIcon(new ImageIcon("image/login/登录按下.png"));
                username=jTextField.getText();
                System.out.println(username);
                try {
                    new GameJFrame();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                this.setVisible(false);
                
            }else {//用户名获取密码不等于输入框密码
                jButton.setIcon(new ImageIcon("image/login/登录按下.png"));
                JOptionPane.showMessageDialog(this, "密码错误!");
                jButton.setIcon(new ImageIcon("image/login/登录按钮.png"));
            }
        }


    }


}

4.更换图片

        主要是把图片地址定义,然后根据Collection的方法打乱数据在选择的图片种类中生成一个全新的图片

@Override
public void actionPerformed(ActionEvent e) {

    //随机图片
    ArrayList<Integer> list = new ArrayList<>();
    Collections.addAll(list,1,2,3,4,5,6,7,8);
    Collections.shuffle(list);
    Object obj = e.getSource();
    //判断
    if (obj==replayItem){
        System.out.println("重新游戏");
        //计步器清零
        this.step=0;
        //再次打乱
        initDate();
        //重新加载
        intiImage();
    } else if (obj == reLoginItem) {
        System.out.println("重新登陆");
        //关闭当前游戏界面
        this.setVisible(false);
        //打开登录界面
        new LoginJFrame();
    }else if (obj==closeItem){
        System.out.println("关闭游戏");
        System.exit(0);
    }else if (obj==accountItem){
        System.out.println("公众号");

        //创建一个弹框对象
        JDialog jDialog = new JDialog();
        //创建一个管理图片的容器对象
        JLabel jLabel = new JLabel(new ImageIcon("image/damie.jpg"));
        //设置位置宽高
        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);
    } else if (obj == animal) {
        System.out.println("animal");
        this.path="image/animal/animal"+list.get(0)+"/";
        //计步器清零
        this.step=0;
        //再次打乱
        initDate();
        //重新加载
        intiImage();
        System.out.println(path);

    }else if (obj == girl) {
        System.out.println("girl");
        this.path="image/girl/girl"+list.get(0)+"/";
        //计步器清零
        this.step=0;
        //再次打乱
        initDate();
        //重新加载
        intiImage();

    }else if (obj == sport) {
        System.out.println("sport");
        this.path="image/sport/sport"+list.get(0)+"/";
        //计步器清零
        this.step=0;
        //再次打乱
        initDate();
        //重新加载
        intiImage();

    }
}

5.排行榜统计

根据登录的姓名和胜利后走的总步数存储到数据库中,并在排行榜中显示出来

弹窗实现

//调用排行榜表的mapper
DateMapper mapper = new Sql().sql().getMapper(DateMapper.class);
//获取数据库信息
List<com.example.pojo.Date> dates = mapper.selectAll();
//定义二维数组,因为JTable支持vector,object,String,int,不支持list<>
String[][] date = new String[dates.size()][20];
//根据循环把list转为数组
for (int i=0;i<dates.size();i++){
    date[i][0]= String.valueOf(i+1);
    date[i][1]=dates.get(i).getUsername();
    date[i][2]= String.valueOf(dates.get(i).getStep());
    date[i][3]=dates.get(i).getDate();
}
//排行榜头信息
String[] name=new String[]{"排名","姓名","步数","日期"};
JTable jTable = new JTable(date,name);
//设置某一列的宽度
jTable.getColumnModel().getColumn(0).setPreferredWidth(17);
jTable.getColumnModel().getColumn(1).setPreferredWidth(17);
jTable.getColumnModel().getColumn(2).setPreferredWidth(17);
//信息不可修改
jTable.setEnabled(false);
jTable.setSize(603,680);
pm.add(new JScrollPane(jTable));

6.游戏主页面

package com.example.ui;

import com.example.util.Sql;
import com.example.mapper.DateMapper;
import lombok.SneakyThrows;

import javax.swing.*;
import javax.swing.border.BevelBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;


public class GameJFrame extends JFrame implements KeyListener, ActionListener {

    int[][] temp = new int[4][4];
    String path="image/animal/animal3/";
    int[][] win = new int[][]{
            {1,2,3,4},
            {5,6,7,8},
            {9,10,11,12},
            {13,14,15,0}
    };
    public GameJFrame() throws IOException {
        //初始化界面
        intiJFrame();

        //初始化菜单
        initJMenuBar();

        //初始化数据
        initDate();

        //初始化图片
        intiImage();

        this.setVisible(true);
    }
    int x=0,y=0;
    int step=0;
    //创建选项下面的条目对象
    JMenuItem replayItem = new JMenuItem("重新游戏");
    JMenu menu;
    JMenu jMenuBar1 = new JMenu("选择图片");
    JMenuItem animal = new JMenuItem("animal");
    JMenuItem girl = new JMenuItem("girl");
    JMenuItem sport = new JMenuItem("sport");

    JMenuItem reLoginItem = new JMenuItem("重新登录");
    JMenuItem closeItem = new JMenuItem("关闭游戏");

    JMenuItem accountItem = new JMenuItem("公众号");
    private void initDate() {

        ArrayList<Integer> list = new ArrayList<>();

        Collections.addAll(list,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15);

        Collections.shuffle(list);

        for (int i=0;i<list.size();i++){
            if(list.get(i)==0){
                x=i/4;
                y=i%4;
            }
            temp[i/4][i%4]= list.get(i);


        }

    }

    @SneakyThrows
    private void intiImage() {
    //清空原本已经出现的所有图片
        this.getContentPane().removeAll();

        if (victory()){
            //显示胜利的图标
            JLabel winjlable = new JLabel(new ImageIcon("image/win.png"));
            winjlable.setBounds(203,273,197,73);
            this.getContentPane().add(winjlable);
            Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            DateMapper mapper;
            try {
                mapper = new Sql().sql().getMapper(DateMapper.class);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            com.example.pojo.Date date1 = new com.example.pojo.Date();
            date1.setUsername(LoginJFrame.username);
            date1.setStep(step);
            date1.setDate(formatter.format(date));

            mapper.insertAll(date1);
            System.out.println(formatter.format(date));
            System.out.println(LoginJFrame.username);
            System.out.println(step);
        }

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

        for (int i=0;i<4;i++) {
            for (int j=0;j<4;j++) {
                //获取当前要加载图片的序号
                int num = temp[i][j];
                //创建一个图片ImageIcon的对象
                ImageIcon icon = new ImageIcon(path+num+".jpg");
                //创建一个JLabel的对象(管理容器)
                JLabel jLabel = new JLabel(icon);
                //制定图片位置
                jLabel.setBounds(105*j+83,105*i+100,105,105);
                //给图片添加边框
                //0: 表示让图片凸起来
                //1: 表示让图片凹下去
                jLabel.setBorder(new BevelBorder(BevelBorder.LOWERED));
                //把管理容器添加到界面中
                this.getContentPane().add(jLabel);
            }
        }
        //添加背景图片
        JLabel label = new JLabel(new ImageIcon("image/background.png"));
        label.setBounds(37,6,508,560);

        //把背景图片添加到界面中
        this.getContentPane().add(label);

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

    private void initJMenuBar() throws IOException {
        //初始化菜单
        //创建整个的菜单对象
        JMenuBar jMenuBar = new JMenuBar();
        //创建菜单上面的两个选项的对象
        JMenu functionJMenu = new JMenu("功能");
        JMenu aboutJMenu = new JMenu("关于我们");
        JMenu pm = new JMenu("排行榜");
        menu = new JMenu("教程");

        JLabel jp=new JLabel("<html><p style=\"text-align: center\">游戏说明:<p><br>&emsp;&emsp;1.按键盘上下左右可以使空白格上下左右的图片与之对换,完成之后会显示成功。<br>&emsp;&emsp;2.长按a可以查看原图。<br>&emsp;&emsp;3.按w可以一键成功。</html>; ");    //创建一个JPanel对象
        jp.setBounds(0,-20,330,200);
        jp.setFont(new Font("楷体",Font.BOLD,18));    //修改字体样式
        JTextArea jta=new JTextArea("",10,30);
        jta.setEditable(false);
        jta.add(jp);
        menu.add(jta);

        DateMapper mapper = new Sql().sql().getMapper(DateMapper.class);
        List<com.example.pojo.Date> dates = mapper.selectAll();
        String[][] date = new String[dates.size()][20];
        for (int i=0;i<dates.size();i++){
            date[i][0]= String.valueOf(i+1);
            date[i][1]=dates.get(i).getUsername();
            date[i][2]= String.valueOf(dates.get(i).getStep());
            date[i][3]=dates.get(i).getDate();
        }
        String[] name=new String[]{"排名","姓名","步数","日期"};
        JTable jTable = new JTable(date,name);
        jTable.getColumnModel().getColumn(0).setPreferredWidth(17);
        jTable.getColumnModel().getColumn(1).setPreferredWidth(17);
        jTable.getColumnModel().getColumn(2).setPreferredWidth(17);
        jTable.setEnabled(false);
        jTable.setSize(603,680);
        pm.add(new JScrollPane(jTable));

        jMenuBar1.add(animal);
        jMenuBar1.add(girl);
        jMenuBar1.add(sport);
        //将每一个选项下面的条目添加到选项当中
        functionJMenu.add(replayItem);
        functionJMenu.add(jMenuBar1);
        functionJMenu.add(reLoginItem);
        functionJMenu.add(closeItem);

        aboutJMenu.add(accountItem);

        //添加到点击事件中
        animal.addActionListener(this);
        girl.addActionListener(this);
        sport.addActionListener(this);

        replayItem.addActionListener(this);
        reLoginItem.addActionListener(this);
        closeItem.addActionListener(this);

        accountItem.addActionListener(this);

        //将菜单里面的两个选项添加到菜单当中
        jMenuBar.add(functionJMenu);
        jMenuBar.add(aboutJMenu);
        jMenuBar.add(menu);
        jMenuBar.add(pm);
        //给整个界面设置菜单
        this.setJMenuBar(jMenuBar);
    }

    private void intiJFrame() {
        //设置宽高
        this.setSize(603,680);
        //设置界面的主题
        this.setTitle("拼图单机版 v1.0");
        //设置界面置顶
        this.setAlwaysOnTop(true);
        //设置界面居中
        this.setLocationRelativeTo(null);
        //设置关闭模式
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //取消默认的居中放置
        this.setLayout(null);
        //给整个界面添加键盘监听事件
        this.addKeyListener(this);
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (victory()) {
            return;
        }
        int code = e.getKeyCode();
        if (code==65){
            //把界面中所有的图片删除
            this.getContentPane().removeAll();
            //加载第一张完整的图片
            JLabel jLabel = new JLabel(new ImageIcon(path+"all.jpg"));
            jLabel.setBounds(83,100,420,420);
            this.getContentPane().add(jLabel);
            //添加背景图片
            JLabel label = new JLabel(new ImageIcon("image/background.png"));
            label.setBounds(37,6,508,560);
            //把背景图片添加到界面中
            this.getContentPane().add(label);
            //刷新一下界面
            this.getContentPane().repaint();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (victory()) {
            return;
        }
        //对上下左右进行判断
        //左:37 上:38 右:39 下:40
        int code = e.getKeyCode();
        if(code==37){
            System.out.println("向左移动");

            if (y==3){
                return;
            }
            temp[x][y]=temp[x][y+1];
            temp[x][y+1]=0;
            y++;
            step++;
            intiImage();
        } else if (code == 38) {
            System.out.println("向上移动");

            if (x==3){
                return;
            }
            temp[x][y]=temp[x+1][y];
            temp[x+1][y]=0;
            x++;
            step++;

            intiImage();
        } else if (code == 39) {
            System.out.println("向右移动");

            if (y==0){
                return;
            }
            temp[x][y]=temp[x][y-1];
            temp[x][y-1]=0;
            y--;
            step++;

            intiImage();
        } else if (code == 40) {
            System.out.println("向下移动");

            if (x==0){
                return;
            }
            temp[x][y]=temp[x-1][y];
            temp[x-1][y]=0;
            x--;
            step++;

            intiImage();
        } else if (code==65) {
            intiImage();
        } else if (code==87) {
            temp = new int[][]{
                    {1,2,3,4},
                    {5,6,7,8},
                    {9,10,11,12},
                    {13,14,15,0}
            };
            x=3;
            y=3;
            intiImage();
        }
    }

    public boolean victory(){
        for(int i=0;i< temp.length;i++){
            for(int j=0;j<temp[i].length;j++){
                if(temp[i][j]!=win[i][j]){
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void actionPerformed(ActionEvent e) {

        //随机图片
        ArrayList<Integer> list = new ArrayList<>();
        Collections.addAll(list,1,2,3,4,5,6,7,8);
        Collections.shuffle(list);
        Object obj = e.getSource();
        //判断
        if (obj==replayItem){
            System.out.println("重新游戏");
            //计步器清零
            this.step=0;
            //再次打乱
            initDate();
            //重新加载
            intiImage();
        } else if (obj == reLoginItem) {
            System.out.println("重新登陆");
            //关闭当前游戏界面
            this.setVisible(false);
            //打开登录界面
            new LoginJFrame();
        }else if (obj==closeItem){
            System.out.println("关闭游戏");
            System.exit(0);
        }else if (obj==accountItem){
            System.out.println("公众号");

            //创建一个弹框对象
            JDialog jDialog = new JDialog();
            //创建一个管理图片的容器对象
            JLabel jLabel = new JLabel(new ImageIcon("image/damie.jpg"));
            //设置位置宽高
            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);
        } else if (obj == animal) {
            System.out.println("animal");
            this.path="image/animal/animal"+list.get(0)+"/";
            //计步器清零
            this.step=0;
            //再次打乱
            initDate();
            //重新加载
            intiImage();
            System.out.println(path);

        }else if (obj == girl) {
            System.out.println("girl");
            this.path="image/girl/girl"+list.get(0)+"/";
            //计步器清零
            this.step=0;
            //再次打乱
            initDate();
            //重新加载
            intiImage();

        }else if (obj == sport) {
            System.out.println("sport");
            this.path="image/sport/sport"+list.get(0)+"/";
            //计步器清零
            this.step=0;
            //再次打乱
            initDate();
            //重新加载
            intiImage();

        }
    }
}

结语

        以下是完整代码链接,需要可以自行下载,有什么问题也可以私信

https://download.csdn.net/download/A1234567asdpoi/88397105

百度网盘

https://pan.baidu.com/s/1BPFVmmrIL9D-l7S2weqdHQ?pwd=88l2

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值