4.2学习总结 API+拼图小游戏半成品

发布于:2025-04-07 ⋅ 阅读:(11) ⋅ 点赞:(0)

SimpleDateFormat

Date中时间的格式是固定的,如果我们想要将时间变为我们喜欢的格式,就可以使用SimpleDateFormat来改变时间的格式。

例如:

//1利用空参构造创建SimpleDateFormat的对象,默认格式
        SimpleDateFormat sdf=new SimpleDateFormat();
        Date d1=new Date(0L);
        String str1=sdf.format(d1);
        System.out.println(str1);

        //2利用带参构造创建SimpleDateFormat的对象,指定格式
        SimpleDateFormat sdf2=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
        String str2=sdf2.format(d1);
        System.out.println(str2);

阶段项目:拼图游戏

游戏功能已经写完了,代码如下

package 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[][] data = new int[4][4];

    //记录空白方块在二维数组中的索引
    int x = 0;
    int y = 0;
    //定义一个变量,记录当前展示图片的路径
    String path = "puzzlegame\\image\\animal\\animal3\\";
    //定义一个二维数组,用来判断胜利
    int[][] win = {
            {1,2,3,4},
            {5,6,7,8},
            {9,10,11,12},
            {13,14,15,0}
    };

    //创建选项下面的条目对象
    JMenuItem girlJMenuItem = new JMenuItem("美女");
    JMenuItem animalJMenuItem = new JMenuItem("动物");
    JMenuItem sportJMenuItem = new JMenuItem("运动");
    JMenuItem replayJMenuItem = new JMenuItem("重新游戏");
    JMenuItem reLoginJMenuItem = new JMenuItem("重新登录");
    JMenuItem closeJMenuItem = new JMenuItem("关闭游戏");
    JMenuItem accountJMenuItem = new JMenuItem("公众号");
    //定义一个变量,用来统计步数
    int step = 0;

    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;
        }

        //3.遍历一维数组,把一维数组中的元素放到二维数组中
        for (int i = 0; i < tempArr.length; i++) {
            if(tempArr[i] == 0){
                //记录0的索引
                x = i/4;
                y = i%4;
            }
                //i/4 表示二维数组的行索引
                //i%4 表示二维数组的列索引
                data[i/4][i%4] = tempArr[i];
        }

    }

    //初始化图片
    //添加图片的时候,按照二维数组中的数据,来添加图片
    private void initImage() {
        //清空原本已经出现的所有图片
        this.getContentPane().removeAll();

        if(victory()){
            //添加胜利的图片
            JLabel winJLabel = new JLabel(new ImageIcon("puzzlegame\\image\\win.png"));
            winJLabel.setBounds(203,283,197,73);
            //把图片添加到界面中
            this.getContentPane().add(winJLabel);
        }

        //添加步数
        JLabel stepJLabel = new JLabel("步数:"+step);
        stepJLabel.setBounds(50,30,100,20);
        //把步数添加到界面中
        this.getContentPane().add(stepJLabel);

        //先添加的图片在上方,后添加的图片在下方
        //外循环---把内循环的代码重复执行4次
        for (int i = 0; i < 4; i++) {
            //内循环---表示在一行添加四张图片
            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);
                //给图片添加边框
                jLabel.setBorder(new BevelBorder(BevelBorder.LOWERED));
                //把管理容器添加到界面中
                this.getContentPane().add(jLabel);
                //添加一次之和number需要自增,表示下一次加载后面一张图片
            }
        }

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


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


    }

    //创建菜单
    private void initJMenuBar() {
        //创建整个的菜单对象
        JMenuBar jMenuBar = new JMenuBar();

        //创建菜单上面的两个选项的对象(功能 关于我们)
        JMenu functionJMenu = new JMenu("功能");
        JMenu aboutJMenu = new JMenu("关于我们");
        JMenu changeJMenu = new JMenu("更换图片");

        //将每一个选项下面的条目添加到选项当中
        changeJMenu.add(girlJMenuItem);
        changeJMenu.add(animalJMenuItem);
        changeJMenu.add(sportJMenuItem);

        functionJMenu.add(changeJMenu);
        functionJMenu.add(replayJMenuItem);
        functionJMenu.add(reLoginJMenuItem);
        functionJMenu.add(closeJMenuItem);

        aboutJMenu.add(accountJMenuItem);

        //给选项下面的条目添加监听
        girlJMenuItem.addActionListener(this);
        animalJMenuItem.addActionListener(this);
        sportJMenuItem.addActionListener(this);
        replayJMenuItem.addActionListener(this);
        reLoginJMenuItem.addActionListener(this);
        closeJMenuItem.addActionListener(this);
        accountJMenuItem.addActionListener(this);

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

        //给整个界面设置菜单
        this.setJMenuBar(jMenuBar);
    }

    //初始化界面
    private void initJFrame() {
        //设置界面的宽高
        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) {

        int code = e.getKeyCode();

        if(code == 65){
            //把界面中的图片全部删除
            this.getContentPane().removeAll();
            //加载第一张完整的图片
            JLabel jLabel = new JLabel(new ImageIcon(path+"all.jpg"));
            jLabel.setBounds(83,134,420,420);
            //把图片添加到界面中
            this.getContentPane().add(jLabel);
            //加载背景图片
            JLabel background = new JLabel(new ImageIcon("puzzlegame\\image\\background.png"));
            background.setBounds(40,40,520,600);
            //把背景图片添加到界面中
            this.getContentPane().add(background);
            //刷新界面
            this.getContentPane().repaint();


        }
    }

    //松开按键时,触发该方法
    @Override
    public void keyReleased(KeyEvent e) {
        //判断游戏是否胜利,如果胜利了,就不再接收键盘的输入了
        if(victory()){
            return;
        }

        //对上,下,左,右四个方向键进行判断
        //左:37 上:38 右:39 下:40
        int code = e.getKeyCode();
        if(code == 37){
            //左
            if(y == 3){
                //如果空白方块已经在最左边了,就不能再往左移动了
                return;
            }
            System.out.println("向左移动");
            data[x][y] = data[x][y+1];
            data[x][y+1] = 0;
            y++;
            step++;
            //重新加载图片
            initImage();
        }else if(code == 38){
            //上
            if(x == 3){
                //如果空白方块已经在最上面了,就不能再往上移动了
                return;
            }
            System.out.println("向上移动");
            data[x][y] = data[x+1][y];
            data[x+1][y] = 0;
            x++;
            step++;
            //重新加载图片
            initImage();
        }else if(code == 39){
            //右
            if(y == 0){
                //如果空白方块已经在最右边了,就不能再往右移动了
                return;
            }
            System.out.println("向右移动");
            data[x][y] = data[x][y-1];
            data[x][y-1] = 0;
            y--;
            step++;
            //重新加载图片
            initImage();
        }else if(code == 40){
            //下
            if(x == 0){
                //如果空白方块已经在最下面了,就不能再往下移动了
                return;
            }
            System.out.println("向下移动");
            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();
        }
    }

    //判断是否胜利
    public boolean victory(){
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                if(data[i][j] != win[i][j]){
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //获取到当前点击的条目对象
        Object obj = e.getSource();
        if(obj == replayJMenuItem){
            System.out.println("重新游戏");

            //计步器清零
            step = 0;
            //重新打乱图片的顺序
            initData();
            //重新加载图片
            initImage();

        }else if(obj == reLoginJMenuItem){
            System.out.println("重新登录");
            //关闭当前的游戏界面
            this.setVisible(false);
            //打开登录界面
            new LoginJFrame();
        }else if(obj == closeJMenuItem){
            System.out.println("关闭游戏");
            System.exit(0);
        }else if(obj == accountJMenuItem){
            System.out.println("公众号");
            //创建一个弹窗对象
            JDialog jDialog = new JDialog();
            //创建一个弹窗的容器对象JLabel
            JLabel jLabel = new JLabel(new ImageIcon("puzzlegame\\image\\about.png"));
            //设置位置和宽高
            jDialog.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 == girlJMenuItem){
            System.out.println("美女");
            Random r=new Random();
            int i=r.nextInt(13)+1;
            path="puzzlegame\\image\\girl\\girl"+i+"\\";
            step=0;
            initData();
            initImage();
        }else if(obj == animalJMenuItem){
            System.out.println("动物");
            Random r=new Random();
            int i=r.nextInt(8)+1;
            path="puzzlegame\\image\\animal\\animal"+i+"\\";
            step=0;
            initData();
            initImage();
        }else if(obj == sportJMenuItem){
            System.out.println("运动");
            Random r=new Random();
            int i=r.nextInt(10)+1;
            path="puzzlegame\\image\\sport\\sport"+i+"\\";
            step=0;
            initData();
            initImage();
        }
    }
}

运行结果如图

可以按住A键实现完整的图片,W键直接胜利,同时可以通过菜单实现更换图片,重新登录,重新开始游戏,退出,查看公众号等功能。

此外,登录界面刚刚实现图形化界面

代码如下

package ui;

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

public class LoginJFrame extends JFrame implements MouseListener
{
    //表示登录界面
    //创建一个集合存储正确的用户名和密码
    static ArrayList<User>list=new ArrayList<>();
    static {
        list.add(new User("阳雨婵","Nell羊"));
        list.add(new User("何治锦","牢大666"));
    }

    JButton login = new JButton();
    JButton register = new JButton();
    public LoginJFrame(){
        //初始化界面
        initJFramed();

        //初始化图片
        initView();

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

    //初始化页面
    private void initView() {
        //1.添加用户名文字
        JLabel usernameText = new JLabel(new ImageIcon("puzzlegame\\image\\login\\用户名.png"));
        usernameText.setBounds(116,135,47,17);
        this.getContentPane().add(usernameText);

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

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

        //4.添加密码输入框
        JPasswordField password = new JPasswordField();
        password.setBounds(195,194,200,30);
        this.getContentPane().add(password);

        //5.添加验证码文字
        JLabel codeText = new JLabel(new ImageIcon("puzzlegame\\image\\login\\验证码.png"));
        codeText.setBounds(133,256,50,30);
        this.getContentPane().add(codeText);

        //6.添加验证码输入框
        JTextField code = new JTextField();
        code.setBounds(195,256,100,30);
        this.getContentPane().add(code);

        //随机生成一个验证码
        String codeStr= CodeUtil.getCode();
        JLabel rightCode=new JLabel();
        //设置内容
        rightCode.setText(codeStr);
        //位置和宽高
        rightCode.setBounds(300,256,50,30);
        //添加到桌面
        this.getContentPane().add(rightCode);

        //7.添加登录按钮
        login.setBounds(120,310,128,47);
        login.setIcon(new ImageIcon("puzzlegame\\image\\login\\登录按钮.png"));
        //去除按钮的边框
        login.setBorderPainted(false);
        //去除按钮的背景
        login.setContentAreaFilled(false);
        //添加鼠标监听事件
        login.addMouseListener(this);
        this.getContentPane().add(login);

        //8.添加注册按钮
        register.setBounds(256,310,128,47);
        register.setIcon(new ImageIcon("puzzlegame\\image\\login\\注册按钮.png"));
        //去除按钮的边框
        register.setBorderPainted(false);
        //去除按钮的背景
        register.setContentAreaFilled(false);
        //添加鼠标监听事件
        register.addMouseListener(this);
        this.getContentPane().add(register);

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

    //初始化界面
    private void initJFramed() {
        //在创建登录界面的时候,同时给这个界面去设置一些信息
        this.setSize(488,430);
        //设置界面的标题
        this.setTitle("拼图 登录");
        //设置界面置顶
        this.setAlwaysOnTop(true);
        //设置界面居中显示
        this.setLocationRelativeTo(null);
        //设置关闭模式
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //取消默认的居中放置,而是采用绝对定位的方式
        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) {
        if(e.getSource()==login){
        }

    }

    //鼠标按下事件
    @Override
    public void mousePressed(MouseEvent e) {
        if(e.getSource()==login){
            System.out.println("登录按钮被按下了");
            login.setIcon(new ImageIcon("puzzlegame\\image\\login\\登录按下.png"));
        } else if (e.getSource()==register) {
            System.out.println("注册按钮被按下了");
            register.setIcon(new ImageIcon("puzzlegame\\image\\login\\注册按下.png"));
        }
    }

    //鼠标释放事件
    @Override
    public void mouseReleased(MouseEvent e) {

    }

    //鼠标进入事件
    @Override
    public void mouseEntered(MouseEvent e) {

    }

    //鼠标离开事件
    @Override
    public void mouseExited(MouseEvent e) {

    }
}

运行结果如图

其中登录和注册按钮按下,按钮颜色会变深,用户名之类验证正确还未实现,验证码是定义工具类随机生成的

工具类代码如下

package ui;

import java.util.Random;

public final class CodeUtil {
    private CodeUtil(){

    }

    public static String getCode(){
        //a-97 A-65
        char []str=new char[52];
        for (int i = 0; i < str.length; i++) {
            if(i<=25){
                str[i]=(char)(i+65);
            }else{
                str[i]=(char)(i+71);
            }
        }
        StringBuilder sb=new StringBuilder();
        Random random=new Random();
        String code="";
        for (int i = 0; i < 4; i++) {
            int index = random.nextInt(str.length);
            code+=str[index];
        }
        code+=(random.nextInt(10));
        char[] chars = code.toCharArray();
        int index = random.nextInt(chars.length);
        char temp = chars[4];
        chars[4] = chars[index];
        chars[index] = temp;
        String result = new String(chars);
        return result;
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到