溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用Java怎么實(shí)現(xiàn)一個貪吃蛇小游戲

發(fā)布時間:2021-04-16 15:46:24 來源:億速云 閱讀:196 作者:Leah 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)使用Java怎么實(shí)現(xiàn)一個貪吃蛇小游戲,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

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

??程序結(jié)構(gòu)圖如圖:
使用Java怎么實(shí)現(xiàn)一個貪吃蛇小游戲

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)建游戲窗口,在窗口中添加一個游戲面板。

  • 實(shí)現(xiàn):使用JFrame類創(chuàng)建游戲窗口,利用其add()方法添加一個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)游戲的動態(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)行小蛇移動操作(注意禁用直接回頭操作),進(jìn)行吃食物判定和死亡判定。使用Timer計(jì)時器讓游戲動態(tài)變化,用repaint()方法實(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){
            //移動身體
            for (int i = length-1; i > 0 ; i--) {
                snakeX[i] = snakeX[i-1];
                snakeY[i] = snakeY[i-1];
            }
            //移動頭部
            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();
    }}

關(guān)于使用Java怎么實(shí)現(xiàn)一個貪吃蛇小游戲就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI