<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>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # Kotlin 貪食蛇 > 原文: [http://zetcode.com/kotlin/snake/](http://zetcode.com/kotlin/snake/) Kotlin 貪食蛇游戲教程展示了如何使用 Swing 在 Kotlin 中創建蛇游戲。 源代碼和圖像可從作者的 Github [Kotlin-Snake-Game](https://github.com/janbodnar/Kotlin-Snake-Game) 存儲庫中獲得。 ## 貪食蛇 貪食蛇是較舊的經典視頻游戲。 它最初是在 70 年代后期創建的。 后來它被帶到 PC 上。 在這個游戲中,玩家控制蛇。 游戲的目的是盡可能多地吃蘋果。 當蛇吃了一個蘋果時,它的身體就長了。 蛇必須避開墻壁和自己的身體。 該游戲有時稱為 Nibbles 。 ## Swing Swing 是 Java 編程語言的主要 GUI 工具包。 它是 JFC(Java 基礎類)的一部分,JFC 是用于為 Java 程序提供圖形用戶界面的 API。 ## Kotlin 貪食蛇游戲 蛇的每個關節的大小為 10 像素。 蛇由光標鍵控制。 最初,蛇具有三個關節。 如果游戲結束,則在面板中間顯示`"Game Over"`消息。 `Board.kt` ```kt package com.zetcode import java.awt.* 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 class Board : JPanel(), ActionListener { private val boardWidth = 300 private val boardHeight = 300 private val dotSize = 10 private val allDots = 900 private val randPos = 29 private val delay = 140 private val x = IntArray(allDots) private val y = IntArray(allDots) private var nOfDots: Int = 0 private var appleX: Int = 0 private var appleY: Int = 0 private var leftDirection = false private var rightDirection = true private var upDirection = false private var downDirection = false private var inGame = true private var timer: Timer? = null private var ball: Image? = null private var apple: Image? = null private var head: Image? = null init { addKeyListener(TAdapter()) background = Color.black isFocusable = true preferredSize = Dimension(boardWidth, boardHeight) loadImages() initGame() } private fun loadImages() { val iid = ImageIcon("src/main/resources/dot.png") ball = iid.image val iia = ImageIcon("src/main/resources/apple.png") apple = iia.image val iih = ImageIcon("src/main/resources/head.png") head = iih.image } private fun initGame() { nOfDots = 3 for (z in 0 until nOfDots) { x[z] = 50 - z * 10 y[z] = 50 } locateApple() timer = Timer(delay, this) timer!!.start() } public override fun paintComponent(g: Graphics) { super.paintComponent(g) doDrawing(g) } private fun doDrawing(g: Graphics) { if (inGame) { g.drawImage(apple, appleX, appleY, this) for (z in 0 until nOfDots) { 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 fun gameOver(g: Graphics) { val msg = "Game Over" val small = Font("Helvetica", Font.BOLD, 14) val fontMetrics = getFontMetrics(small) val rh = RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) rh[RenderingHints.KEY_RENDERING] = RenderingHints.VALUE_RENDER_QUALITY (g as Graphics2D).setRenderingHints(rh) g.color = Color.white g.font = small g.drawString(msg, (boardWidth - fontMetrics.stringWidth(msg)) / 2, boardHeight / 2) } private fun checkApple() { if (x[0] == appleX && y[0] == appleY) { nOfDots++ locateApple() } } private fun move() { for (z in nOfDots downTo 1) { x[z] = x[z - 1] y[z] = y[z - 1] } if (leftDirection) { x[0] -= dotSize } if (rightDirection) { x[0] += dotSize } if (upDirection) { y[0] -= dotSize } if (downDirection) { y[0] += dotSize } } private fun checkCollision() { for (z in nOfDots downTo 1) { if (z > 4 && x[0] == x[z] && y[0] == y[z]) { inGame = false } } if (y[0] >= boardHeight) { inGame = false } if (y[0] < 0) { inGame = false } if (x[0] >= boardWidth) { inGame = false } if (x[0] < 0) { inGame = false } if (!inGame) { timer!!.stop() } } private fun locateApple() { var r = (Math.random() * randPos).toInt() appleX = r * dotSize r = (Math.random() * randPos).toInt() appleY = r * dotSize } override fun actionPerformed(e: ActionEvent) { if (inGame) { checkApple() checkCollision() move() } repaint() } private inner class TAdapter : KeyAdapter() { override fun keyPressed(e: KeyEvent?) { val key = e!!.keyCode 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 } } } } ``` 首先,我們將定義游戲中使用的屬性。 ```kt private val boardWidth = 300 private val boardHeight = 300 private val dotSize = 10 private val allDots = 900 private val randPos = 29 private val delay = 140 ``` `boardWidth`和`boardHeight`屬性確定電路板的大小。 `dotSize`是蘋果的大小和蛇的點。 `allDots`屬性定義了板上可能的最大點數(`900 = (300 * 300) / (10 * 10)`)。 `randPos`屬性用于計算蘋果的隨機位置。 `delay`屬性確定游戲的速度。 ```kt private val x = IntArray(allDots) private val y = IntArray(allDots) ``` 這兩個數組存儲蛇的所有關節的`x`和`y`坐標。 ```kt private fun loadImages() { val iid = ImageIcon("src/main/resources/dot.png") ball = iid.image val iia = ImageIcon("src/main/resources/apple.png") apple = iia.image val iih = ImageIcon("src/main/resources/head.png") head = iih.image } ``` 在`loadImages()`方法中,我們獲得了游戲的圖像。 `ImageIcon`類用于顯示 PNG 圖像。 ```kt private fun initGame() { nOfDots = 3 for (z in 0 until nOfDots) { x[z] = 50 - z * 10 y[z] = 50 } locateApple() timer = Timer(delay, this) timer!!.start() } ``` 在`initGame()`方法中,我們創建蛇,在板上隨機放置一個蘋果,然后啟動計時器。 ```kt private fun doDrawing(g: Graphics) { if (inGame) { g.drawImage(apple, appleX, appleY, this) for (z in 0 until nOfDots) { 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) } } ``` 在`doDrawing()`方法中,我們繪制了蘋果和蛇對象。 如果游戲結束,我們將根據消息繪制游戲。 ```kt private fun gameOver(g: Graphics) { val msg = "Game Over" val small = Font("Helvetica", Font.BOLD, 14) val fontMetrics = getFontMetrics(small) val rh = RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) rh[RenderingHints.KEY_RENDERING] = RenderingHints.VALUE_RENDER_QUALITY (g as Graphics2D).setRenderingHints(rh) g.color = Color.white g.font = small g.drawString(msg, (boardWidth - fontMetrics.stringWidth(msg)) / 2, boardHeight / 2) } ``` `gameOver()`方法在窗口中間繪制`"Game Over"`消息。 我們使用渲染提示來平滑地繪制消息。 我們使用字體指標來獲取消息的大小。 ```kt private fun checkApple() { if (x[0] == appleX && y[0] == appleY) { nOfDots++ locateApple() } } ``` 如果蘋果與頭部碰撞,我們會增加蛇的關節數。 我們稱`locateApple()`方法為隨機放置一個新的`Apple`對象。 在`move()`方法中,我們有游戲的關鍵算法。 要了解它,請看一下蛇是如何運動的。 我們控制蛇的頭。 我們可以使用光標鍵更改其方向。 其余關節在鏈上向上移動一個位置。 第二關節移動到第一個關節的位置,第三關節移動到第二個關節的位置,依此類推。 ```kt for (z in nOfDots downTo 1) { x[z] = x[z - 1] y[z] = y[z - 1] } ``` 該代碼將關節向上移動。 ```kt if (leftDirection) { x[0] -= dotSize } ``` 這條線將頭向左移動。 在`checkCollision()`方法中,我們確定蛇是否擊中了自己或撞墻之一。 ```kt for (z in nOfDots downTo 1) { if (z > 4 && x[0] == x[z] && y[0] == y[z]) { inGame = false } } ``` 如果蛇用頭撞到其關節之一,則游戲結束。 ```kt if (y[0] >= boardHeight) { inGame = false } ``` 如果蛇擊中了棋盤的底部,則游戲結束。 `Snake.kt` ```kt package com.zetcode import java.awt.EventQueue import javax.swing.JFrame class Snake : JFrame() { init { initUI() } private fun initUI() { add(Board()) title = "Snake" isResizable = false pack() setLocationRelativeTo(null) defaultCloseOperation = JFrame.EXIT_ON_CLOSE } companion object { @JvmStatic fun main(args: Array<String>) { EventQueue.invokeLater { val ex = Snake() ex.isVisible = true } } } } ``` 這是主要的類。 ```kt isResizable = false pack() ``` `isResizable`屬性會影響某些平臺上`JFrame`容器的插入。 因此,在`pack()`方法之前調用它很重要。 否則,蛇的頭部與右邊界和底邊界的碰撞可能無法正常進行。 ![Snake](https://img.kancloud.cn/62/51/62512e0b261ba6ecf79590b9082ec925_302x325.jpg) 圖:貪食蛇 這是 Kotlin 和 Swing 中的貪食蛇游戲。 您可能也對相關教程感興趣: [Kotlin Swing 教程](/kotlin/swing/), [Kotlin 讀取文件教程](/kotlin/readfile/)和 [Kotlin 寫入文件教程](/kotlin/writefile/)。
                  <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>

                              哎呀哎呀视频在线观看