const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Character properties
const character = {
x: 50,
y: 50,
width: 20,
height: 20,
speed: 5
};
// Coin properties
const coin = {
x: 200,
y: 200,
size: 10
};
// Obstacle properties
const obstacle = {
x: 100,
y: 300,
width: 80,
height: 20
};
// Handle keyboard controls
document.addEventListener('keydown', (event) => {
const key = event.key;
switch (key) {
case 'ArrowUp':
character.y -= character.speed;
break;
case 'ArrowDown':
character.y += character.speed;
break;
case 'ArrowLeft':
character.x -= character.speed;
break;
case 'ArrowRight':
character.x += character.speed;
break;
}
});
// Update game state and draw the game
function update() {
// Clear the canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw the character
ctx.fillStyle = 'blue';
ctx.fillRect(character.x, character.y, character.width, character.height);
// Draw the coin
ctx.fillStyle = 'yellow';
ctx.beginPath();
ctx.arc(coin.x, coin.y, coin.size, 0, Math.PI * 2);
ctx.fill();
// Draw the obstacle
ctx.fillStyle = 'red';
ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
// Check for collisions with the coin and obstacle
if (checkCollision(character, coin)) {
// If the character collects the coin
coin.x = Math.random() * (canvas.width - 2 * coin.size) + coin.size;
coin.y = Math.random() * (canvas.height - 2 * coin.size) + coin.size;
}
if (checkCollision(character, obstacle)) {
// If the character hits the obstacle
alert('Game Over! You hit an obstacle.');
window.location.reload(); // Restart the game
}
// Request a new animation frame
requestAnimationFrame(update);
}
// Function to check collisions between two objects
function checkCollision(obj1, obj2) {
return (
obj1.x < obj2.x + obj2.width &&
obj1.x + obj1.width > obj2.x &&
obj1.y < obj2.y + obj2.height &&
obj1.y + obj1.height > obj2.y
);
}
// Start the game loop
update();
0 Comments (Please let us know your query)