ゲームスコア
ボタンを押すと赤いブロックを移動できます:
スコア
ゲーム中にスコアを記録する方法がたくさんあります。キャンバスにスコアを書き込む方法を説明します。
まずスコアコンポーネントを作成します:
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, "緑色", x, 0)); myObstacles.push(new component(10, x - height - gap, "緑色", x, height + gap)); } for (i = 0; i < myObstacles.length; i += 1) { myObstacles[i].speedX = -1; myObstacles[i].newPos(); myObstacles[i].update(); } myScore.text = "得点: " + myGameArea.frameNo; myScore.update(); myGamePiece.newPos(); myGamePiece.update(); }