Certainly! Below is a simple HTML game where two bases send armies against one another using ASCII art. The user plays against an AI, and the game continues until either base is destroyed. We'll use JavaScript alongside the HTML5 Canvas for rendering and the Matter.js physics engine for handling collisions and smooth movements.
HTML File (index.html):
<!DOCTYPE html>
<html>
<head>
<title>ASCII Army Battle Game</title>
<style>
body {
text-align: center;
background-color: #222;
color: #fff;
font-family: monospace;
}
canvas {
border: 1px solid #555;
background-color: #333;
display: block;
margin: 0 auto;
}
#controls {
margin-top: 10px;
}
button {
padding: 10px 20px;
font-size: 16px;
font-family: monospace;
}
</style>
</head>
<body>
<h1>ASCII Army Battle Game</h1>
<canvas id="gameCanvas" width="800" height="400"></canvas>
<div id="controls">
<button id="sendUnitBtn">Send Unit</button>
</div>
<!-- Include Matter.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.17.1/matter.min.js"></script>
<!-- Include the game script -->
<script src="game.js"></script>
</body>
</html>
Explanation:
- We set up a basic HTML page with a canvas element where the game will be rendered.
- A "Send Unit" button allows the player to send units from their base.
- The Matter.js library is included via CDN to handle physics and collisions.
- The
game.js script contains the game's logic.
JavaScript File (game.js):
// game.js
// Module aliases for Matter.js
const Engine = Matter.Engine,
Render = Matter.Render,
World = Matter.World,
Bodies = Matter.Bodies,
Body = Matter.Body,
Events = Matter.Events;
// Create the physics engine
const engine = Engine.create();
const world = engine.world;
// Create the renderer
const render = Render.create({
canvas: document.getElementById('gameCanvas'),
engine: engine,
options: {
width: 800,
height: 400,
wireframes: false, // We'll handle drawing manually
background: '#333'
}
});
// Base properties
const baseWidth = 50;
const baseHeight = 200;
let playerBaseHealth = 100;
let aiBaseHealth = 100;
// Create bases
const playerBase = Bodies.rectangle(50, 200, baseWidth, baseHeight, { isStatic: true, label: 'playerBase' });
const aiBase = Bodies.rectangle(750, 200, baseWidth, baseHeight, { isStatic: true, label: 'aiBase' });
// Add bases to the world
World.add(world, [playerBase, aiBase]);
// Arrays to keep track of units
let playerUnits = [];
let aiUnits = [];
// ASCII rendering function
function draw() {
const context = render.context;
context.clearRect(0, 0, render.options.width, render.options.height);
// Draw bases
context.fillStyle = '#aaa';
context.font = '20px monospace';
// Player Base
context.fillText('[BASE]', playerBase.position.x - 30, playerBase.position.y + 10);
context.fillText(`HP: ${playerBaseHealth}`, playerBase.position.x - 40, playerBase.position.y + 40);
// AI Base
context.fillText('[BASE]', aiBase.position.x - 30, aiBase.position.y + 10);
context.fillText(`HP: ${aiBaseHealth}`, aiBase.position.x - 20, aiBase.position.y + 40);
// Draw player units
context.fillStyle = '#0f0';
playerUnits.forEach(unit => {
context.fillText('>@', unit.position.x - 10, unit.position.y + 5);
});
// Draw AI units
context.fillStyle = '#f00';
aiUnits.forEach(unit => {
context.fillText('@<', unit.position.x - 10, unit.position.y + 5);
});
requestAnimationFrame(draw);
}
// Function to create a unit
function createUnit(x, y, isPlayer) {
let unit = Bodies.rectangle(x, y, 20, 20, {
label: isPlayer ? 'playerUnit' : 'aiUnit',
isSensor: true, // So units don't physically block each other
collisionFilter: {
group: isPlayer ? -1 : -2 // So units from the same side don't collide
}
});
// Set unit velocity towards the enemy base
const speed = isPlayer ? 2 : -2;
Body.setVelocity(unit, { x: speed, y: 0 });
// Add unit to appropriate array and to the world
if (isPlayer) {
playerUnits.push(unit);
} else {
aiUnits.push(unit);
}
World.add(world, unit);
}
// Player sends a unit when the button is clicked
document.getElementById('sendUnitBtn').addEventListener('click', () => {
createUnit(100, 200, true);
});
// AI sends units at intervals
setInterval(() => {
createUnit(700, 200, false);
}, 3000); // Every 3 seconds
// Collision handling
Events.on(engine, 'collisionStart', event => {
let pairs = event.pairs;
pairs.forEach(pair => {
const labels = [pair.bodyA.label, pair.bodyB.label];
// Unit vs Unit collision
if (labels.includes('playerUnit') && labels.includes('aiUnit')) {
// Remove both units upon collision
removeUnit(pair.bodyA);
removeUnit(pair.bodyB);
}
// Player Unit reaches AI base
if (labels.includes('playerUnit') && labels.includes('aiBase')) {
aiBaseHealth -= 10;
removeUnit(pair.bodyA);
checkGameOver();
}
// AI Unit reaches Player base
if (labels.includes('aiUnit') && labels.includes('playerBase')) {
playerBaseHealth -= 10;
removeUnit(pair.bodyA);
checkGameOver();
}
});
});
// Function to remove units from the world and arrays
function removeUnit(unit) {
if (unit.label === 'playerUnit') {
playerUnits = playerUnits.filter(u => u !== unit);
} else if (unit.label === 'aiUnit') {
aiUnits = aiUnits.filter(u => u !== unit);
}
World.remove(world, unit);
}
// Check for game over
function checkGameOver() {
if (playerBaseHealth <= 0) {
alert('Defeat! Your base has been destroyed.');
restartGame();
} else if (aiBaseHealth <= 0) {
alert('Victory! You have destroyed the enemy base.');
restartGame();
}
}
// Restart the game
function restartGame() {
// Reset health
playerBaseHealth = 100;
aiBaseHealth = 100;
// Remove all units
playerUnits.forEach(unit => World.remove(world, unit));
aiUnits.forEach(unit => World.remove(world, unit));
playerUnits = [];
aiUnits = [];
}
// Run the engine and renderer
Engine.run(engine);
Render.run(render);
// Start drawing
draw();
Explanation:
-
Game Setup:
- We create the physics engine and renderer using Matter.js.
- The player's base and AI base are added to the world as static bodies.
- Health for both bases is initialized to 100.
-
Unit Creation:
- The
createUnit function generates a unit at a specified position for either the player or the AI.
- Units are added to the world and assigned a velocity towards the enemy base.
- Units are stored in arrays to keep track of them.
-
User Interaction:
- The player can send a unit by clicking the "Send Unit" button.
- The AI automatically sends units every 3 seconds using
setInterval.
-
Collision Handling:
- The
collisionStart event listens for collisions between bodies.
- When units from opposite sides collide, both are removed from the game.
- If a unit reaches the enemy base, it decreases the base's health by 10 and is removed.
- The
checkGameOver function checks if a base's health has reached zero and restarts the game if necessary.
-
Drawing the Game:
- Instead of using Matter.js's default renderer, we manually draw the game elements using the canvas context (
context).
- The bases and units are represented using ASCII art:
- Bases are shown as
[BASE] with their remaining health.
- Player units are displayed as
>@, moving towards the right.
- AI units are displayed as
@<, moving towards the left.
- The
draw function updates the canvas every frame using requestAnimationFrame.
-
Restarting the Game:
- When the game ends, an alert is shown to the player.
- The
restartGame function resets the base health and removes all units from the world and arrays.
Notes:
Running the Game:
-
Create the Files:
- Save the HTML code as
index.html.
- Save the JavaScript code as
game.js in the same directory.
-
Open in Browser:
- Open
index.html in a modern web browser (e.g., Chrome, Firefox).
-
Gameplay:
- Click the "Send Unit" button to deploy units from your base.
- Units will automatically move towards the enemy base.
- The AI will send units every few seconds.
- The game ends when either base's health reaches zero.
Visual Example:
- Player Base and Units: Displayed on the left side, units move right.
- AI Base and Units: Displayed on the right side, units move left.
- ASCII Characters:
- Player Unit:
>@
- AI Unit:
@<
- Bases:
[BASE]
Enjoy battling against the AI in this simple ASCII art game! Feel free to customize and expand upon this code to add more features and improve the gameplay experience.