js實(shí)現(xiàn)貪吃蛇游戲 canvas繪制地圖
本文實(shí)例為大家分享了js實(shí)現(xiàn)貪吃蛇游戲的具體代碼,供大家參考,具體內(nèi)容如下

思路
400px * 400px的地圖,每20px*20px分成單元格繪制蛇身每次移動即更換尾 部 頭部的顏色

全部代碼
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>Document</title> <style> html, body { display: flex; align-items: center; justify-content: center; height: 100%; } </style></head><body> <canvas style='background-color: #362E3D;'>給我換chromium</canvas> <script> const map = document.getElementsByTagName(’canvas’)[0].getContext(’2d’); // 數(shù)組存蛇身位置 一行 1-20 二行21-40 總共20*20 var snake = [23, 22, 21]; // 數(shù)組頭部蛇頭 后部蛇尾 var direction = 1; // 1右 -1左 -20上 20下 var flag = 1; // 解決快速鍵盤bug var food = 50; // 食物位置 function draw(x, color) { map.fillStyle = color; //用1-400標(biāo)識沒找到通用像素?fù)Q算公式 最后一列分開計(jì)算 if (x % 20 == 0) { // 最后一列 map.fillRect(380 + 2, Math.floor(x / 21) * 20 + 2, 18, 18); // 使1-400的塊標(biāo)志對應(yīng)像素點(diǎn) } else { // 其余列 map.fillRect((x % 20 - 1) * 20 + 2, Math.floor(x / 20) * 20 + 2, 18, 18); } flag = 1; // draw()完后才能改變direction } let len = snake.length; for (let i = 0; i < len; i++) draw(snake[i], '#FDE5C5'); (function () { let head = snake[0] + direction; if (head % 20 == 1 && direction == 1 || head % 20 == 0 && direction == -1 || head < 1 || head > 400 || snake.includes(head)) return alert(’GG’); snake.unshift(head); draw(head, '#FDE5C5'); if (head == food) { while (snake.includes(food = Math.floor(Math.random() * 400 + 1))); // arr.includes 有的話返回true 否則false } else { //正常移動 沒吃到才改變尾部顏色 draw(snake.pop(), '#362E3D'); } draw(food, '#EB1A4B'); setTimeout(arguments.callee, 100); // arguments.callee 代表函數(shù)名 調(diào)用匿名函數(shù)自己 })(); document.onkeydown = function (event) { event = event || window.event; // ie中是windo.event if (flag) { // draw執(zhí)行后(蛇移動后)才可以改變direction switch (event.keyCode) { case 37: direction != 1 ? direction = -1 : 0; break; case 38: direction != 20 ? direction = -20 : 0; break; case 39: direction != -1 ? direction = 1 : 0; break; case 40: direction != -20 ? direction = 20 : 0; break; } } flag = 0; // 等待下一次draw執(zhí)行 } </script></body></html>
解決 連續(xù)快速鍵盤bug方向鍵上下左右實(shí)際改變 direction 的值,如果再蛇下一次移動之前連續(xù)改變,有可能會產(chǎn)生反向吃自己的bug所以加入flag 詳情看源碼
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. PHP驗(yàn)證碼工具-Securimage2. Vue 實(shí)現(xiàn)對quill-editor組件中的工具欄添加title3. JavaScript實(shí)現(xiàn)簡單的彈窗效果4. 我所理解的JavaScript中的this指向5. javascript實(shí)現(xiàn)貪吃蛇小練習(xí)6. PHP利用curl發(fā)送HTTP請求的實(shí)例代碼7. Java commons-httpclient如果實(shí)現(xiàn)get及post請求8. PHP單件模式和命令鏈模式的基礎(chǔ)知識9. 一文帶你徹底理解Java序列化和反序列化10. js實(shí)現(xiàn)碰撞檢測

網(wǎng)公網(wǎng)安備