<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國際加速解決方案。 廣告
                # JavaScript 貪食蛇教程 > 原文: [http://zetcode.com/javascript/snake/](http://zetcode.com/javascript/snake/) JavaScript 貪食蛇教程展示了如何在 JavaScript 中創建貪食蛇游戲。 這些圖像和源可從作者的 Github [JavaScript-Snake-Game](https://github.com/janbodnar/JavaScript-Snake-Game) 存儲庫中獲得。 ## 貪食蛇游戲 貪食蛇是一款較老的經典視頻游戲,最早于 70 年代后期創建。 后來它被帶到 PC 上。 在這個游戲中,玩家控制蛇。 目的是盡可能多地吃蘋果。 蛇每次吃一個蘋果,它的身體就會長大。 蛇必須避開墻壁和自己的身體。 該游戲有時稱為 Nibbles。 ## HTML5 畫布 HTML5 `canvas`元素提供了一個與分辨率有關的位圖區域,該區域可用于動態繪制圖形,游戲圖形,藝術作品或其他可視圖像。 簡單來說,`canvas`是 HTML5 中的新元素,它使您可以使用 JavaScript 繪制圖形。 `Canvas`無需將插件插入 Flash,Silverlight 或 Java,即可將動畫帶入網頁。 ## JavaScript 貪食蛇代碼示例 蛇的每個關節的大小為 10 像素。 蛇由光標鍵控制。 最初,蛇具有三個關節。 如果游戲結束,則畫布中間會顯示`"Game Over"`消息。 `index.html` ```js <!DOCTYPE html> <html> <head> <title>JavaScript Snake game</title> <style> canvas {background: black} </style> <script src="snake.js"></script> </head> <body onload="init();"> <canvas id="myCanvas" width="300" height="300"> </canvas> </body> </html> ``` 這是 HTML 來源。 我們將 JavaScript 源代碼放置在`snake.js`文件中。 ```js <canvas id="myCanvas" width="300" height="300"> </canvas> ``` 我們創建一個畫布對象。 這是我們游戲的渲染區域。 `snake.js` ```js // JavaScript Snake example // Author Jan Bodnar // http://zetcode.com/javascript/snake/ var canvas; var ctx; var head; var apple; var ball; var dots; var apple_x; var apple_y; var leftDirection = false; var rightDirection = true; var upDirection = false; var downDirection = false; var inGame = true; const DOT_SIZE = 10; const ALL_DOTS = 900; const MAX_RAND = 29; const DELAY = 140; const C_HEIGHT = 300; const C_WIDTH = 300; const LEFT_KEY = 37; const RIGHT_KEY = 39; const UP_KEY = 38; const DOWN_KEY = 40; var x = new Array(ALL_DOTS); var y = new Array(ALL_DOTS); function init() { canvas = document.getElementById('myCanvas'); ctx = canvas.getContext('2d'); loadImages(); createSnake(); locateApple(); setTimeout("gameCycle()", DELAY); } function loadImages() { head = new Image(); head.src = 'head.png'; ball = new Image(); ball.src = 'dot.png'; apple = new Image(); apple.src = 'apple.png'; } function createSnake() { dots = 3; for (var z = 0; z < dots; z++) { x[z] = 50 - z * 10; y[z] = 50; } } function checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); } } function doDrawing() { ctx.clearRect(0, 0, C_WIDTH, C_HEIGHT); if (inGame) { ctx.drawImage(apple, apple_x, apple_y); for (var z = 0; z < dots; z++) { if (z == 0) { ctx.drawImage(head, x[z], y[z]); } else { ctx.drawImage(ball, x[z], y[z]); } } } else { gameOver(); } } function gameOver() { ctx.fillStyle = 'white'; ctx.textBaseline = 'middle'; ctx.textAlign = 'center'; ctx.font = 'normal bold 18px serif'; ctx.fillText('Game over', C_WIDTH/2, C_HEIGHT/2); } function checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); } } function move() { for (var 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; } } function checkCollision() { for (var z = dots; z > 0; z--) { if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) { inGame = false; } } if (y[0] >= C_HEIGHT) { inGame = false; } if (y[0] < 0) { inGame = false; } if (x[0] >= C_WIDTH) { inGame = false; } if (x[0] < 0) { inGame = false; } } function locateApple() { var r = Math.floor(Math.random() * MAX_RAND); apple_x = r * DOT_SIZE; r = Math.floor(Math.random() * MAX_RAND); apple_y = r * DOT_SIZE; } function gameCycle() { if (inGame) { checkApple(); checkCollision(); move(); doDrawing(); setTimeout("gameCycle()", DELAY); } } onkeydown = function(e) { var key = e.keyCode; if ((key == LEFT_KEY) && (!rightDirection)) { leftDirection = true; upDirection = false; downDirection = false; } if ((key == RIGHT_KEY) && (!leftDirection)) { rightDirection = true; upDirection = false; downDirection = false; } if ((key == UP_KEY) && (!downDirection)) { upDirection = true; rightDirection = false; leftDirection = false; } if ((key == DOWN_KEY) && (!upDirection)) { downDirection = true; rightDirection = false; leftDirection = false; } }; ``` 這是 JavaScript 貪食蛇的源代碼。 ```js const DOT_SIZE = 10; const ALL_DOTS = 900; const MAX_RAND = 29; const DELAY = 140; const C_HEIGHT = 300; const C_WIDTH = 300; ``` `DOT_SIZE`是蘋果的大小和蛇的點。 `ALL_DOTS`常數定義畫布上可能的最大點數(`900 = 300 * 300 / 10 * 10`)。 `MAX_RAND`常數用于計算蘋果的隨機位置。 `DELAY`常數確定游戲的速度。 `C_HEIGHT`和`C_WIDTH`常數存儲畫布的大小。 ```js const LEFT_KEY = 37; const RIGHT_KEY = 39; const UP_KEY = 38; const DOWN_KEY = 40; ``` 這些常量存儲箭頭鍵的值。 它們用于提高可讀性。 ```js var x = new Array(ALL_DOTS); var y = new Array(ALL_DOTS); ``` 這兩個數組存儲蛇的所有關節的`x`和`y`坐標。 ```js function init() { canvas = document.getElementById('myCanvas'); ctx = canvas.getContext('2d'); loadImages(); createSnake(); locateApple(); setTimeout("gameCycle()", DELAY); } ``` `init()`函數獲取對畫布對象及其上下文的引用。 調用`loadImages()`,`createSnake()`和`locateApple()`函數來執行特定任務。 `setTimeout()`開始動畫。 ```js function loadImages() { head = new Image(); head.src = 'head.png'; ball = new Image(); ball.src = 'dot.png'; apple = new Image(); apple.src = 'apple.png'; } ``` 在`loadImages()`函數中,我們為游戲加載了三張圖像。 ```js function createSnake() { dots = 3; for (var z = 0; z < dots; z++) { x[z] = 50 - z * 10; y[z] = 50; } } ``` 在`createSnake()`函數中,我們創建蛇對象。 首先,它具有三個關節。 ```js function checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); } } ``` 如果頭部與蘋果相撞,我們會增加蛇的關節數。 我們稱`locateApple()`方法為隨機放置一個新的 Apple 對象。 ```js function move() { ... ``` 在`move()`方法中,我們有游戲的關鍵算法。 為了理解它,請看一下蛇是如何運動的。 我們控制蛇的頭。 我們可以使用光標鍵更改其方向。 其余關節在鏈上向上移動一個位置。 第二關節移動到第一個關節的位置,第三關節移動到第二個關節的位置,依此類推。 ```js for (var z = dots; z > 0; z--) { x[z] = x[(z - 1)]; y[z] = y[(z - 1)]; } ``` `for`循環將蛇的關節向上移動。 ```js if (leftDirection) { x[0] -= DOT_SIZE; } ``` 這條線將頭向左移動。 ```js function checkCollision() { ... ``` 在`checkCollision()`方法中,我們確定蛇是否擊中了自己或邊界之一。 ```js for (var z = dots; z > 0; z--) { if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) { inGame = false; } } ``` 如果蛇用頭撞到其關節之一,則游戲結束。 ```js if (y[0] >= C_HEIGHT) { inGame = false; } ``` 如果蛇撞到畫布底部,則游戲結束。 ```js function locateApple() { var r = Math.floor(Math.random() * MAX_RAND); apple_x = r * DOT_SIZE; r = Math.floor(Math.random() * MAX_RAND); apple_y = r * DOT_SIZE; } ``` `locateApple()`隨機選擇蘋果對象的`x`和`y`坐標。 `apple_x`和`apple_y`是蘋果圖像左上點的坐標。 ```js function gameCycle() { if (inGame) { checkApple(); checkCollision(); move(); doDrawing(); setTimeout("gameCycle()", DELAY); } } ``` `gameCycle()`函數形成游戲周期。 如果游戲尚未完成,我們將執行碰撞檢測,移動和繪畫。 `setTimeout()`函數遞歸調用`gameCycle()`函數。 ```js if ((key == LEFT_KEY) && (!rightDirection)) { leftDirection = true; upDirection = false; downDirection = false; } ``` 如果單擊左光標鍵,則將`leftDirection`變量設置為`true`。 `move()`函數中使用此變量來更改蛇對象的坐標。 還要注意,當蛇向右行駛時,我們不能立即向左轉。 ![Snake game](https://img.kancloud.cn/fd/c2/fdc2f1f27b0fa9752475c4f960e13f36_549x426.jpg) 圖:貪食蛇 gmae 這是 JavaScript 貪食蛇游戲。
                  <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>

                              哎呀哎呀视频在线观看