This Chat is read-only. Login to resume chatting.
<!DOCTYPE html>
<html>
<head>
<title>Space Invaders</title>
<style>
canvas {
background: black;
display: block;
margin: 0 auto;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const player = {
x: canvas.width / 2 - 15,
y: canvas.height - 50,
width: 30,
height: 30,
speed: 5,
color: '#00FF00'
};
const enemies = [];
const enemyWidth = 30;
const enemyHeight = 30;
const enemyPadding = 20;
const enemyRows = 4;
const enemyCols = 8;
for (let r = 0; r < enemyRows; r++) {
for (let c = 0; c < enemyCols; c++) {
enemies.push({
x: c * (enemyWidth + enemyPadding) + 30,
y: r * (enemyHeight + enemyPadding) + 30,
width: enemyWidth,
height: enemyHeight,
color: '#FF0000'
});
}
}
function drawPlayer() {
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}
function drawEnemies() {
enemies.forEach(enemy => {
ctx.fillStyle = enemy.color;
ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
});
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawPlayer();
drawEnemies();
requestAnimationFrame(update);
}
function movePlayer(e) {
if (e.key === 'ArrowLeft' && player.x > 0) {
player.x -= player.speed;
} else if (e.key === 'ArrowRight' && player.x < canvas.width - player.width) {
player.x += player.speed;
}
}
document.addEventListener('keydown', movePlayer);
update();
</script>
</body>
</html>