Chicken Hunt
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
}
const canvas = document.getElementById(‘gameCanvas’);
const ctx = canvas.getContext(‘2d’);
// Set canvas size
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
let score = 0;
let chickenSpeed = 2;
let chickens = [];
let pistolCharge = 10;
// Player
const player = {
x: canvas.width / 2,
y: canvas.height – 50,
width: 50,
height: 50,
color: ‘red’,
speed: 5
};
// Chicken
function Chicken() {
this.x = Math.random() * canvas.width;
this.y = Math.random() * canvas.height;
this.width = 30;
this.height = 30;
this.color = ‘yellow’;
this.speed = chickenSpeed;
}
Chicken.prototype.draw = function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
Chicken.prototype.update = function() {
this.y += this.speed;
if (this.y > canvas.height) {
this.y = 0 – this.height;
this.x = Math.random() * canvas.width;
score -= 5; // Deduct score if chicken escapes
}
this.draw();
}
function drawPlayer() {
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}
function shoot() {
if (pistolCharge > 0) {
pistolCharge–;
for (let i = 0; i < chickens.length; i++) {
if (
player.x chickens[i].x &&
player.y chickens[i].y
) {
chickens.splice(i, 1);
score += 10;
}
}
}
}
function updateScore() {
ctx.fillStyle = ‘white’;
ctx.font = ’20px Arial’;
ctx.fillText(‘Score: ‘ + score, 20, 30);
}
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
updateScore();
if (Math.random() < 0.02) {
chickens.push(new Chicken());
}
for (let i = 0; i {
switch (e.key) {
case ‘ArrowLeft’:
if (player.x > 0) player.x -= player.speed;
break;
case ‘ArrowRight’:
if (player.x < canvas.width – player.width) player.x += player.speed;
break;
case ' ':
shoot();
break;
}
});
gameLoop();