function Game() {
this.score = 0;
this.playerX = 50;
this.playerY = 50;
this.playerSize = 20;
this.enemyX = 200;
this.enemyY = 200;
this.enemySize = 20;
this.drawPlayer = function() {
ctx.fillStyle = "blue";
ctx.fillRect(this.playerX, this.playerY, this.playerSize, this.playerSize);
};
this.drawEnemy = function() {
ctx.fillStyle = "red";
ctx.fillRect(this.enemyX, this.enemyY, this.enemySize, this.enemySize);
};
this.checkCollision = function() {
if (this.playerX < this.enemyX + this.enemySize &&
this.playerX + this.playerSize > this.enemyX &&
this.playerY < this.enemyY + this.enemySize &&
this.playerY+ this.playerSize > this.enemyY) {
this.score++;
this.enemyX = Math.random() * canvas.width;
this.enemyY = Math.random() * canvas.height;
}
};
this.update = function() {
this.playerX = Math.max(0, Math.min(canvas.width - this.playerSize, this.playerX));
this.playerY = Math.max(0, Math.min(canvas.height - this.playerSize, this.playerY));
this.enemyX += (this.playerX - this.enemyX) * 0.1;
this.enemyY += (this.playerY - this.enemyY) * 0.1;
this.checkCollision();
};
this.draw = function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
this.drawPlayer();
this.drawEnemy();
ctx.font = "30px Arial";
ctx.fillStyle = "black";
ctx.fillText("Score: " + this.score, 10, 30);
};
this.loop = function() {
this.update();
this.draw();
requestAnimationFrame(this.loop.bind(this));
};
this.loop();
}