package demo;
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.util.Random;
public class MyPanel extends JPanel implements KeyListener, ActionListener {
ImageIcon right = new ImageIcon("src/demo/right.png");
ImageIcon body = new ImageIcon("src/demo/body.png");
ImageIcon up = new ImageIcon("src/demo/up.png");
ImageIcon down = new ImageIcon("src/demo/down.png");
ImageIcon left = new ImageIcon("src/demo/left.png");
//声明一个初始值,表示蛇的长度
int len = 3;
//两个数组表示x、y坐标
int[] snakeX = new int[1008];
int[] snakeY = new int[1008];
Direction direction = Direction.right;
Direction lastDirect = Direction.right;
boolean isStart = false;
//定时器对象
Timer timer = new Timer(100, this);
//食物位置
int foodX;
int foodY;
//随机变量
Random random = new Random();
ImageIcon food = new ImageIcon("src/demo/food.png");
public MyPanel() {
//设定蛇的头部和身体初始位置
snakeX[0] = 100;
snakeY[0] = 100;
snakeX[1] = 75;
snakeY[1] = 100;
snakeX[2] = 50;
snakeY[2] = 100;
//获取键盘事件
this.setFocusable(true);
//添加监听
this.addKeyListe
java实现贪吃蛇
最新推荐文章于 2024-08-18 14:29:55 发布
这篇文章详细描述了一个使用JavaSwing编写的蛇游戏,包括蛇的移动、键盘控制(上、下、左、右)以及游戏规则(吃到食物增长、撞墙游戏结束)。代码展示了如何处理键盘输入、定时更新游戏状态和画布渲染。

最低0.47元/天 解锁文章
4747

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



