实战 使用Java开发简易小游戏:贪吃蛇(附源码!)

贪吃蛇

此游戏主要包括三个类:

  1. 主启动类:GameStart
  2. 游戏面板类:GamePanel
  3. 数据中心类:Data

话不多说,直接开始

主启动类:GameStart

package com.teng.Snake;

import javax.swing.*;

//游戏的主启动类
public class GameStart{
          
   
    public static void main(String[] args) {
          
   
        JFrame jFrame = new JFrame("小梁学Java之贪吃蛇游戏");

        jFrame.add(new GamePanel());//添加面板

        jFrame.setVisible(true);
        jFrame.setResizable(false);//设置窗口大小不可变
        jFrame.setBounds(100,100,915,720);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }
}

游戏面板类:GamePanel

数据中心类:Data

package com.teng.Snake;

import javax.swing.*;
import java.net.URL;

//数据中心
public class Data {
          
   
    public static URL headURL = Data.class.getResource("statics/head.png");
    public static URL foodURL = Data.class.getResource("statics/food.png");
    public static URL upURL = Data.class.getResource("statics/up.png");
    public static URL downURL = Data.class.getResource("statics/down.png");
    public static URL leftURL = Data.class.getResource("statics/left.png");
    public static URL rightURL = Data.class.getResource("statics/right.png");
    public static URL bodyURL = Data.class.getResource("statics/body.png");
    public static ImageIcon head = new ImageIcon(headURL);
    public static ImageIcon food = new ImageIcon(foodURL);
    public static ImageIcon up = new ImageIcon(upURL);
    public static ImageIcon down = new ImageIcon(downURL);
    public static ImageIcon left = new ImageIcon(leftURL);
    public static ImageIcon right = new ImageIcon(rightURL);
    public static ImageIcon body = new ImageIcon(bodyURL);
}

运行图: 游戏初始界面: 游戏运行界面: 游戏暂停界面: 游戏结束界面:


总结

  1. 贪吃蛇游戏汇总了GUI编程所学知识
  2. 游戏还可以进行大量优化,比如失败判定加一个边界、食物不会刷新到小蛇身体的坐标、游戏难度分级,甚至还想加个数据库记录最高分哈哈哈哈(日后慢慢来嘿嘿)

最后附上游戏源码: 链接: 提取码:gqas

经验分享 程序员 微信小程序 职场和发展