<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                合規國際互聯網加速 OSASE為企業客戶提供高速穩定SD-WAN國際加速解決方案。 廣告
                # Java 貪食蛇 > 原文: [https://zetcode.com/tutorials/javagamestutorial/snake/](https://zetcode.com/tutorials/javagamestutorial/snake/) 在 Java 2D 游戲教程的這一部分中,我們創建一個 Java 貪食蛇游戲克隆。 源代碼和圖像可以在作者的 Github [Java-Snake-Game](https://github.com/janbodnar/Java-Snake-Game) 存儲庫中找到。 ## 貪食蛇 貪食蛇是較舊的經典視頻游戲。 它最初是在 70 年代后期創建的。 后來它被帶到 PC 上。 在這個游戲中,玩家控制蛇。 目的是盡可能多地吃蘋果。 蛇每吃一個蘋果,它的身體就會長大。 蛇必須避開墻壁和自己的身體。 該游戲有時稱為 Nibbles 。 ## Java 貪食蛇游戲的開發 蛇的每個關節的大小為 10 像素。 蛇由光標鍵控制。 最初,蛇具有三個關節。 如果游戲結束,則在面板中間顯示`"Game Over"`消息。 `Board.java` ```java 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; } } } } ``` 首先,我們將定義游戲中使用的常量。 ```java 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`常數確定游戲的速度。 ```java private final int x[] = new int[ALL_DOTS]; private final int y[] = new int[ALL_DOTS]; ``` 這兩個數組存儲蛇的所有關節的 x 和 y 坐標。 ```java 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 圖像。 ```java 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()`方法中,我們創建蛇,在板上隨機放置一個蘋果,然后啟動計時器。 ```java private void checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); } } ``` 如果蘋果與頭部碰撞,我們會增加蛇的關節數。 我們稱`locateApple()`方法為隨機放置一個新的`Apple`對象。 在`move()`方法中,我們有游戲的關鍵算法。 要了解它,請看一下蛇是如何運動的。 我們控制蛇的頭。 我們可以使用光標鍵更改其方向。 其余關節在鏈上向上移動一個位置。 第二關節移動到第一個關節的位置,第三關節移動到第二個關節的位置,依此類推。 ```java for (int z = dots; z > 0; z--) { x[z] = x[(z - 1)]; y[z] = y[(z - 1)]; } ``` 該代碼將關節向上移動。 ```java if (leftDirection) { x[0] -= DOT_SIZE; } ``` 這條線將頭向左移動。 在`checkCollision()`方法中,我們確定蛇是否擊中了自己或撞墻之一。 ```java for (int z = dots; z > 0; z--) { if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) { inGame = false; } } ``` 如果蛇用頭撞到其關節之一,則游戲結束。 ```java if (y[0] >= B_HEIGHT) { inGame = false; } ``` 如果蛇擊中了棋盤的底部,則游戲結束。 `Snake.java` ```java 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); }); } } ``` 這是主要的類。 ```java setResizable(false); pack(); ``` `setResizable()`方法會影響某些平臺上`JFrame`容器的插入。 因此,在`pack()`方法之前調用它很重要。 否則,蛇的頭部與右邊界和底邊界的碰撞可能無法正常進行。 ![Snake](https://img.kancloud.cn/8c/4c/8c4c0f3e7e22c74ecb2e8f84fdd8a780_302x325.jpg) 圖:貪食蛇 這是 Java 中的貪食蛇游戲。
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看