perrabyte's picture
Upload 270 files
96cca27 verified
Raw History Blame Contribute Delete
60.1 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>RTS-CHESS: Real-Time Strategy Chess</title> <!-- Tailwind CSS CDN --> <script src="https://cdn.tailwindcss.com"></script> <!-- Google Fonts: Orbitron & Inter --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Orbitron:wght@500;700;900&display=swap" rel="stylesheet"> <style> body { font-family: 'Inter', sans-serif; background-color: #080c14; color: #f1f5f9; user-select: none; overflow-x: hidden; } .font-orbitron { font-family: 'Orbitron', sans-serif; } /* Custom Scrollbar */ ::-webkit-scrollbar { width: 6px; } ::-webkit-scrollbar-track { background: #0f172a; } ::-webkit-scrollbar-thumb { background: #334155; border-radius: 3px; } /* Neon Glow FX */ .glow-cyan { box-shadow: 0 0 15px rgba(0, 240, 255, 0.4); } .glow-red { box-shadow: 0 0 15px rgba(255, 0, 85, 0.4); } .text-glow-cyan { text-shadow: 0 0 8px rgba(0, 240, 255, 0.6); } .text-glow-red { text-shadow: 0 0 8px rgba(255, 0, 85, 0.6); } .border-glow-cyan { border-color: #00f0ff; box-shadow: 0 0 10px rgba(0, 240, 255, 0.3); } /* Canvas Container */ #canvas-container { position: relative; touch-action: none; } /* Modal Backdrop */ .modal-backdrop { background: rgba(4, 7, 13, 0.85); backdrop-filter: blur(8px); } </style> </head> <body class="min-h-screen flex flex-col justify-between"> <!-- TOP HEADER / NAV --> <header class="bg-slate-900/90 border-b border-slate-800 px-4 py-2 flex items-center justify-between z-10 sticky top-0"> <div class="flex items-center gap-3"> <div class="w-9 h-9 rounded-lg bg-gradient-to-br from-cyan-500 to-blue-600 flex items-center justify-center font-orbitron font-black text-xl text-black shadow-lg shadow-cyan-500/30"> β™” </div> <div> <h1 class="font-orbitron font-black text-lg md:text-xl tracking-wider text-transparent bg-clip-text bg-gradient-to-r from-cyan-400 via-blue-400 to-indigo-400"> RTS-CHESS </h1> <p class="text-xs text-slate-400 font-medium hidden sm:block">14x14 Real-Time Tactical Warfare</p> </div> </div> <!-- Match Status Center --> <div class="flex items-center gap-4 bg-slate-950/80 px-4 py-1.5 rounded-full border border-slate-800"> <div id="game-phase-badge" class="px-2.5 py-0.5 rounded-full text-xs font-orbitron font-bold uppercase bg-amber-500/20 text-amber-400 border border-amber-500/30"> Draft Phase </div> <div class="h-4 w-[1px] bg-slate-800"></div> <div class="flex items-center gap-2"> <span class="text-xs text-slate-400 uppercase font-semibold">Time:</span> <span id="match-timer" class="font-orbitron text-sm font-bold text-cyan-400">00:00</span> </div> </div> <!-- Settings & Quick Actions --> <div class="flex items-center gap-2"> <button id="btn-sound" class="p-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition text-sm flex items-center gap-1.5 border border-slate-700"> <span id="sound-icon">πŸ”Š</span> </button> <button id="btn-howtoplay" class="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-semibold border border-slate-700 transition"> Help / Rules </button> </div> </header> <!-- MAIN CONTENT CONTAINER --> <main class="flex-1 max-w-7xl w-full mx-auto p-2 sm:p-4 grid grid-cols-1 lg:grid-cols-12 gap-4 items-start"> <!-- LEFT SIDEBAR: CONTROLS & SHOP --> <aside class="lg:col-span-4 xl:col-span-3 flex flex-col gap-3 order-2 lg:order-1"> <!-- Player Commander Card --> <div class="bg-slate-900/80 border border-cyan-500/30 rounded-xl p-3.5 shadow-xl relative overflow-hidden"> <div class="absolute top-0 right-0 w-24 h-24 bg-cyan-500/5 rounded-full blur-xl pointer-events-none"></div> <div class="flex items-center justify-between mb-2"> <span class="text-xs font-bold text-cyan-400 uppercase tracking-wider font-orbitron flex items-center gap-1.5"> <span class="w-2 h-2 rounded-full bg-cyan-400 animate-pulse"></span> Blue Commander </span> <span id="ai-difficulty-badge" class="text-[10px] font-bold px-2 py-0.5 rounded bg-slate-800 text-slate-300 border border-slate-700"> AI: Medium </span> </div> <!-- Gold & Income Display --> <div class="grid grid-cols-2 gap-2 my-2"> <div class="bg-slate-950/70 p-2.5 rounded-lg border border-slate-800/80"> <span class="text-[10px] text-slate-400 block uppercase font-medium">Gold Vault</span> <div class="flex items-center gap-1"> <span class="text-amber-400 text-lg">πŸͺ™</span> <span id="player-gold" class="font-orbitron font-black text-xl text-amber-300">250</span> </div> </div> <div class="bg-slate-950/70 p-2.5 rounded-lg border border-slate-800/80"> <span class="text-[10px] text-slate-400 block uppercase font-medium">Income Rate</span> <div class="flex items-center gap-1"> <span class="text-emerald-400 font-bold text-sm">+</span> <span id="player-income" class="font-orbitron font-bold text-lg text-emerald-400">5</span> <span class="text-[10px] text-slate-400">g/s</span> </div> </div> </div> <!-- Control Point Summary --> <div class="flex items-center justify-between text-xs bg-slate-950/50 p-2 rounded-lg border border-slate-800"> <span class="text-slate-400">Control Nodes (4):</span> <div class="flex items-center gap-1.5 font-bold"> <span id="nodes-blue" class="text-cyan-400">0</span> <span class="text-slate-600">/</span> <span id="nodes-red" class="text-rose-400">0</span> <span class="text-slate-600">/</span> <span id="nodes-neutral" class="text-slate-400">4</span> </div> </div> </div> <!-- Piece Purchasing Shop --> <div class="bg-slate-900/80 border border-slate-800 rounded-xl p-3.5 flex flex-col gap-2 shadow-xl"> <div class="flex items-center justify-between mb-1"> <h2 class="font-orbitron font-bold text-xs uppercase tracking-wider text-slate-300 flex items-center gap-1.5"> <span>πŸ›’</span> Piece Reinforcements </h2> <span class="text-[10px] text-slate-400">Click to Select/Buy</span> </div> <!-- Shop Items Grid --> <div class="grid grid-cols-2 gap-2" id="shop-grid"> <!-- Dynamically populated via JS --> </div> </div> <!-- Selected Unit Details Card --> <div class="bg-slate-900/80 border border-slate-800 rounded-xl p-3.5 shadow-xl min-h-[120px] flex flex-col justify-between"> <div class="flex items-center justify-between border-b border-slate-800 pb-2"> <span class="text-xs font-bold text-slate-400 uppercase tracking-wider font-orbitron">Selected Unit</span> <span id="selected-unit-coords" class="text-xs font-mono text-cyan-400">None</span> </div> <div id="selected-unit-body" class="my-2 flex items-center gap-3"> <div id="selected-unit-icon" class="w-12 h-12 rounded-lg bg-slate-950 border border-slate-800 flex items-center justify-center text-3xl text-slate-600"> βš”οΈ </div> <div class="flex-1"> <div id="selected-unit-name" class="font-bold text-sm text-slate-200">No Unit Selected</div> <div id="selected-unit-type" class="text-xs text-slate-400">Click any unit on the board</div> <div id="selected-unit-cooldown-wrap" class="mt-1.5 hidden"> <div class="flex justify-between text-[10px] text-slate-400 mb-0.5"> <span>Cooldown Status</span> <span id="selected-unit-cooldown-text">Ready</span> </div> <div class="w-full bg-slate-950 h-1.5 rounded-full overflow-hidden border border-slate-800"> <div id="selected-unit-cooldown-bar" class="bg-cyan-400 h-full w-full transition-all duration-100"></div> </div> </div> </div> </div> </div> <!-- Primary Action Buttons --> <div class="flex flex-col gap-2"> <button id="btn-primary-action" class="w-full py-3 px-4 rounded-xl font-orbitron font-bold text-sm tracking-wider uppercase transition-all duration-200 bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-400 hover:to-teal-500 text-black shadow-lg shadow-emerald-500/25 active:scale-[0.98]"> πŸš€ Start War (Combat Phase) </button> <div class="grid grid-cols-2 gap-2"> <button id="btn-pause" class="py-2 px-3 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 text-xs font-semibold border border-slate-700 transition"> ⏸️ Pause </button> <button id="btn-reset" class="py-2 px-3 rounded-lg bg-rose-950/40 hover:bg-rose-900/50 text-rose-300 text-xs font-semibold border border-rose-800/50 transition"> πŸ”„ Reset </button> </div> </div> </aside> <!-- CENTER AREA: GAME CANVAS --> <section class="lg:col-span-8 xl:col-span-9 flex flex-col items-center justify-center order-1 lg:order-2"> <div id="canvas-container" class="w-full max-w-[840px] aspect-square rounded-2xl bg-slate-950 border-2 border-slate-800 shadow-2xl overflow-hidden flex items-center justify-center relative"> <canvas id="gameCanvas" class="w-full h-full block cursor-crosshair"></canvas> <!-- Dynamic Floating Overlay Banners (Draft Helper / Pause) --> <div id="overlay-banner" class="absolute top-4 left-1/2 -translate-x-1/2 bg-slate-900/90 border border-cyan-500/40 px-4 py-2 rounded-full shadow-xl pointer-events-none flex items-center gap-2 backdrop-blur-md"> <span class="w-2 h-2 rounded-full bg-cyan-400 animate-ping"></span> <span id="overlay-banner-text" class="text-xs font-semibold text-cyan-300 font-orbitron"> DRAFT PHASE: Place your King & Army on Blue Rows (12-14) </span> </div> </div> </section> </main> <!-- BATTLE LOG & FOOTER --> <footer class="bg-slate-900/90 border-t border-slate-800 px-4 py-2.5 mt-2"> <div class="max-w-7xl mx-auto flex flex-col sm:flex-row items-center justify-between gap-2 text-xs text-slate-400"> <div class="flex items-center gap-2 overflow-x-auto max-w-full py-1"> <span class="font-orbitron font-bold text-slate-500 uppercase text-[10px] shrink-0">Battle Log:</span> <div id="battle-log" class="font-mono text-slate-300 whitespace-nowrap overflow-hidden text-ellipsis"> System initialized. Draft your army to begin... </div> </div> <div class="text-[11px] text-slate-500 shrink-0"> RTS-CHESS &copy; 2026 | HTML5 Canvas & Web Audio Engine </div> </div> </footer> <!-- MODAL: HELP / RULES --> <div id="modal-help" class="fixed inset-0 z-50 modal-backdrop hidden flex items-center justify-center p-4"> <div class="bg-slate-900 border border-slate-700 rounded-2xl max-w-lg w-full p-6 shadow-2xl relative"> <h3 class="font-orbitron font-bold text-lg text-cyan-400 mb-3 flex items-center gap-2"> πŸ“œ RTS-CHESS Manual & Rules </h3> <div class="space-y-3 text-xs text-slate-300 leading-relaxed max-h-[60vh] overflow-y-auto pr-2"> <p><strong>RTS-CHESS</strong> merges classic chess movement rules with real-time strategy cooldowns, dynamic resource nodes, and army drafting on a huge 14x14 battlefield!</p> <div class="bg-slate-950 p-3 rounded-lg border border-slate-800"> <h4 class="font-bold text-amber-400 mb-1">1. Draft & Placement Phase</h4> <p>Spend your 250 Starting Gold to draft pieces in the bottom 3 Blue rows. <strong>You must place a King</strong> before entering real-time combat!</p> </div> <div class="bg-slate-950 p-3 rounded-lg border border-slate-800"> <h4 class="font-bold text-cyan-400 mb-1">2. Real-Time Cooldowns</h4> <p>There are no alternating turns! Each piece has an individual cooldown timer after moving. Fast pawns move every 1.2s, while powerful Queens take 4.0s.</p> </div> <div class="bg-slate-950 p-3 rounded-lg border border-slate-800"> <h4 class="font-bold text-emerald-400 mb-1">3. Control Nodes & Economy</h4> <p>Gain passive income (+5g/s). Capture the 4 dynamic power-nodes on the board to gain +3g/s extra per node! You can buy and warp in new units during battle.</p> </div> <div class="bg-slate-950 p-3 rounded-lg border border-slate-800"> <h4 class="font-bold text-rose-400 mb-1">4. Victory Condition</h4> <p>Capture the enemy Red King to declare instant total victory! Protect your King at all costs.</p> </div> </div> <button id="btn-close-help" class="mt-5 w-full py-2.5 rounded-xl bg-cyan-500 hover:bg-cyan-400 text-black font-bold font-orbitron text-xs transition"> Understood / Back To Game </button> </div> </div> <!-- MODAL: GAME OVER / VICTORY --> <div id="modal-gameover" class="fixed inset-0 z-50 modal-backdrop hidden flex items-center justify-center p-4"> <div id="gameover-card" class="bg-slate-900 border-2 border-cyan-500 rounded-2xl max-w-md w-full p-6 text-center shadow-2xl relative"> <div id="gameover-icon" class="text-6xl mb-2">πŸ†</div> <h2 id="gameover-title" class="font-orbitron font-black text-2xl text-cyan-400 uppercase tracking-wide"> VICTORY! </h2> <p id="gameover-subtitle" class="text-xs text-slate-300 mt-2 mb-4"> You captured the Red King and dominated the 14x14 battlefield! </p> <div class="bg-slate-950 p-3 rounded-xl border border-slate-800 my-4 text-xs space-y-1.5 text-left"> <div class="flex justify-between text-slate-400"> <span>Match Duration:</span> <span id="stat-match-time" class="font-bold text-slate-200">02:45</span> </div> <div class="flex justify-between text-slate-400"> <span>Pieces Captured:</span> <span id="stat-captures" class="font-bold text-emerald-400">12</span> </div> <div class="flex justify-between text-slate-400"> <span>Total Gold Earned:</span> <span id="stat-gold" class="font-bold text-amber-400">850g</span> </div> </div> <button id="btn-restart-gameover" class="w-full py-3 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-600 hover:from-cyan-400 hover:to-blue-500 text-black font-bold font-orbitron text-sm shadow-lg shadow-cyan-500/30 transition"> Play Again </button> </div> </div> <!-- GAME ENGINE SCRIPT --> <script> /* ========================================================================== 1. CONSTANTS & GAME CONFIGURATION ========================================================================== */ const GRID_SIZE = 14; const STARTING_BUDGET = 250; const BASE_INCOME_PER_SEC = 5; const NODE_INCOME_PER_SEC = 3; // Control Nodes coordinates (Symmetric 14x14) const CONTROL_NODES = [ { id: 0, x: 3, y: 3, owner: null }, { id: 1, x: 10, y: 3, owner: null }, { id: 2, x: 3, y: 10, owner: null }, { id: 3, x: 10, y: 10, owner: null } ]; // Piece Specifications const PIECE_SPECS = { pawn: { name: "Pawn", cost: 15, cooldown: 1.2, symbol: "β™Ÿ", bounty: 10, desc: "Fast moves. Captures diagonally." }, knight: { name: "Knight", cost: 35, cooldown: 2.5, symbol: "β™ž", bounty: 20, desc: "Jumps in L-shape over pieces." }, bishop: { name: "Bishop", cost: 40, cooldown: 2.8, symbol: "♝", bounty: 25, desc: "Long range diagonal slides." }, rook: { name: "Rook", cost: 50, cooldown: 3.2, symbol: "β™œ", bounty: 30, desc: "Long range linear slides." }, queen: { name: "Queen", cost: 90, cooldown: 4.0, symbol: "β™›", bounty: 50, desc: "Omnidirectional long slides." }, king: { name: "King", cost: 100, cooldown: 2.0, symbol: "β™š", bounty: 100, desc: "Commander. 1-square omni move." } }; /* = antiquity AUDIO SYNTHESIZER = */ class SoundEngine { constructor() { this.ctx = null; this.enabled = true; } init() { if (!this.ctx) { const AudioContext = window.AudioContext || window.webkitAudioContext; this.ctx = new AudioContext(); } } playTone(freq, type, duration, vol = 0.1) { if (!this.enabled || !this.ctx) return; try { const osc = this.ctx.createOscillator(); const gain = this.ctx.createGain(); osc.type = type; osc.frequency.setValueAtTime(freq, this.ctx.currentTime); gain.gain.setValueAtTime(vol, this.ctx.currentTime); gain.gain.exponentialRampToValueAtTime(0.0001, this.ctx.currentTime + duration); osc.connect(gain); gain.connect(this.ctx.destination); osc.start(); osc.stop(this.ctx.currentTime + duration); } catch(e){} } select() { this.playTone(520, 'sine', 0.08, 0.05); } move() { if (!this.enabled || !this.ctx) return; try { const osc = this.ctx.createOscillator(); const gain = this.ctx.createGain(); osc.type = 'triangle'; osc.frequency.setValueAtTime(240, this.ctx.currentTime); osc.frequency.exponentialRampToValueAtTime(480, this.ctx.currentTime + 0.12); gain.gain.setValueAtTime(0.08, this.ctx.currentTime); gain.gain.exponentialRampToValueAtTime(0.001, this.ctx.currentTime + 0.12); osc.connect(gain); gain.connect(this.ctx.destination); osc.start(); osc.stop(this.ctx.currentTime + 0.12); } catch(e){} } capture() { if (!this.enabled || !this.ctx) return; try { // Noise + low impact punch const osc = this.ctx.createOscillator(); const gain = this.ctx.createGain(); osc.type = 'sawtooth'; osc.frequency.setValueAtTime(180, this.ctx.currentTime); osc.frequency.exponentialRampToValueAtTime(40, this.ctx.currentTime + 0.2); gain.gain.setValueAtTime(0.18, this.ctx.currentTime); gain.gain.exponentialRampToValueAtTime(0.001, this.ctx.currentTime + 0.2); osc.connect(gain); gain.connect(this.ctx.destination); osc.start(); osc.stop(this.ctx.currentTime + 0.2); } catch(e){} } buy() { if (!this.enabled || !this.ctx) return; const notes = [440, 554.37, 659.25]; notes.forEach((freq, idx) => { setTimeout(() => this.playTone(freq, 'sine', 0.15, 0.08), idx * 60); }); } node() { this.playTone(880, 'sine', 0.25, 0.08); } victory() { if (!this.enabled || !this.ctx) return; const fanfare = [261.63, 329.63, 392.00, 523.25]; fanfare.forEach((freq, idx) => { setTimeout(() => this.playTone(freq, 'triangle', 0.4, 0.12), idx * 120); }); } defeat() { if (!this.enabled || !this.ctx) return; const fanfare = [300, 280, 240, 180]; fanfare.forEach((freq, idx) => { setTimeout(() => this.playTone(freq, 'sawtooth', 0.4, 0.1), idx * 150); }); } } const sound = new SoundEngine(); /* ========================================================================== 2. GAME STATE & VARIABLES ========================================================================== */ let canvas, ctx; let tileSize = 60; let gameState = 'DRAFT'; // 'DRAFT', 'PLAYING', 'PAUSED', 'GAMEOVER' let aiDifficulty = 'medium'; // 'easy', 'medium', 'hard' let matchTimeSeconds = 0; let matchTimerInterval = null; let incomeTimerInterval = null; let selectedShopItem = null; // Piece key selected for purchase let selectedUnit = null; // Piece on board selected let validMoves = []; // [{x, y, isCapture}] // Players let player = { color: 'blue', gold: STARTING_BUDGET, income: BASE_INCOME_PER_SEC, totalEarned: STARTING_BUDGET, captures: 0 }; let ai = { color: 'red', gold: STARTING_BUDGET, income: BASE_INCOME_PER_SEC, lastActionTime: 0 }; // Board state: 14x14 matrix let board = []; let pieces = []; // Particles & FX let particles = []; let floatingTexts = []; /* ========================================================================== 3. PIECE CLASS & CHESS RULES ========================================================================== */ class Piece { constructor(type, color, x, y) { this.id = Math.random().toString(36).substring(2, 9); this.type = type; this.color = color; // 'blue' or 'red' this.x = x; this.y = y; // Animation positions this.renderX = x; this.renderY = y; this.targetX = x; this.targetY = y; this.animating = false; // Cooldowns this.maxCooldown = PIECE_SPECS[type].cooldown; this.cooldownTimer = 0; // seconds remaining this.hasMoved = false; } isReady() { return this.cooldownTimer <= 0 && !this.animating; } triggerCooldown(customTime = null) { this.cooldownTimer = customTime !== null ? customTime : this.maxCooldown; } update(dt) { if (this.cooldownTimer > 0) { this.cooldownTimer = Math.max(0, this.cooldownTimer - dt); } // Lerp movement animation if (this.animating) { const speed = 12 * dt; this.renderX += (this.targetX - this.renderX) * speed; this.renderY += (this.targetY - this.renderY) * speed; if (Math.hypot(this.targetX - this.renderX, this.targetY - this.renderY) < 0.05) { this.renderX = this.targetX; this.renderY = this.targetY; this.x = this.targetX; this.y = this.targetY; this.animating = false; } } } } // Initialize Board Matrix function initBoard() { board = Array(GRID_SIZE).fill(null).map(() => Array(GRID_SIZE).fill(null)); pieces = []; CONTROL_NODES.forEach(n => n.owner = null); } function getPieceAt(x, y) { if (x < 0 || x >= GRID_SIZE || y < 0 || y >= GRID_SIZE) return null; return board[y][x]; } function placePiece(piece) { board[piece.y][piece.x] = piece; pieces.push(piece); } function removePiece(piece) { if (!piece) return; board[piece.y][piece.x] = null; const idx = pieces.indexOf(piece); if (idx !== -1) pieces.splice(idx, 1); } /* CHESS MOVEMENT VALIDATION (14x14) */ function getValidMoves(piece) { if (!piece || !piece.isReady()) return []; const moves = []; const px = piece.x; const py = piece.y; const color = piece.color; const isEnemy = (targetPiece) => targetPiece && targetPiece.color !== color; const isEmpty = (x, y) => getPieceAt(x, y) === null; switch (piece.type) { case 'pawn': { const dir = (color === 'blue') ? -1 : 1; // Blue moves UP (-Y), Red moves DOWN (+Y) // 1 Square Forward const f1x = px, f1y = py + dir; if (f1y >= 0 && f1y < GRID_SIZE && isEmpty(f1x, f1y)) { moves.push({ x: f1x, y: f1y, isCapture: false }); // 2 Squares Initial Forward Move const isBlueStart = (color === 'blue' && py >= 11); const isRedStart = (color === 'red' && py <= 2); if (isBlueStart || isRedStart) { const f2x = px, f2y = py + (dir * 2); if (f2y >= 0 && f2y < GRID_SIZE && isEmpty(f2x, f2y)) { moves.push({ x: f2x, y: f2y, isCapture: false }); } } } // Diagonal Captures const capOffsets = [-1, 1]; capOffsets.forEach(dx => { const cx = px + dx, cy = py + dir; if (cx >= 0 && cx < GRID_SIZE && cy >= 0 && cy < GRID_SIZE) { const target = getPieceAt(cx, cy); if (target && isEnemy(target)) { moves.push({ x: cx, y: cy, isCapture: true }); } } }); break; } case 'knight': { const knightOffsets = [ {dx: -2, dy: -1}, {dx: -2, dy: 1}, {dx: -1, dy: -2}, {dx: -1, dy: 2}, {dx: 1, dy: -2}, {dx: 1, dy: 2}, {dx: 2, dy: -1}, {dx: 2, dy: 1} ]; knightOffsets.forEach(o => { const nx = px + o.dx, ny = py + o.dy; if (nx >= 0 && nx < GRID_SIZE && ny >= 0 && ny < GRID_SIZE) { const target = getPieceAt(nx, ny); if (!target) { moves.push({ x: nx, y: ny, isCapture: false }); } else if (isEnemy(target)) { moves.push({ x: nx, y: ny, isCapture: true }); } } }); break; } case 'bishop': { const directions = [{dx:-1, dy:-1}, {dx:1, dy:-1}, {dx:-1, dy:1}, {dx:1, dy:1}]; raycastMoves(piece, directions, moves); break; } case 'rook': { const directions = [{dx:0, dy:-1}, {dx:0, dy:1}, {dx:-1, dy:0}, {dx:1, dy:0}]; raycastMoves(piece, directions, moves); break; } case 'queen': { const directions = [ {dx:-1, dy:-1}, {dx:1, dy:-1}, {dx:-1, dy:1}, {dx:1, dy:1}, {dx:0, dy:-1}, {dx:0, dy:1}, {dx:-1, dy:0}, {dx:1, dy:0} ]; raycastMoves(piece, directions, moves); break; } case 'king': { const kingOffsets = [ {dx:-1, dy:-1}, {dx:0, dy:-1}, {dx:1, dy:-1}, {dx:-1, dy:0}, {dx:1, dy:0}, {dx:-1, dy:1}, {dx:0, dy:1}, {dx:1, dy:1} ]; kingOffsets.forEach(o => { const kx = px + o.dx, ky = py + o.dy; if (kx >= 0 && kx < GRID_SIZE && ky >= 0 && ky < GRID_SIZE) { const target = getPieceAt(kx, ky); if (!target) { moves.push({ x: kx, y: ky, isCapture: false }); } else if (isEnemy(target)) { moves.push({ x: kx, y: ky, isCapture: true }); } } }); break; } } return moves; } function raycastMoves(piece, directions, movesList) { directions.forEach(d => { let step = 1; while (true) { const tx = piece.x + (d.dx * step); const ty = piece.y + (d.dy * step); if (tx < 0 || tx >= GRID_SIZE || ty < 0 || ty >= GRID_SIZE) break; const target = getPieceAt(tx, ty); if (!target) { movesList.push({ x: tx, y: ty, isCapture: false }); } else { if (target.color !== piece.color) { movesList.push({ x: tx, y: ty, isCapture: true }); } break; // Blocked by piece } step++; } }); } /* Execute Command Move */ function executeMove(piece, targetX, targetY) { if (!piece) return; const targetPiece = getPieceAt(targetX, targetY); // Remove from old board spot board[piece.y][piece.x] = null; // Reserve target spot piece.startX = piece.x; piece.startY = piece.y; piece.targetX = targetX; piece.targetY = targetY; piece.animating = true; piece.hasMoved = true; piece.triggerCooldown(); // Handle Capture if (targetPiece) { // Spawn Explosion Particles createExplosion(targetX, targetY, targetPiece.color === 'blue' ? '#00f0ff' : '#ff0055'); // Award Bounty Gold const bounty = PIECE_SPECS[targetPiece.type].bounty; if (piece.color === 'blue') { player.gold += bounty; player.totalEarned += bounty; player.captures++; addFloatingText(`+${bounty}g`, targetX, targetY, '#f59e0b'); logBattle(`Blue ${piece.type.toUpperCase()} captured Red ${targetPiece.type.toUpperCase()}! (+${bounty}g)`); } else { ai.gold += bounty; logBattle(`Red ${piece.type.toUpperCase()} captured Blue ${targetPiece.type.toUpperCase()}!`); } sound.capture(); // Check King Elimination if (targetPiece.type === 'king') { removePiece(targetPiece); board[targetY][targetX] = piece; endGame(piece.color === 'blue' ? 'player' : 'ai'); return; } removePiece(targetPiece); } else { sound.move(); } board[targetY][targetX] = piece; // Update Node Control checkControlNodes(); } /* Check Control Points Ownership */ function checkControlNodes() { CONTROL_NODES.forEach(node => { const occupant = getPieceAt(node.x, node.y); const oldOwner = node.owner; if (occupant) { node.owner = occupant.color; if (oldOwner !== occupant.color) { sound.node(); const colorName = occupant.color === 'blue' ? 'Blue' : 'Red'; logBattle(`${colorName} Commander captured Control Node (${node.x + 1}, ${node.y + 1})!`); addFloatingText(`NODE CAPTURED!`, node.x, node.y, occupant.color === 'blue' ? '#00f0ff' : '#ff0055'); } } }); updateIncomeRates(); } function updateIncomeRates() { let blueNodes = CONTROL_NODES.filter(n => n.owner === 'blue').length; let redNodes = CONTROL_NODES.filter(n => n.owner === 'red').length; player.income = BASE_INCOME_PER_SEC + (blueNodes * NODE_INCOME_PER_SEC); ai.income = BASE_INCOME_PER_SEC + (redNodes * NODE_INCOME_PER_SEC); document.getElementById('nodes-blue').textContent = blueNodes; document.getElementById('nodes-red').textContent = redNodes; document.getElementById('nodes-neutral').textContent = 4 - blueNodes - redNodes; document.getElementById('player-income').textContent = player.income; } /* ========================================================================== 4. AI OPPONENT LOGIC ========================================================================== */ function setupAIArmy() { // AI Drafts army with 250 Gold let budget = STARTING_BUDGET; // Mandatory King at back row center (y = 0) const kingX = 6 + Math.floor(Math.random() * 2); placePiece(new Piece('king', 'red', kingX, 0)); budget -= PIECE_SPECS.king.cost; // AI Draft roster template const desiredUnits = ['queen', 'rook', 'rook', 'bishop', 'bishop', 'knight', 'knight', 'pawn', 'pawn', 'pawn', 'pawn']; for (let type of desiredUnits) { if (budget >= PIECE_SPECS[type].cost) { // Find empty square in top 3 rows (Y = 0, 1, 2) let placed = false; let attempts = 0; while (!placed && attempts < 50) { let rx = Math.floor(Math.random() * GRID_SIZE); let ry = Math.floor(Math.random() * 3); if (!getPieceAt(rx, ry)) { placePiece(new Piece(type, 'red', rx, ry)); budget -= PIECE_SPECS[type].cost; placed = true; } attempts++; } } } ai.gold = budget; } function updateAILogic(now) { if (gameState !== 'PLAYING') return; // AI Action Intervals based on Difficulty const intervals = { easy: 1800, medium: 1000, hard: 450 }; const cooldown = intervals[aiDifficulty] || 1000; if (now - ai.lastActionTime < cooldown) return; ai.lastActionTime = now; // 1. AI Real-Time Purchases if gold permits if (ai.gold >= 40 && Math.random() < 0.4) { const affordable = Object.keys(PIECE_SPECS).filter(k => k !== 'king' && PIECE_SPECS[k].cost <= ai.gold); if (affordable.length > 0) { const buyType = affordable[Math.floor(Math.random() * affordable.length)]; // Find spawn row (Y = 0 or 1) let spawnX = Math.floor(Math.random() * GRID_SIZE); let spawnY = Math.floor(Math.random() * 2); if (!getPieceAt(spawnX, spawnY)) { const p = new Piece(buyType, 'red', spawnX, spawnY); p.triggerCooldown(2.0); // Warp-in cooldown placePiece(p); ai.gold -= PIECE_SPECS[buyType].cost; logBattle(`AI Reinforcement: Red ${buyType.toUpperCase()} warped onto battlefield!`); createWarpEffect(spawnX, spawnY, '#ff0055'); } } } // 2. AI Combat Moves Evaluation const readyPieces = pieces.filter(p => p.color === 'red' && p.isReady()); if (readyPieces.length === 0) return; let bestMove = null; let highestScore = -999; readyPieces.forEach(p => { const moves = getValidMoves(p); moves.forEach(m => { let score = 0; const targetPiece = getPieceAt(m.x, m.y); // Priority 1: High-value Captures if (targetPiece) { score += PIECE_SPECS[targetPiece.type].cost * 10; if (targetPiece.type === 'king') score += 10000; // Immediate win } // Priority 2: Occupying / Capturing Control Nodes const isNode = CONTROL_NODES.some(n => n.x === m.x && n.y === m.y && n.owner !== 'red'); if (isNode) score += 40; // Priority 3: Advancing towards opponent King / forward progression score += (m.y * 2); // Moving down board (+Y) // Randomness noise depending on difficulty const noise = { easy: 30, medium: 10, hard: 2 }[aiDifficulty]; score += (Math.random() * noise); if (score > highestScore) { highestScore = score; bestMove = { piece: p, x: m.x, y: m.y }; } }); }); if (bestMove) { executeMove(bestMove.piece, bestMove.x, bestMove.y); } } /* ========================================================================== 5. PARTICLES & VISUAL FX ========================================================================== */ function createExplosion(gridX, gridY, color) { const px = (gridX + 0.5) * tileSize; const py = (gridY + 0.5) * tileSize; for (let i = 0; i < 25; i++) { const angle = Math.random() * Math.PI * 2; const speed = 1 + Math.random() * 6; particles.push({ x: px, y: py, vx: Math.cos(angle) * speed, vy: Math.sin(angle) * speed, size: 3 + Math.random() * 4, color: color, alpha: 1, life: 0.4 + Math.random() * 0.4 }); } } function createWarpEffect(gridX, gridY, color) { const px = (gridX + 0.5) * tileSize; const py = (gridY + 0.5) * tileSize; for (let i = 0; i < 15; i++) { particles.push({ x: px + (Math.random() - 0.5) * tileSize * 0.8, y: py + (Math.random() - 0.5) * tileSize * 0.8, vx: 0, vy: -1 - Math.random() * 2, size: 2 + Math.random() * 3, color: color, alpha: 1, life: 0.5 }); } } function addFloatingText(text, gridX, gridY, color) { const px = (gridX + 0.5) * tileSize; const py = (gridY + 0.5) * tileSize; floatingTexts.push({ text, x: px, y: py, color, alpha: 1, life: 1.2 }); } function updateParticles(dt) { for (let i = particles.length - 1; i >= 0; i--) { const p = particles[i]; p.x += p.vx; p.y += p.vy; p.life -= dt; p.alpha = Math.max(0, p.life); if (p.life <= 0) particles.splice(i, 1); } for (let i = floatingTexts.length - 1; i >= 0; i--) { const ft = floatingTexts[i]; ft.y -= 20 * dt; ft.life -= dt; ft.alpha = Math.max(0, ft.life); if (ft.life <= 0) floatingTexts.splice(i, 1); } } /* ========================================================================== 6. RENDERER (CANVAS) ========================================================================== */ function render() { ctx.clearRect(0, 0, canvas.width, canvas.height); // 1. Draw Board Grid for (let r = 0; r < GRID_SIZE; r++) { for (let c = 0; c < GRID_SIZE; c++) { const x = c * tileSize; const y = r * tileSize; // Alternating Dark / Slate Tiles const isDark = (r + c) % 2 === 1; ctx.fillStyle = isDark ? '#0f172a' : '#1e293b'; ctx.fillRect(x, y, tileSize, tileSize); // Deployment Zone Overlays if (r >= 11) { // Blue Zone ctx.fillStyle = 'rgba(0, 240, 255, 0.04)'; ctx.fillRect(x, y, tileSize, tileSize); } else if (r <= 2) { // Red Zone ctx.fillStyle = 'rgba(255, 0, 85, 0.04)'; ctx.fillRect(x, y, tileSize, tileSize); } // Grid Lines ctx.strokeStyle = '#1e293b'; ctx.lineWidth = 0.5; ctx.strokeRect(x, y, tileSize, tileSize); } } // 2. Draw Board Coordinates (A-N, 1-14) ctx.fillStyle = '#475569'; ctx.font = '10px Orbitron'; for (let i = 0; i < GRID_SIZE; i++) { const char = String.fromCharCode(65 + i); ctx.fillText(char, i * tileSize + 4, 12); ctx.fillText(14 - i, 4, i * tileSize + tileSize - 4); } // 3. Draw Control Nodes const nowTime = Date.now() * 0.003; CONTROL_NODES.forEach(node => { const nx = (node.x + 0.5) * tileSize; const ny = (node.y + 0.5) * tileSize; const radius = tileSize * 0.38; // Node Glow Ring ctx.save(); ctx.beginPath(); ctx.arc(nx, ny, radius, 0, Math.PI * 2); let nodeColor = '#64748b'; // neutral if (node.owner === 'blue') nodeColor = '#00f0ff'; if (node.owner === 'red') nodeColor = '#ff0055'; ctx.strokeStyle = nodeColor; ctx.lineWidth = 3; ctx.shadowColor = nodeColor; ctx.shadowBlur = 12; ctx.stroke(); // Pulsing Core ctx.beginPath(); ctx.arc(nx, ny, radius * 0.4 + Math.sin(nowTime) * 3, 0, Math.PI * 2); ctx.fillStyle = nodeColor; ctx.globalAlpha = 0.3; ctx.fill(); ctx.restore(); }); // 4. Draw Valid Moves / Highlights validMoves.forEach(m => { const mx = m.x * tileSize; const my = m.y * tileSize; ctx.save(); if (m.isCapture) { // Red Capture Highlight ctx.fillStyle = 'rgba(255, 0, 85, 0.3)'; ctx.strokeStyle = '#ff0055'; ctx.lineWidth = 2; ctx.fillRect(mx, my, tileSize, tileSize); ctx.strokeRect(mx + 1, my + 1, tileSize - 2, tileSize - 2); } else { // Cyan Move Highlight ctx.fillStyle = 'rgba(0, 240, 255, 0.2)'; ctx.fillRect(mx, my, tileSize, tileSize); ctx.beginPath(); ctx.arc(mx + tileSize / 2, my + tileSize / 2, tileSize * 0.18, 0, Math.PI * 2); ctx.fillStyle = '#00f0ff'; ctx.fill(); } ctx.restore(); }); // 5. Draw Selected Unit Highlight if (selectedUnit) { ctx.save(); ctx.strokeStyle = '#00f0ff'; ctx.lineWidth = 3; ctx.shadowColor = '#00f0ff'; ctx.shadowBlur = 10; ctx.strokeRect(selectedUnit.x * tileSize + 2, selectedUnit.y * tileSize + 2, tileSize - 4, tileSize - 4); ctx.restore(); } // 6. Draw Pieces pieces.forEach(p => { const px = p.renderX * tileSize; const py = p.renderY * tileSize; ctx.save(); // Piece Symbol const spec = PIECE_SPECS[p.type]; ctx.font = `${tileSize * 0.62}px Inter, sans-serif`; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; // Neon Shadow for Piece const isBlue = (p.color === 'blue'); ctx.shadowColor = isBlue ? '#00f0ff' : '#ff0055'; ctx.shadowBlur = p.isReady() ? 10 : 2; ctx.fillStyle = isBlue ? '#00f0ff' : '#ff0055'; ctx.fillText(spec.symbol, px + tileSize / 2, py + tileSize / 2 + 2); // Cooldown Bar above piece if (!p.isReady()) { const barW = tileSize * 0.7; const barH = 4; const barX = px + (tileSize - barW) / 2; const barY = py + 6; const progress = 1 - (p.cooldownTimer / p.maxCooldown); // Bar Background ctx.shadowBlur = 0; ctx.fillStyle = 'rgba(15, 23, 42, 0.8)'; ctx.fillRect(barX, barY, barW, barH); // Fill Progress ctx.fillStyle = isBlue ? '#38bdf8' : '#fb7185'; ctx.fillRect(barX, barY, barW * Math.max(0, Math.min(1, progress)), barH); } ctx.restore(); }); // 7. Draw Particles & Floating Text particles.forEach(p => { ctx.save(); ctx.globalAlpha = p.alpha; ctx.fillStyle = p.color; ctx.shadowColor = p.color; ctx.shadowBlur = 6; ctx.beginPath(); ctx.arc(p.x, p.y, p.size, 0, Math.PI * 2); ctx.fill(); ctx.restore(); }); floatingTexts.forEach(ft => { ctx.save(); ctx.globalAlpha = ft.alpha; ctx.font = 'bold 13px Orbitron'; ctx.fillStyle = ft.color; ctx.shadowColor = ft.color; ctx.shadowBlur = 8; ctx.textAlign = 'center'; ctx.fillText(ft.text, ft.x, ft.y); ctx.restore(); }); } /* ========================================================================== 7. UI & INTERACTION CONTROLLERS ========================================================================== */ function setupShopUI() { const grid = document.getElementById('shop-grid'); grid.innerHTML = ''; Object.keys(PIECE_SPECS).forEach(key => { const p = PIECE_SPECS[key]; const card = document.createElement('div'); card.className = `shop-item bg-slate-950 p-2 rounded-lg border border-slate-800 hover:border-cyan-500/50 cursor-pointer transition flex flex-col justify-between group`; card.dataset.type = key; card.innerHTML = ` <div class="flex items-center justify-between"> <span class="text-xl group-hover:scale-110 transition-transform">${p.symbol}</span> <span class="font-orbitron font-bold text-xs text-amber-400">${p.cost}g</span> </div> <div class="mt-1"> <div class="font-bold text-xs text-slate-200">${p.name}</div> <div class="text-[10px] text-slate-400">CD: ${p.cooldown}s</div> </div> `; card.addEventListener('click', () => selectShopItem(key)); grid.appendChild(card); }); } function selectShopItem(type) { sound.select(); if (selectedShopItem === type) { selectedShopItem = null; } else { selectedShopItem = type; selectedUnit = null; validMoves = []; } updateShopUIState(); } function updateShopUIState() { document.querySelectorAll('.shop-item').forEach(el => { const type = el.dataset.type; const cost = PIECE_SPECS[type].cost; if (selectedShopItem === type) { el.className = `shop-item bg-cyan-950/60 p-2 rounded-lg border-2 border-cyan-400 cursor-pointer transition flex flex-col justify-between shadow-lg shadow-cyan-500/20`; } else if (player.gold < cost) { el.className = `shop-item bg-slate-950/50 p-2 rounded-lg border border-slate-900 opacity-50 cursor-not-allowed flex flex-col justify-between`; } else { el.className = `shop-item bg-slate-950 p-2 rounded-lg border border-slate-800 hover:border-cyan-500/50 cursor-pointer transition flex flex-col justify-between group`; } }); } function updateSelectedUnitUI() { const coords = document.getElementById('selected-unit-coords'); const icon = document.getElementById('selected-unit-icon'); const name = document.getElementById('selected-unit-name'); const type = document.getElementById('selected-unit-type'); const cooldownWrap = document.getElementById('selected-unit-cooldown-wrap'); const cooldownText = document.getElementById('selected-unit-cooldown-text'); const cooldownBar = document.getElementById('selected-unit-cooldown-bar'); if (!selectedUnit) { coords.textContent = 'None'; icon.textContent = 'βš”οΈ'; icon.className = 'w-12 h-12 rounded-lg bg-slate-950 border border-slate-800 flex items-center justify-center text-3xl text-slate-600'; name.textContent = 'No Unit Selected'; type.textContent = 'Click any unit on the board'; cooldownWrap.classList.add('hidden'); return; } const spec = PIECE_SPECS[selectedUnit.type]; const charX = String.fromCharCode(65 + selectedUnit.x); coords.textContent = `${charX}${14 - selectedUnit.y}`; icon.textContent = spec.symbol; icon.className = `w-12 h-12 rounded-lg bg-slate-950 border border-cyan-500 flex items-center justify-center text-3xl ${selectedUnit.color === 'blue' ? 'text-cyan-400' : 'text-rose-400'}`; name.textContent = `${selectedUnit.color.toUpperCase()} ${spec.name}`; type.textContent = spec.desc; cooldownWrap.classList.remove('hidden'); if (selectedUnit.isReady()) { cooldownText.textContent = 'Ready'; cooldownText.className = 'text-emerald-400 font-bold'; cooldownBar.style.width = '100%'; cooldownBar.className = 'bg-emerald-400 h-full transition-all duration-100'; } else { const pct = ((1 - (selectedUnit.cooldownTimer / selectedUnit.maxCooldown)) * 100).toFixed(0); cooldownText.textContent = `${selectedUnit.cooldownTimer.toFixed(1)}s`; cooldownText.className = 'text-amber-400 font-bold'; cooldownBar.style.width = `${pct}%`; cooldownBar.className = 'bg-amber-400 h-full transition-all duration-100'; } } function logBattle(msg) { const log = document.getElementById('battle-log'); const time = new Date().toLocaleTimeString([], { hour12: false, minute: '2-digit', second: '2-digit' }); log.textContent = `[${time}] ${msg}`; } /* Handle Board Click / Touch */ function handleCanvasClick(e) { sound.init(); const rect = canvas.getBoundingClientRect(); const clickX = e.clientX - rect.left; const clickY = e.clientY - rect.top; const gridX = Math.floor(clickX / tileSize); const gridY = Math.floor(clickY / tileSize); if (gridX < 0 || gridX >= GRID_SIZE || gridY < 0 || gridY >= GRID_SIZE) return; const clickedPiece = getPieceAt(gridX, gridY); // 1. DRAFT OR IN-GAME PURCHASING MODE if (selectedShopItem) { const spec = PIECE_SPECS[selectedShopItem]; // Ensure within Blue deployment zone (rows 11-13) if (gridY < 11) { logBattle(`Must deploy reinforcements in Blue Zone (Rows 12-14)!`); return; } if (clickedPiece) { logBattle(`Tile occupied! Choose an empty tile.`); return; } if (player.gold >= spec.cost) { player.gold -= spec.cost; const p = new Piece(selectedShopItem, 'blue', gridX, gridY); if (gameState === 'PLAYING') p.triggerCooldown(2.0); // Warp-in delay in real time placePiece(p); sound.buy(); logBattle(`Deployed Blue ${spec.name.toUpperCase()} at (${gridX + 1}, ${gridY + 1})`); createWarpEffect(gridX, gridY, '#00f0ff'); // Keep item selected if still affordable, else clear selection if (player.gold < spec.cost) selectedShopItem = null; updateShopUIState(); } else { logBattle(`Insufficient gold! Needed ${spec.cost}g.`); } return; } // 2. UNIT SELECTION & MOVEMENT if (selectedUnit) { // Check if clicking a valid move square const targetMove = validMoves.find(m => m.x === gridX && m.y === gridY); if (targetMove && gameState === 'PLAYING') { executeMove(selectedUnit, gridX, gridY); selectedUnit = null; validMoves = []; updateSelectedUnitUI(); return; } } // 3. SELECT PIECE ON BOARD if (clickedPiece) { if (gameState === 'DRAFT' && clickedPiece.color === 'blue' && e.button === 2) { // Right-click refund during draft player.gold += PIECE_SPECS[clickedPiece.type].cost; removePiece(clickedPiece); selectedUnit = null; validMoves = []; logBattle(`Refunded ${clickedPiece.type.toUpperCase()}`); updateShopUIState(); return; } sound.select(); selectedUnit = clickedPiece; if (selectedUnit.color === 'blue' && gameState === 'PLAYING') { validMoves = getValidMoves(selectedUnit); } else { validMoves = []; } } else { selectedUnit = null; validMoves = []; } updateSelectedUnitUI(); } /* ========================================================================== 8. MATCH TIMERS & GAME LIFECYCLE ========================================================================== */ function startCombat() { // Ensure player has placed a King const playerKing = pieces.find(p => p.color === 'blue' && p.type === 'king'); if (!playerKing) { alert("You must draft & place your Blue King on the board before starting combat!"); return; } gameState = 'PLAYING'; selectedShopItem = null; selectedUnit = null; validMoves = []; updateShopUIState(); document.getElementById('game-phase-badge').textContent = 'REAL-TIME COMBAT'; document.getElementById('game-phase-badge').className = 'px-2.5 py-0.5 rounded-full text-xs font-orbitron font-bold uppercase bg-cyan-500/20 text-cyan-400 border border-cyan-500/30 animate-pulse'; document.getElementById('btn-primary-action').textContent = 'βš”οΈ War In Progress'; document.getElementById('btn-primary-action').disabled = true; document.getElementById('btn-primary-action').className = 'w-full py-3 px-4 rounded-xl font-orbitron font-bold text-sm tracking-wider uppercase bg-slate-800 text-slate-500 cursor-not-allowed'; document.getElementById('overlay-banner').classList.add('hidden'); logBattle("War declared! Passive income & node capture activated."); // Start Income Timer (+1s tick) if (!incomeTimerInterval) { incomeTimerInterval = setInterval(() => { if (gameState === 'PLAYING') { player.gold += player.income; player.totalEarned += player.income; ai.gold += ai.income; document.getElementById('player-gold').textContent = player.gold; updateShopUIState(); } }, 1000); } // Start Match Duration Clock if (!matchTimerInterval) { matchTimerInterval = setInterval(() => { if (gameState === 'PLAYING') { matchTimeSeconds++; const m = String(Math.floor(matchTimeSeconds / 60)).padStart(2, '0'); const s = String(matchTimeSeconds % 60).padStart(2, '0'); document.getElementById('match-timer').textContent = `${m}:${s}`; } }, 1000); } } function endGame(winner) { gameState = 'GAMEOVER'; clearInterval(matchTimerInterval); clearInterval(incomeTimerInterval); matchTimerInterval = null; incomeTimerInterval = null; const card = document.getElementById('gameover-card'); const title = document.getElementById('gameover-title'); const sub = document.getElementById('gameover-subtitle'); const icon = document.getElementById('gameover-icon'); const m = String(Math.floor(matchTimeSeconds / 60)).padStart(2, '0'); const s = String(matchTimeSeconds % 60).padStart(2, '0'); document.getElementById('stat-match-time').textContent = `${m}:${s}`; document.getElementById('stat-captures').textContent = player.captures; document.getElementById('stat-gold').textContent = `${player.totalEarned}g`; if (winner === 'player') { sound.victory(); icon.textContent = 'πŸ†'; title.textContent = 'VICTORY!'; title.className = 'font-orbitron font-black text-2xl text-cyan-400 uppercase tracking-wide text-glow-cyan'; sub.textContent = 'You captured the enemy Red King and claimed total tactical supremacy!'; card.className = 'bg-slate-900 border-2 border-cyan-500 rounded-2xl max-w-md w-full p-6 text-center shadow-2xl relative glow-cyan'; } else { sound.defeat(); icon.textContent = 'πŸ’€'; title.textContent = 'DEFEAT'; title.className = 'font-orbitron font-black text-2xl text-rose-500 uppercase tracking-wide text-glow-red'; sub.textContent = 'Your Blue King was captured by the AI commander.'; card.className = 'bg-slate-900 border-2 border-rose-500 rounded-2xl max-w-md w-full p-6 text-center shadow-2xl relative glow-red'; } document.getElementById('modal-gameover').classList.remove('hidden'); } function resetGame() { gameState = 'DRAFT'; matchTimeSeconds = 0; clearInterval(matchTimerInterval); clearInterval(incomeTimerInterval); matchTimerInterval = null; incomeTimerInterval = null; player = { color: 'blue', gold: STARTING_BUDGET, income: BASE_INCOME_PER_SEC, totalEarned: STARTING_BUDGET, captures: 0 }; ai = { color: 'red', gold: STARTING_BUDGET, income: BASE_INCOME_PER_SEC, lastActionTime: 0 }; selectedShopItem = null; selectedUnit = null; validMoves = []; particles = []; floatingTexts = []; document.getElementById('player-gold').textContent = player.gold; document.getElementById('match-timer').textContent = '00:00'; document.getElementById('game-phase-badge').textContent = 'Draft Phase'; document.getElementById('game-phase-badge').className = 'px-2.5 py-0.5 rounded-full text-xs font-orbitron font-bold uppercase bg-amber-500/20 text-amber-400 border border-amber-500/30'; document.getElementById('btn-primary-action').textContent = 'πŸš€ Start War (Combat Phase)'; document.getElementById('btn-primary-action').disabled = false; document.getElementById('btn-primary-action').className = 'w-full py-3 px-4 rounded-xl font-orbitron font-bold text-sm tracking-wider uppercase transition-all duration-200 bg-gradient-to-r from-emerald-500 to-teal-600 hover:from-emerald-400 hover:to-teal-500 text-black shadow-lg shadow-emerald-500/25 active:scale-[0.98]'; document.getElementById('overlay-banner').classList.remove('hidden'); document.getElementById('modal-gameover').classList.add('hidden'); initBoard(); setupAIArmy(); updateShopUIState(); updateSelectedUnitUI(); logBattle("Game reset. Draft your army to begin!"); } /* MAIN GAME LOOP */ let lastFrameTime = performance.now(); function gameLoop(now) { const dt = Math.min(0.1, (now - lastFrameTime) / 1000); lastFrameTime = now; if (gameState === 'PLAYING') { // Update Piece Cooldowns & Interpolations pieces.forEach(p => p.update(dt)); updateAILogic(now); } updateParticles(dt); updateSelectedUnitUI(); render(); requestAnimationFrame(gameLoop); } /* ========================================================================== 9. INITIALIZATION & EVENT BINDINGS ========================================================================== */ window.addEventListener('DOMContentLoaded', () => { canvas = document.getElementById('gameCanvas'); ctx = canvas.getContext('2d'); // Auto-fit Canvas internal resolution const size = 840; canvas.width = size; canvas.height = size; tileSize = size / GRID_SIZE; // Event Listeners canvas.addEventListener('click', handleCanvasClick); canvas.addEventListener('contextmenu', (e) => { e.preventDefault(); handleCanvasClick(e); }); document.getElementById('btn-primary-action').addEventListener('click', startCombat); document.getElementById('btn-reset').addEventListener('click', resetGame); document.getElementById('btn-restart-gameover').addEventListener('click', resetGame); document.getElementById('btn-pause').addEventListener('click', () => { if (gameState === 'PLAYING') { gameState = 'PAUSED'; document.getElementById('btn-pause').textContent = '▢️ Resume'; logBattle("Game Paused"); } else if (gameState === 'PAUSED') { gameState = 'PLAYING'; document.getElementById('btn-pause').textContent = '⏸️ Pause'; logBattle("Game Resumed"); } }); // Sound Toggle document.getElementById('btn-sound').addEventListener('click', () => { sound.enabled = !sound.enabled; document.getElementById('sound-icon').textContent = sound.enabled ? 'πŸ”Š' : 'πŸ”‡'; }); // Help Modal document.getElementById('btn-howtoplay').addEventListener('click', () => { document.getElementById('modal-help').classList.remove('hidden'); }); document.getElementById('btn-close-help').addEventListener('click', () => { document.getElementById('modal-help').classList.add('hidden'); }); // Difficulty Selector Cycle document.getElementById('ai-difficulty-badge').addEventListener('click', () => { const diffs = ['easy', 'medium', 'hard']; const next = diffs[(diffs.indexOf(aiDifficulty) + 1) % diffs.length]; aiDifficulty = next; document.getElementById('ai-difficulty-badge').textContent = `AI: ${next.toUpperCase()}`; logBattle(`AI Difficulty changed to ${next.toUpperCase()}`); }); // Setup UI & Board setupShopUI(); resetGame(); // Start loop requestAnimationFrame(gameLoop); }); </script> </body> </html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>RTS-CHESS: Real-Time Strategy Chess</title>
<!-- Tailwind CSS CDN -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Google Fonts: Orbitron & Inter -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Orbitron:wght@500;700;900&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Inter', sans-serif;
background-color: #080c14;
color: #f1f5f9;
user-select: none;
overflow-x: hidden;
}
.font-orbitron {
font-family: 'Orbitron', sans-serif;
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: #0f172a;
}
::-webkit-scrollbar-thumb {
background: #334155;
border-radius: 3px;
}
/* Neon Glow FX */
.glow-cyan {
box-shadow: 0 0 15px rgba(0, 240, 255, 0.4);
}
.glow-red {
box-shadow: 0 0 15px rgba(255, 0, 85, 0.4);
}
.text-glow-cyan {
text-shadow: 0 0 8px rgba(0, 240, 255, 0.6);
}
.text-glow-red {
text-shadow: 0 0 8px rgba(255, 0, 85, 0.6);
}
.border-glow-cyan {
border-color: #00f0ff;
box-shadow: 0 0 10px rgba(0, 240, 255, 0.3);
}
/* Canvas Container */
#canvas-container {
position: relative;
touch-action: none;
}
/* Modal Backdrop */
.modal-backdrop {
background: rgba(4, 7, 13, 0.85);
backdrop-filter: blur(8px);
}
</style>
</head>
<body class="min-h-screen flex flex-col justify-between">
<!-- TOP HEADER / NAV -->
<header class="bg-slate-900/90 border-b border-slate-800 px-4 py-2 flex items-center justify-between z-10 sticky top-0">
<div class="flex items-center gap-3">
<div class="w-9 h-9 rounded-lg bg-gradient-to-br from-cyan-500 to-blue-600 flex items-center justify-center font-orbitron font-black text-xl text-black shadow-lg shadow-cyan-500/30">
β™”
</div>
<div>
<h1 class="font-orbitron font-black text-lg md:text-xl tracking-wider text-transparent bg-clip-text bg-gradient-to-r from-cyan-400 via-blue-400 to-indigo-400">
RTS-CHESS
</h1>
<p class="text-xs text-slate-400 font-medium hidden sm:block">14x14 Real-Time Tactical Warfare</p>
</div>
</div>
<!-- Match Status Center -->
<div class="flex items-center gap-4 bg-slate-950/80 px-4 py-1.5 rounded-full border border-slate-800">
<div id="game-phase-badge" class="px-2.5 py-0.5 rounded-full text-xs font-orbitron font-bold uppercase bg-amber-500/20 text-amber-400 border border-amber-500/30">
Draft Phase
</div>
<div class="h-4 w-[1px] bg-slate-800"></div>
<div class="flex items-center gap-2">
<span class="text-xs text-slate-400 uppercase font-semibold">Time:</span>
<span id="match-timer" class="font-orbitron text-sm font-bold text-cyan-400">00:00</span>
</div>
</div>
<!-- Settings & Quick Actions -->
<div class="flex items-center gap-2">
<button id="btn-sound" class="p-2 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-300 transition text-sm flex items-center gap-1.5 border border-slate-700">
<span id="sound-icon">πŸ”Š</span>
</button>
<button id="btn-howtoplay" class="px-3 py-1.5 rounded-lg bg-slate-800 hover:bg-slate-700 text-slate-200 text-xs font-semibold border border-slate-700 transition">
Help / Rules
</button>