게임 점수
버튼을 누르면 빨간 정육면체를 이동시킬 수 있습니다:
점수
게임에서 점수를 기록하는 많은 방법들이 있습니다. 캔버스에 점수를 적는 방법을 안내해 드리겠습니다.
처음으로 점수 컴포넌트를 만듭니다:
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" 타입인지 테스트하는 것을 확인합니다. "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 = "점수: " + myGameArea.frameNo; myScore.update(); myGamePiece.newPos(); myGamePiece.update(); }