欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

GUI编程-贪吃蛇小游戏

程序员文章站 2022-07-14 17:22:42
...

【狂神说Java】GUI编程入门到游戏实战
https://www.bilibili.com/video/BV1DJ411B75F

主要逻辑

  1. 定义数据
  2. 初始化数据
    init()
  3. 在画板上画出组件
    paintComponent(Graphics g)
  4. 编辑监听事件,分为键盘监听事件和事件监听
    keyPressed(KeyEvent e)
    actionPerformed(ActionEvent e)
package com.harbin.snake;

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 GamePanel extends JPanel implements KeyListener , ActionListener {
    //绘制面板,游戏中所有东西都用这个画笔来画
    //定义蛇的数据结构
    int length; //长度
    int[] snakeX = new int[600];
    int[] snakeY = new int[500];
    //蛇的方向
    String fx;

    //食物的坐标
    int foodX;
    int foodY;
    Random random = new Random();

    //当前游戏状态,开始 停止
    boolean isStart = false;

    //游戏失败
    boolean isFail = false;

    //成绩
    int score;

    //定时器
    Timer timer = new Timer(200,this);

    public GamePanel() {
        init();
        this.setFocusable(true);//获得焦点事件
        this.addKeyListener(this);//获得键盘监听事件
        timer.start();//游戏开始定时器就启动
    }

    public void init(){
        length = 3;
        snakeX[0] = 100;snakeY[0]=100;
        snakeX[1] = 75;snakeY[1]=100;
        snakeX[2] = 50;snakeY[2]=100;
        fx = "R";//初始化方向向右

        //食物随机放在屏幕
        foodX = 25 + 25*random.nextInt(34);
        foodY = 75 + 25*random.nextInt(24);

        //初始化成绩
        score = 0;

    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//清屏
        //绘制静态面板
        this.setBackground(Color.WHITE);
        //参数(画到哪里:this当前面板,用什么画:画笔参数g,画的位置:x,y)
        Data.header.paintIcon(this,g,25,11); //头部广告
        g.fillRect(25,75,850,600);//游戏界面

        //画积分
        g.setColor(Color.WHITE);
        g.setFont(new Font("微软雅黑",Font.BOLD,18));
        g.drawString("长度"+length,750,30);
        g.drawString("分数"+score,750,55);

        //画食物
        Data.food.paintIcon(this,g,foodX,foodY);

        //画蛇头,初始化蛇头向右,需要通过方向判断
        if (fx.equals("R")){
            Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (fx.equals("L")){
            Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (fx.equals("U")){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }else if (fx.equals("D")){
            Data.down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        //画身体
        for (int i = 1; i < length; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }

        //游戏状态
        if (!isStart){
            g.setColor(Color.WHITE);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("按下空格开始游戏",300,300);
        }

        if (isFail){
            g.setColor(Color.RED);
            g.setFont(new Font("微软雅黑",Font.BOLD,40));
            g.drawString("游戏失败,按下空格重新开始",300,300);
        }

    }

    //键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();//获取按下的键
        System.out.println(keyCode);
        if (keyCode == KeyEvent.VK_SPACE){ //如果按下空格键
            if (isFail){
                isFail = false;
                init();
            }else {
                isStart = !isStart;
            }

            repaint();
        }

        //小蛇移动
        if (keyCode == KeyEvent.VK_UP){
            fx = "U";
        }else if (keyCode == KeyEvent.VK_DOWN){
            fx = "D";
        }else if (keyCode == KeyEvent.VK_LEFT){
            fx = "L";
        }else if (keyCode == KeyEvent.VK_RIGHT){
            fx = "R";
        }


    }

    //事件监听-通过定时事件刷新
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && !isFail){
            //吃食物 头和食物坐标重合
            if (snakeX[0] == foodX && snakeY[0] == foodY){
                //长度+1
                length++;
                //分数+10
                score += 10;
                //再次生成食物
                foodX = 25 + 25*random.nextInt(34);
                foodY = 75 + 25*random.nextInt(24);
            }


            //走向
            for (int i = length-1; i > 0 ; i--) {
                snakeX[i] = snakeX[i-1];
                snakeY[i] = snakeY[i-1];
            }

            //走向
            if (fx.equals("R")){
                snakeX[0] += 25;
                if (snakeX[0] > 850){snakeX[0] = 25;}//边界判断
            }else if (fx.equals("L")){
                snakeX[0] -= 25;
                if (snakeX[0] < 25){snakeX[0] = 850;}//边界判断
            }else if (fx.equals("U")){
                snakeY[0] -= 25;
                if (snakeY[0] < 75){snakeY[0] = 650;}//边界判断
            }else if (fx.equals("D")){
                snakeY[0] += 25;
                if (snakeY[0] > 650){snakeY[0] = 75;}//边界判断
            }

            //失败判断,撞到自己就算失败
            for (int i = 1; i < length; i++) {
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]){isFail=true;}
            }
            repaint();
        }
        timer.start();
    }
    @Override
    public void keyTyped(KeyEvent e) {}
    @Override
    public void keyReleased(KeyEvent e) {}
}

游戏启动入口

package com.harbin.snake;

import javax.swing.*;

public class StartGame {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        frame.setBounds(10,10,900,720);
        frame.setResizable(false);

        //游戏界面放入画板
        frame.add(new GamePanel());

        //一定放在下面,否则监听事件无效
        frame.setVisible(true);

    }
}

将以下文件放进项目目录的statics包下

GUI编程-贪吃蛇小游戏
GUI编程-贪吃蛇小游戏
GUI编程-贪吃蛇小游戏
GUI编程-贪吃蛇小游戏
GUI编程-贪吃蛇小游戏
GUI编程-贪吃蛇小游戏
GUI编程-贪吃蛇小游戏