Simple HTML Game: Dodge the Obstacle
<html>
<body>
<style>
#canvas {
border: 1px solid #000;
}
#score {
font-family: sans-serif;
font-size: 0.75rem;
color: red;
}
</style>
<p><canvas id='canvas' width='300' height='300'></canvas></p>
<div id='score'>Score: 0</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let score = 0;
let interval;
// Create a box
let box = {
x: 10,
y: 10,
width: 10,
height: 10,
color: '#0095DD'
}
// Create an obstacle
let obstacle = {
x: Math.random() * 300,
y: -50,
width: 10,
height: 10,
color: '#FF4136'
}
// Draw box and obstacle
function draw() {
ctx.clearRect(0, 0, 300, 300);
ctx.fillStyle = box.color;
ctx.fillRect(box.x, box.y, box.width, box.height);
ctx.fillStyle = obstacle.color;
ctx.fillRect(obstacle.x, obstacle.y, obstacle.width, obstacle.height);
}
// Move box when arrow keys are pressed
document.addEventListener('keydown', moveBox);
function moveBox(e) {
if (e.keyCode === 37 && box.x > 0) {
box.x -= 10;
} else if (e.keyCode === 38 && box.y > 0) {
box.y -= 10;
} else if (e.keyCode === 39 && box.x + box.width < 300) {
box.x += 10;
} else if (e.keyCode === 40 && box.y + box.height < 300) {
box.y += 10;
}
}
// Move the obstacle down
function moveObstacle() {
obstacle.y += 5;
// Check for collision
if (obstacle.x < box.x + box.width &&
obstacle.x + obstacle.width > box.x &&
obstacle.y < box.y + box.height &&
obstacle.y + obstacle.height > box.y) {
// Collision detected
clearInterval(interval);
alert('Game Over!');
} else if (obstacle.y > 300) {
// Obstacle has gone off screen
obstacle.y = -50;
obstacle.x = Math.random() * 300;
score++;
document.getElementById('score').innerText = 'Score: ' + score;
}
}
// Start the game loop
interval = setInterval(() => {
draw();
moveObstacle();
}, 1000/60);
</script>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/lniO 著作权归作者所有。请勿转载和采集!