نمره‌های بازی

با فشار دادن دکمه‌ها می‌توانید مکعب قرمز را حرکت دهید:






امتیاز

روش‌های مختلفی برای ثبت امتیاز در بازی وجود دارد، ما به شما نشان خواهیم داد که چگونه امتیاز را بر روی کانواس بنویسیم.

ابتدا یک کامپوننت امتیاز بسازید:

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;
    
    
    myObstacles.push(new component(10, x - height - gap, \
  }
  for (i = 0; i < myObstacles.length; i += 1) {
    myObstacles[i].speedX = -1;
    myObstacles[i].newPos();
    myObstacles[i].update();
  }
  myScore.text = "+ \
  myScore.update();
  myGamePiece.newPos();
  myGamePiece.update();
}

آزمایش کنید