一.工程文件
二.Main.java
package com.company;
import javax.swing.*;
public class Main {
public static void main(String[] args) {
//创建窗体对象
JFrame frame = new JFrame();
//创建窗体参数()
frame.setBounds(10,10,900,720);
//设置不允许更改大小
//frame.setResizable(false);
//设置关闭方式
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//添加主题逻辑框架
frame.add(new Mpanel());
//设置窗体可见
frame.setVisible(true);
}
}
三.Mpanel.java
package com.company;
import javax.imageio.ImageIO;
import javax.sound.sampled.*;
import javax.swing.*;
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.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
//基本套路,继承JPanel,实现KeyListener, ActionListener接口
public class Mpanel extends JPanel implements KeyListener, ActionListener {
//定义所需要的图片元素
//标题
ImageIcon title;
//蛇的身体部位
ImageIcon body;
//蛇向上方向的头
ImageIcon up;
//蛇向下方向的头
ImageIcon down;
//蛇向左方向的头
ImageIcon left;
//蛇向右方向的头
ImageIcon right;
//食物元素
ImageIcon food;
//定义初始长度
int len = 3;
//定义初始分数
int score = 0;
//存放蛇位置坐标的数组
int[] snakex = new int[750];
int[] snakey = new int[750];
//定义方向
String fx = "R";
//定义游戏是否开始
Boolean isStart = false;
//定义游戏是否失败
Boolean isFailed = false;
//定义游戏时钟,在此可以设置蛇移动速度,默认100ms
Timer timer = new Timer(100,this);
//定义食物的坐标
int foodx;
int foody;
//引入随机数,用于生成食物的随机位置
Random