40行贪吃蛇 原生js

Posted migeater

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了40行贪吃蛇 原生js相关的知识,希望对你有一定的参考价值。

  • <!doctype html>
  • <html>
  • <body>
  • <canvas id="1" width="400" height="400" ></canvas>
  • <script>
  • ????let ctx = document.getElementById("1").getContext("2d");
  • ????let SpecialLen = 20, snakeDir = 2, snakeDirNow , food = [2,0], snakeBody = [ [0, 0], [1, 0] ]; //2 for right direction
  • ????let Map = {}; //map对象存放 location:val ,‘1,2‘:1 ,1表示蛇身,2表示食物
  • ????for(let snakeNode of snakeBody) Map[snakeNode] = 1;
  • ????let dirMat = [[-1, 0], [0, -1], [1, 0], [0, 1]]; //0 1 2 3 <- ->
  • ????let pairEqual = ((pair1, pair2) => pair1[0] == pair2[0] && pair1[1] == pair2[1]); //碰撞检测
  • ????document.onkeydown = function (env) {
  • ????????arrowKeyCode = env.keyCode - 37; //37"leftArrow"
  • ????????if (0 <= arrowKeyCode == arrowKeyCode < 4)
  • ????????????if (snakeDirNow !== (arrowKeyCode + 2) % 4) //周期过后才改变方向&&不能走相反方向
  • ????????????????snakeDir = arrowKeyCode;
  • ????};
  • ????!function () {
  • ????????let snakeHeadNext = snakeBody[snakeBody.length-1].map((x, i) => x + dirMat[snakeDirNow=snakeDir][i]); //得到蛇头的下一步位置
  • ????????if (!pairEqual(snakeHeadNext, food)) { //没吃到食物
  • ????????????Map[snakeBody.shift()] = 0; //先去除蛇尾
  • ????????????if (snakeBody.some(x=>pairEqual(x,snakeHeadNext)) || !snakeHeadNext.every(x => 0<=x == x < SpecialLen)) //蛇头不对
  • ????????????????return document.write("Game Over"); //overwrite all
  • ????????}
  • ????????snakeBody.push(snakeHeadNext);
  • ????????Map[snakeHeadNext] = 1; //蛇头合适,加入蛇身
  • ????????while (snakeBody.some(x => pairEqual(x, food)))
  • ????????????food = [Math.floor(Math.random() * SpecialLen), Math.floor(Math.random() * SpecialLen)];
  • ????????Map[food] = 2;
  • ????????for(let i =0;i<SpecialLen ;i++)
  • ????????????for(let j =0;j<SpecialLen ;j++){
  • ????????????switch (Map[[i,j]]) {
  • ????????????????case 1:ctx.fillStyle= purple;break;
  • ????????????????case 2:ctx.fillStyle= green;break;
  • ????????????????default:ctx.fillStyle= grey;break;
  • ????????????}
  • ????????????ctx.fillRect(i*SpecialLen,j*SpecialLen, SpecialLen, SpecialLen)
  • ????????}
  • ????????setTimeout(arguments.callee, 100); //130ms后执行function 一次
  • ????}()
  • </script>
  • </body>
  • </html>

?

以上是关于40行贪吃蛇 原生js的主要内容,如果未能解决你的问题,请参考以下文章

使用前端原生 js,贪吃蛇小游戏

纯原生JS面向对象构造函数方法实现贪吃蛇小游戏

原生web实现贪吃蛇

javascript:用原生js模拟贪吃蛇游戏练习

13行js写贪吃蛇游戏

100行Python代码,轻松完成贪吃蛇小游戏?