最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

js實(shí)現(xiàn)貪吃蛇游戲 canvas繪制地圖

 更新時(shí)間:2020年09月09日 08:38:57   作者:S_aitama  
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)貪吃蛇游戲,canvas繪制地圖,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(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 width="400" height="400" 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í)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

肇州县| 苍梧县| 天峨县| 汉阴县| 阿克苏市| 浦江县| 宿松县| 大安市| 宜丰县| 平定县| 怀仁县| 陇南市| 额敏县| 绥宁县| 宁波市| 天津市| 紫云| 岫岩| 伊春市| 普安县| 镇赉县| 盐亭县| 湖州市| 三原县| 保康县| 且末县| 巩义市| 道孚县| 个旧市| 罗田县| 盈江县| 靖安县| 修文县| 基隆市| 抚松县| 通许县| 汶川县| 康保县| 溧水县| 天峨县| 特克斯县|