黄色网址大全免费-黄色网址你懂得-黄色网址你懂的-黄色网址有那些-免费超爽视频-免费大片黄国产在线观看

專注Java教育14年 全國咨詢/投訴熱線:400-8080-105
動力節點LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁 學習攻略 Java學習 Java貪吃蛇源代碼講解

Java貪吃蛇源代碼講解

更新時間:2022-03-31 11:11:54 來源:動力節點 瀏覽1692次

貪吃蛇是一款較老的經典電子游戲。它最初是在 70 年代后期創建的。后來它被帶到了PC上。在這個游戲中,玩家控制一條蛇。目標是盡可能多地吃蘋果。蛇每吃一個蘋果,它的身體就會變大。蛇必須避開墻壁和自己的身體。這個游戲有時被稱為Nibbles。

Java Sname 游戲的開發

蛇的每個關節的大小是 10 像素。蛇是用光標鍵控制的。最初,這條蛇有三個關節。如果游戲結束,棋盤中央會顯示“游戲結束”消息。

package com.zetcode;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener {
    private final int B_WIDTH = 300;
    private final int B_HEIGHT = 300;
    private final int DOT_SIZE = 10;
    private final int ALL_DOTS = 900;
    private final int RAND_POS = 29;
    private final int DELAY = 140;
    private final int x[] = new int[ALL_DOTS];
    private final int y[] = new int[ALL_DOTS];
    private int dots;
    private int apple_x;
    private int apple_y;
    private boolean leftDirection = false;
    private boolean rightDirection = true;
    private boolean upDirection = false;
    private boolean downDirection = false;
    private boolean inGame = true;
    private Timer timer;
    private Image ball;
    private Image apple;
    private Image head;
    public Board() {        
        initBoard();
    }    
    private void initBoard() {
        addKeyListener(new TAdapter());
        setBackground(Color.black);
        setFocusable(true);
        setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
        loadImages();
        initGame();
    }
    private void loadImages() {
        ImageIcon iid = new ImageIcon("src/resources/dot.png");
        ball = iid.getImage();
        ImageIcon iia = new ImageIcon("src/resources/apple.png");
        apple = iia.getImage();
        ImageIcon iih = new ImageIcon("src/resources/head.png");
        head = iih.getImage();
    }
    private void initGame() {
        dots = 3;
        for (int z = 0; z < dots; z++) {
            x[z] = 50 - z * 10;
            y[z] = 50;
        }       
        locateApple();
        timer = new Timer(DELAY, this);
        timer.start();
    }
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        doDrawing(g);
    }    
    private void doDrawing(Graphics g) {        
        if (inGame) {
            g.drawImage(apple, apple_x, apple_y, this);
            for (int z = 0; z < dots; z++) {
                if (z == 0) {
                    g.drawImage(head, x[z], y[z], this);
                } else {
                    g.drawImage(ball, x[z], y[z], this);
                }
            }
            Toolkit.getDefaultToolkit().sync();
        } else {
            gameOver(g);
        }        
    }
    private void gameOver(Graphics g) {        
        String msg = "Game Over";
        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = getFontMetrics(small);
        g.setColor(Color.white);
        g.setFont(small);
        g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
    }
    private void checkApple() {
        if ((x[0] == apple_x) && (y[0] == apple_y)) {
            dots++;
            locateApple();
        }
    }
    private void move() {
        for (int z = dots; z > 0; z--) {
            x[z] = x[(z - 1)];
            y[z] = y[(z - 1)];
        }
        if (leftDirection) {
            x[0] -= DOT_SIZE;
        }
        if (rightDirection) {
            x[0] += DOT_SIZE;
        }
        if (upDirection) {
            y[0] -= DOT_SIZE;
        }
        if (downDirection) {
            y[0] += DOT_SIZE;
        }
    }
    private void checkCollision() {
        for (int z = dots; z > 0; z--) {
            if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
                inGame = false;
            }
        }
        if (y[0] >= B_HEIGHT) {
            inGame = false;
        }
        if (y[0] < 0) {
            inGame = false;
        }
        if (x[0] >= B_WIDTH) {
            inGame = false;
        }
        if (x[0] < 0) {
            inGame = false;
        }        
        if (!inGame) {
            timer.stop();
        }
    }
    private void locateApple() {
        int r = (int) (Math.random() * RAND_POS);
        apple_x = ((r * DOT_SIZE));
        r = (int) (Math.random() * RAND_POS);
        apple_y = ((r * DOT_SIZE));
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        if (inGame) {
            checkApple();
            checkCollision();
            move();
        }
        repaint();
    }
    private class TAdapter extends KeyAdapter {
        @Override
        public void keyPressed(KeyEvent e) {
            int key = e.getKeyCode();
            if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
                leftDirection = true;
                upDirection = false;
                downDirection = false;
            }
            if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
                rightDirection = true;
                upDirection = false;
                downDirection = false;
            }
            if ((key == KeyEvent.VK_UP) && (!downDirection)) {
                upDirection = true;
                rightDirection = false;
                leftDirection = false;
            }
            if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
                downDirection = true;
                rightDirection = false;
                leftDirection = false;
            }
        }
    }
}

首先,我們將定義游戲中使用的常量。

private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;

B_WIDTH和B_HEIGHT常量決定了板子的大小 。DOT_SIZE是蘋果的大小和蛇的圓點。該ALL_DOTS常數定義了板上可能的最大點數 (900 = (300*300)/(10*10))。該RAND_POS 常數用于計算蘋果的隨機位置。DELAY常數決定了游戲的速度 。

private final int x[] = new int[ALL_DOTS];
private final int y[] = new int[ALL_DOTS];

這兩個數組存儲蛇所有關節的 x 和 y 坐標。

private void loadImages() {
    ImageIcon iid = new ImageIcon("src/resources/dot.png");
    ball = iid.getImage();
    ImageIcon iia = new ImageIcon("src/resources/apple.png");
    apple = iia.getImage();
    ImageIcon iih = new ImageIcon("src/resources/head.png");
    head = iih.getImage();
}

在該loadImages()方法中,我們獲取游戲的圖像。該類ImageIcon用于顯示 PNG 圖像。

private void initGame() {
    dots = 3;
    for (int z = 0; z < dots; z++) {
        x[z] = 50 - z * 10;
        y[z] = 50;
    }
    locateApple();
    timer = new Timer(DELAY, this);
    timer.start();
}

在initGame()我們創建蛇的方法中,在板上隨機定位一個蘋果,然后啟動計時器。

private void checkApple() {
    if ((x[0] == apple_x) && (y[0] == apple_y)) {
        dots++;
        locateApple();
    }
}

如果蘋果撞到頭部,我們增加蛇的關節數。我們調用locateApple()隨機定位新蘋果對象的方法。

在move()方法中我們有游戲的關鍵算法。要理解它,看看蛇是如何移動的。我們控制了蛇的頭。我們可以用光標鍵改變它的方向。其余關節沿鏈條向上移動一個位置。第二個關節移動到第一個關節的位置,第三個關節移動到第二個關節的位置,依此類推。

for (int z = 點; z > 0; z--) { 
    x[z] = x[(z - 1)]; 
    y[z] = y[(z - 1)]; 
}

此代碼將關節沿鏈向上移動。

if (leftDirection) { 
    x[0] -= DOT_SIZE; 
}

這條線將頭部向左移動。

在該checkCollision()方法中,我們確定蛇是撞到自己還是撞到了一堵墻。

for (int z = dots; z > 0; z--) {
    if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) {
        inGame = false;
    }
}

如果蛇用頭撞到它的一個關節,游戲就結束了。

if (y[0] >= B_HEIGHT) { 
    inGame = false; 
}

如果蛇擊中棋盤底部,則游戲結束。

package com.zetcode;
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Snake extends JFrame {
    public Snake() {        
        initUI();
    }    
    private void initUI() {        
        add(new Board());        
        setResizable(false);
        pack();        
        setTitle("Snake");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }    
    public static void main(String[] args) {        
        EventQueue.invokeLater(() -> {
            JFrame ex = new Snake();
            ex.setVisible(true);
        });
    }
}

這是主要課程。

setResizable(false);
pack();

該方法會影響某些平臺上容器setResizable()的插圖。JFrame因此,在方法之前調用它很重要 pack()。否則,蛇的頭部與右邊界和下邊界的碰撞可能無法正常工作。

這是 Java 中的 Snake 游戲。

提交申請后,顧問老師會電話與您溝通安排學習

免費課程推薦 >>
技術文檔推薦 >>
主站蜘蛛池模板: 性视频网| 欧美高清在线精品一区 | 天天操操操操 | 中文字幕一区日韩在线视频 | 美女被cao免费看在线看网站 | 色老头在线观看精品 | 国产成人精选免费视频 | 污视频网站免费看 | 欧美在线你懂的 | 欧美一区二区三区视频在线观看 | 免费中文字幕在线观看 | 欧美深夜福利视频 | 五月婷婷视频在线 | 日韩精品视频免费网址 | 国产成人a∨麻豆精品 | 免费黄色影院 | 在线免费观看黄 | 国产在线观看成人免费视频 | 成人看片软件 | 久久er精品热线免费 | 北条麻妃在线一区二区 | 成人女人a毛片在线看 | caopren免费视频国产 | 亚洲视频一区网站 | 最近中文字幕在线6 | 在线你懂 | 天天躁天天碰天天看 | 一个人看的www免费在线视频 | 97青草香蕉依人在线播放 | 国产成人精品高清不卡在线 | 午夜精品福利影院 | 污视频网站大全 | 成人在色线视频在线观看免费大全 | 午夜影院免费看 | 人人夜 | 手机看片1024国产 | 18成网站www在线观看 | 亚洲成人黄色网址 | 久久香蕉国产线看观看亚洲片 | 国产一区二区中文字幕 | 国产黄色免费看 |