1. 程式人生 > >40行貪吃蛇 原生js

40行貪吃蛇 原生js

tel 1.0 ott 執行 htm html oct bre aps

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