Sure! Below is a simple 2D space shooter game implemented in a single HTML file using HTML5 Canvas and JavaScript. This game includes a player-controlled ship, enemy ships, shooting mechanics, collision detection, and basic scoring. You can copy the following code into a file (e.g., space_game.html) and open it in your web browser to play.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2D Space Shooter Game</title>
<style>
body {
margin: 0;
background: black;
overflow: hidden;
color: white;
font-family: Arial, sans-serif;
}
#gameCanvas {
display: block;
margin: 0 auto;
background: #000;
}
#score {
position: absolute;
top: 10px;
left: 50%;
transform: translateX(-50%);
font-size: 20px;
z-index: 1;
}
</style>
</head>
<body>
<div id="score">Score: 0</div>
<canvas id="gameCanvas" width="800" height="600"></canvas>
<script>
// Get Canvas and Context
const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
// Game Variables
let score = 0;
const keys = {};
const player = {
x: canvas.width / 2 - 25,
y: canvas.height - 60,
width: 50,
height: 50,
speed: 5,
color: 'white',
bullets: []
};
const enemies = [];
const enemyFrequency = 60; // Frames between enemy spawn
let frameCount = 0;
// Handle Keyboard Input
document.addEventListener('keydown', (e) => {
keys[e.code] = true;
});
document.addEventListener('keyup', (e) => {
keys[e.code] = false;
});
// Bullet Class
class Bullet {
constructor(x, y, dy, color) {
this.x = x;
this.y = y;
this.radius = 5;
this.dy = dy;
this.color = color;
}
update() {
this.y += this.dy;
}
draw() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
ctx.fillStyle = this.color;
ctx.fill();
ctx.closePath();
}
}
// Enemy Class
class Enemy {
constructor(x, y, dy, color) {
this.x = x;
this.y = y;
this.width = 40;
this.height = 40;
this.dy = dy;
this.color = color;
}
update() {
this.y += this.dy;
}
draw() {
ctx.fillStyle = this.color;
ctx.fillRect(this.x, this.y, this.width, this.height);
}
}
// Handle Player Movement
function movePlayer() {
if (keys['ArrowLeft'] && player.x > 0) {
player.x -= player.speed;
}
if (keys['ArrowRight'] && player.x + player.width < canvas.width) {
player.x += player.speed;
}
if (keys['ArrowUp'] && player.y > 0) {
player.y -= player.speed;
}
if (keys['ArrowDown'] && player.y + player.height < canvas.height) {
player.y += player.speed;
}
}
// Handle Shooting
function handleShooting() {
if (keys['Space']) {
// Limit the rate of fire
if (!player.lastShot || frameCount - player.lastShot > 15) {
const bullet = new Bullet(player.x + player.width / 2, player.y, -7, 'yellow');
player.bullets.push(bullet);
player.lastShot = frameCount;
}
}
}
// Spawn Enemies
function spawnEnemies() {
if (frameCount % enemyFrequency === 0) {
const x = Math.random() * (canvas.width - 40);
const enemy = new Enemy(x, -40, 2, 'red');
enemies.push(enemy);
}
}
// Detect Collision between Bullet and Enemy
function detectCollisions() {
player.bullets.forEach((bullet, bIndex) => {
enemies.forEach((enemy, eIndex) => {
if (
bullet.x > enemy.x &&
bullet.x < enemy.x + enemy.width &&
bullet.y > enemy.y &&
bullet.y < enemy.y + enemy.height
) {
// Remove enemy and bullet
enemies.splice(eIndex, 1);
player.bullets.splice(bIndex, 1);
score += 10;
document.getElementById('score').innerText = `Score: ${score}`;
}
});
});
// Remove enemies that are off-screen
enemies.forEach((enemy, index) => {
if (enemy.y > canvas.height) {
enemies.splice(index, 1);
}
});
// Remove bullets that are off-screen
player.bullets.forEach((bullet, index) => {
if (bullet.y < 0) {
player.bullets.splice(index, 1);
}
});
}
// Draw Player
function drawPlayer() {
ctx.fillStyle = player.color;
ctx.fillRect(player.x, player.y, player.width, player.height);
}
// Update Bullets
function updateBullets() {
player.bullets.forEach((bullet) => {
bullet.update();
bullet.draw();
});
}
// Update Enemies
function updateEnemies() {
enemies.forEach((enemy) => {
enemy.update();
enemy.draw();
});
}
// Game Loop
function gameLoop() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
movePlayer();
handleShooting();
spawnEnemies();
detectCollisions();
drawPlayer();
updateBullets();
updateEnemies();
frameCount++;
requestAnimationFrame(gameLoop);
}
// Start the Game
gameLoop();
</script>
</body>
</html>
How to Play
- Movement: Use the arrow keys to move your ship up, down, left, and right.
- Shooting: Press the Spacebar to shoot bullets upwards to destroy enemy ships.
- Objective: Destroy as many enemy ships as possible to increase your score. Avoid letting enemies reach the bottom of the screen.
Game Features
- Player Ship: Represented by a white square that can move in all four directions.
- Enemies: Red squares that spawn at the top and move downward.
- Bullets: Yellow circles that the player can shoot to destroy enemies.
- Collision Detection: Detects when a bullet hits an enemy, removes both, and increments the score.
- Scoring: Displays the current score at the top center of the screen.
- Responsive Controls: Smooth movement and shooting mechanics for responsive gameplay.
Customization
You can further customize and enhance the game by adding features such as:
- Lives and Game Over: Implement a lives system and display a game over screen when all lives are lost.
- Different Enemy Types: Introduce various enemies with different speeds and behaviors.
- Power-Ups: Add power-ups that grant temporary abilities like rapid fire or shields.
- Sound Effects and Music: Incorporate audio to enhance the gaming experience.
- Graphics Enhancements: Replace simple shapes with images or sprites for a more polished look.
Feel free to modify the code to add more features and make the game more engaging. Have fun coding and playing your 2D space shooter game!