게임 점수


버튼을 눌러 빨간색 사각형을 이동합니다.








점수 계산

게임에서 점수를 유지하는 방법에는 여러 가지가 있습니다. 캔버스에 점수를 기록하는 방법을 알려 드리겠습니다.

먼저 점수 구성 요소를 만듭니다.

예시

var myGamePiece;
var myObstacles = [];
var myScore;

function startGame() {
  myGamePiece = new component(30, 30, "red", 10, 160);
  myScore = new component("30px", "Consolas", "black", 280, 40, "text");
  myGameArea.start();
}

캔버스 요소에 텍스트를 작성하는 구문은 사각형을 그리는 것과 다릅니다. 따라서 추가 인수를 사용하여 구성 요소 생성자를 호출하여 이 구성 요소가 "텍스트" 유형임을 생성자에게 알려야 합니다.

구성 요소 생성자에서 구성 요소가 "텍스트" 유형인지 테스트하고 fillText메서드 대신 메서드를 사용합니다 fillRect.

예시

function component(width, height, color, x, y, type) {
  this.type = type;
  this.width = width;
  this.height = height;
  this.speedX = 0;
  this.speedY = 0;
  this.x = x;
  this.y = y;
  this.update = function() {
    ctx = myGameArea.context;
    if (this.type == "text") {
      ctx.font = this.width + " " + this.height;
      ctx.fillStyle = color;
      ctx.fillText(this.text, this.x, this.y);
    } else {
      ctx.fillStyle = color;
      ctx.fillRect(this.x, this.y, this.width, this.height);
    }
  }
...
}



마지막으로 캔버스에 점수를 기록하는 updateGameArea 함수에 몇 가지 코드를 추가합니다. 이 속성을 사용 frameNo하여 점수를 계산합니다.

예시

function updateGameArea() {
  var x, height, gap, minHeight, maxHeight, minGap, maxGap;
  for (i = 0; i < myObstacles.length; i += 1) {
    if (myGamePiece.crashWith(myObstacles[i])) {
      myGameArea.stop();
      return;
    }
  }
  myGameArea.clear();
  myGameArea.frameNo += 1;
  if (myGameArea.frameNo == 1 || everyinterval(150)) {
    x = myGameArea.canvas.width;
    minHeight = 20;
    maxHeight = 200;
    height = Math.floor(Math.random()*(maxHeight-minHeight+1)+minHeight);
    minGap = 50;
    maxGap = 200;
    gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap);
    myObstacles.push(new component(10, height, "green", x, 0));
    myObstacles.push(new component(10, x - height - gap, "green", x, height + gap));
  }
  for (i = 0; i < myObstacles.length; i += 1) {
    myObstacles[i].speedX = -1;
    myObstacles[i].newPos();
    myObstacles[i].update();
  }
  myScore.text = "SCORE: " + myGameArea.frameNo;
  myScore.update();
  myGamePiece.newPos();
  myGamePiece.update();
}