Greedy Snake_java application Gui

1. GUI introduction

In the early days, computers provided users with a monotonous, boring, and character-only "command line interface (CLI)." Even now, we can still see them vaguely: open a DOS window in Windows, and you can see the footprints of history. Later, Apple took the lead in implementing a Graphical User Interface (GUI) in the computer operating system, but due to Apple’s closed market strategy, it completed its own computer hardware, operating system, and application software one-stop product , It is not compatible with other PCs. This makes Apple miss a good opportunity to unify the global PC.
Later, Microsoft introduced the Windows operating system, which is popular all over the world. With its excellent graphical user interface, it established its status as an operating system standard in one fell swoop. This also created the world's richest man-Bill Gates and IT industry's Tarzan Beidou Microsoft.
In today's world where graphical user interfaces are popular, an application software cannot be accepted by users without a good GUI. The Java language is also well aware of the importance of this point, and it provides a set of tools that can easily build GUIs. In this chapter and the next chapter, we will fully prove this to you.

2. Snake code

Data.java

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

public class Data {
    //头部图片
    public static URL headerUrl = Data.class.getResource("/statics/header.png");
    public static ImageIcon header = new ImageIcon(headerUrl);
    //头部:上下左右
    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 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 URL bodyUrl = Data.class.getResource("/statics/body.png");
    public static ImageIcon body = new ImageIcon(bodyUrl);
    //食物
    public static URL foodUrl = Data.class.getResource("/statics/food.png");
    public static ImageIcon food = new ImageIcon(foodUrl);
}

GamePanel.java

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 lenth; //蛇的长度
    int[] snakeX = new int[600];  //蛇的坐标x
    int[] snakeY = new int[500];  //蛇的坐标y
    String fx = "R"; //蛇的方向 : R:右  L:左  U:上  D:下
    boolean isStart = false; //游戏是否开始
    Timer timer = new Timer(100, this); //定时器:第一个参数,就是定时执行时间
    //食物
    int foodx;
    int foody;
    Random random = new Random();
    boolean isFail = false; //游戏是否结束
    int score; //游戏分数!

    //构造方法
    public GamePanel(){
        init();//初始化
        this.setFocusable(true); //获取焦点事件
        this.addKeyListener(this); //键盘监听事件
        timer.start();
    }
    //初始化方法
    public void init(){
        lenth = 3;//初始小蛇有三节,包括小脑袋
        //初始化开始的蛇,给蛇定位,
        snakeX[0] = 100; snakeY[0] = 100;
        snakeX[1] = 75; snakeY[1] = 100;
        snakeX[2] = 50; snakeY[2] = 100;

        //初始化食物数据
        foodx = 25 + 25* random.nextInt(34);
        foody = 75 + 25* random.nextInt(24);

        score = 0; //初始化游戏分数
    }


    //画组件
    public void paintComponent(Graphics g){
        super.paintComponent(g);//清屏
        this.setBackground(Color.WHITE); //设置面板的背景色
        Data.header.paintIcon(this,g,25,11); //绘制头部信息区域
        g.fillRect(25,75,850,600); //绘制游戏区域

        //把小蛇画上去
        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 < lenth; i++) {
            Data.body.paintIcon(this,g,snakeX[i],snakeY[i]); //蛇的身体长度根据lenth来控制
        }

        //画食物
        Data.food.paintIcon(this,g,foodx,foody);

        g.setColor(Color.white);
        g.setFont(new Font("微软雅黑",Font.BOLD,18));
        g.drawString("长度 " + lenth,750,35);
        g.drawString("分数 " + score,750,50);

        //游戏提示
        if (isStart==false){
            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("失败, 按下空格重新开始",200,300);
        }

    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    //键盘监听事件
    @Override
    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode(); //获取按下的键盘

        if (keyCode==KeyEvent.VK_SPACE){ //如果是空格
            if (isFail){ //如果游戏失败,从头再来!
                isFail = false;
                init(); //重新初始化
            }else { //否则,暂停游戏
                isStart = !isStart;
            }
            repaint();
        }

        //键盘控制走向
        if (keyCode==KeyEvent.VK_LEFT){
            fx = "L";
        }else if (keyCode==KeyEvent.VK_RIGHT){
            fx = "R";
        }else if (keyCode==KeyEvent.VK_UP){
            fx = "U";
        }else if (keyCode==KeyEvent.VK_DOWN){
            fx = "D";
        }

    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    //定时执行的操作
    @Override
    public void actionPerformed(ActionEvent e) {
        //如果游戏处于开始状态,并且没有结束,则小蛇可以移动
        if (isStart && isFail==false){
            //右移:即让后一个移到前一个的位置即可 !
            for (int i = lenth-1; i > 0; i--) { //除了脑袋都往前移:身体移动
                snakeX[i] = snakeX[i-1]; //即第i节(后一节)的位置变为(i-1:前一节)节的位置!
                snakeY[i] = snakeY[i-1];
            }
            //通过方向控制,头部移动
            if (fx.equals("R")){
                snakeX[0] = snakeX[0]+25;
                if (snakeX[0]>850) snakeX[0] = 25;
            }else if (fx.equals("L")){
                snakeX[0] = snakeX[0]-25;
                if (snakeX[0]<25) snakeX[0] = 850;
            }else if (fx.equals("U")){
                snakeY[0] = snakeY[0]-25;
                if (snakeY[0]<75) snakeY[0] = 650;
            }else if (fx.equals("D")){
                snakeY[0] = snakeY[0]+25;
                if (snakeY[0]>650) snakeY[0] = 75;
            }

            //吃食物:当蛇的头和食物一样时,算吃到食物!
            if (snakeX[0]==foodx && snakeY[0]==foody){
                //1.长度加一
                lenth++;
                //每吃一个食物,增加积分
                score = score + 10;
                //2.重新生成食物
                foodx = 25 + 25* random.nextInt(34);
                foody = 75 + 25* random.nextInt(24);
            }

            //结束判断,头和身体撞到了
            for (int i = 1; i < lenth; i++) {
                //如果头和身体碰撞,那就说明游戏失败
                if (snakeX[i]==snakeX[0] && snakeY[i]==snakeY[0] ){
                    isFail = true;
                }
            }

            repaint(); //需要不断的更新页面实现动画
        }
        timer.start();//让时间动起来!

    }

}

StartGame.java

import javax.swing.*;

public class StartGame {

    public static void main(String[] args) {
        //1.新建一个窗口
        JFrame frame = new JFrame("狂神说Java-贪吃蛇小游戏");
        frame.setBounds(10,10,900,720);  // 设置窗口的位置和大小
        frame.setResizable(false); //窗口大小不可调整,即固定窗口大小
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置关闭事件,游戏可以关闭

        //2.添加我们自己编写的画布背景
        frame.add(new GamePanel());

        frame.setVisible(true); //将窗口展示出来
    }

}

Insert picture description here

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_43141726/article/details/114412434