Java笔记——使用GUI完成贪吃蛇小游戏
本次笔记的目录
游戏界面展示
-
开始界面

-
得分情况

-
死亡界面

代码编辑展示
全部代码如下所示:
- 图片文件夹:

- 图片加载类
package com.linstack.testsnake;
import javax.swing.*;
import java.net.URL;
/**
* @Auther: LinStack
*/
class Images {
//图片类对象,操作对象来实现对包内的图片进行利用
//封装图片保存的路径成一个url对象,利用反射将图片路径转为一个url信息
private static URL bodyURL = Images.class.getResource("/images/body.png"); //身体
private static URL upURL = Images.class.getResource("/images/headup.png"); //头向上
private static URL downURL = Images.class.getResource("/images/headdown.png"); //头向下
private static URL leftURL = Images.class.getResource("/images/headleft.png"); //头向左
private static URL rightURL = Images.class.getResource("/images/headright.png"); //头向右
private static URL headerURL = Images.class.getResource("/images/header.png"); //标题
private static URL foodURL = Images.class.getResource("/images/food.png"); //食物
//将获取的url信息传入图标对象中用作后续使用
static ImageIcon bodyIMG = new ImageIcon(bodyURL); //静态修饰方便后续直接调用
static ImageIcon upIMG = new ImageIcon(upURL);
static ImageIcon downIMG = new ImageIcon(downURL);
static ImageIcon leftIMG = new ImageIcon(leftURL);
static ImageIcon rightIMG = new ImageIcon(rightURL);
static ImageIcon headerIMG = new ImageIcon(headerURL);
static ImageIcon foodIMG = new ImageIcon(foodURL);
}
- 游戏界面类
package com.linstack.testsnake;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
/**
* @Auther: LinStack
*/
public class GamePanel extends JPanel {
//游戏面板类,继承自Jpanel面板类
//属性:
private int snakeLength; //蛇的初始长度
private String direction; //蛇运动方向
private int[] snakeX = new int[200]; //蛇运动的X坐标,初始值为200
private int[] snakeY = new int[200]; //蛇运动的Y坐标,初始值为200
private boolean isStart = false; //游戏运行状态,初始为关
private Timer timer; //加入一个定时器
private int foodX; //食物x坐标
private int foodY; //食物y坐标
private int score; //定义得分
private boolean isDead = false; //定义蛇的存活状态
//初始化坐标
private void init(){
//定义蛇的初始长度
snakeLength = 3;
//初始化蛇头方向
direction = "R"; //U上,D下,L左,R右
//初始化snake各部位的坐标
snakeX[0] = 175; //初始头部坐标,图片的像素尺寸是25*25px
snakeY[0] = 275;
snakeX[1] = 150; //初始身体坐标
snakeY[1] = 275;
snakeX[2] = 125; //初始尾部坐标
snakeY[2] = 275;
//初始化食物的坐标
foodX = 300;
foodY = 200;
//初始化得分:
score = 0;
}
//定义构造器
GamePanel() {
init();
//将焦点定位在当前操作的面板上
this.setFocusable(true);
//加入监控
this.addKeyListener(new KeyAdapter(){
<


2173

被折叠的 条评论
为什么被折叠?



