Here's an implementation of the "ASCII Base Battle" game as per your specifications. The game is built using HTML5, CSS, and JavaScript with the Matter.js physics engine to handle movement and collisions.
HTML Code
First, we'll set up the HTML structure, including the canvas, buttons for unit deployment, and displays for gold and health.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ASCII Base Battle</title>
<style>
/* CSS styles go here */
</style>
</head>
<body>
<h1>ASCII Base Battle</h1>
<div id="game-info">
<div>
<strong>Gold: </strong><span id="gold">200</span>
</div>
<div>
<strong>Your Base HP: </strong><span id="player-base-hp">100</span>
</div>
<div>
<strong>Enemy Base HP: </strong><span id="enemy-base-hp">100</span>
</div>
</div>
<div id="controls">
<button id="deploy-soldier">Deploy Soldier (50 Gold)</button>
<button id="deploy-archer">Deploy Archer (75 Gold)</button>
<button id="deploy-heavy">Deploy Heavy Unit (100 Gold)</button>
</div>
<canvas id="game-canvas" width="800" height="400"></canvas>
<!-- Matter.js Physics Engine -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/matter-js/0.19.0/matter.min.js"></script>
<!-- Game Script -->
<script>
// JavaScript code goes here
</script>
</body>
</html>
CSS Code
Add some basic styling to position elements and improve visual clarity.
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
background-color: #222;
color: #fff;
}
#game-info {
margin-bottom: 20px;
}
#controls button {
margin: 5px;
padding: 10px 20px;
font-size: 16px;
}
#game-canvas {
border: 1px solid #555;
background-color: #111;
}
</style>
JavaScript Code
Now, we implement the game logic, including unit classes, game state management, and rendering.
<script>
// 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 Matter.js engine
const engine = Engine.create();
engine.gravity.y = 0; // Disable gravity for horizontal movement
const world = engine.world;
// Game variables
let gold = 200;
let playerBaseHP = 100;
let enemyBaseHP = 100;
const goldElement = document.getElementById('gold');
const playerBaseHPElement = document.getElementById('player-base-hp');
const enemyBaseHPElement = document.getElementById('enemy-base-hp');
const canvas = document.getElementById('game-canvas');
const context = canvas.getContext('2d');
// Unit definitions
const unitTypes = {
'soldier': {
cost: 50,
speed: 2,
health: 30,
damage: 10,
ascii: '>@', // Player unit
enemyAscii: '@<', // Enemy unit
color: '#0f0', // Green for player
enemyColor: '#f00' // Red for enemy
},
'archer': {
cost: 75,
speed: 3,
health: 20,
damage: 20,
ascii: '}-@',
enemyAscii: '@-{',
color: '#0f0',
enemyColor: '#f00'
},
'heavy': {
cost: 100,
speed: 1,
health: 50,
damage: 20,
ascii: '=>@',
enemyAscii: '@<=',
color: '#0f0',
enemyColor: '#f00'
}
};
// Arrays to hold units
let playerUnits = [];
let enemyUnits = [];
// Base representations
const playerBase = {
x: 50,
y: canvas.height / 2,
ascii: '[BASE]',
color: '#0f0'
};
const enemyBase = {
x: canvas.width - 50,
y: canvas.height / 2,
ascii: '[BASE]',
color: '#f00'
};
// Update displayed gold and base HP
function updateStats() {
goldElement.innerText = gold;
playerBaseHPElement.innerText = playerBaseHP;
enemyBaseHPElement.innerText = enemyBaseHP;
}
// Passive gold income
setInterval(() => {
gold += 5;
updateStats();
}, 3000); // Every 3 seconds
// Unit class
class Unit {
constructor(type, isPlayer) {
this.type = type;
this.isPlayer = isPlayer;
this.health = type.health;
this.damage = type.damage;
this.speed = type.speed * (isPlayer ? 1 : -1); // Negative speed for enemy
this.ascii = isPlayer ? type.ascii : type.enemyAscii;
this.color = isPlayer ? type.color : type.enemyColor;
// Create a Matter.js body for physics
this.body = Bodies.rectangle(
isPlayer ? playerBase.x + 30 : enemyBase.x - 30,
Math.random() * (canvas.height - 100) + 50, // Random y position
20,
20,
{
isSensor: true,
collisionFilter: {
group: isPlayer ? -1 : -2
}
}
);
World.add(world, this.body);
}
update() {
// Move the unit
Body.setVelocity(this.body, { x: this.speed, y: 0 });
}
draw() {
const pos = this.body.position;
context.fillStyle = this.color;
context.fillText(this.ascii, pos.x, pos.y);
}
takeDamage(amount) {
this.health -= amount;
}
}
// Deploy unit functions
function deployUnit(unitName) {
const unitType = unitTypes[unitName];
if (gold >= unitType.cost) {
gold -= unitType.cost;
const unit = new Unit(unitType, true);
playerUnits.push(unit);
updateStats();
}
}
// AI deploy units
function enemyDeployUnit() {
// Simple AI that deploys random units
const unitNames = Object.keys(unitTypes);
const unitName = unitNames[Math.floor(Math.random() * unitNames.length)];
const unitType = unitTypes[unitName];
const unit = new Unit(unitType, false);
enemyUnits.push(unit);
}
// Set AI deployment interval
setInterval(enemyDeployUnit, 4000); // Every 4 seconds
// Handle unit collisions
Events.on(engine, 'collisionStart', function(event) {
const pairs = event.pairs;
pairs.forEach(pair => {
const bodyA = pair.bodyA;
const bodyB = pair.bodyB;
let unitA = getUnitByBody(bodyA);
let unitB = getUnitByBody(bodyB);
if (unitA && unitB && unitA.isPlayer !== unitB.isPlayer) {
// Units engage in combat
unitA.takeDamage(unitB.damage);
unitB.takeDamage(unitA.damage);
// Check for unit destruction
if (unitA.health <= 0) {
removeUnit(unitA);
gold += unitA.isPlayer ? 0 : 10; // Earn gold for destroying enemy
updateStats();
}
if (unitB.health <= 0) {
removeUnit(unitB);
gold += unitB.isPlayer ? 0 : 10;
updateStats();
}
} else {
// Unit vs Base collision
if (unitA && !unitB) {
handleBaseCollision(unitA);
}
if (unitB && !unitA) {
handleBaseCollision(unitB);
}
}
});
});
function getUnitByBody(body) {
return [...playerUnits, ...enemyUnits].find(unit => unit.body === body);
}
function removeUnit(unit) {
World.remove(world, unit.body);
if (unit.isPlayer) {
playerUnits = playerUnits.filter(u => u !== unit);
} else {
enemyUnits = enemyUnits.filter(u => u !== unit);
}
}
// Handle units reaching the enemy base
function handleBaseCollision(unit) {
if (unit.isPlayer && unit.body.position.x >= enemyBase.x - 20) {
// Damage enemy base
enemyBaseHP -= unit.damage;
gold += 20; // Gold for damaging the base
removeUnit(unit);
updateStats();
checkGameOver();
} else if (!unit.isPlayer && unit.body.position.x <= playerBase.x + 20) {
// Damage player base
playerBaseHP -= unit.damage;
removeUnit(unit);
updateStats();
checkGameOver();
}
}
// Check for game over condition
function checkGameOver() {
if (playerBaseHP <= 0) {
alert('Your base has been destroyed! Game Over.');
window.location.reload();
}
if (enemyBaseHP <= 0) {
alert('Enemy base has been destroyed! You Win!');
window.location.reload();
}
}
// Rendering
function render() {
context.clearRect(0, 0, canvas.width, canvas.height);
// Draw bases
context.fillStyle = playerBase.color;
context.fillText(playerBase.ascii, playerBase.x, playerBase.y);
context.fillStyle = enemyBase.color;
context.fillText(enemyBase.ascii, enemyBase.x - 40, enemyBase.y);
// Draw units
playerUnits.forEach(unit => {
unit.draw();
});
enemyUnits.forEach(unit => {
unit.draw();
});
}
// Game loop
function gameLoop() {
Engine.update(engine);
// Update units
playerUnits.forEach(unit => {
unit.update();
});
enemyUnits.forEach(unit => {
unit.update();
});
render();
requestAnimationFrame(gameLoop);
}
// Start the game loop
gameLoop();
// Event listeners for unit deployment
document.getElementById('deploy-soldier').addEventListener('click', () => deployUnit('soldier'));
document.getElementById('deploy-archer').addEventListener('click', () => deployUnit('archer'));
document.getElementById('deploy-heavy').addEventListener('click', () => deployUnit('heavy'));
// Initialize the game stats
updateStats();
</script>
Explanation
-
HTML Structure: The HTML defines the game's canvas, buttons for deploying units, and displays for current gold and base health.
-
CSS Styling: Basic styles are applied to center the content, set background colors, and style buttons and text for better visual appeal.
-
JavaScript Logic:
- Matter.js Setup: The physics engine is initialized without gravity to allow horizontal movement.
- Game Variables: Gold, base health, unit definitions, and arrays to hold player and enemy units are initialized.
- Unit Class: Defines the properties and behaviors of units, including movement (
update method), rendering (draw method), and taking damage.
- Deploying Units: Functions to deploy player units are linked to button clicks. The AI deploys units at regular intervals.
- Collision Handling: The
collisionStart event detects when units collide and processes combat interactions.
- Base Interaction: When units reach the enemy base, they inflict damage, and the unit is removed from the game.
- Rendering: The
render function draws the bases and units on the canvas using ASCII art.
- Game Loop:
gameLoop updates the physics engine, unit positions, and renders the game frame by frame.
- Event Listeners: Buttons are connected to deploy functions, and the game stats are updated accordingly.
- Game Over Conditions: The game checks for base destruction and displays an alert when the game ends.
Additional Notes
- Passive Gold Income: Implemented using
setInterval to add gold every few seconds.
- AI Behavior: The AI randomly selects unit types to deploy at fixed intervals.
- Unit Interaction: Units deal damage upon collision, and health bars can be added for visual feedback.
- ASCII Art: Units and bases are represented using ASCII characters, with color coding to distinguish sides.
Running the Game
To run the game:
- Save the HTML, CSS, and JavaScript code into a single
.html file.
- Open the file in a modern web browser (e.g., Chrome, Firefox).
- The game will start automatically, and you can deploy units using the buttons.
Potential Enhancements
- Health Bars: Add small bars or numbers above units to display their remaining health.
- Upgrades and Special Abilities: Implement features to upgrade units or activate special abilities.
- Sound Effects: Incorporate audio for a more immersive experience.
- Difficulty Levels: Adjust AI behavior or provide difficulty settings for the player.
- Instructions and Pause Functionality: Add a help section and allow the player to pause the game.
Conclusion
This implementation provides a functional ASCII-based real-time strategy game that meets the core requirements specified. It can serve as a foundation for further development and enhancements to create a more engaging and complex game.