最新的Web開發教程
 

HTML遊戲得分


按動按鈕,移動紅色方形:








計數的分數

有許多方法來保持在一場比賽的比分,我們會告訴你如何寫一個分數到畫布上。

首先做一個得分組件:

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

對於canvas元素上書寫文字的語法是從繪製矩形不同。 因此,我們必須調用使用一個額外的參數組件構造,告訴構造此組件的類型為"text"

在組件構造我們測試如果組件類型"text" ,並使用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();
}
試一試»