java-贪吃蛇小游戏

java GUI编程实现贪吃蛇小游戏

一 准备
首先准备三张图片,分别是:蛇头,蛇身体,食物。(尺寸 25 * 25 像素)
我创建的是一个springboot项目,所以我把这些静态资源放在了resources目录下的static文件夹下,创建个文件夹叫snake,再把这三张图片放进去。

image

二 新建一个Data类,作为图片资源

import cn.hutool.core.io.resource.ClassPathResource;

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

/**
 * create by fzg
 * 2022/11/15 13:07
 * 获取数据,图片
 */

// 数据:图片资源
public class Data {
   

    // 图片资源放哪里都可以,只要能找到,并且将类型转化为URL
    // 我用的是胡图工具的 ClassPathResource

    // 蛇头
    public static URL headerURL = new ClassPathResource("/static/snake/header.png").getUrl();
    // 蛇身体
    public static URL bodyURL = new ClassPathResource("/static/snake/body.png").getUrl();
    // 食物
    public static URL foodURL  = new ClassPathResource("/static/snake/food.png").getUrl();


    public static ImageIcon header = new ImageIcon(headerURL);
    public static ImageIcon body = new ImageIcon(bodyURL);
    public static ImageIcon food = new ImageIcon(foodURL);

    

}

三 Snake类,定义蛇的数据结构和初始化方法

/**
 * create by fzg
 * 2022/11/15 13:33
 */

// 贪吃蛇基本类
public class Snake {
   

    // 定义蛇的数据结构
    int length; // 蛇的长度
    int[] snakex = new int[600]; // 蛇的x坐标
    int[] snakey = new int[500]; // 蛇的y坐标

    // 初始化方向
    String fx;

    // 初始化方法
    public void init(){
   
        // 初始化长度3
        length = 3;
        // 脑袋的坐标
        snakex[0] = 100;
        snakey[0] = 100;
        // 第一个身体的坐标
        snakex[1] = 75;
        snakey[1] = 100;
        // 第二个身体的坐标
        snakex[2] = 50;
        snakey[2] = 100;
        // 初始化方向往右
        fx = "D";

    }

    public Snake(){
   
        init();
    }

}

四 游戏面板类 GamePanel(核心代码)

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;

/**
 * create by fzg
 * 2022/11/15 13:39
 */

/**
 * 游戏面板
 * 键盘监听器
 * 定时器
 */
public class GamePanel extends JPanel implements KeyListener, ActionListener {
   

    // 游戏当前的状态
    boolean isStart = false; // 默认不开始<
  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.util.*; public class snate extends JFrame implements KeyListener,Runnable { JLabel j; Canvas j1; public static final int canvasWidth = 200; public static final int canvasHeight = 300; public static final int nodeWidth = 10; public static final int nodeHeight = 10; //SnakeModel se=null; //222222 // boolean[][] matrix; LinkedList nodeArray = new LinkedList();//表 Node food;//节点 int maxX; int maxY; int direction = 2; boolean running = false; int timeInterval = 200; double speedChangeRate = 0.75; boolean paused = false; int score = 0; int countMove = 0; // UP and DOWN should be even // RIGHT and LEFT should be odd public static final int UP = 2; public static final int DOWN = 4; public static final int LEFT = 1; public static final int RIGHT = 3; snate() { super(); //setSize(500,400); Container c=getContentPane(); j=new JLabel("Score:"); c.add(j,BorderLayout.NORTH); j1=new Canvas(); j1.setSize(canvasWidth+1,canvasHeight+1); j1.addKeyListener(this); c.add(j1,BorderLayout.CENTER); JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); JLabel j2; j2 = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER); p1.add(j2, BorderLayout.NORTH); j2 = new JLabel("ENTER or R or S for start;", JLabel.CENTER); p1.add(j2, BorderLayout.CENTER); j2 = new JLabel("SPACE or P for pause",JLabel.CENTER); p1.add(j2, BorderLayout.SOUTH); c.add(p1,BorderLayout.SOUTH); addKeyListener(this); pack(); setResizable(false); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); // begin(); // //2222222 // this.gs = gs; this.maxX = maxX; this.maxY = maxY; // initial matirx matrix = new boolean[maxX][]; for(int i=0; i<maxX; ++i){ matrix[i] = new boolean[maxY]; Arrays.fill(matrix[i],false); } // initial the snake int initArrayLength = maxX > 20 ? 10 : maxX/2; for(int i = 0; i < initArrayLength; ++i){ int x = maxX/2+i; int y = maxY/2; nodeArray.addLast(new Node(x, y)); matrix[x][y] = true; } food = createFood(); matrix[food.x][food.y] = true; } public void keyPressed(KeyEvent e) { if(e.getKeyCode()==KeyEvent.VK_UP) { //se.changeDirection(SnakeModel.UP); } if(e.getKeyCode()==KeyEvent.VK_DOWN) { //se.changeDirection(SnakeModel.DOWN); } if(e.getKeyCode()==KeyEvent.VK_LEFT) { //se.changeDirection(SnakeModel.LEFT); } if(e.getKeyCode()==KeyEvent.VK_RIGHT) { //se.changeDirection(SnakeModel.RIGHT); } if(e.getKeyCode()==KeyEvent.VK_R||e.getKeyCode()==KeyEvent.VK_S||e.getKeyCode()==KeyEvent.VK_ENTER) { } } public void keyTyped(KeyEvent e) {} public void keyReleased(KeyEvent e) {} public void repaint() { Graphics g = j1.getGraphics(); //背景 g.setColor(Color.red); g.fillRect(0,0,canvasWidth,canvasHeight); //蛇 //g.setColor(Color.BLUE); } public void paint(Graphics g) { g.setColor(Color.red); g.fillRect(10,10,10,10); } // //222222 // public void changeDirection(int newDirection){ if (direction % 2 != newDirection % 2){ direction = newDirection; } } public boolean moveOn(){ Node n = (Node)nodeArray.getFirst(); int x = n.x; int y = n.y; switch(direction){ case UP: y--; break; case DOWN: y++; break; case LEFT: x--; break; case RIGHT: x++; break; } if ((0 <= x && x < maxX) && (0 <= y && y < maxY)){ if (matrix[x][y]){ if(x == food.x && y == food.y){ nodeArray.addFirst(food); int scoreGet = (10000 - 200 * countMove) / timeInterval; score += scoreGet > 0? scoreGet : 10; countMove = 0; food = createFood(); matrix[food.x][food.y] = true; return true; } else return false; } else{ nodeArray.addFirst(new Node(x,y)); matrix[x][y] = true; n = (Node)nodeArray.removeLast(); matrix[n.x][n.y] = false; countMove++; return true; } } return false; } public void run(){ running = true; while (running){ try{ Thread.sleep(timeInterval); } catch(Exception e){ break; } if(!paused){ if (moveOn()){ gs.repaint(); } else{ JOptionPane.showMessageDialog( null, "you failed", "Game Over", JOptionPane.INFORMATION_MESSAGE); break; } } } running = false; } private Node createFood(){ int x = 0; int y = 0; do{ Random r = new Random(); x = r.nextInt(maxX); y = r.nextInt(maxY); }while(matrix[x][y]); return new Node(x,y); } public void speedUp(){ timeInterval *= speedChangeRate; } public void speedDown(){ timeInterval /= speedChangeRate; } public void changePauseState(){ paused = !paused; } public String toString(){ String result = ""; for(int i=0; i<nodeArray.size(); ++i){ Node n = (Node)nodeArray.get(i); result += "[" + n.x + "," + n.y + "]"; } return result; } } class Node{ int x; int y; Node(int x, int y){ this.x = x; this.y = y; } } public static void main(String[] args) { //Graphics g=j1.getGraphics(); snate s=new snate(); //s.draw_something(g); //s.setVisible(true); } }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值