js 뱀 탐식 게임 canvas 지도 그리 기

3440 단어 js탐식 사
본 논문 의 사례 는 js 가 뱀 을 게 걸 스 럽 게 먹 는 게임 을 실현 하 는 구체 적 인 코드 를 공유 하여 여러분 께 참고 하 시기 바 랍 니 다.구체 적 인 내용 은 다음 과 같 습 니 다.

사고의 방향
400 px*400 px 의 지도,20px*20px 당 단원 격 으로 뱀 몸 그리 기
이동 할 때마다 꼬리 머리 색 을 바 꿔 요.

모든 코드

<!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'); //            1-20   21-40   20*20
 var snake = [23, 22, 21]; //            
 var direction = 1; // 1  -1  -20  20 
 var flag = 1; //       bug
 var food = 50; //     

 function draw(x, color) {
  map.fillStyle = color;
 
 // 1-400                      
  if (x % 20 == 0) { //     
  map.fillRect(380 + 2, Math.floor(x / 21) * 20 + 2, 18, 18); //  1-400         
  } 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 { //               
  draw(snake.pop(), "#362E3D");
  }
  draw(food, "#EB1A4B");

  setTimeout(arguments.callee, 100); // arguments.callee               
 })();

 document.onkeydown = function (event) {
  event = event || window.event; // ie  windo.event
  if (flag) { // draw   (    )     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  
 }
 </script>
</body>


</html>
연속 빠 른 키보드 버그 해결
방향 키 상하 좌우 로 direction 의 값 을 실제 변경 합 니 다.뱀 이 다음 이동 전에 계속 바 뀌 면 자신 을 거꾸로 먹 는 bug 가 생 길 수 있 습 니 다.
그래서 flag 에 가입 해서 소스 코드 를 자세히 보 세 요.
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기