最新的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();
}
试一试»