Below is a complete, self-contained HTML document that includes the HTML structure, CSS styles, and JavaScript code for a simple 2D space shooter game. This game uses the HTML5 Canvas API for rendering. The game features:
A player-controlled spaceship that can move left and right using the arrow keys.
Enemies (simple rectangles) that spawn at the top and move downward.
Bullets that the player can shoot upward using the spacebar.
Basic collision detection: Bullets destroy enemies, and enemies hitting the player end the game.
A score counter displayed on the screen.
To play:
Use the left/right arrow keys to move the player.
Use the spacebar to shoot bullets.
The game resets on page reload.
Here's the full code:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2D Space Shooter Game</title>
<style>
/* CSS Styles */
body {
margin: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: black; /* Dark background for space theme */
color: white; /* For score text */
font-family: Arial, sans-serif;
overflow: hidden; /* Prevent scrolling */
}
canvas {
border: 1px solid white;
background-color: #000; /* Black canvas for space */
}
#score {
position: absolute;
top: 10px;
left: 10px;
font-size: 20px;
}
</style>
</head>
<body>
<div id="score">Score: 0</div>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
// JavaScript Code
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const scoreElement = document.getElementById('score');
// Game variables
const player = {
x: canvas.width / 2 - 25, // Player starting position
y: canvas.height - 50,
width: 50,
height: 50,
speed: 5,
dx: 0 // Direction of movement
};
const bullet = {
x: 0,
y: 0,
width: 5,
height: 10,
speed: 7,
fired: false
};
const enemies = []; // Array to hold enemies
const enemyWidth = 50;
const enemyHeight = 50;
const enemySpeed = 2;
let score = 0;
let animationId; // For game loop
// Event listeners for keyboard
document.addEventListener('keydown', keyDown);
document.addEventListener('keyup', keyUp);
function keyDown(e) {
if (e.key === 'ArrowRight') {
player.dx = player.speed;
} else if (e.key === 'ArrowLeft') {
player.dx = -player.speed;
} else if (e.key === ' ') { // Spacebar to shoot
if (!bullet.fired) {
fireBullet();
}
}
}
function keyUp(e) {
if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
player.dx = 0;
}
}
function fireBullet() {
bullet.x = player.x + player.width / 2 - bullet.width / 2;
bullet.y = player.y;
bullet.fired = true;
}
function createEnemy() {
const x = Math.random() * (canvas.width - enemyWidth);
enemies.push({
x: x,
y: 0,
width: enemyWidth,
height: enemyHeight,
speed: enemySpeed
});
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
// Draw and update player
ctx.fillStyle = 'blue'; // Player color
ctx.fillRect(player.x, player.y, player.width, player.height);
player.x += player.dx; // Move player
// Boundary checks for player
if (player.x < 0) player.x = 0;
if (player.x + player.width > canvas.width) player.x = canvas.width - player.width;
// Update and draw bullet
if (bullet.fired) {
ctx.fillStyle = 'red'; // Bullet color
ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
bullet.y -= bullet.speed; // Move bullet up
if (bullet.y + bullet.height < 0) {
bullet.fired = false; // Reset bullet
}
}
// Create enemies periodically
if (Math.random() < 0.02) { // Adjust probability for enemy spawn rate
createEnemy();
}
// Update and draw enemies
ctx.fillStyle = 'green'; // Enemy color
enemies.forEach((enemy, index) => {
ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
enemy.y += enemy.speed; // Move enemy down
// Check collision with bullet
if (bullet.fired &&
bullet.x < enemy.x + enemy.width &&
bullet.x + bullet.width > enemy.x &&
bullet.y < enemy.y + enemy.height &&
bullet.y + bullet.height > enemy.y) {
// Collision detected
enemies.splice(index, 1); // Remove enemy
bullet.fired = false; // Reset bullet
score++;
scoreElement.textContent = 'Score: ' + score;
}
// Check collision with player
if (enemy.y + enemy.height > player.y &&
enemy.x < player.x + player.width &&
enemy.x + enemy.width > player.x) {
gameOver();
}
// Remove enemies that go off-screen
if (enemy.y > canvas.height) {
enemies.splice(index, 1);
}
});
animationId = requestAnimationFrame(update); // Loop
}
function gameOver() {
cancelAnimationFrame(animationId);
alert('Game Over! Final Score: ' + score);
document.location.reload(); // Reload page to restart
}
// Start the game
update();
</script>
</body>
</html>
How This Works:
HTML: The <canvas> element is the game area, and a <div> displays the score.
CSS: Styles the body for centering, sets a dark theme, and positions the score.
JavaScript:
Handles player movement, bullet firing, enemy creation, and updates.
Uses requestAnimationFrame for a smooth game loop.
Detects collisions between bullets/enemies and enemies/player.
The game ends when an enemy hits the player, and it alerts the score before reloading.
This is a basic implementation. You can enhance it by adding sounds, more enemy types, power-ups, or better graphics. If you'd like any modifications, let me know!