码迷,mamicode.com
首页 > Web开发 > 详细

40行贪吃蛇 原生js

时间:2018-07-10 00:36:17      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:不能   val   context   group   ret   next   for   case   height   

  • <!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

标签:不能   val   context   group   ret   next   for   case   height   

原文地址:https://www.cnblogs.com/migeater/p/9286761.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!