clash royale
Anonymous
Plain Text
08/27/2025 4:10 PM
16.3 KB
14
Indexable
Never
import React, { useEffect, useMemo, useRef, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
// ---------------------------------------------------------
// Arena Duel — a small, original, Clash Royale–inspired web game
// Single-file React component. No assets needed.
// ---------------------------------------------------------
// How it works (quick dev notes):
// - 3 lanes. Each lane hosts arrays of units for player and AI.
// - Units advance toward the enemy tower and auto-attack the closest enemy in range.
// - Towers auto-attack the closest enemy in range as well.
// - Elixir (energy) regenerates; spend it to deploy units.
// - First to destroy the opponent's King Tower wins.
// ---------------------------------------------------------
// ---- Balance knobs ----
const CONFIG = {
lanes: 3,
arenaLength: 100, // abstract distance units 0..100
tickMs: 60, // game loop tick
matchSeconds: 180,
elixir: {
max: 10,
regenPerSecond: 0.35, // base regen
doubleTimeFrom: 90, // last 90s = double elixir
},
towers: {
hp: 1200,
range: 14,
dps: 22,
},
unitTypes: {
// cost, hp, speed (dist/s), range, dps
knight: { cost: 3, hp: 260, speed: 8, range: 1.5, dps: 32, emoji: "🗡️", name: "Knight" },
archer: { cost: 3, hp: 150, speed: 7, range: 9, dps: 24, emoji: "🏹", name: "Archer" },
tank: { cost: 5, hp: 520, speed: 5, range: 1.5, dps: 20, emoji: "🛡️", name: "Tank" },
mage: { cost: 4, hp: 170, speed: 6, range: 11, dps: 36, emoji: "✨", name: "Mage" },
},
};
// Types
/** @typedef {"player" | "ai"} Owner */
const rand = (a, b) => a + Math.random() * (b - a);
function useInterval(callback, delay) {
const savedRef = useRef(callback);
useEffect(() => { savedRef.current = callback; }, [callback]);
useEffect(() => {
if (delay === null) return;
const id = setInterval(() => savedRef.current(), delay);
return () => clearInterval(id);
}, [delay]);
}
function formatTime(totalSeconds) {
const m = Math.floor(totalSeconds / 60);
const s = (totalSeconds % 60).toString().padStart(2, "0");
return `${m}:${s}`;
}
function distance(a, b) { return Math.abs(a - b); }
function clamp(v, min, max) { return Math.max(min, Math.min(max, v)); }
const initialUnits = () => Array.from({ length: CONFIG.lanes }, () => []);
export default function ArenaDuel() {
const [time, setTime] = useState(0); // seconds elapsed
const [paused, setPaused] = useState(false);
const [winner, setWinner] = useState/** @type {null | Owner} */(null);
const [elixir, setElixir] = useState({ player: 5, ai: 5 });
const [towers, setTowers] = useState({ player: CONFIG.towers.hp, ai: CONFIG.towers.hp });
const [units, setUnits] = useState(() => ({ player: initialUnits(), ai: initialUnits() }));
const doubleElixir = time >= CONFIG.elixir.doubleTimeFrom;
const gameOver = winner || time >= CONFIG.matchSeconds || towers.player <= 0 || towers.ai <= 0;
// Derived winner state
useEffect(() => {
if (winner) return;
if (towers.player <= 0 && towers.ai > 0) setWinner("ai");
else if (towers.ai <= 0 && towers.player > 0) setWinner("player");
else if (time >= CONFIG.matchSeconds) {
if (towers.player === towers.ai) setWinner("ai"); // tie-breaker to AI
else setWinner(towers.player > towers.ai ? "player" : "ai");
}
}, [time, towers, winner]);
// --- Game loop ---
useInterval(() => {
if (paused || gameOver) return;
setTime((t) => t + CONFIG.tickMs / 1000);
// Elixir regen
setElixir((e) => {
const regen = CONFIG.elixir.regenPerSecond * (doubleElixir ? 2 : 1) * (CONFIG.tickMs / 1000);
return {
player: clamp(e.player + regen, 0, CONFIG.elixir.max),
ai: clamp(e.ai + regen, 0, CONFIG.elixir.max),
};
});
// Unit movement & combat
setUnits((prev) => {
const next = { player: prev.player.map((lane) => lane.map((u) => ({ ...u }))), ai: prev.ai.map((lane) => lane.map((u) => ({ ...u }))) };
// Helper to process one side vs the other
const stepSide = (owner /** @type {Owner} */) => {
const foe = owner === "player" ? "ai" : "player";
for (let lane = 0; lane < CONFIG.lanes; lane++) {
const sideUnits = next[owner][lane];
const foeUnits = next[foe][lane];
// Move
sideUnits.forEach((u) => {
const dir = owner === "player" ? 1 : -1;
u.pos = clamp(u.pos + (u.speed * (CONFIG.tickMs / 1000)) * dir, 0, CONFIG.arenaLength);
});
// Combat (units target closest foe in lane)
sideUnits.forEach((u) => {
// Check enemies in range
let target = null;
let bestDist = Infinity;
foeUnits.forEach((v) => {
const d = distance(u.pos, v.pos);
if (d <= u.range && d < bestDist) { bestDist = d; target = v; }
});
// If none, consider tower
const towerPos = owner === "player" ? CONFIG.arenaLength : 0;
const towerHP = towers[foe];
if (!target && distance(u.pos, towerPos) <= u.range && towerHP > 0) {
// mark tower damage via queued state change outside loop
u._hitsTower = (u._hitsTower || 0) + u.dps * (CONFIG.tickMs / 1000);
}
if (target) {
target.hp -= u.dps * (CONFIG.tickMs / 1000);
}
});
// Remove dead
next[owner][lane] = sideUnits.filter((u) => u.hp > 0);
next[foe][lane] = foeUnits.filter((u) => u.hp > 0);
}
};
stepSide("player");
stepSide("ai");
// Apply deferred tower dmg
let dmgPlayer = 0, dmgAI = 0;
for (let lane = 0; lane < CONFIG.lanes; lane++) {
next.player[lane].forEach((u) => { if (u._hitsTower) { dmgAI += u._hitsTower; u._hitsTower = 0; } });
next.ai[lane].forEach((u) => { if (u._hitsTower) { dmgPlayer += u._hitsTower; u._hitsTower = 0; } });
}
if (dmgPlayer || dmgAI) {
setTowers((t) => ({ player: Math.max(0, t.player - dmgPlayer), ai: Math.max(0, t.ai - dmgAI) }));
}
return next;
});
// Towers auto-attack
setUnits((prev) => {
const next = { player: prev.player.map((lane) => lane.map((u) => ({ ...u }))), ai: prev.ai.map((lane) => lane.map((u) => ({ ...u }))) };
for (let lane = 0; lane < CONFIG.lanes; lane++) {
// Player tower shoots AI units near pos 0
next.ai[lane].forEach((u) => {
if (u.pos <= CONFIG.towers.range) {
u.hp -= CONFIG.towers.dps * (CONFIG.tickMs / 1000);
}
});
// AI tower shoots Player units near pos 100
next.player[lane].forEach((u) => {
if (CONFIG.arenaLength - u.pos <= CONFIG.towers.range) {
u.hp -= CONFIG.towers.dps * (CONFIG.tickMs / 1000);
}
});
next.player[lane] = next.player[lane].filter((u) => u.hp > 0);
next.ai[lane] = next.ai[lane].filter((u) => u.hp > 0);
}
return next;
});
// Simple AI: periodically deploy based on elixir
setElixir((e) => {
if (e.ai >= 2.8 && Math.random() < 0.18) {
const lane = Math.floor(Math.random() * CONFIG.lanes);
const picks = Object.values(CONFIG.unitTypes);
const choice = picks[Math.floor(Math.random() * picks.length)];
if (choice.cost <= e.ai) {
setUnits((prev) => {
const u = { owner: "ai", lane, pos: CONFIG.arenaLength - 1.5, hp: choice.hp, speed: choice.speed, range: choice.range, dps: choice.dps, emoji: choice.emoji };
const next = { player: prev.player.map((l) => l.slice()), ai: prev.ai.map((l) => l.slice()) };
next.ai[lane] = [...next.ai[lane], u];
return next;
});
return { ...e, ai: e.ai - choice.cost };
}
}
return e;
});
}, CONFIG.tickMs);
const deploy = (key) => {
const def = CONFIG.unitTypes[key];
if (!def) return;
if (elixir.player < def.cost || gameOver || paused) return;
// choose the center lane by default; user can tap on lane to set target
const lane = targetLaneRef.current ?? 1;
setUnits((prev) => {
const u = { owner: "player", lane, pos: 1.5, hp: def.hp, speed: def.speed, range: def.range, dps: def.dps, emoji: def.emoji };
const next = { player: prev.player.map((l) => l.slice()), ai: prev.ai.map((l) => l.slice()) };
next.player[lane] = [...next.player[lane], u];
return next;
});
setElixir((e) => ({ ...e, player: e.player - def.cost }));
};
// lane target selection
const targetLaneRef = useRef/** @type {null | number} */(null);
const resetGame = () => {
setTime(0);
setPaused(false);
setWinner(null);
setElixir({ player: 5, ai: 5 });
setTowers({ player: CONFIG.towers.hp, ai: CONFIG.towers.hp });
setUnits({ player: initialUnits(), ai: initialUnits() });
};
const percent = (hp) => (hp / CONFIG.towers.hp) * 100;
return (
<div className="min-h-screen w-full bg-gradient-to-b from-slate-900 to-slate-800 text-slate-100 px-4 py-6">
<div className="max-w-5xl mx-auto">
<header className="flex items-center justify-between mb-4">
<h1 className="text-2xl sm:text-3xl font-bold tracking-tight">Arena Duel</h1>
<div className="flex items-center gap-2">
<button onClick={() => setPaused((p) => !p)} className="px-3 py-2 rounded-2xl bg-slate-700 hover:bg-slate-600 text-sm shadow">
{paused ? "Resume" : "Pause"}
</button>
<button onClick={resetGame} className="px-3 py-2 rounded-2xl bg-slate-700 hover:bg-slate-600 text-sm shadow">Restart</button>
</div>
</header>
{/* Top HUD */}
<div className="grid grid-cols-3 gap-4 items-center mb-4">
<div>
<div className="text-xs uppercase text-slate-300">Your Tower</div>
<div className="h-3 bg-slate-700 rounded-xl overflow-hidden mt-1">
<div className="h-full bg-emerald-400" style={{ width: `${percent(towers.player)}%` }} />
</div>
</div>
<div className="text-center">
<div className="text-xs uppercase text-slate-300">Time</div>
<div className="text-lg font-semibold">{formatTime(Math.floor(time))} {doubleElixir && <span className="text-amber-300 text-sm">(2× elixir)</span>}</div>
</div>
<div className="text-right">
<div className="text-xs uppercase text-slate-300">Enemy Tower</div>
<div className="h-3 bg-slate-700 rounded-xl overflow-hidden mt-1">
<div className="h-full bg-rose-400" style={{ width: `${percent(towers.ai)}%` }} />
</div>
</div>
</div>
{/* Arena */}
<div className="relative rounded-3xl overflow-hidden bg-gradient-to-b from-emerald-900/30 to-cyan-900/30 border border-slate-700 shadow-xl">
{/* Lanes */}
{[0,1,2].map((lane) => (
<div key={lane} className="relative h-28 sm:h-32 border-t border-slate-700/60 first:border-t-0">
{/* Lane click for targeting */}
<button
className={`absolute inset-0 w-full h-full ${targetLaneRef.current===lane?"ring-2 ring-amber-300/80": ""}`}
onClick={() => { targetLaneRef.current = lane; }}
aria-label={`Select lane ${lane+1}`}
/>
{/* Midline */}
<div className="absolute left-1/2 top-0 bottom-0 w-0.5 bg-white/10" />
{/* Player tower icon */}
<div className="absolute left-1 top-1/2 -translate-y-1/2 text-2xl select-none">🏰</div>
{/* AI tower icon */}
<div className="absolute right-1 top-1/2 -translate-y-1/2 text-2xl select-none">🏰</div>
{/* Units */}
<AnimatePresence initial={false}>
{units.player[lane].map((u, idx) => (
<motion.div key={`p${lane}-${idx}`} initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.6 }}
className="absolute -translate-x-1/2 top-1/2 -translate-y-1/2 text-xl select-none">
<div style={{ left: `${(u.pos/CONFIG.arenaLength)*100}%` }} className="absolute">
<div>{u.emoji}</div>
<div className="w-10 h-1 bg-slate-700 rounded mt-0.5 overflow-hidden">
<div className="h-full bg-emerald-400" style={{ width: `${(u.hp / CONFIG.unitTypes.knight.hp)*100}%` }} />
</div>
</div>
</motion.div>
))}
{units.ai[lane].map((u, idx) => (
<motion.div key={`a${lane}-${idx}`} initial={{ opacity: 0, y: -6 }} animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, scale: 0.6 }}
className="absolute -translate-x-1/2 top-1/2 -translate-y-1/2 text-xl select-none">
<div style={{ left: `${(u.pos/CONFIG.arenaLength)*100}%` }} className="absolute">
<div className="rotate-180">{u.emoji}</div>
<div className="w-10 h-1 bg-slate-700 rounded mt-0.5 overflow-hidden">
<div className="h-full bg-rose-400" style={{ width: `${(u.hp / CONFIG.unitTypes.knight.hp)*100}%` }} />
</div>
</div>
</motion.div>
))}
</AnimatePresence>
</div>
))}
</div>
{/* Deploy bar */}
<div className="mt-4 p-3 bg-slate-800/80 rounded-3xl border border-slate-700">
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
{Object.entries(CONFIG.unitTypes).map(([key, def]) => (
<button key={key} onClick={() => deploy(key)}
className="px-3 py-2 rounded-2xl bg-slate-700 hover:bg-slate-600 shadow text-sm flex flex-col items-center min-w-[64px]">
<span className="text-xl leading-none">{def.emoji}</span>
<span className="text-[11px] mt-1">{def.name}</span>
<span className="text-[10px] mt-0.5 opacity-80">{def.cost}⚡</span>
</button>
))}
</div>
<div className="text-right">
<div className="text-xs uppercase text-slate-300">Elixir</div>
<div className="flex items-center gap-2">
<div className="w-40 h-3 bg-slate-700 rounded-xl overflow-hidden">
<div className="h-full bg-amber-300" style={{ width: `${(elixir.player/CONFIG.elixir.max)*100}%` }} />
</div>
<div className="text-sm font-semibold">{elixir.player.toFixed(1)}</div>
</div>
</div>
</div>
<div className="mt-2 text-xs text-slate-400">Tip: click a lane to set your deploy target. Double elixir activates at 1:30.</div>
</div>
{/* Winner Modal */}
<AnimatePresence>
{gameOver && (
<motion.div className="fixed inset-0 bg-black/50 backdrop-blur flex items-center justify-center z-50"
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
<motion.div className="bg-slate-900 border border-slate-700 rounded-3xl p-6 w-[min(92vw,28rem)] shadow-2xl text-center"
initial={{ scale: 0.9, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} exit={{ scale: 0.9, opacity: 0 }}>
<div className="text-5xl mb-2">{winner === "player" ? "🎉" : "💀"}</div>
<h2 className="text-xl font-bold mb-1">{winner === "player" ? "You Win!" : "Defeat"}</h2>
<p className="text-slate-400 mb-4">Final towers — You: {Math.max(0, Math.round(towers.player))} · Enemy: {Math.max(0, Math.round(towers.ai))}</p>
<div className="flex justify-center gap-3">
<button onClick={resetGame} className="px-4 py-2 rounded-2xl bg-slate-700 hover:bg-slate-600 shadow">Play again</button>
</div>
</motion.div>
</motion.div>
)}
</AnimatePresence>
{/* Footer */}
<footer className="mt-6 text-xs text-slate-400">
This is a fan-made, original browser game inspired by arena battlers. It is not affiliated with or endorsed by Supercell.
</footer>
</div>
</div>
);
}
Editor is loading...
Leave a Comment