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; // 解決快速鍵盤bug var food = 50; // 食物位置 function draw(x, color) { map.fillStyle = color; //用1-400標(biāo)識(shí)沒找到通用像素?fù)Q算公式 最后一列分開計(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) 沒吃到才改變尾部顏色 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ù)快速鍵盤bug方向鍵上下左右實(shí)際改變 direction 的值,如果再蛇下一次移動(dòng)之前連續(xù)改變,有可能會(huì)產(chǎn)生反向吃自己的bug所以加入flag 詳情看源碼
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. phpstudy apache開啟ssi使用詳解2. vue3+ts+elementPLus實(shí)現(xiàn)v-preview指令3. Xml簡介_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理4. JSP之表單提交get和post的區(qū)別詳解及實(shí)例5. 詳解瀏覽器的緩存機(jī)制6. xml中的空格之完全解說7. jsp實(shí)現(xiàn)登錄驗(yàn)證的過濾器8. jsp文件下載功能實(shí)現(xiàn)代碼9. 使用Hangfire+.NET 6實(shí)現(xiàn)定時(shí)任務(wù)管理(推薦)10. 如何在jsp界面中插入圖片
