Điểm trận đấu


Nhấn các nút để di chuyển hình vuông màu đỏ:








Đếm điểm

Có nhiều cách để giữ điểm số trong một trò chơi, chúng tôi sẽ hướng dẫn bạn cách ghi điểm số lên canvas.

Đầu tiên hãy tạo thành phần điểm số:

Thí dụ

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();
}

Cú pháp để viết văn bản trên một phần tử canvas khác với việc vẽ một hình chữ nhật. Do đó, chúng ta phải gọi hàm tạo thành phần bằng cách sử dụng một đối số bổ sung, nói với hàm tạo rằng thành phần này thuộc kiểu "văn bản".

Trong hàm tạo thành phần, chúng tôi kiểm tra xem thành phần có thuộc loại "văn bản" hay không và sử dụng fillTextphương thức thay vì fillRectphương thức:

Thí dụ

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);
    }
  }
...
}



Cuối cùng, chúng tôi thêm một số mã trong hàm updateGameArea để ghi điểm vào canvas. Chúng tôi sử dụng thuộc frameNotính để tính điểm số:

Thí dụ

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();
}