java实现贪吃蛇

这篇文章详细描述了一个使用JavaSwing编写的蛇游戏,包括蛇的移动、键盘控制(上、下、左、右)以及游戏规则(吃到食物增长、撞墙游戏结束)。代码展示了如何处理键盘输入、定时更新游戏状态和画布渲染。
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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值