댓글 검색 목록

[javascript] ~ 100 줄의 JavaScript로 작성된 타워 게임

페이지 정보

작성자 운영자 작성일 20-09-06 10:30 조회 690 댓글 0

파란색 사각형을 클릭하여 상단 상자를 하단 상자 위에 놓습니다!


https://slicker.me/javascript/tower.htm


이 게임의 요점은 가능한 한 많은 상자를 쌓는 것입니다. 화면을 클릭하면 바운스 박스가 떨어지기 시작합니다. 두 상자가 이상적으로 정렬 된 정확한 순간을 클릭하지 않으면 튀어 나온 상자 부분이 화면에서 떨어지고 ( "파편") 다음 상자는 착륙 할 공간이 적습니다. 일을 더 어렵게 만들기 위해 각 상자는 이전 상자보다 빠르게 튀어 오릅니다.


전체 소스 코드는 다음과 같습니다. 여기에 간단한 설명이 있습니다.



<html>
<body>
<canvas id="myCanvaswidth="800height="600"></canvas>
<script>
let canvas = document.getElementById("myCanvas");
let context = canvas.getContext("2d");
context.font = 'bold 30px sans-serif';
let scrollCountercameraYcurrentmodexSpeed;
let ySpeed = 5;
let height = 50;
let boxes = [];
boxes[0] = {
  x300,
  y300,
  width200
};
let debris = {
  x0,
  width0
};
 
function newBox() {
  boxes[current] = {
    x0,
    y: (current + 10) * height,
    widthboxes[current - 1].width
  };
}
 
function gameOver() {
  mode = 'gameOver';
  context.fillText('Game overClick to play again!', 5050);
}
 
function animate() {
  if (mode != 'gameOver') {
    context.clearRect(00canvas.widthcanvas.height);
    context.fillText('Score: ' + (current - 1).toString(), 100200);
    for (let n = 0n < boxes.lengthn++) {
      let box = boxes[n];
      context.fillStyle = 'rgb(' + n * 16 + ',' + n * 16 + ',' + n * 16 + ')';
      context.fillRect(box.x600 - box.y + cameraYbox.widthheight);
    }
    context.fillStyle = 'red';
    context.fillRect(debris.x600 - debris.y + cameraYdebris.widthheight);
    if (mode == 'bounce') {
      boxes[current].x = boxes[current].x + xSpeed;
      if (xSpeed > 0 && boxes[current].x + boxes[current].width > canvas.width)
        xSpeed = -xSpeed;
      if (xSpeed < 0 && boxes[current].x < 0)
        xSpeed = -xSpeed;
    }
    if (mode == 'fall') {
      boxes[current].y = boxes[current].y - ySpeed;
      if (boxes[current].y == boxes[current - 1].y + height) {
        mode = 'bounce';
        let difference = boxes[current].x - boxes[current - 1].x;
        if (Math.abs(difference) >= boxes[current].width) {
          gameOver();
        }
        debris = {
          yboxes[current].y,
          widthdifference
        };
        if (boxes[current].x > boxes[current - 1].x) {
          boxes[current].width = boxes[current].width - difference;
          debris.x = boxes[current].x + boxes[current].width;
        } else {
          debris.x = boxes[current].x - difference;
          boxes[current].width = boxes[current].width + difference;
          boxes[current].x = boxes[current - 1].x;
        }
        if (xSpeed > 0)
          xSpeed++;
        else
          xSpeed--;
        current++;
        scrollCounter = height;
        newBox();
      }
    }
    debris.y = debris.y - ySpeed;
    if (scrollCounter) {
      cameraY++;
      scrollCounter--;
    }
  }
  window.requestAnimationFrame(animate);
}
 
function restart() {
  boxes.splice(1boxes.length - 1);
  mode = 'bounce';
  cameraY = 0;
  scrollCounter = 0;
  xSpeed = 2;
  current = 1;
  newBox();
  debris.y = 0;
}
 
canvas.onpointerdown = function() {
  if (mode == 'gameOver')
    restart();
  else {
    if (mode == 'bounce')
      mode = 'fall';
  }
};
 
restart();
animate();
</script>
</body>
</html>


[Lines 1-7] HTML5 Canvas를 초기화합니다.

[8-20] 변수와 개체를 선언합니다.

[22-28] 이전 상자 이후에 새 상자를 만드는 함수.

[30-33] '게임 오버' 함수.

[35-89] 메인 게임 루프. 여기가 모든 작업이 있는 곳이므로 세부 사항을 살펴 보겠습니다.

[36] 게임이 활성화 된 경우 :

[37-38] 이전 프레임을 지우고 점수를 표시합니다.

[39-43] 모든 상자를 그립니다.

[41] 상자의 색상을 선택하십시오.

[44-45] 파편을 그립니다.

[46] 게임이 '바운스'모드 인 경우 (현재 상자가 벽에서 수평으로 튀어 오르는 경우) :

[47-52] x 축에서 현재 상자를 이동합니다. 벽에 부딪히면 방향을 바꾸십시오.

[53] 게임이 '추락'모드 인 경우 (현재 상자가 출시됨)

[54] 현재 상자를 y 축으로 이동합니다.

[55] 이전 상자 위에 있는 경우 :

[56] 모드를 다시 '바운스'로 변경하십시오

[57] 겹치지 않는 부분의 길이를 계산합니다.

[58-60] 차이가 상자보다 크면 플레이어가 완전히 놓쳤다는 의미입니다. 게임 오버!

[61-64] 파편 개체를 업데이트합니다.

[65-72] 파편이 상자의 왼쪽 또는 오른쪽에 있는지 확인합니다.

[73-76] 바운싱 속도를 높입니다.

[77-79] 새 상자를 만듭니다.

[82] 파편 애니메이션-[61-64]에서 다시 업데이트 될 때까지 계속 떨어집니다.

[83-85] scrollCounter는 카메라가 위로 이동해야 하는 프레임 수를 결정합니다. 양수이면 카메라 위치가 업데이트 됩니다.

[88] 다음 애니메이션 프레임을 기다립니다.

[91] 새 게임을 시작할 때 변수에 초기 값을 다시 할당하는 함수입니다.

[102-109] 클릭 (마우스 또는 터치) 핸들러 :

[103-4] 'gameOver'모드에 있는 경우 게임을 다시 시작하면 됩니다.

[106-7] '바운스' 모드에 있는 경우 '낙하'로 전환합니다 (상자에서 손을 뗍니다).

[111] 첫 번째 게임을 초기화합니다.

[112] 애니메이션을 시작합니다.


댓글목록 0

등록된 댓글이 없습니다.

웹학교 로고

온라인 코딩학교

코리아뉴스 2001 - , All right reserved.