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();
    }
    在画布元素上写入文本的语法与绘制矩形的语法不同。因此,我们必须使用附加参数调用组件构造函数,告诉构造函数该组件属于 “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();
    }
    尝试一下