Below is a complete HTML file that implements a modernized Space Invaders–style game using HTML5 Canvas and JavaScript. This version includes:
- A player ship that can move and shoot.
- Waves of invaders that can be shot.
- When you shoot down an enemy, there’s a chance an upgrade “power-up” will drop.
- Basic explosion effects and particle effects on hit.
- Modern clean code structure using requestAnimationFrame.
To try it out, simply save the code below as an HTML file (for example, space_invaders.html) and open it in your browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Modern Space Invaders Clone</title>
<style>
body {
margin: 0;
background: #000;
overflow: hidden;
}
canvas {
display: block;
background: #111;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script>
/* ---------------------
SETUP THE CANVAS
--------------------- */
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
resizeCanvas();
window.addEventListener('resize', resizeCanvas);
/* ---------------------
GAME VARIABLES
--------------------- */
const keys = {};
const player = {
x: canvas.width / 2,
y: canvas.height - 60,
width: 40,
height: 20,
speed: 7,
cooldown: 0,
upgrade: null // can store current upgrade type
};
const bullets = [];
const alienBullets = [];
const aliens = [];
const alienCols = 10;
const alienRows = 5;
const alienPadding = 20;
const alienSize = 30;
let alienOffsetX = 50;
let alienOffsetY = 50;
let alienDirection = 1;
let alienSpeed = 1;
const upgrades = [];
const particles = [];
let score = 0;
let gameOver = false;
/* ---------------------
UTILITY FUNCTIONS
--------------------- */
function random(min, max) {
return Math.random() * (max - min) + min;
}
function chance(probability) {
return Math.random() < probability;
}
/* ---------------------
EVENT LISTENERS
--------------------- */
window.addEventListener('keydown', (e) => {
keys[e.code] = true;
});
window.addEventListener('keyup', (e) => {
keys[e.code] = false;
});
/* ---------------------
INITIALIZE ALIENS
--------------------- */
function createAliens() {
aliens.length = 0; // clear if restarting
for (let row = 0; row < alienRows; row++) {
for (let col = 0; col < alienCols; col++) {
aliens.push({
x: alienOffsetX + col * (alienSize + alienPadding),
y: alienOffsetY + row * (alienSize + alienPadding),
width: alienSize,
height: alienSize,
alive: true
});
}
}
}
createAliens();
/* ---------------------
GAME LOGIC FUNCTIONS
--------------------- */
function handlePlayer() {
// Movement
if (keys['ArrowLeft'] && player.x - player.speed > 0) {
player.x -= player.speed;
}
if (keys['ArrowRight'] && player.x + player.speed + player.width < canvas.width) {
player.x += player.speed;
}
// Shooting
if (keys['Space'] && player.cooldown <= 0) {
// If player has an upgrade like "triple shot", fire more bullets
if (player.upgrade === 'triple') {
bullets.push({
x: player.x + player.width/2,
y: player.y,
dy: -8,
dx: -2
});
bullets.push({
x: player.x + player.width/2,
y: player.y,
dy: -8,
dx: 0
});
bullets.push({
x: player.x + player.width/2,
y: player.y,
dy: -8,
dx: 2
});
} else {
bullets.push({
x: player.x + player.width/2,
y: player.y,
dy: -8,
dx: 0
});
}
player.cooldown = 15; // frames between shots
}
if (player.cooldown > 0) player.cooldown--;
}
function handleBullets() {
// Player bullets
for (let i = bullets.length - 1; i >= 0; i--) {
let b = bullets[i];
b.y += b.dy;
b.x += b.dx;
// Remove bullet if off-screen
if (b.y < 0 || b.x < 0 || b.x > canvas.width) {
bullets.splice(i, 1);
continue;
}
// Collision with aliens
for (let j = 0; j < aliens.length; j++) {
const alien = aliens[j];
if (!alien.alive) continue;
if (b.x > alien.x && b.x < alien.x + alien.width &&
b.y > alien.y && b.y < alien.y + alien.height) {
alien.alive = false;
bullets.splice(i, 1);
score += 10;
triggerExplosion(alien.x + alien.width/2, alien.y + alien.height/2);
// 20% chance to drop an upgrade
if (chance(0.2)) {
upgrades.push(new Upgrade(alien.x + alien.width/2, alien.y + alien.height/2));
}
break;
}
}
}
// Alien bullets movement (if you want enemies shooting, extend here)
for (let i = alienBullets.length - 1; i >= 0; i--) {
let b = alienBullets[i];
b.y += b.dy;
if (b.y > canvas.height) {
alienBullets.splice(i, 1);
}
}
}
function handleAliens() {
// Determine edges for changing direction
let hitEdge = false;
for (let alien of aliens) {
if (!alien.alive) continue;
if (alien.x + alien.width >= canvas.width || alien.x <= 0) {
hitEdge = true;
break;
}
}
// Update aliens based on direction
for (let alien of aliens) {
if (!alien.alive) continue;
alien.x += alienSpeed * alienDirection;
}
if (hitEdge) {
alienDirection *= -1;
for (let alien of aliens) {
if (alien.alive) {
alien.y += alienSize/2;
}
}
}
// Optional: Have aliens shoot bullets occasionally
for (let alien of aliens) {
if (!alien.alive) continue;
if (chance(0.001)) {
alienBullets.push({
x: alien.x + alien.width/2,
y: alien.y + alien.height,
dy: 4
});
}
// Check if aliens reach the player (game over condition)
if (alien.y + alien.height >= player.y) {
gameOver = true;
}
}
}
function handleUpgrades() {
for (let i = upgrades.length - 1; i >= 0; i--) {
upgrades[i].update();
// Check collision with the player
if (upgrades[i].y + upgrades[i].size > player.y &&
upgrades[i].y < player.y + player.height &&
upgrades[i].x + upgrades[i].size > player.x &&
upgrades[i].x < player.x + player.width) {
// Apply upgrade effect (e.g., triple shot lasts for some time)
player.upgrade = 'triple';
// Remove upgrade and set a timer to remove it later
upgrades.splice(i, 1);
setTimeout(() => {
if (player.upgrade === 'triple') player.upgrade = null;
}, 10000); // lasts for 10 seconds
} else if (upgrades[i].y > canvas.height) {
upgrades.splice(i, 1);
}
}
}
function handleParticles() {
for (let i = particles.length - 1; i >= 0; i--) {
const p = particles[i];
p.x += p.dx;
p.y += p.dy;
p.life -= 1;
if (p.life <= 0) {
particles.splice(i, 1);
}
}
}
function triggerExplosion(x, y) {
// create explosion particles
for (let i = 0; i < 20; i++) {
particles.push({
x: x,
y: y,
dx: random(-3, 3),
dy: random(-3, 3),
life: 30,
color: `hsl(${Math.floor(random(0, 360))}, 100%, 50%)`
});
}
}
/* ---------------------
OBJECT CLASSES
--------------------- */
class Upgrade {
constructor(x, y) {
this.x = x;
this.y = y;
this.size = 20;
this.dy = 2;
this.type = 'triple'; // future expansion: different types
this.color = '#0f0';
}
update() {
this.y += this.dy;
}
draw(ctx) {
ctx.save();
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.x, this.y, this.size/2, 0, Math.PI * 2);
ctx.fill();
ctx.restore();
}
}
/* ---------------------
DRAW FUNCTIONS
--------------------- */
function drawPlayer() {
ctx.save();
ctx.fillStyle = "#00f";
ctx.fillRect(player.x, player.y, player.width, player.height);
// Draw an upgrade indicator if active
if (player.upgrade === 'triple') {
ctx.strokeStyle = "#ff0";
ctx.lineWidth = 3;
ctx.strokeRect(player.x - 5, player.y - 5, player.width + 10, player.height + 10);
}
ctx.restore();
}
function drawBullets() {
ctx.save();
ctx.fillStyle = "#fff";
bullets.forEach(b => {
ctx.beginPath();
ctx.arc(b.x, b.y, 3, 0, Math.PI * 2);
ctx.fill();
});
ctx.restore();
}
function drawAlienBullets() {
ctx.save();
ctx.fillStyle = "#f00";
alienBullets.forEach(b => {
ctx.beginPath();
ctx.arc(b.x, b.y, 5, 0, Math.PI * 2);
ctx.fill();
});
ctx.restore();
}
function drawAliens() {
ctx.save();
aliens.forEach(alien => {
if (!alien.alive) return;
ctx.fillStyle = "#0ff";
ctx.fillRect(alien.x, alien.y, alien.width, alien.height);
});
ctx.restore();
}
function drawUpgrades() {
upgrades.forEach(u => u.draw(ctx));
}
function drawParticles() {
particles.forEach(p => {
ctx.save();
ctx.fillStyle = p.color;
ctx.globalAlpha = Math.max(p.life / 30, 0);
ctx.fillRect(p.x, p.y, 4, 4);
ctx.restore();
});
}
function drawScore() {
ctx.save();
ctx.fillStyle = "#fff";
ctx.font = "20px sans-serif";
ctx.fillText("Score: " + score, 10, 30);
ctx.restore();
}
/* ---------------------
MAIN LOOP
--------------------- */
function gameLoop() {
if (gameOver) {
ctx.save();
ctx.fillStyle = "rgba(0,0,0,0.7)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#fff";
ctx.font = "50px sans-serif";
ctx.textAlign = "center";
ctx.fillText("GAME OVER", canvas.width / 2, canvas.height / 2);
ctx.font = "30px sans-serif";
ctx.fillText("Your Score: " + score, canvas.width / 2, canvas.height / 2 + 50);
ctx.restore();
return;
}
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
handlePlayer();
handleBullets();
handleAliens();
handleUpgrades();
handleParticles();
drawPlayer();
drawBullets();
drawAlienBullets();
drawAliens();
drawUpgrades();
drawParticles();
drawScore();
requestAnimationFrame(gameLoop);
}
gameLoop();
</script>
</body>
</html>
Explanation
-
Canvas Setup:
The canvas is resized to cover the browser window, and we update its dimensions on window resize.
-
Game Entities:
- Player: Moves left/right with arrow keys and fires bullets using the space bar. When the player has the
"triple" upgrade, three bullets are shot with slight spreads.
- Aliens: Arranged in a grid. They move horizontally and drop down when reaching canvas edges.
- Bullets: The player’s shot bullets are checked for collisions with aliens.
- Upgrades: When an alien is hit, there is a chance (20%) that an upgrade will drop, which the player can collect.
- Particles: Simple explosion particles that fade out over time.
-
Game Loop:
The gameLoop() function updates and draws all game entities, and stops the game when an alien reaches the player.
-
Upgrades:
The "triple" upgrade is applied for 10 seconds on collection, temporarily enabling a triple shot.
Feel free to expand or tweak this starting code. You can add more enemy types, effects, sounds, and advanced power-ups to truly modernize the classic Space Invaders feel. Enjoy coding!