java開發貪吃蛇小遊戲-(B站狂神說)(自己又補充了一些功能-不能撞牆-不能掉頭)

2020-09-29 14:00:01

根據B站狂神說java視訊 一點一點寫的貪吃蛇小遊戲(自己又補充了一些功能)不能撞牆-不能掉頭
直接上原始碼
StartGame.java

package codeyuaiiao;

import javax.swing.*;

/**
 * 遊戲開始
 * by:codeyuaiiao
 */
public class StartGame {
    public static void main(String[] args) {
        //1.繪製一個靜態視窗
        JFrame jf = new JFrame("codeyuaiiao-java貪吃蛇小遊戲");
        jf.setBounds(10,10,900,720);//給視窗制定位置和長寬大小
        jf.setResizable(false);//自動更改視窗大小
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//是否可以手動關閉視窗

        //2.繪製一個面板  新增元件到JFrame
        jf.add(new GamePanel());

        //3.顯示視窗
        jf.setVisible(true);
    }
}

GamePanel.java

package codeyuaiiao;

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;

/**
 * 遊戲畫板
 * by:codeyuaiiao
 */
public class GamePanel extends JPanel implements KeyListener, ActionListener {

    int length;//蛇的長度
    int[] snakeX = new int[600];//蛇的座標X
    int[] snakeY = new int[500];//蛇的座標Y
    String fx; //"R":right;"D":down;"U":up;"L":Left;
    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(){
        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;
    }
    //畫面板   Ctrl+O 重寫
    //Graphics g: 畫筆
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);//清屏
        this.setBackground(Color.white);//設定背景顏色
        Date.header.paintIcon(this,g,25,11); //繪製頭部廣告欄
        g.fillRect(25,75,850,600);//繪製遊戲區域

        //畫一條靜態的小蛇
        if(fx.equals("R")){
            Date.right.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        if(fx.equals("D")){
            Date.down.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        if(fx.equals("U")){
            Date.up.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        if(fx.equals("L")){
            Date.left.paintIcon(this,g,snakeX[0],snakeY[0]);
        }

        //通過控制length的長度來控制小蛇的長度
        for (int i = 1; i < length; i++) {
            Date.body.paintIcon(this,g,snakeX[i],snakeY[i]);
        }

        //畫積分
        g.setColor(Color.white);
        g.setFont(new Font("楷體",Font.BOLD,16));
        g.drawString("長度"+length,750,35);
        g.drawString("分數"+score,750,55);

        //畫食物
        Date.food.paintIcon(this,g,foodX,foodY);
        if(snakeX[0]==foodX && snakeY[0]==foodY){
            //小蛇長度+1
            length++;
            //積分+10
            score += 10;
            foodX = 25 + 25*random.nextInt(34);
            foodY = 75 + 25*random.nextInt(24);
        }

        //畫開始文字
        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);
        }
    }
    //按鍵監聽
    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){
            if(fx.equals("R")){
                fx = "R";
            }else{
                fx = "L";
            }
        } else if (keyCode == KeyEvent.VK_RIGHT){
            if(fx.equals("L")){
                fx = "L";
            }else{
                fx = "R";
            }
        }if(keyCode == KeyEvent.VK_UP){
            if(fx.equals("D")){
                fx = "D";
            }else{
                fx = "U";
            }
        } else if (keyCode == KeyEvent.VK_DOWN){
            if(fx.equals("U")){
                fx = "U";
            }else{
                fx = "D";
            }
        }
    }
    //定時器 監聽事件.幀:執行定時操作
    public void actionPerformed(ActionEvent e) {
        if (isStart && isfail == false) {//如果遊戲開始,且遊戲沒有失敗
            //右移
            for (int i = length - 1; i > 0; i--) {
                snakeX[i] = snakeX[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;
//                }
            }
            //碰撞檢測---小蛇頭和身體
            for (int i = 1; i < length; i++) {
                if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
                    isfail = true;
                }
            }
            //碰撞檢測--小蛇頭和牆壁
            if ((snakeX[0]<25 || snakeX[0]>850)||(snakeY[0]<75 || snakeY[0]>650 ) ){
                isfail = true;
            }
            repaint();//重新整理介面
        }
        timer.start();
    }
    public void keyReleased(KeyEvent e) {}
    public void keyTyped(KeyEvent e) {}
}

Date.java


package codeyuaiiao;

import javax.swing.*;
import java.net.URL;
/**
 * 存放外部資料
 * by:codeyuaiiao
 */
public class Date {
    //頭部
    public static URL headerURL = Date.class.getResource("/main/java/statics/header.png");
    public static ImageIcon header = new ImageIcon(headerURL);
    //貪吃蛇 頭部上下左右
    public static URL upURL = Date.class.getResource("/main/java/statics/up.png");
    public static URL downURL = Date.class.getResource("/main/java/statics/down.png");
    public static URL leftURL = Date.class.getResource("/main/java/statics/left.png");
    public static URL rightURL = Date.class.getResource("/main/java/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 = Date.class.getResource("/main/java/statics/body.png");
    public static ImageIcon body = new ImageIcon(bodyURL);
    //食物
    public static URL foodURL = Date.class.getResource("/main/java/statics/food.png");
    public static ImageIcon food = new ImageIcon(foodURL);
}

pom.xml

<build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>1.2.1</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>codeyuaiiao.StartGame</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

一共三個類
還有一個pom檔案 裡面的這些程式碼 用於maven打包 如果沒有pom中這些程式碼 匯出來的jar包會出現錯誤"找不到主類"
可以看我另一篇部落格
maven匯出jar包出現"找不到主類"錯誤

最後是程式執行的成果
在這裡插入圖片描述

看到最後的幫忙點個👍🙏 謝謝,這個對我真的很重要!
在這裡插入圖片描述