App下載

Java實(shí)例代碼實(shí)現(xiàn)一個(gè)簡單的貪吃蛇小游戲

猿友 2021-08-03 10:51:54 瀏覽數(shù) (13571)
反饋

貪吃蛇是一款非常經(jīng)典的游戲,也十分適合許多初學(xué)編程語言用來練習(xí)的一個(gè)簡單練習(xí)。下面,我將通過Java編程語言,和大家分享一下怎么制作一個(gè)簡單且有趣的貪吃蛇小游戲。

1. 程序結(jié)構(gòu)

程序結(jié)構(gòu)圖如圖:

2021416115356969

2. 程序設(shè)計(jì)思路

2.1 Data類

作用:連接statics文件夾,將靜態(tài)資源包中的圖片轉(zhuǎn)化為圖標(biāo) 方便在面板上繪制。

實(shí)現(xiàn):使用class.getResource(String path)方法。

代碼如下:

package com.snake;
import javax.swing.*;
import java.net.URL;
public class Data {
    //貪吃蛇頭部
    public static URL upUrl = Data.class.getResource("/statics/up.png");
    public static ImageIcon up = new ImageIcon(upUrl);
    public static URL downUrl = Data.class.getResource("/statics/down.png");
    public static ImageIcon down = new ImageIcon(downUrl);
    public static URL leftUrl = Data.class.getResource("/statics/left.png");
    public static ImageIcon left = new ImageIcon(leftUrl);
    public static URL rightUrl = Data.class.getResource("/statics/right.png");
    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);
}

2.2 StartGame類

作用:創(chuàng)建游戲窗口,在窗口中添加一個(gè)游戲面板。
實(shí)現(xiàn):使用JFrame類創(chuàng)建游戲窗口,利用其add()方法添加一個(gè)GamePanel類實(shí)例化對象。

代碼如下:

package com.snake;
import javax.swing.*;
import java.awt.*;
public class StartGame {
    public static void main(String[] args){
        //建立游戲窗口
        JFrame frame = new JFrame("Java-貪吃蛇小游戲");//標(biāo)題
        frame.setSize(900,720);//窗口大小
        frame.setLocationRelativeTo(null);//窗口顯示屏幕中間
        frame.setResizable(false);//固定窗口大小
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//設(shè)置窗體關(guān)閉事件
        frame.add(new GamePanel());//添加游戲內(nèi)容
        frame.setVisible(true);//設(shè)置窗體可見
    }
}

2.3 GamePanel類

作用:實(shí)現(xiàn)游戲的動(dòng)態(tài)頁面。

實(shí)現(xiàn):

(1)init()方法:初始化小蛇位置;
(2)eat()方法:用隨機(jī)種子隨機(jī)食物的位置,并進(jìn)行判定,食物位置不能和小蛇位置重合;
(3)繼承JPanel類,重寫paintComponent(Graphics g)方法,在方法中繪制標(biāo)題欄、小蛇的位置(根據(jù)direction小蛇頭部方向變量繪制小蛇頭部)、小蛇身體、積分欄、游戲提醒項(xiàng)與失敗判斷項(xiàng);
(4)實(shí)現(xiàn)KeyListener 接口中的keyPressed(KeyEvent e)方法,獲取鍵盤輸入,根據(jù)鍵盤輸入對游戲狀態(tài)或者小蛇頭部方向direction變量進(jìn)行更改;
(5)實(shí)現(xiàn)ActionListener接口中的actionPerformed(ActionEvent e)方法,根據(jù)游戲狀態(tài)和direction變量進(jìn)行小蛇移動(dòng)操作(注意禁用直接回頭操作),進(jìn)行吃食物判定和死亡判定。使用Timer計(jì)時(shí)器讓游戲動(dòng)態(tài)變化,用repaint()方法實(shí)時(shí)更新界面。

代碼如下:

package com.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[] snakeX = new int[500];//貪吃蛇橫坐標(biāo)
    int[] snakeY = new int[500];//貪吃蛇縱坐標(biāo)
    int foodX;//食物橫坐標(biāo)
    int foodY;//食物蛇縱坐標(biāo)
    int length;//貪吃蛇的長度
    String  direction;//貪吃蛇頭方向
    int score;//積分
    Random r = new Random();
    Timer timer = new Timer(100,this);
    boolean isStart;
    boolean isFail;
    //構(gòu)造函數(shù)
    public GamePanel(){
        init();
        this.setFocusable(true);
        this.addKeyListener(this);
        timer.start();
    }
    private void init(){
        length=3;
        snakeX[0]=100;snakeY[0]=100;
        snakeX[1]=75;snakeY[1]=100;
        snakeX[2]=50;snakeY[2]=100;
        direction = "R";
        eat(foodX,foodY);
        isStart = false;
        isFail = false;
        score = 0;

    }
    private void eat(int x,int y){
        x= 25 + 25*r.nextInt(34);
        y= 75 + 25*r.nextInt(24);
        for (int i = 0; i < length; i++) {
            if(snakeX[i]==x&&snakeY[i]==y){
                x = 25 + 25*r.nextInt(34);
                y = 75 + 25*r.nextInt(24);
            }
        }
        foodX = x;foodY = y;
    }
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        this.setBackground(Color.white);//設(shè)置背景板為白色
        //畫標(biāo)題
        g.setColor(Color.GREEN);
        g.setFont(new Font("幼圓",Font.BOLD,50));
        g.drawString("貪吃蛇游戲",300,60);
        //繪制游戲區(qū)域
        g.setColor(Color.GRAY);
        g.fillRect(25,75,850,600);
        //畫貪吃蛇頭部
        if(direction=="R"){
            Data.right.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        else if(direction=="L"){
            Data.left.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        if(direction=="U"){
            Data.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        else if(direction=="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]);
        }
        //畫食物
        Data.food.paintIcon(this,g,foodX,foodY);
        //繪制積分欄
        g.setColor(Color.BLACK);
        g.setFont(new Font("幼圓",Font.BOLD,20));
        g.drawString("長度:"+length,730,30);
        g.drawString("得分:"+score,730,60);
        //游戲開始提醒
        if(isStart==false){
            g.setColor(Color.BLACK);
            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();//獲取按下的按鍵
        //判斷空格
        if(keyCode==KeyEvent.VK_SPACE){
            if(isFail){
                isFail = false;
                init();
            }
            else{
                isStart = !isStart;
            }
            repaint();
        }
        //判斷方向
        if(keyCode==KeyEvent.VK_LEFT&&direction!="R"){
            direction = "L";
        }
        else if(keyCode==KeyEvent.VK_RIGHT&&direction!="L"){
            direction = "R";
        }
        else if(keyCode==KeyEvent.VK_UP&&direction!="D"){
            direction = "U";
        }
        else if(keyCode==KeyEvent.VK_DOWN&&direction!="U"){
            direction = "D";
        }
    }
    @Override
    public void keyReleased(KeyEvent e) {

    }
    @Override
    public void keyTyped(KeyEvent e) {
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        //判斷游戲狀態(tài)
        if(isStart&&!isFail){
            //移動(dòng)身體
            for (int i = length-1; i > 0 ; i--) {
                snakeX[i] = snakeX[i-1];
                snakeY[i] = snakeY[i-1];
            }
            //移動(dòng)頭部
            if(direction=="R"){
                snakeX[0] += 25;
                if(snakeX[0]>850){
                    snakeX[0] = 25;
                }
            }
            else  if(direction=="L"){
                snakeX[0] -= 25;
                if(snakeX[0]<25){
                    snakeX[0] = 850;
                }
            }
            else  if(direction=="U"){
                snakeY[0] -= 25;
                if(snakeY[0]<75){
                    snakeY[0] = 650;
                }
            }
            else  if(direction=="D"){
                snakeY[0] += 25;
                if(snakeY[0]>650){
                    snakeY[0] = 75;
                }
            }
            //吃食物
            if(snakeX[0]==foodX&&snakeY[0]==foodY){
                length++;
                score += 10;
                eat(foodX,foodY);
            }
            //死亡判定
            for (int i = 1; i < length; i++) {
                if(snakeX[0]==snakeX[i]&&snakeY[0]==snakeY[i]){
                    isFail=true;
                }
            }
            repaint();
        }
        timer.start();
    }
}

3. 游戲展示

2021416115527973

以上就是關(guān)于使用 Java 編程語言來實(shí)現(xiàn)簡單的貪吃蛇小游戲的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持W3Cschool。


0 人點(diǎn)贊