Okay, here is a functional Space Invaders game implemented entirely within a single HTML file. It uses the HTML5 Canvas API for rendering and JavaScript for all game logic, controls, and state management.
How to Use:
- Save the code below as an HTML file (e.g.,
space_invaders.html).
- Open the file in your web browser.
- Press Enter or Spacebar to start.
- Use the Left and Right Arrow keys to move the player ship.
- Press the Spacebar to fire.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Space Invaders</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #000;
color: #fff;
font-family: 'Courier New', Courier, monospace;
flex-direction: column;
}
canvas {
border: 1px solid #fff;
background-color: #000;
display: block; /* Removes extra space below canvas */
}
#game-info {
margin-top: 20px;
text-align: center;
font-size: 1.2em;
}
#instructions {
margin-top: 10px;
font-size: 0.9em;
opacity: 0.8;
}
</style>
</head>
<body>
<canvas id="gameCanvas" width="600" height="400"></canvas>
<div id="game-info">
Score: <span id="score">0</span> | Lives: <span id="lives">3</span>
<div id="instructions">
Press ENTER or SPACE to Start | Use Left/Right Arrows to Move | Press SPACE to Fire
</div>
</div>
<script>
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Game Constants
const PLAYER_WIDTH = 20;
const PLAYER_HEIGHT = 15;
const PLAYER_COLOR = '#00ff00'; // Green
const PLAYER_SPEED = 4;
const BULLET_WIDTH = 3;
const BULLET_HEIGHT = 10;
const BULLET_COLOR = '#fff';
const PLAYER_BULLET_SPEED = 7;
const ENEMY_BULLET_SPEED = 4;
const SHOOT_DELAY = 500; // ms between player shots
const ENEMY_SHOOT_PROBABILITY = 0.005; // Chance per frame per enemy
const ENEMY_WIDTH = 25;
const ENEMY_HEIGHT = 20;
const ENEMY_COLOR = '#ff0000'; // Red
const ENEMY_ROWS = 4;
const ENEMY_COLS = 10;
const ENEMY_HORIZONTAL_SPACING = 40;
const ENEMY_VERTICAL_SPACING = 30;
const ENEMY_START_Y = 50;
const ENEMY_MOVE_X_SPEED = 1;
const ENEMY_DROP_SPEED = 15; // How much they drop when hitting edge
// Game State Variables
let score = 0;
let lives = 3;
let player;
let bullets = []; // Player bullets
let enemyBullets = [];
let enemies = [];
let keysPressed = {};
let lastShotTime = 0;
let gameOver = false;
let gameStarted = false;
// DOM Elements
const scoreDisplay = document.getElementById('score');
const livesDisplay = document.getElementById('lives');
const instructionsDisplay = document.getElementById('instructions');
// --- Object Constructors ---
function Player() {
this.width = PLAYER_WIDTH;
this.height = PLAYER_HEIGHT;
this.x = (canvas.width - this.width) / 2;
this.y = canvas.height - this.height - 10;
this.color = PLAYER_COLOR;
this.draw = function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
this.move = function(direction) {
this.x += direction * PLAYER_SPEED;
// Keep player within bounds
if (this.x < 0) {
this.x = 0;
}
if (this.x > canvas.width - this.width) {
this.x = canvas.width - this.width;
}
};
this.shoot = function() {
const now = Date.now();
if (now - lastShotTime > SHOOT_DELAY) {
bullets.push(new PlayerBullet(this.x + this.width / 2 - BULLET_WIDTH / 2, this.y));
lastShotTime = now;
}
};
}
function PlayerBullet(x, y) {
this.x = x;
this.y = y;
this.width = BULLET_WIDTH;
this.height = BULLET_HEIGHT;
this.color = BULLET_COLOR;
this.draw = function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
this.update = function() {
this.y -= PLAYER_BULLET_SPEED;
};
}
function EnemyBullet(x, y) {
this.x = x;
this.y = y;
this.width = BULLET_WIDTH / 2; // Smaller enemy bullets
this.height = BULLET_HEIGHT / 2;
this.color = '#ffcc00'; // Yellowish
this.draw = function() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
};
this.update = function() {
this.y += ENEMY_BULLET_SPEED;
};
}
function Enemy(x, y, points) {
this.x = x;
this.y = y;
this.width = ENEMY_WIDTH;
this.height = ENEMY_HEIGHT;
this.color = ENEMY_COLOR;
this.points = points;
this.isAlive = true;
this.moveDirection = 1; // 1 for right, -1 for left
this.draw = function() {
if (this.isAlive) {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
};
this.update = function() {
if (this.isAlive) {
this.x += this.moveDirection * ENEMY_MOVE_X_SPEED;
}
};
// Check if this enemy needs to trigger a row drop/direction change
this.checkEdgeCollision = function() {
if (!this.isAlive) return false;
const goingRight = this.moveDirection === 1;
const hittingRightEdge = this.x + this.width >= canvas.width;
const hittingLeftEdge = this.x <= 0;
if ((goingRight && hittingRightEdge) || (!goingRight && hittingLeftEdge)) {
return true;
}
return false;
}
// Check if enemy reached player level
this.checkPlayerLevelCollision = function() {
if (!this.isAlive) return false;
return this.y + this.height >= player.y;
}
}
// --- Initialization ---
function initGame() {
score = 0;
lives = 3;
bullets = [];
enemyBullets = [];
enemies = [];
player = new Player();
keysPressed = {};
lastShotTime = 0;
gameOver = false;
gameStarted = false;
instructionsDisplay.textContent = "Press ENTER or SPACE to Start | Use Left/Right Arrows to Move | Press SPACE to Fire";
// Create enemies
let points = 10;
for (let row = 0; row < ENEMY_ROWS; row++) {
for (let col = 0; col < ENEMY_COLS; col++) {
const enemyX = col * ENEMY_HORIZONTAL_SPACING + (canvas.width - ENEMY_COLS * ENEMY_HORIZONTAL_SPACING) / 2;
const enemyY = row * ENEMY_VERTICAL_SPACING + ENEMY_START_Y;
enemies.push(new Enemy(enemyX, enemyY, points));
}
// Optionally change points value for different rows
// if (row === 1) points = 20;
// if (row === 2) points = 30;
}
updateDisplay();
}
function updateDisplay() {
scoreDisplay.textContent = score;
livesDisplay.textContent = lives;
}
// --- Input Handling ---
window.addEventListener('keydown', function(e) {
keysPressed[e.code] = true;
if (!gameStarted && (e.code === 'Enter' || e.code === 'Space')) {
startGame();
} else if (gameStarted && !gameOver && e.code === 'Space') {
player.shoot();
}
});
window.addEventListener('keyup', function(e) {
keysPressed[e.code] = false;
});
function startGame() {
gameStarted = true;
instructionsDisplay.textContent = ""; // Clear instructions
gameLoop(); // Start the loop
}
// --- Game Logic ---
function update() {
if (!gameStarted || gameOver) return;
// Player Movement
if (keysPressed['ArrowLeft']) {
player.move(-1);
}
if (keysPressed['ArrowRight']) {
player.move(1);
}
// Update Bullets
bullets.forEach(bullet => bullet.update());
enemyBullets.forEach(bullet => bullet.update());
// Filter out-of-bounds bullets
bullets = bullets.filter(bullet => bullet.y > 0);
enemyBullets = enemyBullets.filter(bullet => bullet.y < canvas.height);
// Update Enemies and Check for Edge Collision
let edgeCollision = false;
enemies.forEach(enemy => {
enemy.update();
if (enemy.checkEdgeCollision()) {
edgeCollision = true;
}
// Check if enemy reached player level
if (enemy.checkPlayerLevelCollision()) {
handlePlayerDeath();
}
});
// Handle Enemy Drop and Direction Change
if (edgeCollision) {
enemies.forEach(enemy => {
enemy.y += ENEMY_DROP_SPEED;
enemy.moveDirection *= -1; // Reverse direction
});
}
// Enemy Shooting
enemies.forEach(enemy => {
if (enemy.isAlive && Math.random() < ENEMY_SHOOT_PROBABILITY) {
enemyBullets.push(new EnemyBullet(enemy.x + enemy.width / 2 - (BULLET_WIDTH/4), enemy.y + enemy.height));
}
});
// Collision Detection: Player Bullets vs Enemies
for (let i = bullets.length - 1; i >= 0; i--) {
for (let j = enemies.length - 1; j >= 0; j--) {
if (bullets[i] && enemies[j] && enemies[j].isAlive) {
const bullet = bullets[i];
const enemy = enemies[j];
// Simple bounding box collision
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)
{
score += enemy.points;
enemies[j].isAlive = false; // Mark enemy as dead
bullets.splice(i, 1); // Remove bullet
updateDisplay();
// Check for win condition
if (enemies.every(e => !e.isAlive)) {
winGame();
}
break; // Bullet destroyed one enemy, move to next bullet
}
}
}
}
// Collision Detection: Enemy Bullets vs Player
for (let i = enemyBullets.length - 1; i >= 0; i--) {
const bullet = enemyBullets[i];
// Simple bounding box collision
if (!gameOver &&
bullet.x < player.x + player.width &&
bullet.x + bullet.width > player.x &&
bullet.y < player.y + player.height &&
bullet.y + bullet.height > player.y)
{
handlePlayerDeath();
enemyBullets.splice(i, 1); // Remove bullet
break; // Player hit, stop checking other bullets
}
}
}
function handlePlayerDeath() {
lives--;
updateDisplay();
player.x = (canvas.width - player.width) / 2; // Reset player position
player.y = canvas.height - player.height - 10;
bullets = []; // Clear player bullets
enemyBullets = []; // Clear enemy bullets (optional, could let them continue)
// Maybe pause briefly? For now, just reset player.
if (lives <= 0) {
endGame();
}
}
function winGame() {
instructionsDisplay.textContent = "YOU WIN! Score: " + score + " Press ENTER to Play Again";
gameOver = true;
gameStarted = false; // Stop the loop implicitly next frame
}
function endGame() {
instructionsDisplay.textContent = "GAME OVER! Score: " + score + " Press ENTER to Play Again";
gameOver = true;
gameStarted = false; // Stop the loop implicitly next frame
}
// --- Drawing ---
function draw() {
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw player
player.draw();
// Draw enemies
enemies.forEach(enemy => enemy.draw());
// Draw bullets
bullets.forEach(bullet => bullet.draw());
enemyBullets.forEach(bullet => bullet.draw());
// Draw Game Over / Start Message if applicable
if (!gameStarted) {
ctx.fillStyle = 'rgba(255, 255, 255, 0.7)';
ctx.font = '24px Courier New';
ctx.textAlign = 'center';
ctx.fillText('SPACE INVADERS', canvas.width / 2, canvas.height / 2 - 30);
}
if (gameOver) {
ctx.fillStyle = 'rgba(255, 0, 0, 0.7)';
ctx.font = '30px Courier New';
ctx.textAlign = 'center';
ctx.fillText('GAME OVER', canvas.width / 2, canvas.height / 2);
}
if (enemies.every(e => !e.isAlive) && gameStarted) { // Check win condition during gameplay
ctx.fillStyle = 'rgba(0, 255, 0, 0.7)';
ctx.font = '30px Courier New';
ctx.textAlign = 'center';
ctx.fillText('YOU WIN!', canvas.width / 2, canvas.height / 2);
}
}
// --- Game Loop ---
function gameLoop() {
if (gameOver) {
// If game over or won, wait for restart input
if (keysPressed['Enter']) {
initGame(); // Re-initialize
startGame(); // Start the loop again
} else {
requestAnimationFrame(gameLoop); // Keep drawing the final screen
}
return;
}
update();
draw();
requestAnimationFrame(gameLoop);
}
// --- Initial Setup ---
initGame();
// Initial draw to show the start screen before Enter is pressed
draw();
</script>
</body>
</html>
Explanation:
-
HTML Structure:
- Sets up the basic page with a title and links to the CSS (within
<style>) and JavaScript (within <script>).
- Includes a
<canvas> element with the id gameCanvas where the game will be drawn.
- Includes
div elements (#score, #lives, #instructions) to display game information and instructions.
-
CSS Styling:
- Centers the canvas and info text on the page.
- Styles the canvas border and background.
- Sets a monospace font for a retro feel.
-
JavaScript - Core Components:
- Canvas Context: Gets the 2D rendering context (
ctx) needed for drawing.
- Constants: Defines sizes, colors, speeds, and layout parameters for all game elements. This makes the code easier to adjust.
- Game State Variables: Tracks the score, lives, player object, arrays for bullets and enemies, pressed keys, etc.
gameStarted and gameOver flags manage the flow.
- Object Constructors:
Player, PlayerBullet, EnemyBullet, and Enemy define the properties and methods (draw, update, move, shoot, etc.) for each game entity.
initGame(): Resets all variables, creates the player and the initial grid of enemies.
updateDisplay(): Updates the score and lives shown on the page.
- Input Handling: Event listeners for
keydown and keyup track which arrow keys and the spacebar are pressed. It also handles starting the game (Enter or Space) and player shooting (Space).
startGame(): Sets the gameStarted flag and calls gameLoop() to begin the main game cycle.
update(): Contains the core game logic:
- Moves the player based on input.
- Updates bullet positions and removes off-screen bullets.
- Moves enemies, checks if they hit the sides, and triggers the group drop/direction change.