Meta Description" name="description" />
<!DOCTYPE html>
<html>
<head>
<title>Shooting Game</title>
<style>
body { margin:0; background:black; overflow:hidden; }
canvas { display:block; }
</style>
</head>
<body>
<canvas id="canvas"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
// Player
let player = { x: 100, y: canvas.height/2, size: 30 };
// Enemy
let enemy = { x: canvas.width - 150, y: canvas.height/2, size: 30, alive: true };
// Bullets
let bullets = [];
// Controls
window.addEventListener("keydown", (e) => {
if (e.key === "ArrowUp") player.y -= 20;
if (e.key === "ArrowDown") player.y += 20;
if (e.key === " ") {
bullets.push({ x: player.x + 20, y: player.y + 10 });
}
});
function drawPlayer() {
ctx.fillStyle = "blue";
ctx.fillRect(player.x, player.y, player.size, player.size);
}
function drawEnemy() {
if (enemy.alive) {
ctx.fillStyle = "red";
ctx.fillRect(enemy.x, enemy.y, enemy.size, enemy.size);
}
}
function drawBullets() {
ctx.fillStyle = "yellow";
bullets.forEach(b => {
ctx.fillRect(b.x, b.y, 10, 5);
});
}
function updateBullets() {
bullets.forEach(b => {
b.x += 8;
// Collision
if (enemy.alive &&
b.x < enemy.x + enemy.size &&
b.x + 10 > enemy.x &&
b.y < enemy.y + enemy.size &&
b.y + 5 > enemy.y) {
enemy.alive = false;
}
});
}
function drawWin() {
if (!enemy.alive) {
ctx.fillStyle = "white";
ctx.font = "40px Arial";
ctx.fillText("You Win!", canvas.width/2 - 100, 100);
}
}
function update() {
ctx.clearRect(0,0,canvas.width,canvas.height);
drawPlayer();
drawEnemy();
drawBullets();
updateBullets();
drawWin();
requestAnimationFrame(update);
}
update();
</script>
</body>
</html>1
1
2KB
2KB
114.0ms
188.0ms
114.0ms