Java GUI学习,贪吃蛇小游戏

2021/5/16 20:55:28

本文主要是介绍Java GUI学习,贪吃蛇小游戏,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

JAVA GUI练习 贪吃蛇小游戏

前几天虽然生病了,但还是跟着狂神学习了GUI的方面,跟着练习了贪吃蛇的小项目,这里有狂神写的源码点我下载,还有我跟着敲的点我下载,嘿嘿,也就注释了下重要的地方,这方面逻辑层面还是很简单的,主要是GUI绘画,布局等等的学习,这里我也贴出我这里GUI练习写过的包点我下载,不过这个比较乱(前面基础的awt比较乱,没分包写,swing基本都分包写了还是不乱的),但你打开这个包,你idea也是能通过英文看出来什么意思的~~

贴一下贪吃蛇的代码吧~~

JavaDoc可以自己idea生成哦,别忘了设置字符编码防止中文乱码错误~~

package com.zaunekko.gui.game.snake;

import javax.swing.*;
//入口
public class StartGame {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame();

        jFrame.setBounds(50,50,915,738);
        jFrame.setResizable(false);
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        //添加JPanel
        jFrame.add(new GamePanel());
        
        jFrame.setVisible(true);

    }


}
package com.zaunekko.gui.game.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[900];
    int[] snakeY = new int[900];

    //食物
    int foodX;
    int foodY;
    Random random;

    //成绩
    int score;



    //键盘按键方向
    String direction;

    //游戏是否开始
    boolean isStart;

    //是否失败
    boolean isFail;


    //定时器
    //Timer timer; 如果在init()里初始化赋值会有bug,死亡之后会double timer,所以只能初始化一次
    Timer timer = new Timer(500,this);//ms为单位
    //构造器
    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;




        random = new Random();
        foodX = 25 + 25*random.nextInt(34);
        foodY = 75 + 25*random.nextInt(24);

        score = 0;

        direction = "R";
        isStart = false;
        isFail = false;


    }



    //画笔
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        this.setBackground(Color.WHITE);

        Data.header.paintIcon(this,g,25,0);
        g.fillRect(25,75,850,600);


        Data.food.paintIcon(this,g,foodX,foodY);


        switch (direction) {
            case "R" -> Data.right.paintIcon(this, g, snakeX[0], snakeY[0]);
            case "L" -> Data.left.paintIcon(this, g, snakeX[0], snakeY[0]);
            case "U" -> Data.up.paintIcon(this, g, snakeX[0], snakeY[0]);
            case "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]);
        }

        g.setColor(Color.WHITE);
        g.setFont(new Font("微软雅黑",Font.BOLD,18));
        g.drawString("长度" + length,800,15);
        g.drawString("分数" + score,800,45);


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

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






    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    //键盘监听
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();
        if (keyCode == KeyEvent.VK_SPACE) {
            if (isFail){
                //死亡就初始化
                repaint();
                init();
            }else {
                isStart = !isStart;
                repaint();
            }
        }else if (keyCode == KeyEvent.VK_UP){
            if (isStart)//如果不加此句判断是否已经开始就可以更改方向,则bug:提示按空格时即可更改初始方向
                direction = "U";
        }else if (keyCode == KeyEvent.VK_DOWN){
            if (isStart)
                direction = "D";
        }else if (keyCode == KeyEvent.VK_LEFT){
            if (isStart)
                direction = "L";
        }else if (keyCode == KeyEvent.VK_RIGHT){
            if (isStart)
                direction = "R";
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    //事件监听
    @Override
    public void actionPerformed(ActionEvent e) {
        if (isStart && !isFail){

            //吃食物
            if (snakeX[0] == foodX && snakeY[0] == foodY) {
                ++length;
                foodX = 25 + 25*random.nextInt(34);
                foodY = 75 + 25*random.nextInt(24);

                score += 10;

            }


            //蛇的第i个元素为上一个元素的位置
            for (int i = length - 1; i > 0 ; --i){
                snakeX[i] = snakeX[i-1];
                snakeY[i] = snakeY[i-1];
            }

            //方向以及越界判定
            switch (direction) {
                case "R" -> {
                    snakeX[0] += 25;
                    if (snakeX[0] >= 875) {
                        snakeX[0] = 25;
                    }
                }
                case "L" -> {
                    snakeX[0] -= 25;
                    if (snakeX[0] < 25) {
                        snakeX[0] = 850;
                    }
                }
                case "U" -> {
                    snakeY[0] -= 25;
                    if (snakeY[0] < 75) {
                        snakeY[0] = 650;
                    }
                }
                case "D" -> {
                    snakeY[0] += 25;
                    if (snakeY[0] >= 675) {
                        snakeY[0] = 75;
                    }
                }
            }

            //失败
            for (int i = 1; i < length; i++) {
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]){
                    isFail = true;
                    break;
                }
            }



            repaint();
        }
        timer.start();

    }
}

package com.zaunekko.gui.game.snake;

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

public class Data {


    public static URL headerURL = Data.class.getResource("header.png");
    public static URL upURL = Data.class.getResource("up.png");
    public static URL downURL = Data.class.getResource("down.png");
    public static URL leftURL = Data.class.getResource("left.png");
    public static URL rightURL = Data.class.getResource("right.png");
    public static URL foodURL = Data.class.getResource("food.png");
    public static URL bodyURL = Data.class.getResource("body.png");

    public static ImageIcon header = new ImageIcon(headerURL);
    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 food = new ImageIcon(foodURL);
    public static ImageIcon body = new ImageIcon(bodyURL);





}



这篇关于Java GUI学习,贪吃蛇小游戏的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程