js實(shí)現(xiàn)貪吃蛇游戲 canvas繪制地圖
本文實(shí)例為大家分享了js實(shí)現(xiàn)貪吃蛇游戲的具體代碼,供大家參考,具體內(nèi)容如下
思路
400px * 400px的地圖,每20px*20px分成單元格繪制蛇身每次移動(dòng)即更換尾 部 頭部的顏色
全部代碼
<!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; // 解決快速鍵盤(pán)bug var food = 50; // 食物位置 function draw(x, color) { map.fillStyle = color; //用1-400標(biāo)識(shí)沒(méi)找到通用像素?fù)Q算公式 最后一列分開(kāi)計(jì)算 if (x % 20 == 0) { // 最后一列 map.fillRect(380 + 2, Math.floor(x / 21) * 20 + 2, 18, 18); // 使1-400的塊標(biāo)志對(duì)應(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 { //正常移動(dòng) 沒(méi)吃到才改變尾部顏色 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í)行后(蛇移動(dòng)后)才可以改變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ù)快速鍵盤(pán)bug方向鍵上下左右實(shí)際改變 direction 的值,如果再蛇下一次移動(dòng)之前連續(xù)改變,有可能會(huì)產(chǎn)生反向吃自己的bug所以加入flag 詳情看源碼
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 以PHP代碼為實(shí)例詳解RabbitMQ消息隊(duì)列中間件的6種模式2. Python如何進(jìn)行時(shí)間處理3. python web框架的總結(jié)4. 詳解Python模塊化編程與裝飾器5. Python通過(guò)format函數(shù)格式化顯示值6. html小技巧之td,div標(biāo)簽里內(nèi)容不換行7. python裝飾器三種裝飾模式的簡(jiǎn)單分析8. Python 如何將integer轉(zhuǎn)化為羅馬數(shù)(3999以內(nèi))9. Python實(shí)現(xiàn)迪杰斯特拉算法過(guò)程解析10. python使用ctypes庫(kù)調(diào)用DLL動(dòng)態(tài)鏈接庫(kù)
