java 贪吃蛇游戏

前言

此实现较为简陋,如有错误请指正。

其次代码中的图片需要自行添加地址并修改。

主类

public class Main {
    public static void main(String[] args) {
        new myGame();

    }

}

1

2

3

4

5

游戏类

import javax.swing.*;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.util.*;

import java.util.Timer;

public class myGame extends JFrame implements KeyListener {
 

    private int[] foodPos; // 食物位置坐标

    private List<int[]> coordinateS; // 总地址

    private int score = 0; // 玩家得分

    private Random random;

    private final String cell = "img/cell.png"; //格子地址

    private int keyCode = -1;

    public myGame() {
        random = new Random();

        foodPos = new int[]{-1, -1}; // 初始化为-1

        // 创建一个定时器

        Timer gameTimer = new Timer();

        // 设置定时器

        gameTimer.schedule(new timer(), 0, 200);

        InitCoordinate(); // 初始化格子地址

        InitJFrame(); // 初始化窗体

        LoadPicture(); // 加载图片

    }

    // 初始化地址

    private void InitCoordinate() {
        coordinateS = new ArrayList<>();

        coordinateS.add(new int[]{200, 200});

        coordinateS.add(new int[]{200, 200});

        this.getContentPane().removeAll(); // 清空图片显示

    }

    // 加载图片

    public void LoadPicture() {
        this.getContentPane().removeAll(); // 清空图片显示

        // 目前得分展示

        JLabel scoreTips = new JLabel("目前得分:" + score);

        scoreTips.setBounds(500, 10, 100, 20);

        this.getContentPane().add(scoreTips);

        // 提示

        JLabel Tips = new JLabel("<html> 按下任意方向键 <br><br> 即开始游戏 </html>

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值