Java 实现 贪吃蛇 小游戏【附源码】

简介: Java 实现 贪吃蛇 小游戏【附源码】

1 前言

🚀获取源码,文末公众号回复【贪吃蛇】,即可。

⭐欢迎点赞留言

2 正文

2.1 展示

0.5MB GIF可以欣赏:https://tva1.sinaimg.cn/large/007F3CC8ly1h0r3m3o16qg31190osan3.gif


2.2 项目结构

2.2 主要代码

package com.dq.ui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Random;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;

import com.dq.utils.PlayMusicUtil;
import com.dq.utils.PropertiesUtils;

/**
 * @author dq
 *
 */
public class SnakeFrame extends JFrame{

  private static final long serialVersionUID = 8866826595307493727L;
  
  private static final int WIDTH = 800; // 
  private static final int HEIGHT = 600; 
  private static final int CELL = 20; 
  
  private JLabel snakeHeader;  
  private JLabel fruit;  
  
  private Random random = new Random();  
  
  private int dir = 1; 
  
  private LinkedList<JLabel> bodies = new LinkedList<JLabel>();
  
  private String[] fruits = {"pineapple.png","apple.png","cherry.png","grape.png","orange.png","peach.png","strawberry.png","tomato.png"};
  
  private String[] snakeBody = {"green.png","red.png","yellow.png","purple.png"};
  
  private JLabel highestLabel; 
  private JLabel currentLabel; 
  private int highestScore; 
  private int currentScore;
  private PropertiesUtils prop = PropertiesUtils.getInstance();
  
  private Timer timer;  
  private boolean status = true;
  
  
  public SnakeFrame(){
    
    ImageIcon icon = new ImageIcon("./src/com/dq/images/snake.jpg");
    this.setIconImage(icon.getImage());
    this.setTitle("贪吃蛇   DQ制作");
    this.setSize(WIDTH+4, HEIGHT+34);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setResizable(false);
    this.setLayout(null);

    SnakePanel snakePanel = new SnakePanel();
    snakePanel.setBounds(0, 0, WIDTH, HEIGHT);
    this.add(snakePanel);
    

    this.addKeyListener(new KeyAdapter() {
      
      @Override
      public void keyPressed(KeyEvent e) {
  
        int keyCode = e.getKeyCode();
        
  
        switch (keyCode) {
          case KeyEvent.VK_LEFT: 
            if(dir != SnakeDirection.RIGHT){ 
              dir = SnakeDirection.LEFT;
              setBackgrounImage(snakeHeader, "header_l.png");
            }
            break;
          case KeyEvent.VK_RIGHT: 
            if(dir != SnakeDirection.LEFT){ 
              dir = SnakeDirection.RIGHT;
              setBackgrounImage(snakeHeader, "header_r.png");
            }
            break;
          case KeyEvent.VK_UP: 
            if(dir != SnakeDirection.BOTTOM){
              dir = SnakeDirection.TOP;
              setBackgrounImage(snakeHeader, "header_t.png");
            }
            break;
          case KeyEvent.VK_DOWN: 
            if(dir != SnakeDirection.TOP){
              dir = SnakeDirection.BOTTOM;
              setBackgrounImage(snakeHeader, "header_b.png");
            }
            break;
          case KeyEvent.VK_SPACE: 
//            if(status){ 
//              status = !status;
//            }else{
//              status = !status;
//              timer.notify();
//            }
            
        }
        
      }
    });
    
    this.setVisible(true);
    

    PlayMusicUtil.playBGM();
    
    new Timer(98000, new ActionListener() {
      
      @Override
      public void actionPerformed(ActionEvent e) {
        
        PlayMusicUtil.playBGM();
      }
    }).start();
    
    
  }
  
  private void setBackgrounImage(JLabel label,String fileName){
    
    ImageIcon icon = new ImageIcon("./src/com/dq/images/"+fileName);
    icon.setImage( icon.getImage().
        getScaledInstance(label.getWidth(),label.getHeight(),Image.SCALE_DEFAULT));
    label.setIcon(icon);
  }
  
  class SnakePanel extends JPanel{
    
    private static final long serialVersionUID = 1L;

    public SnakePanel(){
      init();
    }

    private void init() {
      
      this.setSize(SnakeFrame.WIDTH, SnakeFrame.HEIGHT);
      this.setLayout(null);
      
      highestLabel = new JLabel();
      highestScore = Integer.parseInt(prop.getProperty("highest"));
      highestLabel.setText("历史最高分"+highestScore);
      highestLabel.setBounds(20, 20, 300, 30);
      this.add(highestLabel);
      
      currentLabel = new JLabel("当前得分"+currentScore);
      currentLabel.setBounds(20, 60, 300, 30);
      this.add(currentLabel);
      
      createHeader();
      
      new Thread(new Runnable() {
        
        @Override
        public void run() {
          createFruit();
        }
      }).start();
      
      
      timer = new Timer(250, new ActionListener() {
        
        @Override
        public void actionPerformed(ActionEvent e) {
          Point oldPoint = snakeHeader.getLocation();
          Point newPoint = null;
          
          switch (dir) {
            case SnakeDirection.RIGHT: //鍚戝彸
              newPoint = new Point(oldPoint.x+CELL, oldPoint.y);
              break;
            case SnakeDirection.LEFT: //鍚戝乏
              newPoint = new Point(oldPoint.x-CELL, oldPoint.y);
              break;
            case SnakeDirection.BOTTOM: //鍚戜笅
              newPoint = new Point(oldPoint.x, oldPoint.y+CELL);
              break;
            case SnakeDirection.TOP: //鍚戜笂
              newPoint = new Point(oldPoint.x, oldPoint.y-CELL);
              break;
          }
          
          snakeHeader.setLocation(newPoint);
          isHeatWall();
          
          if(snakeHeader.getLocation().equals( fruit.getLocation())){
            eatBean();
          }
          
          move(oldPoint);
        }

      

        
      });
      timer.start();
      
      
    }
    
    private void move(Point oldPoint) {
      
      Point p = new Point();
      for(int i=1;i<bodies.size();i++){
        p = bodies.get(i).getLocation();
        bodies.get(i).setLocation(oldPoint);
        oldPoint = p;
      }
      
    }
    

    private void eatBean() {
      
      int index = random.nextInt( snakeBody.length);
      setBackgrounImage(fruit, snakeBody[index]);
      bodies.add(fruit);
      new Thread(new Runnable() {
        
        @Override
        public void run() {
          PlayMusicUtil.playEatBean();
        }
      }).start();
      
      currentScore++;
      currentLabel.setText("褰撳墠寰楀垎锛�"+currentScore);    
      
//      new Thread( new Runnable() {
//        
//        @Override
//        public void run() {
//          
//          createFruit();
//        }
//      }).start();
      new Thread( ()->{createFruit();}).start(); 
      
    }
    
    private void isHeatWall() {
      
      int x = snakeHeader.getLocation().x;
      int y = snakeHeader.getLocation().y;
      
      if(x <0 || x >780 || y<0 || y>580){
        
        new Thread( new Runnable() {
          
          @Override
          public void run() {
            PlayMusicUtil.stopBGM();
            PlayMusicUtil.playGameOver();
          }
        }).start();
        
        int op = -1;
        if(currentScore > highestScore){
          op = JOptionPane.showConfirmDialog(null, "鍝﹁眮锛佺牬绾綍浜嗗摝锛佸啀鏉ヤ竴鎶婏紵");
          prop.setProperty("highest", currentScore+"");
          try {
            FileWriter writer = new FileWriter(new File("./src/score.properties"));
            prop.store(writer, null);
          } catch (IOException e) {
            e.printStackTrace();
          }
        }else{
          op = JOptionPane.showConfirmDialog(null, "你死了");
        }
        
        //鍒ゆ柇鏄惁鍐嶆潵涓�鎶�
        if(op == 0){
          
          reStart();
        }else{
          
          System.exit(0);
        
        }
      }
    }

    private void createFruit() {
      
      fruit = new JLabel();
      fruit.setSize(CELL, CELL);
      
      int index = random.nextInt( fruits.length);
      setBackgrounImage(fruit, fruits[index]);
      
      Point p = randomPoint(SnakeFrame.WIDTH/CELL, SnakeFrame.HEIGHT/CELL);
      System.out.println("x:"+p.x+" y:"+p.y);
      fruit.setLocation(p);
      
      this.add(fruit);
      this.repaint();
    }

    private void createHeader() {
      
      snakeHeader = new JLabel();
      snakeHeader.setSize(CELL, CELL);
//      snakeHeader.setOpaque(false);
      
      setBackgrounImage(snakeHeader, "header_r.png");
      
      Point p = randomPoint((SnakeFrame.WIDTH/CELL)/2, (SnakeFrame.HEIGHT/CELL)/2);
      p.x = p.x+10*CELL;
      p.y = p.y+10*CELL;
      snakeHeader.setLocation(p);
      
      
      bodies.add(snakeHeader);
      
      this.add(snakeHeader);
    }
    
    
    
    private Point randomPoint(int xScale,int yScale){
      
      Point point = new Point();
      int x = random.nextInt(xScale)*CELL;
      int y = random.nextInt(yScale)*CELL;
      
      
      
      point.setLocation(x, y);
      return point;
    }
    
  
    @Override
    protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      
      ImageIcon icon = new ImageIcon("./src/com/dq/images/bg.png");
      g.drawImage(icon.getImage(), 0, 0, SnakeFrame.WIDTH, SnakeFrame.HEIGHT, null);
      
      g.setColor(Color.RED);
      
      for(int i=1;i<HEIGHT/CELL;i++){
        g.drawLine(0, i*CELL, 800, i*CELL);
      }
      
      for(int i=1;i<WIDTH/CELL; i++){
        g.drawLine(i*CELL, 0, i*CELL, 600);
      }
      
    }
    
    public void reStart() {
      
      if(currentScore > highestScore){
        highestScore = currentScore;
        highestLabel.setText("最高分"+highestScore);
      }
      currentScore = 0;
      currentLabel.setText("当前得分"+currentScore);
      dir = 1;
      this.remove(fruit);
      for(JLabel body : bodies){
        this.remove(body);
      }
      
      bodies.clear();
      
      createHeader();
      createFruit();
      
      PlayMusicUtil.playBGM();
      
      super.repaint();
      
      
    }
  }
}

2.4 按钮相关类

package com.dq.ui;

/**
 * 存储蛇运动方向的接口
 * @author dq
 *
 */
public interface SnakeDirection {
  
  int LEFT = -1;
  
  int RIGHT = 1;
  
  int BOTTOM = -2;
  
  int TOP = 2;
  
}


2.5 启动类

package com.dq.ui;

public class StartGame {
  
  public static void main(String[] args) {
    
    new SnakeFrame();
  }
}

不会还有人没 点赞 + 关注 + 收藏 吧!

目录
相关文章
|
11月前
|
存储 小程序 Java
热门小程序源码合集:微信抖音小程序源码支持PHP/Java/uni-app完整项目实践指南
小程序已成为企业获客与开发者创业的重要载体。本文详解PHP、Java、uni-app三大技术栈在电商、工具、服务类小程序中的源码应用,提供从开发到部署的全流程指南,并分享选型避坑与商业化落地策略,助力开发者高效构建稳定可扩展项目。
|
11月前
|
消息中间件 人工智能 Java
抖音微信爆款小游戏大全:免费休闲/竞技/益智/PHP+Java全筏开源开发
本文基于2025年最新行业数据,深入解析抖音/微信爆款小游戏的开发逻辑,重点讲解PHP+Java双引擎架构实战,涵盖技术选型、架构设计、性能优化与开源生态,提供完整开源工具链,助力开发者从理论到落地打造高留存、高并发的小游戏产品。
|
存储 安全 Java
Java 集合面试题从数据结构到 HashMap 源码剖析详解及长尾考点梳理
本文深入解析Java集合框架,涵盖基础概念、常见集合类型及HashMap的底层数据结构与源码实现。从Collection、Map到Iterator接口,逐一剖析其特性与应用场景。重点解读HashMap在JDK1.7与1.8中的数据结构演变,包括数组+链表+红黑树优化,以及put方法和扩容机制的实现细节。结合订单管理与用户权限管理等实际案例,展示集合框架的应用价值,助你全面掌握相关知识,轻松应对面试与开发需求。
618 3
|
JavaScript Java 关系型数据库
家政系统源码,java版本
这是一款基于SpringBoot后端框架、MySQL数据库及Uniapp移动端开发的家政预约上门服务系统。
468 6
家政系统源码,java版本
|
供应链 JavaScript 前端开发
Java基于SaaS模式多租户ERP系统源码
ERP,全称 Enterprise Resource Planning 即企业资源计划。是一种集成化的管理软件系统,它通过信息技术手段,将企业的各个业务流程和资源管理进行整合,以提高企业的运营效率和管理水平,它是一种先进的企业管理理念和信息化管理系统。 适用于小微企业的 SaaS模式多租户ERP管理系统, 采用最新的技术栈开发, 让企业简单上云。专注于小微企业的应用需求,如企业基本的进销存、询价,报价, 采购、销售、MRP生产制造、品质管理、仓库库存管理、财务应收付款, OA办公单据、CRM等。
1003 23
|
前端开发 Java 关系型数据库
基于Java+Springboot+Vue开发的鲜花商城管理系统源码+运行
基于Java+Springboot+Vue开发的鲜花商城管理系统(前后端分离),这是一项为大学生课程设计作业而开发的项目。该系统旨在帮助大学生学习并掌握Java编程技能,同时锻炼他们的项目设计与开发能力。通过学习基于Java的鲜花商城管理系统项目,大学生可以在实践中学习和提升自己的能力,为以后的职业发展打下坚实基础。技术学习共同进步
877 7
|
Java 关系型数据库 MySQL
Java汽车租赁系统源码(含数据库脚本)
Java汽车租赁系统源码(含数据库脚本)
722 4
|
消息中间件 算法 安全
JUC并发—1.Java集合包底层源码剖析
本文主要对JDK中的集合包源码进行了剖析。
|
Java
【源码】【Java并发】【ConcurrentHashMap】适合中学体质的ConcurrentHashMap
本文深入解析了ConcurrentHashMap的实现原理,涵盖JDK 7与JDK 8的区别、静态代码块、构造方法、put/get/remove核心方法等。JDK 8通过Node数组+链表/红黑树结构优化并发性能,采用CAS和synchronized实现高效锁机制。文章还详细讲解了hash计算、表初始化、扩容协助及计数更新等关键环节,帮助读者全面掌握ConcurrentHashMap的工作机制。
397 6
【源码】【Java并发】【ConcurrentHashMap】适合中学体质的ConcurrentHashMap
|
人工智能 安全 Java
智慧工地源码,Java语言开发,微服务架构,支持分布式和集群部署,多端覆盖
智慧工地是“互联网+建筑工地”的创新模式,基于物联网、移动互联网、BIM、大数据、人工智能等技术,实现对施工现场人员、设备、材料、安全等环节的智能化管理。其解决方案涵盖数据大屏、移动APP和PC管理端,采用高性能Java微服务架构,支持分布式与集群部署,结合Redis、消息队列等技术确保系统稳定高效。通过大数据驱动决策、物联网实时监测预警及AI智能视频监控,消除数据孤岛,提升项目可控性与安全性。智慧工地提供专家级远程管理服务,助力施工质量和安全管理升级,同时依托可扩展平台、多端应用和丰富设备接口,满足多样化需求,推动建筑行业数字化转型。
477 5

热门文章

最新文章