1. 设计游戏的目的
锻炼逻辑思维能力
利用Java的图形化界面,写一个项目,知道前面学习的知识点在实际开发中的应用场景。
2. 游戏的最终效果呈现
3. 实现思路
先写游戏主界面,实现步骤如下:
1,完成最外层窗体的搭建。
2,再把菜单添加到窗体当中。
3,把小图片添加到窗体当中。
4,打乱数字图片的顺序。
5,让数字图片可以移动起来。
6,通关之后的胜利判断。
7,添加其他额外的功能。
4.主界面设计
//1.召唤主界面
JFrame jFrame = new JFrame();
//2.设置主界面的大小
jFrame.setSize(514,595);
//3.让主界面显示出来
jFrame.setVisible(true);
//1.召唤主界面
JFrame jFrame = new JFrame();
//设置主界面的大小
jFrame.setSize(514,595);
//将主界面设置到屏幕的正中央
jFrame.setLocationRelativeTo(null);
//将主界面置顶
jFrame.setAlwaysOnTop(true);
//关闭主界面的时候让代码一起停止
jFrame.setDefaultCloseOperation(3);
//给主界面设置一个标题
jFrame.setTitle("拼图游戏单机版 v1.0");
//2.让主界面显示出来
jFrame.setVisible(true);
注意事项:
jFrame.setVisible(true);必须要写在最后一行。
5. 利用继承简化代码
如果把所有的代码都写在main方法中,那么main方法里面的代码,就包含游戏主界面的代码,登录界面的代码,注册界面的代码,会变得非常臃肿后期维护也是一件非常难的事情,所以我们需要用继承改进,改进之后,代码就可以分类了。
//登录界面
public class LoginJFrame extends JFrame {
//LoginJFrame 表示登录界面
//以后所有跟登录相关的代码,都写在这里
public LoginJFrame(){
//在创建登录界面的时候,同时给这个界面去设置一些信息
//比如,宽高,直接展示出来
this.setSize(488,430);
//设置界面的标题
this.setTitle("拼图 登录");
//设置界面置顶
this.setAlwaysOnTop(true);
//设置界面居中
this.setLocationRelativeTo(null);
//设置关闭模式
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//让显示显示出来,建议写在最后
this.setVisible(true);
}
}
//注册界面
public class RegisterJFrame extends JFrame {
//跟注册相关的代码,都写在这个界面中
public RegisterJFrame(){
this.setSize(488,500);
//设置界面的标题
this.setTitle("拼图 注册");
//设置界面置顶
this.setAlwaysOnTop(true);
//设置界面居中
this.setLocationRelativeTo(null);
//设置关闭模式
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//让显示显示出来,建议写在最后
this.setVisible(true);
getContentPane();
}
}
//游戏主界面
public class GameJFrame extends JFrame {
public GameJFrame() {
//设置界面的宽高
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.setVisible(true);
}
}
6. 菜单制作
6.1菜单的组成
初始界面 在菜单中有:JMenuBar、JMenu、JMenuItem三个角色。
JMenuBar:如上图中红色边框
JMenu:如上图蓝色边框
JMenuItem:如上图绿色字体处
其中JMenuBar是整体,一个界面中一般只有一个JMenuBar。
而JMenu是菜单中的选项,可以有多个。
JMenuItem是选项下面的条目,也可以有多个。
6.2代码书写步骤
1,创建JMenuBar对象
2,创建JMenu对象
3,创建JMenuItem对象
4,把JMenuItem添加到JMenu中
5,把JMenu添加到JMenuBar中
6,把整个JMenuBar设置到整个界面中
//创建一个菜单对象
JMenuBar jMenuBar = new JMenuBar();
//设置菜单的宽高
jMenuBar.setSize(514, 20);
//创建一个选项
JMenu jMenu1 = new JMe