<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>簡単なシューティングゲーム</title>
<style>
canvas {
background-color: #000;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="400" height="600"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
let playerX = canvas.width / 2 - 15;
const playerY = canvas.height - 50;
const playerWidth = 30;
const playerHeight = 30;
const playerSpeed = 5;
let bullets = [];
let enemies = [];
let gameOver = false;
function drawPlayer() {
ctx.fillStyle = 'white';
ctx.fillRect(playerX, playerY, playerWidth, playerHeight);
}
function drawBullet(bullet) {
ctx.fillStyle = 'red';
ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
}
function drawEnemy(enemy) {
ctx.fillStyle = 'green';
ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
}
function update() {
if (gameOver) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
bullets.forEach((bullet, index) => {
bullet.y -= bullet.speed;
drawBullet(bullet);
// Bullet off the screen
if (bullet.y < 0) bullets.splice(index, 1);
});
enemies.forEach((enemy, enemyIndex) => {
enemy.y += enemy.speed;
drawEnemy(enemy);
// Enemy off the screen
if (enemy.y > canvas.height) {
gameOver = true;
alert("Game Over");
}
// Collision detection
bullets.forEach((bullet, bulletIndex) => {
if (bullet.x < enemy.x + enemy.width &&
bullet.x + bullet.width > enemy.x &&
bullet.y < enemy.y + enemy.height &&
bullet.y + bullet.height > enemy.y) {
enemies.splice(enemyIndex, 1);
bullets.splice(bulletIndex, 1);
}
});
});
// Generate enemies
if (Math.random() < 0.02) {
enemies.push({
x: Math.random() * (canvas.width - 30),
y: 0,
width: 30,
height: 30,
speed: 2
});
}
requestAnimationFrame(update);
}
function movePlayer(e) {
if (e.key === "ArrowLeft" && playerX > 0) {
playerX -= playerSpeed;
} else if (e.key === "ArrowRight" && playerX < canvas.width - playerWidth) {
playerX += playerSpeed;
}
}
function shootBullet(e) {
if (e.key === " ") {
bullets.push({
x: playerX + playerWidth / 2 - 2.5,
y: playerY,
width: 5,
height: 10,
speed: 7
});
}
}
document.addEventListener('keydown', movePlayer);
document.addEventListener('keydown', shootBullet);
update();
</script>
</body>
</html>