Certainly! Let's outline how you can create "Base Battle," a real-time strategy web game with pseudo-3D pixel art graphics. We'll use HTML5, JavaScript, and a pixel art library to implement the game. This guide will cover the core components and provide code snippets to get you started.
Game Overview
Objective: Reduce the enemy base's HP to zero before your base is destroyed.
Key Features:
- Units: Soldiers, Archers, and Heavy units, each with unique stats (cost, speed, health, damage).
- Gold Management: Earn gold by defeating enemies, damaging the enemy base, and passive income.
- AI Opponent: The enemy will deploy units to attack your base.
- UI Elements: Display resources, base health, and unit deployment controls.
Technologies Used
- HTML5 Canvas: For rendering the game graphics.
- JavaScript: For game logic and interactivity.
- Pixel Art Library: Phaser 3 for managing sprites and animations.
Project Setup
1. Create the HTML Structure
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Base Battle</title>
<style>
body { margin: 0; padding: 0; background-color: #333; color: #fff; font-family: Arial, sans-serif; }
#game-container { margin: 0 auto; }
#ui { text-align: center; padding: 10px; }
#controls button { margin: 5px; padding: 10px 20px; }
</style>
</head>
<body>
<div id="game-container"></div>
<div id="ui">
<div id="resources">Gold: 100</div>
<div id="base-health">Your Base HP: 100 | Enemy Base HP: 100</div>
<div id="controls">
<button onclick="spawnUnit('soldier')">Soldier (50 Gold)</button>
<button onclick="spawnUnit('archer')">Archer (70 Gold)</button>
<button onclick="spawnUnit('heavy')">Heavy (100 Gold)</button>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/phaser@3/dist/phaser.js"></script>
<script src="game.js"></script>
</body>
</html>
2. Initialize the Phaser Game
game.js
const config = {
type: Phaser.AUTO,
width: 800,
height: 450,
parent: 'game-container',
physics: {
default: 'arcade',
arcade: { debug: false },
},
scene: [MainScene],
};
const game = new Phaser.Game(config);
3. Create the Main Scene
MainScene.js
class MainScene extends Phaser.Scene {
constructor() {
super('MainScene');
this.playerGold = 100;
this.playerBaseHP = 100;
this.enemyBaseHP = 100;
this.units = [];
this.enemyUnits = [];
}
preload() {
// Load assets
this.load.image('soldier', 'assets/soldier.png');
this.load.image('archer', 'assets/archer.png');
this.load.image('heavy', 'assets/heavy.png');
this.load.image('background', 'assets/background.png');
// ... Load more assets as needed
}
create() {
// Add background
this.add.image(400, 225, 'background');
// Initialize UI
updateUI(this.playerGold, this.playerBaseHP, this.enemyBaseHP);
// Set up input
this.input.on('pointerdown', this.handleInput, this);
// Start spawning enemy units
this.time.addEvent({
delay: 5000,
callback: this.spawnEnemyUnit,
callbackScope: this,
loop: true,
});
// Passive income
this.time.addEvent({
delay: 3000,
callback: this.addPassiveIncome,
callbackScope: this,
loop: true,
});
}
update(time, delta) {
// Update units
this.units.forEach((unit) => unit.update(delta));
this.enemyUnits.forEach((unit) => unit.update(delta));
// Check collisions
this.checkCollisions();
// Update base health
if (this.playerBaseHP <= 0 || this.enemyBaseHP <= 0) {
this.endGame();
}
}
// ... Define methods like spawnUnit, spawnEnemyUnit, checkCollisions, addPassiveIncome, endGame
}
4. Define Unit Classes
Unit.js
class Unit extends Phaser.Physics.Arcade.Sprite {
constructor(scene, x, y, texture, type, isEnemy = false) {
super(scene, x, y, texture);
this.scene = scene;
this.type = type;
this.isEnemy = isEnemy;
this.speed = type.speed * (isEnemy ? -1 : 1);
this.health = type.health;
this.damage = type.damage;
this.range = type.range || 0;
// Enable physics
this.scene.physics.world.enable(this);
this.body.setCollideWorldBounds(true);
// Add to scene
this.scene.add.existing(this);
}
update(delta) {
// Move unit
this.x += this.speed * (delta / 16.6667);
// Attack logic will be handled in MainScene
}
}
5. Implement Unit Spawning
In MainScene.js:
spawnUnit(unitType) {
const type = unitDefinitions[unitType];
if (this.playerGold >= type.cost) {
this.playerGold -= type.cost;
const unit = new Unit(this, 100, 350, unitType, type);
this.units.push(unit);
updateUI(this.playerGold, this.playerBaseHP, this.enemyBaseHP);
} else {
alert('Not enough gold!');
}
}
spawnEnemyUnit() {
const unitTypes = ['soldier', 'archer', 'heavy'];
const unitType = unitTypes[Math.floor(Math.random() * unitTypes.length)];
const type = unitDefinitions[unitType];
const unit = new Unit(this, 700, 350, unitType, type, true);
this.enemyUnits.push(unit);
}
Define Unit Stats:
const unitDefinitions = {
soldier: { cost: 50, speed: 50, health: 100, damage: 10 },
archer: { cost: 70, speed: 40, health: 80, damage: 15, range: 150 },
heavy: { cost: 100, speed: 30, health: 200, damage: 25 },
};
6. Handle User Input
In index.html, modify the buttons:
<button onclick="game.scene.scenes[0].spawnUnit('soldier')">Soldier (50 Gold)</button>
<button onclick="game.scene.scenes[0].spawnUnit('archer')">Archer (70 Gold)</button>
<button onclick="game.scene.scenes[0].spawnUnit('heavy')">Heavy (100 Gold)</button>
7. Update the UI
Create a function updateUI in game.js:
function updateUI(gold, playerBaseHP, enemyBaseHP) {
document.getElementById('resources').innerText = `Gold: ${gold}`;
document.getElementById('base-health').innerText = `Your Base HP: ${playerBaseHP} | Enemy Base HP: ${enemyBaseHP}`;
}
8. Implement Collision Detection and Combat
In MainScene.js:
checkCollisions() {
this.physics.world.collide(this.units, this.enemyUnits, this.handleUnitCollision, null, this);
// Units reaching the enemy base
this.units.forEach((unit) => {
if (unit.x >= 750) {
this.enemyBaseHP -= unit.damage;
unit.destroy();
this.units.splice(this.units.indexOf(unit), 1);
updateUI(this.playerGold, this.playerBaseHP, this.enemyBaseHP);
}
});
// Enemy units reaching the player base
this.enemyUnits.forEach((unit) => {
if (unit.x <= 50) {
this.playerBaseHP -= unit.damage;
unit.destroy();
this.enemyUnits.splice(this.enemyUnits.indexOf(unit), 1);
updateUI(this.playerGold, this.playerBaseHP, this.enemyBaseHP);
}
});
}
handleUnitCollision(unitA, unitB) {
// Only allow one attack per update cycle
if (unitA.lastAttackTime === undefined || this.time.now - unitA.lastAttackTime > 500) {
unitB.health -= unitA.damage;
unitA.lastAttackTime = this.time.now;
if (unitB.health <= 0) {
unitB.destroy();
if (unitB.isEnemy) {
this.enemyUnits.splice(this.enemyUnits.indexOf(unitB), 1);
this.playerGold += 20;
} else {
this.units.splice(this.units.indexOf(unitB), 1);
}
updateUI(this.playerGold, this.playerBaseHP, this.enemyBaseHP);
}
}
// Repeat for unitB attacking unitA
if (unitB.lastAttackTime === undefined || this.time.now - unitB.lastAttackTime > 500) {
unitA.health -= unitB.damage;
unitB.lastAttackTime = this.time.now;
if (unitA.health <= 0) {
unitA.destroy();
if (unitA.isEnemy) {
this.enemyUnits.splice(this.enemyUnits.indexOf(unitA), 1);
this.playerGold += 20;
} else {
this.units.splice(this.units.indexOf(unitA), 1);
}
updateUI(this.playerGold, this.playerBaseHP, this.enemyBaseHP);
}
}
}
9. Add Passive Income
In MainScene.js:
addPassiveIncome() {
this.playerGold += 10;
updateUI(this.playerGold, this.playerBaseHP, this.enemyBaseHP);
}
10. End Game Logic
In MainScene.js:
endGame() {
const message = this.playerBaseHP <= 0 ? 'Game Over! You Lose!' : 'Victory! You Win!';
alert(message);
this.scene.restart();
}
11. Enhance Graphics and Animations
- Spritesheets: Use spritesheets for animated units.
- Animations: Define animations in
preload and create:
this.anims.create({
key: 'soldier_walk',
frames: this.anims.generateFrameNumbers('soldier', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1,
});
- Update Unit Class to Play Animations:
this.play(`${texture}_walk`);
12. Potential Additions
- Upgrades: Implement an upgrade system to enhance unit stats.
- Special Abilities: Add abilities that the player can activate.
- Enemy Variety: Introduce new enemy types with different behaviors.
- Levels: Create multiple levels with increasing difficulty.
- Sound Effects: Use Phaser's audio capabilities to add sounds.
- Difficulty Settings: Allow players to choose difficulty, modifying AI behavior and resource rates.
Final Notes
This guide provides a foundational framework for your game. You will need to expand on these concepts to create a full-featured game:
- AI Enhancements: Develop a more complex AI for enemy unit deployment.
- Balancing: Adjust unit stats and costs for balanced gameplay.
- Performance Optimization: Ensure smooth gameplay on various devices.
- User Experience: Improve UI and controls for better player engagement.
Feel free to ask if you need further assistance or explanations on specific parts of the game development process. Happy coding!