目录
在拼图游戏的上一期,完成了拼图游戏的游戏界面和玩法。
但是单纯靠程序,不涉及本地文件完成的游戏是没有储存的能力的,随着程序的结束,完成得游戏数据也会消失,所以,所有的游戏都会将游戏的数据存储,和账号信息到本地文件中,以便下次游戏能继续上一次的进度,所以这一期主要讲一下拼图游戏的存档,和登陆注册界面的完成。
需要注意的是,这次的项目使用了hutool工具包,在项目中创建lib文件夹,将hutool的jar包放入,右键点击Add as Library将jar包与项目关联起来,关于hutool工具包,也有很多的讲解的博客以供查阅这里就不再赘述。
首先还是看一下项目的结构,image用来储存图片,lib中放入jar工具包,save存放的存档,src中的代码和直属src的程序的启动入口App类,最后是项目直属下的userinfo.txt,存放用户的用户名和密码。其中test类包可以不用管,是开发过程中做出的测试,与游戏无关。
依然是分为两个部分,一个部分是每个类实现的过程,一个部分是完整的源码。
一、实现过程
1、User类
由于我们增加了登录和注册的功能,就注定了我们需要一个用户类,来将账号和密码存储到本地文件中。
这个类里只有两个参数,用户名字符串,和密码字符串,都是private定义的
之后就是空参构造方法和带参构造方法,getter和setter方法,重写toString方法都可以让idea自动生成。也都是很直观很简单的代码。
需要注意的是,存储用户名和密码的格式,比如有个账号是zhangsan,密码是123的用户,我们的存储格式是username=zhangsan&password=123。
package domain;
public class User {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return "username=" + username + "&password=" + password;
}
}
2、 GameInfo类
我们在这个类中,将游戏过程中的数据储存下来,包括当前拼图完成的进度,步数等一系列的数据。我们写入数据的时候,直接就将这个类创建的对象写入文件中了。随后,我们只需要在游戏的进程中创建一个GamaInfo对象,将游戏过程中的数据,赋值给这个GameInfo对象,最后将创建的这个对象写入文件中以便下次读取即可。
那我们要储存游戏过程中的那些数据呢?首先是data,就是目前图片的分布情况,x和y,是空白各自的位置,path图片的路径,毕竟你不能读档的时候读出来一套不一样的图片,还有已经使用过的步数。
所以这个类的参数就很好想了,
private int[][] data;
private int x = 0;
private int y = 0;
private String path;
private int step;
最后在自动生成getter和setter,空参构造和带参构造,重写toString方法即可。完整代码可以去目录的第二个大标题查看。
3、CodeUtil类
这个类主要是来生成随机的验证码,所以要给其他的类提供一个能拿到验证码字符串的方法,暂且定为public static String getCode方法,无参数,在这个方法中,必须要返回一个随机的由数字和字母组成的字符串。
我们想一下,要怎么来实现这个随机的字符串。数字我们可以通过random来生成。大小写字母,我们可以将它们加入到一个顺序表当中,最后,定义一个字符串变量,让他随即从这个表中取出字母,在随即添加数字,最后在随即打乱这个顺序即可。
public class CodeUtil {
public static String getCode(){
//1.创建一个集合
ArrayList<Character> list = new ArrayList<>();//52 索引的范围:0 ~ 51
//2.添加字母 a - z A - Z
for (int i = 0; i < 26; i++) {
list.add((char)('a' + i));//a - z
list.add((char)('A' + i));//A - Z
}
//3.打印集合
//System.out.println(list);
//4.生成4个随机字母
String result = "";
Random r = new Random();
for (int i = 0; i < 4; i++) {
//获取随机索引
int randomIndex = r.nextInt(list.size());
char c = list.get(randomIndex);
result = result + c;
}
//System.out.println(result);//长度为4的随机字符串
//5.在后面拼接数字 0~9
int number = r.nextInt(10);
//6.把随机数字拼接到result的后面
result = result + number;
//System.out.println(result);//ABCD5
//7.把字符串变成字符数组
char[] chars = result.toCharArray();//[A,B,C,D,5]
//8.在字符数组中生成一个随机索引
int index = r.nextInt(chars.length);
//9.拿着4索引上的数字,跟随机索引上的数字进行交换
char temp = chars[4];
chars[4] = chars[index];
chars[index] = temp;
//10.把字符数组再变回字符串
String code = new String(chars);
//System.out.println(code);
return code;
}
}
4、 GameJFrame类
我们在上一期拼图游戏中,重点实现了这个类,这里加了存档和读档的功能
首先呢。是存档和读档的JMenuItem,你总得给人家一个存档读档的按钮
JMenuItem saveItem0 = new JMenuItem("存档0(空)");
JMenuItem saveItem1 = new JMenuItem("存档1(空)");
JMenuItem saveItem2 = new JMenuItem("存档2(空)");
JMenuItem saveItem3 = new JMenuItem("存档3(空)");
JMenuItem saveItem4 = new JMenuItem("存档4(空)");
JMenuItem loadItem0 = new JMenuItem("读档0(空)");
JMenuItem loadItem1 = new JMenuItem("读档1(空)");
JMenuItem loadItem2 = new JMenuItem("读档2(空)");
JMenuItem loadItem3 = new JMenuItem("读档3(空)");
JMenuItem loadItem4 = new JMenuItem("读档4(空)");
之后新增了
getGameInfo这个方法,用来获取我们的存档。也是使用listFiles方法来遍历save文件夹。
public void getGameInfo(){
//1.创建File对象表示所有存档所在的文件夹
File file = new File("save");
//2.进入文件夹获取到里面所有的存档文件
File[] files = file.listFiles();
//3.遍历数组,得到每一个存档
for (File f : files) {
//f :依次表示每一个存档文件
//获取每一个存档文件中的步数
GameInfo gi = null;
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
gi = (GameInfo)ois.readObject();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//获取到了步数
int step = gi.getStep();
//把存档的步数同步到菜单当中
//save0 ---> 0
//save1 ---> 1
//...
//获取存档的文件名 save0.data
String name = f.getName();
//获取当存档的序号(索引)
int index = name.charAt(4) - '0';
//修改菜单上所表示的文字信息
saveJMenu.getItem(index).setText("存档" + index + "(" + step + ")步");
loadJMenu.getItem(index).setText("存档" + index + "(" + step + ")步");
}
}
在加点击存档的动作监听
if (obj == saveItem0 || obj == saveItem1 || obj == saveItem2 || obj == saveItem3 || obj == saveItem4) {
//获取当前是哪个存档被点击了,获取其中的序号
JMenuItem item = (JMenuItem) obj;
String str = item.getText();
int index = str.charAt(2) - '0';
//直接把游戏的数据写到本地文件中
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("save\\save" + index + ".data"));
GameInfo gi = new GameInfo(data, x, y, path, step);
IoUtil.writeObj(oos, true, gi);
} catch (IOException ioException) {
ioException.printStackTrace();
}
//修改一下存档item上的展示信息
//存档0(XX步)
item.setText("存档" + index + "(" + step + "步)");
//修改一下读档item上的展示信息
loadJMenu.getItem(index).setText("存档" + index + "(" + step + "步)");
} else if (obj == loadItem0 || obj == loadItem1 || obj == loadItem2 || obj == loadItem3 || obj == loadItem4) {
//获取当前是哪个读档被点击了,获取其中的序号
JMenuItem item = (JMenuItem) obj;
String str = item.getText();
int index = str.charAt(2) - '0';
GameInfo gi = null;
try {
//可以到本地文件中读取数据
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("save\\save" + index + ".data"));
gi = (GameInfo)ois.readObject();
ois.close();
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (ClassNotFoundException classNotFoundException) {
classNotFoundException.printStackTrace();
}
data = gi.getData();
path = gi.getPath();
step = gi.getStep();
x = gi.getX();
y = gi.getY();
//重新刷新界面加载游戏
initImage();
5、LoginJFrame类
用来登录的界面,一个顺序表来存储所有的用户。
ArrayList<User> allUsers = 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();
读取本地文件,由于存储的方式是username=zhangsan&password=123,所以要注意字符串的分搁。
private void readUserInfo() {
//1.读取数据
List<String> userInfoStrList = FileUtil.readUtf8Lines("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\userinfo.txt");
//2.遍历集合获取用户信息并创建User对象
for (String str : userInfoStrList) {
//username=zhangsan&password=123
String[] userInfoArr = str.split("&");
//0 username=zhangsan 1 password=123
String[] arr1 = userInfoArr[0].split("=");
String[] arr2 = userInfoArr[1].split("=");
User u = new User(arr1[1],arr2[1]);
allUsers.add(u);
}
System.out.println(allUsers);
}
其他的都是鼠标监听,初始化界面的代码。完整的代码在下一个完整代码的目录。
6、RegiserJFrame类
ArrayList<User> allUsers;
//提升三个输入框的变量的作用范围,让这三个变量可以在本类中所有方法里面可以使用。
JTextField username = new JTextField();
JTextField password = new JTextField();
JTextField rePassword = new JTextField();
//提升两个按钮变量的作用范围,让这两个变量可以在本类中所有方法里面可以使用。
JButton submit = new JButton();
JButton reset = new JButton();
以及初始化的界面
private void initFrame() {
//对自己的界面做一些设置。
//设置宽高
setSize(488, 430);
//设置标题
setTitle("拼图游戏 V1.0注册");
//取消内部默认布局
setLayout(null);
//设置关闭模式
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//设置居中
setLocationRelativeTo(null);
//设置置顶
setAlwaysOnTop(true);
}
7、App类
这个类只是打开程序的入口,最是简单
import Jframe.LoginJFrame;
//拼图游戏
public class App {
public static void main(String[] args) {
new LoginJFrame();
}
}
二、完整源代码
1、GameInfo类
package domain;
import java.io.Serializable;
public class GameInfo implements Serializable {
private static final long serialVersionUID = 5544981119935263973L;
private int[][] data;
private int x = 0;
private int y = 0;
private String path;
private int step;
public GameInfo() {
}
public GameInfo(int[][] data, int x, int y, String path, int step) {
this.data = data;
this.x = x;
this.y = y;
this.path = path;
this.step = step;
}
/**
* 获取
* @return data
*/
public int[][] getData() {
return data;
}
/**
* 设置
* @param data
*/
public void setData(int[][] data) {
this.data = data;
}
/**
* 获取
* @return x
*/
public int getX() {
return x;
}
/**
* 设置
* @param x
*/
public void setX(int x) {
this.x = x;
}
/**
* 获取
* @return y
*/
public int getY() {
return y;
}
/**
* 设置
* @param y
*/
public void setY(int y) {
this.y = y;
}
/**
* 获取
* @return path
*/
public String getPath() {
return path;
}
/**
* 设置
* @param path
*/
public void setPath(String path) {
this.path = path;
}
/**
* 获取
* @return step
*/
public int getStep() {
return step;
}
/**
* 设置
* @param step
*/
public void setStep(int step) {
this.step = step;
}
public String toString() {
return "GameInfo{data = " + data + ", x = " + x + ", y = " + y + ", path = " + path + ", step = " + step + "}";
}
}
2、User类
package domain;
public class User {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString() {
return "username=" + username + "&password=" + password;
}
}
3、CodeUtil类
package util;
import java.util.ArrayList;
import java.util.Random;
public class CodeUtil {
public static String getCode(){
//1.创建一个集合
ArrayList<Character> list = new ArrayList<>();//52 索引的范围:0 ~ 51
//2.添加字母 a - z A - Z
for (int i = 0; i < 26; i++) {
list.add((char)('a' + i));//a - z
list.add((char)('A' + i));//A - Z
}
//3.打印集合
//System.out.println(list);
//4.生成4个随机字母
String result = "";
Random r = new Random();
for (int i = 0; i < 4; i++) {
//获取随机索引
int randomIndex = r.nextInt(list.size());
char c = list.get(randomIndex);
result = result + c;
}
//System.out.println(result);//长度为4的随机字符串
//5.在后面拼接数字 0~9
int number = r.nextInt(10);
//6.把随机数字拼接到result的后面
result = result + number;
//System.out.println(result);//ABCD5
//7.把字符串变成字符数组
char[] chars = result.toCharArray();//[A,B,C,D,5]
//8.在字符数组中生成一个随机索引
int index = r.nextInt(chars.length);
//9.拿着4索引上的数字,跟随机索引上的数字进行交换
char temp = chars[4];
chars[4] = chars[index];
chars[index] = temp;
//10.把字符数组再变回字符串
String code = new String(chars);
//System.out.println(code);
return code;
}
}
4、GameJFrame类
package Jframe;
import cn.hutool.core.io.IoUtil;
import domain.GameInfo;
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.io.*;
import java.util.Random;
public class GameJFrame extends JFrame implements KeyListener, ActionListener {
//JFrame 界面,窗体
//子类呢?也表示界面,窗体
//规定:GameJFrame这个界面表示的就是游戏的主界面
//以后跟游戏相关的所有逻辑都写在这个类中
//创建一个二维数组
//目的:用来管理数据
//加载图片的时候,会根据二维数组中的数据进行加载
int[][] data = new int[4][4];
//记录空白方块在二维数组中的位置
int x = 0;
int y = 0;
//定义一个变量,记录当前展示图片的路径
String path = "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("关闭游戏");
JMenu saveJMenu = new JMenu("存档");
JMenu loadJMenu = new JMenu("读档");
JMenuItem saveItem0 = new JMenuItem("存档0(空)");
JMenuItem saveItem1 = new JMenuItem("存档1(空)");
JMenuItem saveItem2 = new JMenuItem("存档2(空)");
JMenuItem saveItem3 = new JMenuItem("存档3(空)");
JMenuItem saveItem4 = new JMenuItem("存档4(空)");
JMenuItem loadItem0 = new JMenuItem("读档0(空)");
JMenuItem loadItem1 = new JMenuItem("读档1(空)");
JMenuItem loadItem2 = new JMenuItem("读档2(空)");
JMenuItem loadItem3 = new JMenuItem("读档3(空)");
JMenuItem loadItem4 = new JMenuItem("读档4(空)");
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("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("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("更换图片");
//把5个存档,添加到saveJMenu中
saveJMenu.add(saveItem0);
saveJMenu.add(saveItem1);
saveJMenu.add(saveItem2);
saveJMenu.add(saveItem3);
saveJMenu.add(saveItem4);
//把5个读档,添加到loadJMenu中
loadJMenu.add(loadItem0);
loadJMenu.add(loadItem1);
loadJMenu.add(loadItem2);
loadJMenu.add(loadItem3);
loadJMenu.add(loadItem4);
//把美女,动物,运动添加到更换图片当中
changeImage.add(girl);
changeImage.add(animal);
changeImage.add(sport);
//将更换图片,重新游戏,重新登录,关闭游戏,存档,读档添加到“功能”选项当中
functionJMenu.add(changeImage);
functionJMenu.add(replayItem);
functionJMenu.add(reLoginItem);
functionJMenu.add(closeItem);
functionJMenu.add(saveJMenu);
functionJMenu.add(loadJMenu);
//将公众号添加到关于我们当中
aboutJMenu.add(accountItem);
//绑定点击事件
girl.addActionListener(this);
animal.addActionListener(this);
sport.addActionListener(this);
replayItem.addActionListener(this);
reLoginItem.addActionListener(this);
closeItem.addActionListener(this);
accountItem.addActionListener(this);
saveItem0.addActionListener(this);
saveItem1.addActionListener(this);
saveItem2.addActionListener(this);
saveItem3.addActionListener(this);
saveItem4.addActionListener(this);
loadItem0.addActionListener(this);
loadItem1.addActionListener(this);
loadItem2.addActionListener(this);
loadItem3.addActionListener(this);
loadItem4.addActionListener(this);
//将菜单里面的两个选项添加到菜单当中
jMenuBar.add(functionJMenu);
jMenuBar.add(aboutJMenu);
//读取存档信息,修改菜单上表示的内容
getGameInfo();
//给整个界面设置菜单
this.setJMenuBar(jMenuBar);
}
public void getGameInfo(){
//1.创建File对象表示所有存档所在的文件夹
File file = new File("save");
//2.进入文件夹获取到里面所有的存档文件
File[] files = file.listFiles();
//3.遍历数组,得到每一个存档
for (File f : files) {
//f :依次表示每一个存档文件
//获取每一个存档文件中的步数
GameInfo gi = null;
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
gi = (GameInfo)ois.readObject();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//获取到了步数
int step = gi.getStep();
//把存档的步数同步到菜单当中
//save0 ---> 0
//save1 ---> 1
//...
//获取存档的文件名 save0.data
String name = f.getName();
//获取当存档的序号(索引)
int index = name.charAt(4) - '0';
//修改菜单上所表示的文字信息
saveJMenu.getItem(index).setText("存档" + index + "(" + step + ")步");
loadJMenu.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("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);
//打开登录界面
new LoginJFrame();
} else if (obj == closeItem) {
System.out.println("关闭游戏");
//直接关闭虚拟机即可
System.exit(0);
} else if (obj == accountItem) {
System.out.println("公众号");
//读取配置文件中的信息
showJDialog("image\\about\\about1.png");
//调用下面的showJDialog方法,展示弹框
//showJDialog方法的参数,就是图片的路径
//比如:showJDialog("puzzlegame\\image\\about1.png");
} else if (obj == girl) {
System.out.println("girl");
//下列代码重复了,自己思考一下,能否抽取成一个方法呢?
int number = r.nextInt(13) + 1;
path = "image\\girl\\girl" + number + "\\";
//计步器清零
step = 0;
//再次打乱二维数组中的数据
initData();
//重新加载图片
initImage();
} else if (obj == animal) {
System.out.println("animal");
//下列代码重复了,自己思考一下,能否抽取成一个方法呢?
int number = r.nextInt(8) + 1;
path = "image\\girl\\girl" + number + "\\";
//计步器清零
step = 0;
//再次打乱二维数组中的数据
initData();
//重新加载图片
initImage();
} else if (obj == sport) {
System.out.println("sport");
//下列代码重复了,自己思考一下,能否抽取成一个方法呢?
int number = r.nextInt(10) + 1;
path = "image\\girl\\girl" + number + "\\";
//计步器清零
step = 0;
//再次打乱二维数组中的数据
initData();
//重新加载图片
initImage();
} else if (obj == saveItem0 || obj == saveItem1 || obj == saveItem2 || obj == saveItem3 || obj == saveItem4) {
//获取当前是哪个存档被点击了,获取其中的序号
JMenuItem item = (JMenuItem) obj;
String str = item.getText();
int index = str.charAt(2) - '0';
//直接把游戏的数据写到本地文件中
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("save\\save" + index + ".data"));
GameInfo gi = new GameInfo(data, x, y, path, step);
IoUtil.writeObj(oos, true, gi);
} catch (IOException ioException) {
ioException.printStackTrace();
}
//修改一下存档item上的展示信息
//存档0(XX步)
item.setText("存档" + index + "(" + step + "步)");
//修改一下读档item上的展示信息
loadJMenu.getItem(index).setText("存档" + index + "(" + step + "步)");
} else if (obj == loadItem0 || obj == loadItem1 || obj == loadItem2 || obj == loadItem3 || obj == loadItem4) {
//获取当前是哪个读档被点击了,获取其中的序号
JMenuItem item = (JMenuItem) obj;
String str = item.getText();
int index = str.charAt(2) - '0';
GameInfo gi = null;
try {
//可以到本地文件中读取数据
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("save\\save" + index + ".data"));
gi = (GameInfo)ois.readObject();
ois.close();
} catch (IOException ioException) {
ioException.printStackTrace();
} catch (ClassNotFoundException classNotFoundException) {
classNotFoundException.printStackTrace();
}
data = gi.getData();
path = gi.getPath();
step = gi.getStep();
x = gi.getX();
y = gi.getY();
//重新刷新界面加载游戏
initImage();
}
}
//创建一个弹框对象
JDialog jDialog = new JDialog();
//展示弹框
public void showJDialog(String filepath) {
if(!jDialog.isVisible()){
JLabel jLabel = null;
//判断传递的字符串是否是一个路径,且必须以jpg或者png结尾
//如果满足,则当做图片处理
//如果不满足,则当做普通字符串处理
if(new File(filepath).exists() && (filepath.endsWith(".png")||filepath.endsWith(".jpg") )){
jLabel = new JLabel(new ImageIcon(filepath));
}else{
jLabel = new JLabel(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);
}
}
}
5、LoginJFframe类
package Jframe;
import cn.hutool.core.io.FileUtil;
import domain.User;
import util.CodeUtil;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
public class LoginJFrame extends JFrame implements MouseListener {
ArrayList<User> allUsers = 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() {
//读取本地文件中的用户信息
readUserInfo();
//初始化界面
initJFrame();
//在这个界面中添加内容
initView();
//让当前界面显示出来
this.setVisible(true);
}
//读取本地文件中的用户信息
private void readUserInfo() {
//1.读取数据
List<String> userInfoStrList = FileUtil.readUtf8Lines("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\userinfo.txt");
//2.遍历集合获取用户信息并创建User对象
for (String str : userInfoStrList) {
//username=zhangsan&password=123
String[] userInfoArr = str.split("&");
//0 username=zhangsan 1 password=123
String[] arr1 = userInfoArr[0].split("=");
String[] arr2 = userInfoArr[1].split("=");
User u = new User(arr1[1],arr2[1]);
allUsers.add(u);
}
System.out.println(allUsers);
}
//点击
@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.isEmpty()) {
showJDialog("验证码不能为空");
} else if (usernameInput.isEmpty() || passwordInput.isEmpty()) {
//校验用户名和密码是否为空
System.out.println("用户名或者密码为空");
//调用showJDialog方法并展示弹框
showJDialog("用户名或者密码为空");
} else if (!codeInput.equalsIgnoreCase(rightCode.getText())) {
showJDialog("验证码输入错误");
} else if (contains(userInfo)) {
System.out.println("用户名和密码正确可以开始玩游戏了");
//关闭当前登录界面
this.setVisible(false);
//打开游戏的主界面
//需要把当前登录的用户名传递给游戏界面
new GameJFrame();
} else {
System.out.println("用户名或密码错误");
showJDialog("用户名或密码错误");
}
} else if (e.getSource() == register) {
System.out.println("点击了注册按钮");
//关闭当前的登录界面
this.setVisible(false);
//打开注册界面
new RegisterJFrame(allUsers);
} else if (e.getSource() == rightCode) {
System.out.println("更换验证码");
//获取一个新的验证码
String code = CodeUtil.getCode();
rightCode.setText(code);
}
}
//只创建一个弹框对象
JDialog jDialog = new JDialog();
//因为展示弹框的代码,会被运行多次
//所以,我们把展示弹框的代码,抽取到一个方法中。以后用到的时候,就不需要写了
//直接调用就可以了。
//展示弹框
public void showJDialog(String content) {
if(!jDialog.isVisible()){
//创建一个弹框对象
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("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\登录按下.png"));
} else if (e.getSource() == register) {
register.setIcon(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\注册按下.png"));
}
}
//松开按钮
@Override
public void mouseReleased(MouseEvent e) {
if (e.getSource() == login) {
login.setIcon(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\登录按钮.png"));
} else if (e.getSource() == register) {
register.setIcon(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\注册按钮.png"));
}
}
//鼠标划入
@Override
public void mouseEntered(MouseEvent e) {
}
//鼠标划出
@Override
public void mouseExited(MouseEvent e) {
}
//判断用户在集合中是否存在
public boolean contains(User userInput){
for (User rightUser : allUsers) {
if (userInput.getUsername().equals(rightUser.getUsername()) && userInput.getPassword().equals(rightUser.getPassword())) {
//有相同的代表存在,返回true,后面的不需要再比了
return true;
}
}
//循环结束之后还没有找到就表示不存在
return false;
}
//在这个界面中添加内容
public void initView() {
//1. 添加用户名文字
JLabel usernameText = new JLabel(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\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("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\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("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\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("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\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("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\注册按钮.png"));
//去除按钮的边框
register.setBorderPainted(false);
//去除按钮的背景
register.setContentAreaFilled(false);
//给注册按钮绑定鼠标事件
register.addMouseListener(this);
this.getContentPane().add(register);
//7.添加背景图片
JLabel background = new JLabel(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\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(WindowConstants.EXIT_ON_CLOSE);//设置关闭模式
this.setLocationRelativeTo(null);//居中
this.setAlwaysOnTop(true);//置顶
this.setLayout(null);//取消内部默认布局
}
}
6、RegisJFrame类
package Jframe;
import cn.hutool.core.io.FileUtil;
import domain.User;
import util.CodeUtil;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
public class LoginJFrame extends JFrame implements MouseListener {
ArrayList<User> allUsers = 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() {
//读取本地文件中的用户信息
readUserInfo();
//初始化界面
initJFrame();
//在这个界面中添加内容
initView();
//让当前界面显示出来
this.setVisible(true);
}
//读取本地文件中的用户信息
private void readUserInfo() {
//1.读取数据
List<String> userInfoStrList = FileUtil.readUtf8Lines("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\userinfo.txt");
//2.遍历集合获取用户信息并创建User对象
for (String str : userInfoStrList) {
//username=zhangsan&password=123
String[] userInfoArr = str.split("&");
//0 username=zhangsan 1 password=123
String[] arr1 = userInfoArr[0].split("=");
String[] arr2 = userInfoArr[1].split("=");
User u = new User(arr1[1],arr2[1]);
allUsers.add(u);
}
System.out.println(allUsers);
}
//点击
@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.isEmpty()) {
showJDialog("验证码不能为空");
} else if (usernameInput.isEmpty() || passwordInput.isEmpty()) {
//校验用户名和密码是否为空
System.out.println("用户名或者密码为空");
//调用showJDialog方法并展示弹框
showJDialog("用户名或者密码为空");
} else if (!codeInput.equalsIgnoreCase(rightCode.getText())) {
showJDialog("验证码输入错误");
} else if (contains(userInfo)) {
System.out.println("用户名和密码正确可以开始玩游戏了");
//关闭当前登录界面
this.setVisible(false);
//打开游戏的主界面
//需要把当前登录的用户名传递给游戏界面
new GameJFrame();
} else {
System.out.println("用户名或密码错误");
showJDialog("用户名或密码错误");
}
} else if (e.getSource() == register) {
System.out.println("点击了注册按钮");
//关闭当前的登录界面
this.setVisible(false);
//打开注册界面
new RegisterJFrame(allUsers);
} else if (e.getSource() == rightCode) {
System.out.println("更换验证码");
//获取一个新的验证码
String code = CodeUtil.getCode();
rightCode.setText(code);
}
}
//只创建一个弹框对象
JDialog jDialog = new JDialog();
//因为展示弹框的代码,会被运行多次
//所以,我们把展示弹框的代码,抽取到一个方法中。以后用到的时候,就不需要写了
//直接调用就可以了。
//展示弹框
public void showJDialog(String content) {
if(!jDialog.isVisible()){
//创建一个弹框对象
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("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\登录按下.png"));
} else if (e.getSource() == register) {
register.setIcon(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\注册按下.png"));
}
}
//松开按钮
@Override
public void mouseReleased(MouseEvent e) {
if (e.getSource() == login) {
login.setIcon(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\登录按钮.png"));
} else if (e.getSource() == register) {
register.setIcon(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\注册按钮.png"));
}
}
//鼠标划入
@Override
public void mouseEntered(MouseEvent e) {
}
//鼠标划出
@Override
public void mouseExited(MouseEvent e) {
}
//判断用户在集合中是否存在
public boolean contains(User userInput){
for (User rightUser : allUsers) {
if (userInput.getUsername().equals(rightUser.getUsername()) && userInput.getPassword().equals(rightUser.getPassword())) {
//有相同的代表存在,返回true,后面的不需要再比了
return true;
}
}
//循环结束之后还没有找到就表示不存在
return false;
}
//在这个界面中添加内容
public void initView() {
//1. 添加用户名文字
JLabel usernameText = new JLabel(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\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("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\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("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\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("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\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("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\注册按钮.png"));
//去除按钮的边框
register.setBorderPainted(false);
//去除按钮的背景
register.setContentAreaFilled(false);
//给注册按钮绑定鼠标事件
register.addMouseListener(this);
this.getContentPane().add(register);
//7.添加背景图片
JLabel background = new JLabel(new ImageIcon("C:\\Users\\Lenovo\\Desktop\\code\\Java\\SawPuzzle\\image\\login\\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(WindowConstants.EXIT_ON_CLOSE);//设置关闭模式
this.setLocationRelativeTo(null);//居中
this.setAlwaysOnTop(true);//置顶
this.setLayout(null);//取消内部默认布局
}
}
7、App类
import Jframe.LoginJFrame;
//拼图游戏
public class App {
public static void main(String[] args) {
new LoginJFrame();
}
}
三、图片和代码资源
不太清楚往哪里放,先放百度网盘吧
通过百度网盘分享的文件:SawPuzzl…
链接:https://pan.baidu.com/s/1l_Mu5frnYAOp3qJHgtaugg
提取码:2qnq
复制这段内容打开「百度网盘APP 即可获取」
造成的不便请谅解。。。。。