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