<script type="importmap">
{
"imports": {
"three": "https://unpkg.com/three@0.160.0/build/three.module.js",
"three/addons/": "https://unpkg.com/three@0.160.0/examples/jsm/"
}
}
</script>
<script type="module">
import * as THREE from 'three';
</script>
<script>
// PASTE nipplejs minified source code here
</script>
-->
<!-- *** Game Logic *** -->
<script>
// --- Constants ---
const FACTION = { RED: 1, BLUE: 2, BLACK: 3};
const UNIT_TYPE = { WARRIOR: 'Warrior', MAGE: 'Mage', HEALER: 'Healer', PRIEST: 'Priest', BLOOD_FAIRY: 'BloodFairy', STEALTH_ARCHER: 'StealthArcher' };
const UNIT_COLOR = { [FACTION.RED]: 0xff0000, [FACTION.BLUE]: 0x0000ff, [FACTION.BLACK]: 0x008800};
const PLAYER_FACTION = FACTION.BLACK;
const STEALTH_DELAY = 50; // ms
const STEALTH_ARCHER_RE_STEALTH_DELAY = 2000; // ms
const AOE_RADIUS_PX = 400; // For effect display - will need conversion to 3D units
const AOE_DAMAGE = 400;
const RESURRECT_LIMIT = 995; // Max Stealth Archers
// --- Global Variables ---
let scene, camera, renderer, clock, sceneContainer;
let player = null;
const units = [];
let joystick = null;
let moveVector = { x: 0, y: 0 };
let targetUnit = null;
let resurrectedCount = 0; // Counter for Stealth Archers
// UI Elements
let targetIndicator, aoeIndicator;
// --- Helper Functions ---
function getDistance(unitA, unitB) {
if (!unitA?.mesh || !unitB?.mesh) return Infinity;
return unitA.mesh.position.distanceTo(unitB.mesh.position);
}
function getScreenPosition(worldPosition, camera, renderer) {
const vector = worldPosition.clone().project(camera);
vector.x = (vector.x + 1) / 2 * renderer.domElement.clientWidth;
vector.y = -(vector.y - 1) / 2 * renderer.domElement.clientHeight;
return vector; // Returns {x, y, z} - z is depth but x,y are screen coords
}
function worldUnitsToPixels(worldDistance, camera, renderer) {
// This is an approximation and depends heavily on camera settings (FOV, position)
// A proper calculation involves projecting two points and finding the pixel distance.
// For a rough start, assume a fixed scaling or use a simpler method for UI effects.
// Let's use a placeholder scaling factor - ADJUST THIS BASED ON YOUR CAMERA SETUP
const APPROX_PIXELS_PER_WORLD_UNIT = 50; // Highly dependent on camera zoom/FOV
return worldDistance * APPROX_PIXELS_PER_WORLD_UNIT;
}
function pixelsToWorldUnits(pixelDistance, camera, renderer) {
// Inverse of the above approximation
const APPROX_PIXELS_PER_WORLD_UNIT = 50; // Must match the other function
return pixelDistance / APPROX_PIXELS_PER_WORLD_UNIT;
}
// --- Base Unit Class ---
class Unit {
constructor(faction, type, stats, position = new THREE.Vector3(0, 0.5, 0)) {
this.id = THREE.MathUtils.generateUUID();
this.faction = faction;
this.type = type;
this.stats = {
maxHp: 100,
hp: 100,
attackDamage: 10,
attackRange: 1.5, // World units
attackSpeed: 1.0, // Attacks per second
moveSpeed: 2.0, // World units per second
healPower: 15,
aoeDamage: 0,
aoeRadius: 0,
stealth: false,
buffs: [], // { type: 'damage_boost', value: 0.15, duration: 10 }
...stats // Override defaults
};
this.isAlive = true;
this.target = null;
this.state = 'idle'; // idle, moving, attacking, healing, following, dead, stealth
this.attackCooldown = 0;
this.lastActionTime = Date.now(); // For stealth timer
this.stealthTimer = null;
// 3D Representation (Simple Cube for now)
const geometry = new THREE.BoxGeometry(0.5, 1.3, 0.5); // Adjust size as needed
const material = new THREE.MeshStandardMaterial({ color: UNIT_COLOR[this.faction] });
this.mesh = new THREE.Mesh(geometry, material);
this.mesh.position.copy(position);
this.mesh.userData.unit = this; // Link mesh back to unit object
scene.add(this.mesh);
units.push(this);
// Simple health bar (optional - could be done in UI layer too)
// TODO: Add 3D health bar if desired
}
update(deltaTime) {
if (!this.isAlive) return;
this.attackCooldown = Math.max(0, this.attackCooldown - deltaTime);
this.updateBuffs(deltaTime);
this.updateStealth();
// Basic AI / State Machine
switch (this.state) {
case 'idle':
this.findTarget();
if (this.target) {
this.state = this.shouldAttack(this.target) ? 'attacking' : 'moving';
} else if (this.faction === PLAYER_FACTION && this !== player) {
this.state = 'following'; // Black team follows player
}
break;
case 'moving':
if (!this.target || !this.target.isAlive) {
this.state = 'idle';
break;
}
const distance = getDistance(this, this.target);
if (distance <= this.getStat('attackRange')) {
this.state = 'attacking';
this.mesh.lookAt(this.target.mesh.position); // Stop and look
} else {
this.moveTowards(this.target.mesh.position, deltaTime);
}
break;
case 'attacking':
if (!this.target || !this.target.isAlive) {
this.state = 'idle';
break;
}
const attackDist = getDistance(this, this.target);
if (attackDist > this.getStat('attackRange')) {
this.state = 'moving';
} else {
this.mesh.lookAt(this.target.mesh.position);
this.performAttack(deltaTime);
}
break;
case 'following':
if (this === player) { // Player shouldn't be following
this.state = 'idle';
break;
}
const followDist = getDistance(this, player);
const followThreshold = 3.0; // How close to stay
if (followDist > followThreshold) {
this.moveTowards(player.mesh.position, deltaTime);
} else {
// Optionally look for targets while following
this.findTarget();
if (this.target) {
this.state = this.shouldAttack(this.target) ? 'attacking' : 'moving';
} else {
// Stay idle near player if no target
}
}
break;
case 'healing': // Specific logic for Healer/Priest
// TODO
break;
case 'buffing': // Specific logic for Priest
// TODO
break;
case 'stealth':
// Can still move/follow while stealthed
if (this.faction === PLAYER_FACTION && this !== player) {
const followDistStealth = getDistance(this, player);
if (followDistStealth > 3.0) {
this.moveTowards(player.mesh.position, deltaTime);
}
}
// Break stealth if attacking or attacked (handled elsewhere)
break;
}
}
getStat(statName) {
let baseValue = this.stats[statName] || 0;
let multiplier = 1;
// Apply buffs
this.stats.buffs.forEach(buff => {
// Example: { type: 'damage_boost', value: 0.15 }
// Example: { type: 'range_boost_perc', value: 0.20 }
if (statName === 'attackDamage' && buff.type === 'damage_boost') multiplier += buff.value;
if (statName === 'attackRange' && buff.type === 'range_boost_perc') multiplier += buff.value;
if (statName === 'attackSpeed' && buff.type === 'speed_boost_perc') multiplier += buff.value;
// Add more buff types
});
// Apply stealth bonus for Stealth Archers
if (this.stats.stealth && this.type === UNIT_TYPE.STEALTH_ARCHER) {
if (statName === 'attackDamage') multiplier += 0.50;
if (statName === 'attackRange') multiplier += 0.50;
}
return baseValue * multiplier;
}
updateBuffs(deltaTime) {
this.stats.buffs = this.stats.buffs.filter(buff => {
buff.duration -= deltaTime;
return buff.duration > 0;
});
// TODO: Recalculate stats if needed after buffs expire
}
updateStealth() {
const canStealth = (this === player || this.type === UNIT_TYPE.STEALTH_ARCHER);
if (!canStealth || !this.isAlive || this.state === 'attacking') {
this.breakStealth();
return;
}
const delay = (this.type === UNIT_TYPE.STEALTH_ARCHER) ? STEALTH_ARCHER_RE_STEALTH_DELAY : STEALTH_DELAY;
if (!this.stats.stealth && (Date.now() - this.lastActionTime > delay)) {
this.applyStealth();
}
}
applyStealth() {
if (this.stats.stealth || !this.isAlive) return;
const canStealth = (this === player || this.type === UNIT_TYPE.STEALTH_ARCHER);
if (!canStealth) return;
console.log(`${this.type} ${this.id} entering stealth`);
this.stats.stealth = true;
this.mesh.material.opacity = 0.3; // Visual indicator
this.mesh.material.transparent = true;
this.state = 'stealth';
}
breakStealth() {
if (!this.stats.stealth) return;
console.log(`${this.type} ${this.id} breaking stealth`);
this.stats.stealth = false;
this.mesh.material.opacity = 1.0;
this.mesh.material.transparent = false;
this.lastActionTime = Date.now(); // Reset timer
if(this.state === 'stealth') this.state = 'idle'; // Go back to idle if not doing anything else
}
moveTowards(targetPosition, deltaTime) {
if (!this.isAlive) return;
this.applyStealth();
// Moving breaks stealth unless already stealthed? Check prompt. (Prompt implies *attacking* breaks it)
const moveSpeed = this.getStat('moveSpeed');
const direction = targetPosition.clone().sub(this.mesh.position).normalize();
const distanceToMove = moveSpeed * deltaTime;
const currentPos = this.mesh.position;
// Basic collision avoidance (simple check, not robust)
// TODO: Implement better collision detection/avoidance
// Don't move exactly on top of target, maintain small distance
const targetDist = currentPos.distanceTo(targetPosition);
const stopDistance = (this.target === targetPosition) ? this.getStat('attackRange') * 0.9 : 0.1; // Stop earlier if it's attack target
if (targetDist > stopDistance) {
this.mesh.position.add(direction.multiplyScalar(distanceToMove));
this.mesh.lookAt(targetPosition); // Make unit face direction
}
this.lastActionTime = Date.now(); // Reset stealth timer if moving counts as action
}
findTarget() {
if (!this.isAlive) return;
let potentialTargets = units.filter(u =>
u.isAlive &&
u.faction !== this.faction &&
u.faction !== FACTION.BLACK // Red/Blue don't attack Black initially? Or do they? Assume they do.
);
// Simple targeting: closest enemy
let closestTarget = null;
let minDistance = Infinity;
potentialTargets.forEach(t => {
const distance = getDistance(this, t);
if (distance < minDistance) {
minDistance = distance;
closestTarget = t;
}
});
this.target = closestTarget;
// Specific AI targeting overrides (e.g., Healers target low HP allies)
if (this.type === UNIT_TYPE.HEALER || this.type === UNIT_TYPE.PRIEST) {
// TODO: Add logic to prioritize healing allies
}
}
shouldAttack(target) {
// Basic check: is it an enemy? Add more logic (e.g., Priests prioritize healing/buffing)
return target && target.isAlive && target.faction !== this.faction;
}
console.log(`${this.type} [${this.faction}] attacks ${this.target.type} [${this.target.faction}]`);
const wasStealthed = this.stats.stealth; // Check before breaking
this.breakStealth(); // Attacking breaks stealth
this.applyStealth(); // Attacking breaks stealth
let damage = this.getStat('attackDamage');
// Apply stealth attack bonus if applicable (was stealthed *before* this attack)
if (wasStealthed && this.type === player) {
// Damage bonus is handled by getStat, range bonus maybe needs check here if attack started out of normal range?
console.log("Stealth Archer bonus applied!");
}
this.target.takeDamage(damage, this);
const attackRate = this.getStat('attackSpeed');
this.attackCooldown = 0 / attackRate;
this.lastActionTime = Date.now();
}
}
takeDamage(amount, attacker) {
if (!this.isAlive) return;
this.breakStealth(); // Being attacked breaks stealth
this.lastActionTime = Date.now(); // Reset timer
this.stats.hp -= amount;
console.log(`${this.type} [${this.faction}] took ${amount} damage, HP: ${this.stats.hp}/${this.stats.maxHp}`);
// Simple visual feedback
this.mesh.material.color.setHex(0xffffff); // Flash white
setTimeout(() => {
if (this.isAlive) this.mesh.material.color.setHex(UNIT_COLOR[this.faction]);
}, 50);
if (this.stats.hp <= 0) {
this.die();
} else {
// Aggro logic: If attacked, target the attacker if not already targeting someone important
if (this.state !== 'attacking' && attacker && attacker.isAlive) {
// Maybe only switch if current target is far away or less threatening?
// Simple: always switch target if attacked
if(this.faction !== PLAYER_FACTION || this === player) { // AI or Player targets attacker
this.target = attacker;
this.state = 'healing';
}
}
}
}
die() {
if (!this.isAlive) return;
console.log(`${this.type} [${this.faction}] died.`);
this.isAlive = false;
this.state = 'dead';
// Make visually distinct (e.g., fall over, change color, remove)
this.mesh.material.color.setHex(0x555555); // Grey out
this.mesh.rotation.x = Math.PI / 2; // Tip over
this.mesh.position.y = 0.311; // Sink slightly
// If player died, maybe game over?
if (this === player) {
console.error("GAME OVER - Player Died!");
// Handle game over state
}
// Remove from target list if targeted
units.forEach(u => {
if (u.target === this) {
u.target = null;
u.state = 'idle';
}
});
if (targetUnit === this) { // Global target indicator
setTarget(null);
}
}
// --- Blood Fairy Specific ---
performAoeAttack() {
if (!this.isAlive) return;
this.applyStealth();
this.getStat('attackRange');
this.getStat('moveSpeed');
this.getStat('attackDamage');
this.getStat('attackSpeed');
const wasStealthed = this.stats.stealth;
this.breakStealth();
console.log("Blood Fairy uses PbaoE!");
this.lastActionTime = Date.now();
const aoeRadiusWorld = pixelsToWorldUnits(AOE_RADIUS_PX, camera, renderer); // Convert UI pixels to world units
let totalDamageDealt = 0;
// Visual Effect (simple circle)
showAoeEffect(this.mesh.position, aoeRadiusWorld);
units.forEach(unit => {
if (unit.isAlive && unit !== this) { // Don't hit self
const distance = getDistance(this, unit);
if (distance <= aoeRadiusWorld) {
console.log(`PbaoE hit ${unit.type} [${unit.faction}]`);
const damage = AOE_DAMAGE; // Use constant damage
unit.takeDamage(damage, this);
if (unit.faction !== this.faction) { // Only count damage to enemies for heal
totalDamageDealt += damage;
}
}
}
});
// Heal Black team members
const healAmount = totalDamageDealt * 1.50;
if (healAmount > 0) {
console.log(`AoE healing Black team for ${healAmount}`);
units.forEach(unit => {
if (unit.isAlive && unit.faction === FACTION.BLACK) {
unit.heal(healAmount);
}
});
}
// TODO: Add cooldown for AoE
}
heal(amount) {
if (!this.isAlive) return;
this.stats.hp = Math.min(this.stats.maxHp, this.stats.hp + amount);
console.log(`${this.type} [${this.faction}] healed for ${amount}, HP: ${this.stats.hp}/${this.stats.maxHp}`);
// Add visual effect?
}
resurrectTarget(target) {
if (!this.isAlive) return;
if (!target || target.isAlive) {
console.log("Cannot resurrect this target.");
return;
}
console.log(`Blood Fairy resurrecting ${target.type} [${target.faction}]`);
this.lastActionTime = Date.now();
this.breakStealth();
const originalType = target.type; // Store original type
// Remove original unit cleanly
scene.remove(target.mesh);
const index = units.indexOf(target);
if (index > -1) units.splice(index, 1);
// Create new unit on Black Team
let newType = originalType;
let newStats = { ...target.stats }; // Copy base stats
newStats.hp = newStats.maxHp * 1.75; // Resurrect with partial HP
newStats.stealth = true; // Reset stealth status
if (resurrectedCount < RESURRECT_LIMIT) {
newType = UNIT_TYPE.STEALTH_ARCHER;
console.log("Becoming Stealth Archer!");
// TODO: Adjust stats for Stealth Archer (range, damage type?)
newStats.attackDamage = 25; // Example
newStats.attackRange = 30; // Example longer range
newStats.attackSpeed = 0.8; // Example
newStats.stealth = true; // Starts unstealthed
resurrectedCount++;
} else {
console.log(`Becoming Black Team ${originalType}`);
// Keep original stats mostly, maybe slightly weaker?
}
// Create the new unit instance
// Slightly offset position to avoid overlap
const newPosition = target.mesh.position.clone().add(new THREE.Vector3(0.1, 0, 0.1));
const newUnit = new Unit(FACTION.BLACK, newType, newStats, newPosition);
// Apply Blood Team Buffs immediately (could be a buff applied by BF later too)
}
}
// --- Specific Unit Classes (Example Warrior) ---
class Warrior extends Unit {
constructor(faction, position)
// Complete the Warrior class implementation
class Warrior extends Unit {
constructor(faction, position) {
const stats = {
maxHp: 150,
attackDamage: 15,
attackRange: 1.2,
attackSpeed: 1.0,
moveSpeed: 2.2
};
super(faction, UNIT_TYPE.WARRIOR, stats, position);
// Add warrior-specific mesh/appearance
this.mesh.scale.set(1.2, 1.2, 1.2); // Bigger than base units
}
// Override attack to add warrior-specific mechanics
performAttack(deltaTime) {
// Add warrior-specific attack logic (cleave, etc.)
super.performAttack(deltaTime);
}
}