Creating a simple space shooter game using JavaScript can be a fun and educational project. Below is a detailed implementation of such a game.
HTML
First, create an HTML file to host the game. This file sets up the basic structure of the webpage, including the canvas element where the game will be rendered. The HTML file also includes a link to the external JavaScript file that contains the game logic.
html<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Space Shooter Game</title>
<style>
body {
margin: 0;
overflow: hidden;
}
canvas {
display: block;
background: black;
}
</style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script src="game.js"></script>
</body>
</html>
JavaScript (game.js)
Now, create the game.js
file. This file contains all the logic for rendering the game, handling user input, and updating the game state.
javascriptconst canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const spaceship = {
x: canvas.width / 2,
y: canvas.height - 60,
width: 50,
height: 50,
dx: 5,
bullets: []
};
const enemies = [];
const keys = {};
document.addEventListener('keydown', (e) => keys[e.key] = true);
document.addEventListener('keyup', (e) => keys[e.key] = false);
function createEnemy() {
const x = Math.random() * (canvas.width - 50);
enemies.push({ x: x, y: 0, width: 50, height: 50, dy: 2 });
}
function drawSpaceship() {
ctx.fillStyle = 'white';
ctx.fillRect(spaceship.x, spaceship.y, spaceship.width, spaceship.height);
}
function drawBullet(bullet) {
ctx.fillStyle = 'red';
ctx.fillRect(bullet.x, bullet.y, bullet.width, bullet.height);
}
function drawEnemy(enemy) {
ctx.fillStyle = 'green';
ctx.fillRect(enemy.x, enemy.y, enemy.width, enemy.height);
}
function moveSpaceship() {
if (keys['ArrowLeft'] && spaceship.x > 0) {
spaceship.x -= spaceship.dx;
}
if (keys['ArrowRight'] && spaceship.x + spaceship.width < canvas.width) {
spaceship.x += spaceship.dx;
}
if (keys[' '] && spaceship.bullets.length < 5) {
spaceship.bullets.push({ x: spaceship.x + spaceship.width / 2 - 2.5, y: spaceship.y, width: 5, height: 10, dy: 7 });
}
}
function moveBullets() {
for (let i = 0; i < spaceship.bullets.length; i++) {
const bullet = spaceship.bullets[i];
bullet.y -= bullet.dy;
if (bullet.y < 0) {
spaceship.bullets.splice(i, 1);
i--;
}
}
}
function moveEnemies() {
for (let i = 0; i < enemies.length; i++) {
const enemy = enemies[i];
enemy.y += enemy.dy;
if (enemy.y > canvas.height) {
enemies.splice(i, 1);
i--;
}
}
}
function checkCollisions() {
for (let i = 0; i < spaceship.bullets.length; i++) {
const bullet = spaceship.bullets[i];
for (let j = 0; j < enemies.length; j++) {
const enemy = enemies[j];
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) {
spaceship.bullets.splice(i, 1);
enemies.splice(j, 1);
i--;
break;
}
}
}
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawSpaceship();
spaceship.bullets.forEach(drawBullet);
enemies.forEach(drawEnemy);
moveSpaceship();
moveBullets();
moveEnemies();
checkCollisions();
requestAnimationFrame(update);
}
setInterval(createEnemy, 1000);
update();
Explanation of the Code
The canvas
element is initialized to cover the full width and height of the browser window. The spaceship object contains properties for its position, size, speed, and an array to store bullets. The enemies array will store enemy objects. Key event listeners are added to track which keys are pressed to control the spaceship.
The createEnemy
function creates a new enemy at a random x position and adds it to the enemies array. The drawing functions (drawSpaceship
, drawBullet
, and drawEnemy
) render the spaceship, bullets, and enemies on the canvas.
The movement functions (moveSpaceship
, moveBullets
, and moveEnemies
) handle the movement logic for the spaceship, bullets, and enemies. The checkCollisions
function checks for collisions between bullets and enemies. If a collision is detected, the bullet and enemy are removed from their respective arrays.
The update
function clears the canvas and redraws the spaceship, bullets, and enemies. It also moves the spaceship, bullets, and enemies, and checks for collisions. This function is called recursively using requestAnimationFrame
to create the game loop. The setInterval(createEnemy, 1000)
call creates a new enemy every second.
By saving the HTML and JavaScript code in their respective files (index.html
and game.js
), you can open the HTML file in a web browser to play the game. Use the left and right arrow keys to move the spaceship and the spacebar to shoot bullets. Enemies will appear at random positions at the top of the screen and move downwards. The goal is to shoot the enemies before they reach the bottom of the screen.
Leave a Reply