Certainly! Below is an HTML page that implements a basic 3D space shooter game using ASCII graphics. The game features a spaceship that can move and fire lasers at approaching asteroids. The 3D rendering is achieved by projecting 3D coordinates onto a 2D plane and representing them with ASCII characters.
Please note that due to the complexity and performance limitations of rendering real-time 3D graphics with ASCII in a web browser, this implementation is a simplified version to illustrate the concept.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ASCII Space Shooter</title>
<style>
body {
background-color: black;
color: white;
font-family: monospace;
overflow: hidden;
}
#game {
white-space: pre;
font-size: 12px;
line-height: 12px;
}
</style>
</head>
<body>
<div id="game"></div>
<script>
// Game settings
const canvasWidth = 80;
const canvasHeight = 24;
const starCount = 100;
const asteroidCount = 10;
const frameDelay = 50; // milliseconds
// Game state
let stars = [];
let asteroids = [];
let lasers = [];
let score = 0;
let spaceship = { x: 0, y: 0, z: 0 };
// Matrices for projection
const fov = 90; // Field of view
const aspectRatio = canvasWidth / canvasHeight;
const near = 0.1;
const far = 1000;
const fovRad = 1 / Math.tan((fov * 0.5) * (Math.PI / 180));
// Initialize the game
function init() {
spaceship.x = 0;
spaceship.y = 0;
spaceship.z = 0;
// Generate stars
for (let i = 0; i < starCount; i++) {
stars.push({
x: (Math.random() - 0.5) * 100,
y: (Math.random() - 0.5) * 100,
z: Math.random() * 100 + 10
});
}
// Generate asteroids
for (let i = 0; i < asteroidCount; i++) {
asteroids.push({
x: (Math.random() - 0.5) * 50,
y: (Math.random() - 0.5) * 50,
z: Math.random() * 100 + 50
});
}
document.addEventListener('keydown', handleInput);
gameLoop();
}
// Handle user input
function handleInput(e) {
switch (e.key) {
case 'ArrowUp':
spaceship.y -= 1;
break;
case 'ArrowDown':
spaceship.y += 1;
break;
case 'ArrowLeft':
spaceship.x -= 1;
break;
case 'ArrowRight':
spaceship.x += 1;
break;
case ' ':
// Fire laser
lasers.push({
x: spaceship.x,
y: spaceship.y,
z: spaceship.z,
});
break;
}
}
// Project a 3D point to 2D screen coordinates
function project(point) {
const zInverse = 1 / point.z;
return {
x: (point.x * fovRad * aspectRatio) * zInverse * canvasWidth / 2 + canvasWidth / 2,
y: (point.y * fovRad) * zInverse * canvasHeight / 2 + canvasHeight / 2
};
}
// Main game loop
function gameLoop() {
update();
render();
setTimeout(gameLoop, frameDelay);
}
// Update game state
function update() {
// Move stars
for (let star of stars) {
star.z -= 0.5;
if (star.z <= near) {
star.z = Math.random() * 100 + far;
star.x = (Math.random() - 0.5) * 100;
star.y = (Math.random() - 0.5) * 100;
}
}
// Move asteroids
for (let asteroid of asteroids) {
asteroid.z -= 1;
if (asteroid.z <= near) {
asteroid.z = Math.random() * 100 + far;
asteroid.x = (Math.random() - 0.5) * 50;
asteroid.y = (Math.random() - 0.5) * 50;
}
}
// Move lasers
for (let i = lasers.length - 1; i >= 0; i--) {
lasers[i].z += 2;
if (lasers[i].z > far) {
lasers.splice(i, 1);
}
}
// Check collisions
for (let i = asteroids.length - 1; i >= 0; i--) {
let asteroid = asteroids[i];
for (let j = lasers.length - 1; j >= 0; j--) {
let laser = lasers[j];
if (Math.abs(asteroid.x - laser.x) < 1 &&
Math.abs(asteroid.y - laser.y) < 1 &&
Math.abs(asteroid.z - laser.z) < 5) {
// Collision detected
asteroids.splice(i, 1);
lasers.splice(j, 1);
score += 10;
// Spawn new asteroid
asteroids.push({
x: (Math.random() - 0.5) * 50,
y: (Math.random() - 0.5) * 50,
z: Math.random() * 100 + far
});
break;
}
}
}
}
// Render game state
function render() {
let screen = [];
for (let y = 0; y < canvasHeight; y++) {
let row = '';
for (let x = 0; x < canvasWidth; x++) {
row += ' ';
}
screen.push(row.split(''));
}
// Draw stars
for (let star of stars) {
let projected = project(star);
let x = Math.floor(projected.x);
let y = Math.floor(projected.y);
if (x >= 0 && x < canvasWidth && y >= 0 && y < canvasHeight) {
screen[y][x] = '.';
}
}
// Draw asteroids
for (let asteroid of asteroids) {
let projected = project(asteroid);
let x = Math.floor(projected.x);
let y = Math.floor(projected.y);
if (x >= 0 && x < canvasWidth && y >= 0 && y < canvasHeight) {
screen[y][x] = 'O';
}
}
// Draw lasers
for (let laser of lasers) {
let projected = project(laser);
let x = Math.floor(projected.x);
let y = Math.floor(projected.y);
if (x >= 0 && x < canvasWidth && y >= 0 && y < canvasHeight) {
screen[y][x] = '|';
}
}
// Draw spaceship
let projectedShip = project({
x: spaceship.x,
y: spaceship.y,
z: spaceship.z + 5
});
let sx = Math.floor(projectedShip.x);
let sy = Math.floor(projectedShip.y);
if (sx >= 0 && sx < canvasWidth && sy >= 0 && sy < canvasHeight) {
screen[sy][sx] = 'A';
}
// Display on screen
let output = '';
for (let row of screen) {
output += row.join('') + '\n';
}
output += `Score: ${score}`;
document.getElementById('game').textContent = output;
}
// Start the game
init();
</script>
</body>
</html>
Explanation:
-
HTML Structure:
- The game is rendered inside a
<div> with the ID game.
- The body has a black background, white text color, and uses a monospace font to align the ASCII graphics properly.
-
Game State Variables:
stars: An array of star objects for the background.
asteroids: An array of asteroid objects that the player can destroy.
lasers: An array of laser objects representing the projectiles fired by the spaceship.
spaceship: An object representing the player's position in 3D space.
score: The player's current score.
-
Projection Function:
- The
project function converts 3D coordinates to 2D screen coordinates using a simple perspective projection formula.
- It accounts for the field of view (
fov), aspect ratio, and near/far clipping planes.
-
Game Initialization (init function):
- Generates random positions for stars and asteroids within specified ranges.
- Sets up the event listener for user input.
- Starts the game loop.
-
User Input Handling:
- Uses the
keydown event to move the spaceship with arrow keys.
- The spacebar (
' ') fires a laser.
-
Game Loop:
- The
gameLoop function updates the game state and then renders it.
- Uses
setTimeout to control the frame rate (20 frames per second).
-
Updating Game State (update function):
- Moves stars and resets them when they go past the near clipping plane to create a continuous starfield.
- Moves asteroids toward the player; when they pass the player, they're repositioned ahead.
- Moves lasers forward.
- Checks for collisions between lasers and asteroids:
- If a collision is detected, the asteroid and laser are removed.
- The score is incremented.
- A new asteroid is spawned.
-
Rendering (render function):
Controls:
- Arrow Keys: Move the spaceship up, down, left, or right.
- Spacebar: Fire a laser straight ahead.
Note:
- The 3D effect is simulated by moving objects closer to the camera (decreasing their
z value) and projecting their positions onto the 2D screen.
- This is a simplified 3D projection using basic perspective math suitable for an ASCII rendering.
- Performance may vary depending on the browser and computer due to the non-optimized rendering technique.
To Run the Game:
- Copy the entire code above into a text editor.
- Save the file with an
.html extension, for example, ascii_space_shooter.html.
- Open the file in a modern web browser (Chrome, Firefox, Edge).
- Ensure that JavaScript is enabled in your browser settings.
- Use the arrow keys and spacebar to play the game.
Enjoy your ASCII space adventure!