/* ============================================================ BUFFALO SIEGE · Desert Defense — app core ============================================================ */ 'use strict'; const device = document.getElementById('device'); const screenEl = document.getElementById('screen'); const canvasRoot = document.getElementById('canvasRoot'); const W = 430, H = 932; function fit(){ const s = Math.min(screenEl.clientWidth / W, screenEl.clientHeight / H); canvasRoot.style.transform = `scale(${s})`; } addEventListener('resize', fit); /* ---------------- utils ---------------- */ const fmt = n => Number(n).toLocaleString('en-US'); const todayKey = () => { const d = new Date(); return d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0'); }; const clamp = (v,a,b) => Math.max(a, Math.min(b, v)); const lerp = (a,b,t) => a + (b-a)*t; const rnd = (a,b) => a + Math.random()*(b-a); const pick = arr => arr[(Math.random()*arr.length)|0]; const TAU = Math.PI*2; function rr(c,x,y,w,h,r){ r=Math.min(r,w/2,h/2); c.beginPath(); c.moveTo(x+r,y); c.arcTo(x+w,y,x+w,y+h,r); c.arcTo(x+w,y+h,x,y+h,r); c.arcTo(x,y+h,x,y,r); c.arcTo(x,y,x+w,y,r); c.closePath(); } function seedRnd(seed){ let s=seed>>>0; return ()=>{ s=(s*1664525+1013904223)>>>0; return s/4294967296; }; } /* ---------------- audio ---------------- */ const AU = { ctx:null, get on(){ return state.sfx; }, init(){ if(!this.ctx){ try{ this.ctx = new (window.AudioContext||window.webkitAudioContext)(); }catch(e){} } }, tone(f0,f1,dur,type,vol){ if(!this.on) return; this.init(); const c=this.ctx; if(!c) return; const t=c.currentTime, o=c.createOscillator(), g=c.createGain(); o.type=type||'square'; o.frequency.setValueAtTime(f0,t); o.frequency.exponentialRampToValueAtTime(Math.max(30,f1),t+dur); g.gain.setValueAtTime(0.0001,t); g.gain.exponentialRampToValueAtTime(vol||0.12,t+0.012); g.gain.exponentialRampToValueAtTime(0.0001,t+dur); o.connect(g); g.connect(c.destination); o.start(t); o.stop(t+dur+0.02); }, noise(dur,vol,f){ if(!this.on) return; this.init(); const c=this.ctx; if(!c) return; const n=Math.floor(c.sampleRate*dur), buf=c.createBuffer(1,n,c.sampleRate), d=buf.getChannelData(0); for(let i=0;isetTimeout(()=>this.tone([520,660,780,1040][i],[520,660,780,1040][i],0.22,'triangle',0.11),d)); }, lose(){ [0,140,300].forEach((d,i)=>setTimeout(()=>this.tone([360,280,180][i],[300,200,90][i],0.3,'sawtooth',0.1),d)); }, freeze(){ this.tone(1200,300,0.4,'sine',0.09); }, strike(){ this.noise(0.5,0.24,500); this.tone(200,50,0.4,'sawtooth',0.13); } }; /* ---------------- background music ---------------- */ const BGM = { nodes:null, oscs:[], start(){ if(this.nodes) return; AU.init(); const c = AU.ctx; if(!c) return; const master = c.createGain(); master.gain.value = 0.0001; master.connect(c.destination); // wind: filtered noise loop const len = Math.floor(c.sampleRate*2); const buf = c.createBuffer(1, len, c.sampleRate); const d = buf.getChannelData(0); let last = 0; for(let i=0;i{ const o = c.createOscillator(); o.type = i===2 ? 'triangle' : 'sine'; o.frequency.value = f; const g = c.createGain(); g.gain.value = i===2 ? 0.16 : 0.42; o.connect(g); g.connect(pad); o.start(); const lfo = c.createOscillator(); lfo.frequency.value = 0.05 + i*0.017; const lg = c.createGain(); lg.gain.value = 0.18; lfo.connect(lg); lg.connect(g.gain); lfo.start(); this.oscs.push(o, lfo); }); src.start(); master.gain.exponentialRampToValueAtTime(0.06, c.currentTime + 2.0); this.nodes = { master, src }; }, stop(){ if(!this.nodes) return; const c = AU.ctx, { master, src } = this.nodes; try{ master.gain.cancelScheduledValues(c.currentTime); master.gain.setValueAtTime(master.gain.value, c.currentTime); master.gain.exponentialRampToValueAtTime(0.0001, c.currentTime + 0.5); }catch(e){} const oscs = this.oscs; setTimeout(()=>{ try{ src.stop(); }catch(e){} oscs.forEach(o=>{ try{o.stop();}catch(e){} }); }, 600); this.oscs = []; this.nodes = null; }, sync(){ state.music ? this.start() : this.stop(); } }; /* ---------------- save ---------------- */ const SAVE_KEY = 'buffalo_siege_style_a_preview_v1'; const BOTS = [ {name:'DustDevil',score:48200,wave:34},{name:'PrairieKing',score:41500,wave:31}, {name:'MesaRanger',score:36900,wave:28},{name:'VultureEye',score:31400,wave:26}, {name:'BisonBane',score:27800,wave:24},{name:'CactusJack',score:23100,wave:21}, {name:'RedDune',score:18700,wave:19},{name:'SilverSpur',score:14200,wave:16}, {name:'Tumbleweed',score:9800,wave:13},{name:'RookieRanger',score:5600,wave:10} ]; function defaults(){ return { coins:1500, items:{air:1,frost:0,repair:0,gold:1}, cleared:0, stars:{}, best:{score:0,wave:0}, board:BOTS.map(b=>({...b})), armory:{archer:1,pistol:1,crossbow:1,rifle:1,mortar:1}, player:{ name:'Desert Ranger', id:'', avatar:'bison' }, stats:{ kills:0, towers:0, waves:0 }, checkin:{ day:1, last:'' }, sfx:true, music:false, tutorial:0 }; } let state = defaults(); function save(){ try{ localStorage.setItem(SAVE_KEY, JSON.stringify(state)); }catch(e){} } function load(){ try{ const raw = localStorage.getItem(SAVE_KEY); if(!raw) return; const p = JSON.parse(raw); state = Object.assign(defaults(), p); state.items = Object.assign(defaults().items, p.items||{}); state.armory = Object.assign(defaults().armory, p.armory||{}); state.player = Object.assign(defaults().player, p.player||{}); state.stats = Object.assign(defaults().stats, p.stats||{}); state.checkin = Object.assign(defaults().checkin, p.checkin||{}); state.best = Object.assign({score:0,wave:0}, p.best||{}); if(!Array.isArray(state.board) || !state.board.length) state.board = BOTS.map(b=>({...b})); }catch(e){ state = defaults(); } } /* ---------------- data ---------------- */ const TOWERS = { archer:{ key:'archer', name:'Archer', cost:100, icon:'t-archer', proj:'arrow', pspeed:520, air:false, lv:[{dmg:11,rate:.75,range:108},{dmg:18,rate:.68,range:116},{dmg:29,rate:.60,range:124}], up:[90,150], tint:'#4BE38A', tag:'Rapid single target' }, crossbow:{ key:'crossbow', name:'Crossbow', cost:170, icon:'t-crossbow', proj:'bolt', pspeed:620, air:false, pierce:true, lv:[{dmg:46,rate:2.0,range:150},{dmg:74,rate:1.85,range:160},{dmg:118,rate:1.70,range:172}], up:[150,240], tint:'#FFD34D', tag:'Armor piercing sniper' }, pistol:{ key:'pistol', name:'Pistol', cost:130, icon:'t-pistol', proj:'bullet', pspeed:760, air:false, lv:[{dmg:7,rate:.38,range:92},{dmg:11,rate:.33,range:98},{dmg:17,rate:.29,range:105}], up:[110,180], tint:'#8FE9FF', tag:'Cheap rapid fire' }, rifle:{ key:'rifle', name:'Rifle', cost:250, icon:'t-rifle', proj:'hitscan', air:true, lv:[{dmg:38,rate:1.30,range:180},{dmg:62,rate:1.20,range:192},{dmg:98,rate:1.10,range:205}], up:[220,340], tint:'#FF8FA6', tag:'Long range · hits air' }, mortar:{ key:'mortar', name:'Mortar', cost:320, icon:'t-mortar', proj:'shell', pspeed:300, air:false, splash:1, lv:[{dmg:58,rate:2.5,range:165,splash:48},{dmg:95,rate:2.35,range:175,splash:54},{dmg:150,rate:2.2,range:188,splash:62}], up:[280,430], tint:'#FFA24D', tag:'Splash · ground only' } }; const TOWER_ORDER = ['archer','pistol','crossbow','rifle','mortar']; const ENEMIES = { rabbit: { key:'rabbit', name:'Jackrabbit', hp:30, spd:118, armor:0, gold:10, leak:1, r:12, air:false, col:'#E8C9A0' }, bison: { key:'bison', name:'Bison', hp:84, spd:70, armor:0, gold:14, leak:1, r:16, air:false, col:'#9A6A3A' }, wolf: { key:'wolf', name:'Wolf', hp:104, spd:92, armor:2, gold:16, leak:1, r:14, air:false, col:'#8C97A8' }, vulture: { key:'vulture', name:'Vulture', hp:68, spd:104, armor:0, gold:18, leak:1, r:13, air:true, col:'#6E5A78' }, scorpion:{ key:'scorpion',name:'Scorpion', hp:176, spd:58, armor:9, gold:26, leak:2, r:16, air:false, col:'#B04A2E' }, king: { key:'king', name:'Buffalo King',hp:1200,spd:50, armor:6, gold:150,leak:5, r:27, air:false, col:'#7A3E9E', boss:true } }; const COMBOS = [ { a:'archer', b:'crossbow', name:'Volley', desc:'+15% range, +10% fire rate' }, { a:'pistol', b:'rifle', name:'Suppression', desc:'+25% fire rate' }, { a:'rifle', b:'mortar', name:'Siege Line', desc:'+25% splash, +10% damage' }, { a:'crossbow', b:'mortar', name:'Pierce Shell', desc:'+20% damage, splash ignores armor' } ]; const ITEMS = { air: { key:'air', name:'Airstrike', price:800, icon:'it-air', desc:'Tap the field: 400 damage in a wide blast.' }, frost: { key:'frost', name:'Frost Nova', price:600, icon:'it-frost', desc:'Freeze every enemy on the map for 4 seconds.' }, repair: { key:'repair', name:'Repair Kit', price:1200, icon:'it-heal', desc:'Restore 3 base HP (max 20).' }, gold: { key:'gold', name:'Gold Rush', price:500, icon:'it-gold', desc:'Instantly add 300 battle gold.' } }; const ITEM_ORDER = ['air','frost','repair','gold']; const AVATARS = [ { key:'bison', icon:'a-bison', col:'#FFC21F' }, { key:'wolf', icon:'a-wolf', col:'#8FE9FF' }, { key:'eagle', icon:'a-eagle', col:'#FF6B8A' }, { key:'scorpion', icon:'a-scorpion', col:'#FF8A4D' }, { key:'rabbit', icon:'a-rabbit', col:'#4BE38A' }, { key:'bear', icon:'a-bear', col:'#B98AFF' }, { key:'horse', icon:'a-horse', col:'#FFD98A' }, { key:'snake', icon:'a-snake', col:'#34E0FF' } ]; function avatarOf(key){ return AVATARS.find(a=>a.key===key) || AVATARS[0]; } function newPlayerId(){ return String(Math.floor(10000000 + Math.random()*89999999)); } /* 7 天签到:5 天金币 + 2 天道具 */ const CHECKIN = [ { type:'coins', amt:300 }, { type:'item', key:'air', amt:1 }, { type:'coins', amt:600 }, { type:'coins', amt:1000 }, { type:'item', key:'repair', amt:1 }, { type:'coins', amt:1500 }, { type:'coins', amt:2500 } ]; function checkinIndex(){ return (state.checkin.day - 1) % 7; } function canCheckin(){ return state.checkin.last !== todayKey(); } function renderCheckin(){ const idx = checkinIndex(); const day = state.checkin.day; document.getElementById('ckStreak').textContent = 'DAY ' + day + ' / 7'; document.getElementById('ckBar').style.width = (day/7*100) + '%'; const list = document.getElementById('ckList'); list.innerHTML = ''; CHECKIN.forEach((r,i)=>{ const done = i < idx, today = i === idx; const icon = r.type==='coins' ? 'i-coin' : ITEMS[r.key].icon; const label = r.type==='coins' ? fmt(r.amt) + ' coins' : ITEMS[r.key].name + ' ×' + r.amt; const row = document.createElement('div'); row.className = 'ck-row' + (done?' is-done':'') + (today?' is-today':'') + (!done&&!today?' is-lock':''); row.innerHTML = `
DAY ${i+1}${label}
${done?'CLAIMED':today?'TODAY':'LOCKED'}
`; list.appendChild(row); }); const ok = canCheckin(); const btn = document.getElementById('ckClaim'); btn.disabled = !ok; btn.textContent = ok ? 'CLAIM DAY ' + day : 'CLAIMED TODAY'; document.getElementById('ckHint').textContent = ok ? 'One claim per day · resets every 7 days' : 'Already claimed today · next reward tomorrow'; document.getElementById('checkinDot').classList.toggle('is-on', ok); } function claimCheckin(){ if(!canCheckin()){ AU.err(); toast('Already claimed today'); return; } const r = CHECKIN[checkinIndex()]; if(r.type==='coins'){ state.coins += r.amt; } else { state.items[r.key] = (state.items[r.key]||0) + r.amt; } const day = state.checkin.day; state.checkin.day = (day % 7) + 1; state.checkin.last = todayKey(); save(); AU.upgrade(); renderCheckin(); renderLobby(); toast('Day ' + day + ' claimed · ' + (r.type==='coins' ? fmt(r.amt)+' coins' : ITEMS[r.key].name+' ×'+r.amt)); } function ensurePlayer(){ if(!state.player) state.player = defaults().player; if(!state.player.id) state.player.id = newPlayerId(); if(!state.player.name) state.player.name = 'Desert Ranger'; if(!state.player.avatar) state.player.avatar = 'bison'; if(!state.stats) state.stats = defaults().stats; } const ARMORY_MAX = 5; const ARMORY_DMG = 0.08; // +8% damage per level const ARMORY_RNG = 0.02; // +2% range per level const ARMORY_MULT = [2, 3.5, 5.5, 8]; function armoryLv(type){ return clamp(state.armory[type]||1, 1, ARMORY_MAX); } function armoryBonus(type){ const lv = armoryLv(type); return { lv, dmg:1+ARMORY_DMG*(lv-1), range:1+ARMORY_RNG*(lv-1) }; } function armoryCost(type){ const lv = armoryLv(type); if(lv >= ARMORY_MAX) return 0; return Math.round(TOWERS[type].cost * ARMORY_MULT[lv-1] / 10) * 10; } function upgradeArmory(type){ const lv = armoryLv(type), cost = armoryCost(type); if(lv >= ARMORY_MAX){ AU.err(); toast('Already max level'); return false; } if(state.coins < cost){ AU.err(); toast('Need ' + (cost-state.coins) + ' more coins'); return false; } state.coins -= cost; state.armory[type] = lv + 1; save(); AU.upgrade(); toast(`${TOWERS[type].name} upgraded to Lv.${lv+1}`); renderArmory(type); renderLobby(); if(currentView==='levels') document.getElementById('levelCoins').textContent = fmt(state.coins); return true; } const levelReward = n => 250 + n*135; const recArmory = n => Math.min(ARMORY_MAX, 1 + Math.floor((n-1)/4)); const levelWaves = n => 4 + Math.floor(n/2); /* 关卡血量倍率:二次曲线 + 新手保护(1–4 关 ×0.66,5–6 关 ×0.72) */ const levelHpMul = n => { const base = 1 + 0.20*(n-1) + 0.0125*(n-1)*(n-1); const ease = n<=4 ? 0.66 : (n<=6 ? 0.72 : 1); return base*ease; }; /* ---------------- navigation ---------------- */ let currentView = 'loading'; function showView(name){ document.querySelectorAll('.view').forEach(v=>v.classList.toggle('is-active', v.dataset.view===name)); currentView = name; if(name==='lobby') renderLobby(); if(name==='levels') renderLevels(); } function openSheet(id){ document.getElementById(id).classList.add('is-open'); } function closeSheet(id){ document.getElementById(id).classList.remove('is-open'); } function closeAllSheets(){ document.querySelectorAll('.sheet').forEach(s=>s.classList.remove('is-open')); } let toastTimer = null; function toast(msg){ const el = document.getElementById('toast'); el.textContent = msg; el.classList.add('is-on'); clearTimeout(toastTimer); toastTimer = setTimeout(()=>el.classList.remove('is-on'), 1600); } /* ---------------- start / mesa art ---------------- */ function paintDesert(c, w, h, opts){ opts = opts||{}; const rnd = seedRnd(opts.seed||7); const sky = c.createLinearGradient(0,0,0,h*0.72); sky.addColorStop(0,'#3B0F52'); sky.addColorStop(.28,'#7A1A56'); sky.addColorStop(.52,'#C4392C'); sky.addColorStop(.74,'#F07A28'); sky.addColorStop(1,'#F7BE63'); c.fillStyle = sky; c.fillRect(0,0,w,h*0.72); // sun const sx=w*0.5, sy=h*0.34, sr=Math.min(w,h)*0.24; const sg=c.createRadialGradient(sx,sy,0,sx,sy,sr*1.9); sg.addColorStop(0,'rgba(255,236,170,.95)'); sg.addColorStop(.34,'rgba(255,190,90,.55)'); sg.addColorStop(.62,'rgba(255,120,50,.18)'); sg.addColorStop(1,'rgba(255,120,50,0)'); c.fillStyle=sg; c.beginPath(); c.arc(sx,sy,sr*1.9,0,TAU); c.fill(); // mesa silhouettes for(let layer=0;layer<3;layer++){ const baseY = h*(0.56+layer*0.09); const col = ['rgba(96,32,60,.55)','rgba(120,44,50,.65)','rgba(72,26,40,.9)'][layer]; c.fillStyle = col; c.beginPath(); c.moveTo(0,h); let x=0; while(x{ const c = cv.getContext('2d'), w=cv.width, h=cv.height; paintDesert(c,w,h,{seed: cv.dataset.art==='campaign'?11:29, towers:true}); c.save(); // buffalo head emblem c.globalAlpha=.95; const img = new Path2D(); // simple emblem: shield + horns silhouette const cx=w/2, cy=h*0.44; c.fillStyle='rgba(20,4,20,.28)'; c.beginPath(); c.arc(cx,cy,h*0.3,0,TAU); c.fill(); c.restore(); }); } function paintStartLandscape(){ const cv = document.getElementById('mesaCanvas'); if(!cv) return; const c = cv.getContext('2d'), w = cv.width, h = cv.height; const rnd = seedRnd(913); c.clearRect(0,0,w,h); // ---- distant mesa ranges (atmospheric perspective) ---- const ranges = [ { y:h*0.40, col:'#8A3E6E', hi:'#B25C86', hh:0.13, n:4 }, { y:h*0.50, col:'#6E2A52', hi:'#93426C', hh:0.17, n:5 }, { y:h*0.61, col:'#4A1836', hi:'#6B2848', hh:0.20, n:6 } ]; ranges.forEach((R,ri)=>{ c.fillStyle=R.col; c.beginPath(); c.moveTo(0,h); let y = R.y - h*R.hh*0.55; c.lineTo(0,y); let x = 0; while(x < w+20){ const seg = w*(0.055+rnd()*0.075); const topMin = R.y - h*R.hh, topMax = R.y - h*R.hh*0.18; const dy = (rnd()-0.5)*h*R.hh*0.55; y = Math.max(topMin, Math.min(topMax, y + dy)); c.lineTo(x + seg*0.14, y); c.lineTo(x + seg*0.86, y); const drop = h*R.hh*(0.10+rnd()*0.28); c.lineTo(x + seg, Math.min(R.y, y + drop)); x += seg; } c.lineTo(w,h); c.closePath(); c.fill(); // faint top rim c.strokeStyle=`rgba(255,186,132,${0.22-ri*0.05})`; c.lineWidth=1.4; c.stroke(); }); // ---- sand floor ---- const gg = c.createLinearGradient(0,h*0.64,0,h); gg.addColorStop(0,'#D98A3E'); gg.addColorStop(.4,'#C0702E'); gg.addColorStop(1,'#7E401C'); c.fillStyle=gg; c.beginPath(); c.moveTo(0,h*0.70); c.lineTo(w,h*0.66); c.lineTo(w,h); c.lineTo(0,h); c.closePath(); c.fill(); // horizon glow const rg = c.createLinearGradient(0,h*0.56,0,h*0.74); rg.addColorStop(0,'rgba(255,190,110,.55)'); rg.addColorStop(1,'rgba(255,150,60,0)'); c.fillStyle=rg; c.fillRect(0,h*0.56,w,h*0.18); // dunes for(let i=0;i<6;i++){ c.fillStyle=`rgba(${214+i*5},${142+i*7},${70},.32)`; c.beginPath(); c.ellipse(w*(0.05+rnd()*0.9), h*(0.74+rnd()*0.22), w*0.28, h*0.032, 0,0,TAU); c.fill(); } // ground shadow under everything const sg = c.createLinearGradient(0,h*0.86,0,h); sg.addColorStop(0,'rgba(60,20,12,0)'); sg.addColorStop(1,'rgba(50,14,26,.55)'); c.fillStyle=sg; c.fillRect(0,h*0.86,w,h*0.14); // ---- stampede silhouettes on the horizon ---- const drawBeast = (bx,by,s)=>{ c.save(); c.translate(bx,by); c.scale(s,s); c.fillStyle='rgba(44,12,26,.82)'; c.beginPath(); c.ellipse(0,0,13,7.5,0,0,TAU); c.fill(); c.beginPath(); c.ellipse(6,-3.4,7,5,0,0,TAU); c.fill(); c.beginPath(); c.ellipse(11,-1,4.4,3.4,0,0,TAU); c.fill(); c.strokeStyle='rgba(44,12,26,.82)'; c.lineWidth=2.2; c.lineCap='round'; c.beginPath(); c.moveTo(10,-3); c.quadraticCurveTo(13,-7,11.5,-9); c.stroke(); c.beginPath(); c.moveTo(-9,5); c.lineTo(-9,11); c.moveTo(5,5); c.lineTo(5,11); c.stroke(); c.restore(); }; for(let i=0;i<5;i++) drawBeast(w*(0.5+i*0.115), h*0.655+rnd()*4, 0.72+rnd()*0.4); // ---- outpost silhouette (left) ---- c.save(); c.translate(w*0.13, h*0.87); c.scale(0.72,0.72); c.fillStyle='rgba(42,12,30,.92)'; c.fillRect(-24,-18,48,38); for(let i=0;i<5;i++) c.fillRect(-22+i*9, -26, 6, 46); c.beginPath(); c.moveTo(-30,-20); c.lineTo(0,-40); c.lineTo(30,-20); c.closePath(); c.fill(); c.fillRect(-1.4,-58,2.8,18); c.beginPath(); c.moveTo(1,-58); c.lineTo(16,-53); c.lineTo(1,-48); c.closePath(); c.fill(); c.restore(); // ---- cacti / scrub ---- for(let i=0;i<9;i++){ const cx=rnd()*w, cy=h*(0.75+rnd()*0.2), s=6+rnd()*9; c.strokeStyle='rgba(36,16,14,.8)'; c.lineWidth=3; c.lineCap='round'; c.beginPath(); c.moveTo(cx,cy); c.lineTo(cx,cy-s*1.6); c.moveTo(cx,cy-s); c.lineTo(cx-s*0.5,cy-s*1.2); c.moveTo(cx,cy-s*1.2); c.lineTo(cx+s*0.5,cy-s*1.6); c.stroke(); } } /* ---------------- lobby ---------------- */ function renderLobby(){ ensurePlayer(); const av = avatarOf(state.player.avatar); const lav = document.getElementById('lobbyAva'); if(lav) lav.innerHTML = ``; const lnm = document.getElementById('lobbyName'); if(lnm) lnm.textContent = state.player.name; const lid = document.getElementById('lobbyId'); if(lid) lid.textContent = state.player.id; const cdot = document.getElementById('checkinDot'); if(cdot) cdot.classList.toggle('is-on', canCheckin()); document.getElementById('lobbyCoinVal').textContent = fmt(state.coins); document.getElementById('lobbyBest').textContent = fmt(state.best.score); document.getElementById('campaignGo').textContent = state.cleared>=20 ? 'ALL 20 DONE' : 'LEVEL ' + (state.cleared+1); document.getElementById('lobbyCleared').innerHTML = state.cleared + '/20'; const stars = Object.keys(state.stars).reduce((a,k)=>a+(state.stars[k]||0),0); document.getElementById('lobbyStars').innerHTML = stars + '/60'; document.getElementById('lobbyWave').innerHTML = (state.best.wave||0) + 'W'; const ars = document.getElementById('arsenalRow'); ars.innerHTML = ''; TOWER_ORDER.forEach(k=>{ const d = TOWERS[k], lv = armoryLv(k); const el = document.createElement('div'); el.className = 'ars' + (lv>=ARMORY_MAX?' is-max':''); let pips = ''; for(let i=0;i`; el.innerHTML = `
Lv.${lv}
${d.name}
${pips}
`; el.onclick = ()=> openArmory(k); ars.appendChild(el); }); renderLobbyBoard(); drawModeArt(); } function renderLobbyBoard(){ const wrap = document.getElementById('lobbyBoard'); const list = [...state.board].sort((a,b)=>b.score-a.score); const top = list.slice(0,5); const mine = list.find(r=>r.me); const rows = top.map((r,i)=>boardRow(r, i+1)); if(mine && !top.includes(mine)) rows[4] = boardRow(mine, list.indexOf(mine)+1); wrap.innerHTML = rows.join(''); } function boardRow(r, rank){ const cls = ['r1','r2','r3'][rank-1] || ''; return `
${rank}
${r.name}${r.me?'YOU':''}
${fmt(r.score)}
W${r.wave}
`; } /* ---------------- profile ---------------- */ let profView = 'main'; function openProfile(){ profView='main'; renderProfile(); openSheet('sheetProfile'); } function profShow(v){ profView = v; document.getElementById('profMain').hidden = v!=='main'; document.getElementById('profAvatar').hidden = v!=='avatar'; document.getElementById('profRename').hidden = v!=='rename'; if(v==='rename'){ const inp = document.getElementById('nameInput'); inp.value = state.player.name; document.getElementById('nameMsg').className = 'msg'; document.getElementById('nameMsg').textContent = '3–20 characters · letters, numbers, - and _ · must start with a letter'; setTimeout(()=>{ inp.focus(); inp.select(); }, 60); } } function renderProfile(){ ensurePlayer(); const av = avatarOf(state.player.avatar); document.getElementById('profAva').innerHTML = ``; document.getElementById('profName').textContent = state.player.name; document.getElementById('profId').textContent = state.player.id; document.getElementById('profCoins').textContent = fmt(state.coins); document.getElementById('profBest').textContent = fmt(state.best.score||0); document.getElementById('profKills').textContent = fmt(state.stats.kills||0); document.getElementById('profCleared').textContent = state.cleared + ' / 20'; const stars = Object.keys(state.stars).reduce((a,k)=>a+(state.stars[k]||0),0); document.getElementById('profStars').textContent = stars + ' / 60 stars'; document.getElementById('profXp').style.width = (state.cleared/20*100) + '%'; document.getElementById('profEndless').textContent = 'best wave ' + (state.best.wave||0) + ' · ' + fmt(state.best.score||0) + ' pts'; document.getElementById('profEndlessXp').style.width = clamp((state.best.wave||0)/30*100, 0, 100) + '%'; const ars = document.getElementById('profArsenal'); ars.innerHTML = TOWER_ORDER.map(k=> `
${TOWERS[k].name}Lv.${armoryLv(k)}
` ).join(''); ars.querySelectorAll('[data-arm]').forEach(el=>{ el.onclick = ()=>{ closeSheet('sheetProfile'); openArmory(el.dataset.arm); }; }); document.getElementById('profArmoryLink').onclick = ()=>{ closeSheet('sheetProfile'); openArmory(); }; const bag = document.getElementById('profBag'); bag.innerHTML = ITEM_ORDER.map(k=> `
${ITEMS[k].name.split(' ')[0]}×${state.items[k]||0}
` ).join(''); document.getElementById('profShopLink').onclick = ()=>{ closeSheet('sheetProfile'); renderShop(); openSheet('sheetShop'); }; renderAvatarGrid(); profShow(profView); } function renderAvatarGrid(){ const g = document.getElementById('avGrid'); g.innerHTML = ''; AVATARS.forEach(a=>{ const el = document.createElement('div'); el.className = 'av-cell' + (state.player.avatar===a.key?' is-sel':''); el.setAttribute('aria-label',a.name||a.key); el.dataset.avatar=a.key; el.innerHTML = ``; el.onclick = ()=>{ state.player.avatar = a.key; save(); AU.hit(); renderAvatarGrid(); renderProfile(); renderLobby(); toast('Avatar updated'); }; g.appendChild(el); }); } function validName(n){ if(!/^[A-Za-z][A-Za-z0-9_-]{2,19}$/.test(n)) return '3–20 chars · start with a letter · letters, numbers, - and _ only'; if(['admin','system','buffalo','king','you','player'].includes(n.toLowerCase())) return 'That name is reserved'; return null; } function saveName(){ const inp = document.getElementById('nameInput'); const msg = document.getElementById('nameMsg'); const v = inp.value.trim(); const err = validName(v); if(err){ msg.className='msg bad'; msg.textContent = err; AU.err(); return; } state.player.name = v; save(); AU.upgrade(); msg.className='msg ok'; msg.textContent = 'Saved'; renderProfile(); renderLobby(); toast('Name updated to ' + v); setTimeout(()=>{ if(profView==='rename') profShow('main'); }, 550); } async function copyPlayerId(){ const id = state.player.id; try{ await navigator.clipboard.writeText(id); toast('ID copied · ' + id); }catch(e){ toast('Your ID · ' + id); } AU.coin(); } /* ---------------- armory ---------------- */ function openArmory(type){ renderArmory(type); openSheet('sheetArmory'); } function renderArmory(focus){ document.getElementById('armoryCoins').textContent = fmt(state.coins); const body = document.getElementById('armoryBody'); body.innerHTML = ''; TOWER_ORDER.forEach(k=>{ const d = TOWERS[k], lv = armoryLv(k), maxed = lv>=ARMORY_MAX; const cost = armoryCost(k); let pips = ''; for(let i=0;i`; const dmgPct = Math.round(ARMORY_DMG*(lv-1)*100); const rngPct = Math.round(ARMORY_RNG*(lv-1)*100); const ds = maxed ? 'Fully upgraded · +'+dmgPct+'% DMG · +'+rngPct+'% RNG' : (lv===1 ? 'Base stats · next +'+(ARMORY_DMG*100).toFixed(0)+'% DMG · +2% RNG' : 'DMG +'+dmgPct+'% · RNG +'+rngPct+'% · next +'+(dmgPct+ARMORY_DMG*100).toFixed(0)+'%'); const row = document.createElement('div'); row.className = 'arm-row' + (maxed?' is-max':'') + (focus===k?' is-focus':''); row.innerHTML = `
${d.name} LV.${lv}/${ARMORY_MAX}
${pips}
${ds}
${maxed ? '
MAX
' : `
${fmt(cost)}
`}
`; body.appendChild(row); }); body.querySelectorAll('[data-arm]').forEach(btn=>{ btn.onclick = ()=> upgradeArmory(btn.dataset.arm); }); } function renderLevels(){ document.getElementById('levelCoins').textContent = fmt(state.coins); document.getElementById('levelSub').textContent = `${state.cleared} / 20 cleared`; const grid = document.getElementById('lvGrid'); grid.innerHTML = ''; for(let n=1;n<=20;n++){ const st = state.stars[n]||0; const locked = n > state.cleared+1; const done = n <= state.cleared; const el = document.createElement('div'); el.className = 'lv' + (done?' lv--done':'') + (n===state.cleared+1?' lv--next':'') + (locked?' lv--lock':''); el.innerHTML = `${n}${done?'CLEARED':'WAVES '+levelWaves(n)}
REC Lv.${recArmory(n)}
${(n%5===0||n===20)?'
BOSS
':''}`; if(!locked) el.onclick = ()=>{ closeAllSheets(); startBattle('campaign', n); }; else el.onclick = ()=> toast('Clear level ' + (state.cleared+1) + ' first'); grid.appendChild(el); } } /* ---------------- shop ---------------- */ function renderShop(){ document.getElementById('shopCoins').textContent = fmt(state.coins); const body = document.getElementById('shopBody'); body.innerHTML = ''; ITEM_ORDER.forEach(k=>{ const it = ITEMS[k], own = state.items[k]||0; const row = document.createElement('div'); row.className = 'shop-row'; row.innerHTML = `
${it.name}
${it.desc}
OWNED ×${own}
${fmt(it.price)}
`; body.appendChild(row); }); body.querySelectorAll('[data-buy]').forEach(b=>{ b.onclick = ()=>{ const k=b.dataset.buy, it=ITEMS[k]; if(state.coins < it.price){ AU.err(); toast('Not enough coins'); return; } state.coins -= it.price; state.items[k] = (state.items[k]||0)+1; save(); AU.coin(); renderShop(); renderLobby(); toast(`${it.name} ×1 purchased`); if(currentView==='levels') document.getElementById('levelCoins').textContent = fmt(state.coins); }; }); } /* ---------------- leaderboard ---------------- */ function renderBoard(){ const body = document.getElementById('boardBody'); const list = [...state.board].sort((a,b)=>b.score-a.score).slice(0,10); const meIn = list.some(r=>r.me); let html = ''; list.forEach((r,i)=>{ html += `
${i+1}
${r.name}${r.me?' YOU':''}${r.me?'':'RANGER'}
${fmt(r.score)}
W${r.wave}
`; }); if(!meIn && state.best.score>0){ const mine = state.board.find(r=>r.me); if(mine){ html += `
— YOUR BEST —
—
${mine.name} YOU
${fmt(mine.score)}
W${mine.wave}
`; } } body.innerHTML = html; } function submitScore(score, wave){ state.board = state.board.filter(r=>!r.me); state.board.push({ name:'Desert Ranger', score, wave, me:true }); state.board.sort((a,b)=>b.score-a.score); state.board = state.board.slice(0,12); save(); } /* ---------------- help / settings ---------------- */ const FAQ = [ ['How do I win?','Enemies walk the trail from the top-left to your fort at the bottom-right. Build towers on the gold slots beside the trail. Survive every wave with at least 1 base HP.'], ['How do I build and upgrade?','Tap a tower card in the dock, then tap a gold slot. Tap a built tower to open its panel: upgrade up to LV.3 or sell it back for 60% of what you spent.'], ['What are combos?','Two specific towers placed close together light up a gold link and buff each other. Check the combo line inside the tower panel.'], ['Which towers hit air?','Only the Rifle can shoot flying Vultures. Ground-only towers will never target them.'], ['How does armor work?','Armor subtracts flat damage from every hit. Crossbow bolts ignore armor completely.'], ['What is the difference between the two modes?','Campaign has 20 levels across four desert routes. Endless never stops, scores you on wave + kills + base HP, and feeds the leaderboard.'], ['How do I earn coins?','Clearing a campaign level pays 385–2,950 coins. Endless pays 45 coins per wave survived plus milestone bonuses for each new record.'], ['What do items do?','Airstrike and Gold Rush are bought with coins and used inside battle. Frost Nova freezes the whole map. Repair Kit restores base HP.'], ['Does the game save?','Progress, coins, items and the leaderboard live in this browser only. There is no account and no cross-device sync.'], ['Is there anything to pay for?','No. Coins are earned by playing and spent on support items and permanent tower upgrades. No purchases, no ads, no cash value.'] ]; function renderHelp(){ const body = document.getElementById('helpBody'); body.innerHTML = FAQ.map((q,i)=>`
${q[0]}

${q[1]}

`).join(''); } function renderSettings(){ document.getElementById('tglSfx').classList.toggle('on', !!state.sfx); document.getElementById('tglMusic').classList.toggle('on', !!state.music); } const DOCS = { terms: { title: 'TERMS OF SERVICE', html: `

Buffalo Siege is a single-player tower defense game. By playing you agree to the points below.

1. License

You may play this build for personal entertainment. Do not redistribute it as your own product or resell it.

2. No purchases

All coins and items are earned by playing. There is no real-money purchase, no advertising and no cash value attached to any in-game currency.

3. Local save

Progress is stored in this browser only. Clearing browser data or resetting the save erases progress permanently — this cannot be undone.

4. Changes

Balance values, level layouts and item prices may change between versions without notice.

` }, privacy: { title: 'PRIVACY POLICY', html: `

Buffalo Siege does not collect, transmit or sell any personal data.

What is stored

Only gameplay data lives in your browser's local storage: nickname, avatar, a random 8-digit player ID, coins, items, tower upgrade levels, campaign stars, endless scores and check-in dates.

What is NOT collected

No account, no email, no phone number, no location, no contacts, no device identifiers, no analytics and no third-party SDKs.

Network

The game runs fully offline. Nothing is uploaded anywhere; the leaderboard is a local list with simulated entries.

Deleting your data

Settings → Reset local save removes everything stored by the game.

` } }; function openDoc(key){ const d = DOCS[key]; if(!d) return; document.getElementById('docTitle').textContent = d.title; document.getElementById('docBody').innerHTML = d.html; openSheet('sheetDoc'); } let resetArmed = false, resetTimer = null; /* ---------------- boot ---------------- */ function boot(){ fit(); load(); ensurePlayer(); paintStartLandscape(); const fill = document.getElementById('bootFill'), pct = document.getElementById('bootPct'); let p = 0; const tick = setInterval(()=>{ p += 9 + Math.random()*13; if(p>=100){ p=100; clearInterval(tick); setTimeout(()=>{ showView('start'); }, 420); } fill.style.width = p+'%'; pct.textContent = 'LOADING… ' + Math.round(p) + '%'; }, 130); } /* ---------------- global wiring ---------------- */ document.getElementById('btnStart').onclick = ()=>{ AU.init(); AU.coin(); BGM.sync(); showView('lobby'); }; document.querySelectorAll('[data-open]').forEach(el=>{ el.onclick = ()=>{ const k = el.dataset.open; if(k==='shop'){ renderShop(); openSheet('sheetShop'); } if(k==='leaderboard'){ renderBoard(); openSheet('sheetBoard'); } if(k==='help'){ renderHelp(); openSheet('sheetHelp'); } if(k==='settings'){ renderSettings(); openSheet('sheetSettings'); } }; }); document.querySelectorAll('[data-close]').forEach(el=>{ el.onclick = ()=>{ closeSheet(el.dataset.close); }; }); document.querySelectorAll('[data-back]').forEach(el=>{ el.onclick = ()=> showView(el.dataset.back); }); document.querySelectorAll('.mode').forEach(el=>{ el.onclick = ()=>{ const m = el.dataset.mode; if(m==='campaign') showView('levels'); else startBattle('endless', 0); }; }); document.getElementById('lobbyCoins').onclick = ()=>{ renderShop(); openSheet('sheetShop'); }; document.getElementById('armoryMore').onclick = ()=> openArmory(); document.getElementById('lobbyPlayer').onclick = ()=> openProfile(); document.getElementById('btnCheckin').onclick = ()=>{ renderCheckin(); openSheet('sheetCheckin'); AU.hit(); }; document.getElementById('ckClaim').onclick = ()=> claimCheckin(); document.getElementById('btnAvatar').onclick = ()=>{ AU.hit(); profShow('avatar'); }; document.getElementById('btnRename').onclick = ()=>{ AU.hit(); profShow('rename'); }; document.getElementById('btnCopyId').onclick = ()=> copyPlayerId(); document.getElementById('btnNameCancel').onclick = ()=> profShow('main'); document.getElementById('btnAvatarBack').onclick = ()=> profShow('main'); document.getElementById('btnNameSave').onclick = ()=> saveName(); document.getElementById('nameInput').addEventListener('keydown', e=>{ if(e.key==='Enter') saveName(); }); document.getElementById('pstatCoins').classList.add('is-link'); document.getElementById('pstatCoins').onclick = ()=>{ closeSheet('sheetProfile'); renderShop(); openSheet('sheetShop'); }; document.getElementById('boardMore').onclick = ()=>{ renderBoard(); openSheet('sheetBoard'); }; document.getElementById('tglSfx').onclick = ()=>{ state.sfx=!state.sfx; save(); renderSettings(); AU.coin(); }; document.getElementById('tglMusic').onclick = ()=>{ state.music = !state.music; save(); BGM.sync(); renderSettings(); AU.coin(); toast(state.music ? 'Music on' : 'Music off'); }; document.getElementById('setShop').onclick = ()=>{ closeSheet('sheetSettings'); renderShop(); openSheet('sheetShop'); }; document.getElementById('setHelp').onclick = ()=>{ closeSheet('sheetSettings'); renderHelp(); openSheet('sheetHelp'); }; document.querySelectorAll('[data-doc]').forEach(el=>{ el.onclick = ()=> openDoc(el.dataset.doc); }); document.getElementById('setReset').onclick = ()=>{ if(!resetArmed){ resetArmed = true; const el = document.getElementById('setResetState'); el.textContent = 'TAP AGAIN TO ERASE EVERYTHING'; el.style.color = '#FF4D6A'; resetTimer = setTimeout(()=>{ resetArmed=false; el.textContent='Erase progress, coins and scores'; el.style.color=''; }, 3000); return; } clearTimeout(resetTimer); resetArmed=false; state = defaults(); save(); document.getElementById('setResetState').textContent='Erase progress, coins and scores'; document.getElementById('setResetState').style.color=''; renderSettings(); renderLobby(); renderArmory(); toast('Local save erased'); }; // Boot follows local artwork preload in style-a.js. /* ============================================================ BUFFALO SIEGE — battle engine + renderer ============================================================ */ /* ---------------- field geometry ---------------- */ const FW = 430, FH = 600; const PATH_W = 44; const SLOT_R = 24; /* 每关不同地图:路径折返方式 + 建造格行/列布局不同 */ const MAP_DEFS = [ { key:'serpentine', name:'Serpentine', path:[[-30,80],[300,80],[300,210],[110,210],[110,340],[300,340],[300,470],[110,470],[110,545],[336,545]], base:{x:368,y:545}, rows:[26,145,275,405], cols:[34,90,146,202,258,314,370], minD:53 }, { key:'longhorn', name:'Long Horn', path:[[-30,85],[330,85],[330,225],[60,225],[60,365],[330,365],[330,505],[368,505]], base:{x:384,y:505}, rows:[25,155,295,435], cols:[34,90,146,202,258,314,370], minD:53 }, { key:'switchback', name:'Switchback', path:[[-30,70],[350,70],[350,190],[150,190],[150,310],[350,310],[350,430],[150,430],[150,540],[376,540]], base:{x:390,y:540}, rows:[24,130,250,370,470], cols:[40,100,160,220,280,340,392], minD:53 }, { key:'chokepoint', name:'Chokepoint', path:[[-30,90],[330,90],[330,230],[50,230],[50,370],[330,370],[330,500],[368,500]], base:{x:384,y:500}, rows:[28,160,300,440], cols:[30,90,150,210,270,330,390], minD:53 } ]; function mapForLevel(level){ return MAP_DEFS[((level||1)-1) % MAP_DEFS.length]; } let SEGS = [], PATH_LEN = 0, SLOTS = [], BASE = { x:368, y:545 }, CUR_MAP = MAP_DEFS[0]; function segDist(px,py,x1,y1,x2,y2){ const dx=x2-x1, dy=y2-y1, l=dx*dx+dy*dy; let t = l ? ((px-x1)*dx + (py-y1)*dy)/l : 0; t = Math.max(0, Math.min(1, t)); return Math.hypot(px-(x1+t*dx), py-(y1+t*dy)); } function distToPath(px,py){ let m = 1e9; for(const sg of SEGS) m = Math.min(m, segDist(px,py,sg.x1,sg.y1,sg.x2,sg.y2)); return m; } function posAt(d){ d = clamp(d,0,PATH_LEN); let s = SEGS[SEGS.length-1]; for(const sg of SEGS){ if(d <= sg.acc+sg.len){ s=sg; break; } } const t = (d - s.acc)/s.len; return { x: lerp(s.x1,s.x2,t), y: lerp(s.y1,s.y2,t), ang: s.ang }; } function applyMap(level){ const def = mapForLevel(level); CUR_MAP = def; BASE = { x:def.base.x, y:def.base.y }; SEGS = []; PATH_LEN = 0; for(let i=0;idef.cols.forEach(x=>{ if(x<24||x>406||y<18||y>580) return; if(distToPath(x,y) < def.minD) return; if(Math.hypot(x-BASE.x, y-BASE.y) < 80) return; SLOTS.push({ id:SLOTS.length, x, y, tower:null }); })); buildGround(); } /* ---------------- battle state ---------------- */ const G = { running:false, paused:false, mode:'campaign', level:1, wave:0, totalWaves:0, phase:'prep', // prep | running | done prepLeft:0, gold:0, baseHP:20, maxHP:20, kills:0, score:0, speed:1, time:0, waveTime:0, queue:[], enemies:[], towers:[], projs:[], fx:[], selType:null, selTower:null, armed:null, shake:0, coinsEarned:0, hpMul:1, bossWave:false, flash:0 }; const field = document.getElementById('field'); const ctx = field.getContext('2d'); const DPR = Math.min(2, window.devicePixelRatio||2); field.width = FW*DPR; field.height = FH*DPR; ctx.setTransform(DPR,0,0,DPR,0,0); /* background cache */ const bgCanvas = document.createElement('canvas'); bgCanvas.width = FW*DPR; bgCanvas.height = FH*DPR; const bgc = bgCanvas.getContext('2d'); bgc.setTransform(DPR,0,0,DPR,0,0); function buildGround(){ const c = bgc, rnd = seedRnd(20261026); // sand base const g = c.createLinearGradient(0,0,0,FH); g.addColorStop(0,'#C8843F'); g.addColorStop(.42,'#D6994F'); g.addColorStop(1,'#A9662E'); c.fillStyle=g; c.fillRect(0,0,FW,FH); // warm horizon haze const sky=c.createLinearGradient(0,0,0,150); sky.addColorStop(0,'rgba(255,176,96,.35)'); sky.addColorStop(1,'rgba(255,176,96,0)'); c.fillStyle=sky; c.fillRect(0,0,FW,150); // dune blobs for(let i=0;i<30;i++){ const x=rnd()*FW, y=rnd()*FH, rx=40+rnd()*90, ry=16+rnd()*34; c.fillStyle = `rgba(${196+((rnd()*34)|0)},${140+((rnd()*44)|0)},${78+((rnd()*34)|0)},.34)`; c.beginPath(); c.ellipse(x,y,rx,ry,rnd()*3,0,TAU); c.fill(); } // dry grass / pebbles for(let i=0;i<170;i++){ const x=rnd()*FW, y=rnd()*FH; if(rnd()<.6){ c.strokeStyle='rgba(108,74,36,.42)'; c.lineWidth=1.1; c.beginPath(); c.moveTo(x,y); c.lineTo(x-2.5,y-5); c.moveTo(x,y); c.lineTo(x+2.5,y-4.5); c.stroke(); }else{ c.fillStyle='rgba(104,72,44,.32)'; c.beginPath(); c.arc(x,y,1.2+rnd()*1.8,0,TAU); c.fill(); } } // rocks for(let i=0;i<10;i++){ const x=rnd()*FW, y=70+rnd()*(FH-110), r=5+rnd()*7; c.fillStyle='#7A5A44'; c.beginPath(); c.ellipse(x,y,r,r*0.72,0,0,TAU); c.fill(); c.fillStyle='rgba(255,235,200,.22)'; c.beginPath(); c.ellipse(x-r*0.2,y-r*0.3,r*0.55,r*0.32,0,0,TAU); c.fill(); } // bones + skull props for(let i=0;i<5;i++){ const x=20+rnd()*(FW-40), y=90+rnd()*(FH-160); c.strokeStyle='rgba(240,226,196,.6)'; c.lineWidth=2; c.lineCap='round'; c.beginPath(); c.moveTo(x-6,y+3); c.lineTo(x+6,y-3); c.stroke(); c.beginPath(); c.arc(x-7,y+3,1.6,0,TAU); c.arc(x+7,y-3,1.6,0,TAU); c.fill(); } // path const stroke = (w,col)=>{ c.strokeStyle=col; c.lineWidth=w; c.lineJoin='round'; c.lineCap='round'; c.beginPath(); c.moveTo(SEGS[0].x1, SEGS[0].y1); for(const sg of SEGS) c.lineTo(sg.x2, sg.y2); c.stroke(); }; stroke(PATH_W+11,'rgba(86,48,20,.55)'); stroke(PATH_W+4,'#8A5522'); stroke(PATH_W,'#D9A566'); stroke(PATH_W-15,'#EEC58B'); // path pebbles for(let i=0;i<140;i++){ const d=rnd()*PATH_LEN, p=posAt(d), off=(rnd()-.5)*(PATH_W-12); const x=p.x+Math.cos(p.ang+Math.PI/2)*off, y=p.y+Math.sin(p.ang+Math.PI/2)*off; c.fillStyle=`rgba(${150+rnd()*40|0},${108+rnd()*30|0},${66+rnd()*22|0},.42)`; c.beginPath(); c.arc(x,y,.9+rnd()*1.5,0,TAU); c.fill(); } // vignette const vg=c.createRadialGradient(FW/2,FH/2,150,FW/2,FH/2,430); vg.addColorStop(0,'rgba(0,0,0,0)'); vg.addColorStop(1,'rgba(46,10,38,.52)'); c.fillStyle=vg; c.fillRect(0,0,FW,FH); } applyMap(1); /* ---------------- wave generation ---------------- */ function campaignWaves(level){ const total = levelWaves(level); /* 路径长度补偿:短路径 = 敌人通过快 = 输出窗口短,按 1520px 基准等比降血 */ const lenScale = clamp(PATH_LEN / 1520, 0.86, 1.12); const hpMul = levelHpMul(level) * lenScale; const rng = seedRnd(4200+level*137); const out = []; for(let w=1; w<=total; w++){ const pool = ['rabbit','bison']; if(level>=3) pool.push('wolf'); if(level>=5) pool.push('vulture'); if(level>=8) pool.push('scorpion'); if(level>=13) pool.push('wolf','scorpion'); const kinds = 1 + Math.min(3, Math.floor((w-1)/3)); const baseCount = 2 + Math.round(w*1.15) + Math.floor(level*0.5); const groups = []; for(let i=0;i=15?2:1, gap:3.2, delay:.6 }); } out.push({ groups, hpMul: hpMul*(1+(w-1)*0.05) }); } return out; } function endlessWave(w){ const pool = ['rabbit','bison']; if(w>=3) pool.push('wolf'); if(w>=5) pool.push('vulture'); if(w>=7) pool.push('scorpion'); const kinds = 1 + Math.min(3, Math.floor(w/4)); const baseCount = 4 + Math.round(w*1.45); const groups = []; const rng = seedRnd(900+w*53); for(let i=0;ib.classList.toggle('is-on', b.dataset.spd==='1')); closeAllSheets(); closeTowerPanel(); showView('battle'); renderDock(); renderItemDock(); startNextWave(true); updateHUD(true); if(state.tutorial===0) showCoach('Tap a tower card, then tap a gold slot'); lastT = performance.now(); if(!loopRunning){ loopRunning = true; requestAnimationFrame(loop); } } function startNextWave(first){ G.wave++; if(G.mode==='campaign' && G.wave > G.totalWaves){ endBattle(true); return; } const cfg = G.mode==='campaign' ? G.waves[G.wave-1] : endlessWave(G.wave); G.hpMul = cfg.hpMul; G.bossWave = cfg.groups.some(g=>g.type==='king'); const q = []; cfg.groups.forEach(gr=>{ for(let i=0;ia.t-b.t); G.queue = q; G.waveTime = 0; G.phase = 'running'; G.waveTotalCount = q.length; if(!first) AU.wave(); if(G.bossWave && !first){ toast('BOSS WAVE · Buffalo King'); G.shake = 8; } updateHUD(true); } /* ---------------- towers ---------------- */ function towerStats(t){ const def = TOWERS[t.type], s = def.lv[t.lv-1], ab = armoryBonus(t.type); let dmg = s.dmg * ab.dmg, rate = s.rate, range = s.range * ab.range; let splash = s.splash||0, pierce = !!def.pierce; t.combos.forEach(c=>{ if(c==='Volley'){ range*=1.15; rate/=1.10; } if(c==='Suppression'){ rate/=1.25; } if(c==='Siege Line' && t.type==='mortar'){ splash*=1.25; dmg*=1.10; } if(c==='Pierce Shell'){ if(t.type==='crossbow') dmg*=1.20; if(t.type==='mortar') pierce=true; } }); return { dmg, rate, range, splash, pierce, air:def.air, proj:def.proj, pspeed:def.pspeed }; } function recomputeCombos(){ G.towers.forEach(t=>t.combos=[]); G.comboLinks = []; for(let i=0;i 132) continue; COMBOS.forEach(cb=>{ const m = (cb.a===a.type&&cb.b===b.type) || (cb.a===b.type&&cb.b===a.type); if(m){ if(!a.combos.includes(cb.name)) a.combos.push(cb.name); if(!b.combos.includes(cb.name)) b.combos.push(cb.name); G.comboLinks.push({a,b}); } }); } } } function slotAt(x,y){ let best=null, bd=1e9; SLOTS.forEach(s=>{ const d=Math.hypot(s.x-x,s.y-y); if(d=3){ toast('Already 3 stars'); return; } const cost = TOWERS[t.type].up[t.lv-1]; if(G.gold < cost){ AU.err(); toast('Need ' + (cost-G.gold) + ' more gold'); return; } G.gold -= cost; t.invested += cost; t.lv++; recomputeCombos(); AU.upgrade(); addFx('ring', t.x, t.y, {r0:10, r1:38, col:'255,227,138', life:.55}); floatText(t.x, t.y - 30, '★'.repeat(t.lv), '255,214,110'); addFx('stars', t.x, t.y, {life:.65, lv:t.lv}); openTowerPanel(t); updateHUD(); } function sellTower(t){ const back = Math.round(t.invested*0.6); G.gold += back; t.slot.tower = null; G.towers = G.towers.filter(x=>x!==t); recomputeCombos(); AU.coin(); addFx('text', t.x, t.y-10, {text:'+'+back, col:'255,210,102'}); closeTowerPanel(); updateHUD(); } /* ---------------- tower panel ---------------- */ function openTowerPanel(t){ G.selTower = t; document.getElementById('coach').classList.remove('is-on'); const el = document.getElementById('towerPanel'); el.classList.add('is-open'); const st = towerStats(t); document.getElementById('tpName').textContent = TOWERS[t.type].name; let stars = ''; for(let i=0;i<3;i++) stars += `★`; document.getElementById('tpLevel').innerHTML = stars; document.getElementById('tpLevel').title = 'Star ' + t.lv + ' of 3'; document.getElementById('tpDmg').textContent = Math.round(st.dmg); document.getElementById('tpRate').textContent = (1/st.rate).toFixed(1)+'/s'; document.getElementById('tpRange').textContent = Math.round(st.range); document.getElementById('tpDps').textContent = Math.round(st.dmg/st.rate); const ab = armoryBonus(t.type); const armEl = document.getElementById('tpArm'); if(ab.lv > 1){ armEl.style.display = 'flex'; armEl.innerHTML = '★ ARMORY LV.'+ab.lv+' · +'+Math.round((ab.dmg-1)*100)+'% DMG · +'+Math.round((ab.range-1)*100)+'% RNG'; } else armEl.style.display = 'none'; const comboEl = document.getElementById('tpCombo'); if(t.combos.length){ comboEl.style.display='flex'; comboEl.innerHTML = '★ COMBO · ' + t.combos.join(' + '); } else comboEl.style.display='none'; const upBtn = document.getElementById('tpUpgrade'); if(t.lv>=3){ upBtn.textContent='★★★ MAX'; upBtn.disabled=true; } else { const c = TOWERS[t.type].up[t.lv-1]; upBtn.textContent='★ UPGRADE · '+c; upBtn.disabled = G.gold{ const d = TOWERS[k]; const el = document.createElement('div'); el.className='tcard'; el.dataset.type=k; el.innerHTML = `
★1
${d.name}
${d.cost}
`; el.onclick = ()=>{ if(G.selType===k){ G.selType=null; } else { G.selType=k; closeTowerPanel(); } document.querySelectorAll('.tcard').forEach(c=>c.classList.toggle('is-sel', c.dataset.type===G.selType)); document.getElementById('dockHint').innerHTML = G.selType ? `Tap a gold slot to build ${d.name} · ${d.tag}` : 'Pick a tower · tap an empty gold slot to build'; AU.hit(); }; dock.appendChild(el); }); } function renderItemDock(){ const dock = document.getElementById('dockItems'); dock.innerHTML=''; ITEM_ORDER.forEach(k=>{ const it = ITEMS[k], n = state.items[k]||0; const el = document.createElement('div'); el.className='item'+(n<=0?' is-empty':''); el.dataset.item=k; el.innerHTML = `
${it.name.split(' ')[0]}` + (n>0 ? `
${n}
` : `+`); el.onclick = ()=> useItem(k); dock.appendChild(el); }); } let buyKey = null; function openBuy(k){ buyKey = k; const it = ITEMS[k]; document.getElementById('buyIcon').setAttribute('href', '#'+it.icon); document.getElementById('buyName').textContent = it.name; document.getElementById('buyDesc').textContent = it.desc; document.getElementById('buyOwn').textContent = 'OWNED ×' + (state.items[k]||0); document.getElementById('buyPrice').textContent = fmt(it.price); document.getElementById('buyCoins').textContent = fmt(state.coins); const btn = document.getElementById('buyConfirm'); btn.disabled = state.coins < it.price; btn.textContent = state.coins < it.price ? 'NEED MORE COINS' : 'BUY & USE'; G.paused = true; openSheet('sheetBuy'); } function confirmBuy(){ const it = ITEMS[buyKey]; if(!it) return; if(state.coins < it.price){ AU.err(); toast('Need ' + (it.price-state.coins) + ' more coins'); return; } state.coins -= it.price; state.items[buyKey] = (state.items[buyKey]||0) + 1; save(); AU.coin(); closeSheet('sheetBuy'); G.paused = false; renderItemDock(); toast(it.name + ' purchased'); useItem(buyKey); } function useItem(k){ const n = state.items[k]||0; if(n<=0){ openBuy(k); return; } if(G.phase==='done'){ return; } if(k==='air'){ G.armed = G.armed==='air' ? null : 'air'; document.querySelectorAll('.item').forEach(el=>el.classList.toggle('is-arm', el.dataset.item===G.armed)); if(G.armed) toast('Tap the field to call the airstrike'); return; } if(k==='frost'){ state.items[k]--; save(); G.enemies.forEach(e=>{ e.frozen = 4; }); addFx('frost', 0,0,{life:.8}); AU.freeze(); toast('Frost Nova · all enemies frozen'); } if(k==='repair'){ if(G.baseHP>=G.maxHP){ AU.err(); toast('Base is already at full HP'); return; } state.items[k]--; save(); G.baseHP = Math.min(G.maxHP, G.baseHP+3); addFx('heal', BASE.x, BASE.y, {life:.9}); AU.upgrade(); toast('Base repaired +3 HP'); } if(k==='gold'){ state.items[k]--; save(); G.gold += 300; addFx('text', BASE.x, BASE.y-40, {text:'+300', col:'255,210,102'}); AU.coin(); toast('Gold Rush · +300 gold'); } renderItemDock(); updateHUD(); } /* ---------------- fx ---------------- */ function addFx(kind,x,y,opt){ opt=opt||{}; G.fx.push({kind,x,y,t:0,life:opt.life||.5,...opt}); } function floatText(x,y,text,col){ addFx('text',x,y,{text,col:col||'255,235,180',life:.85}); } /* ---------------- damage ---------------- */ function damageEnemy(e, dmg, pierce, splashCol){ const armor = pierce ? 0 : e.armor; const real = Math.max(1, dmg - armor); e.hp -= real; e.hitFlash = .12; if(e.hp<=0) killEnemy(e); else if(Math.random()<.35) addFx('spark', e.x, e.y, {life:.22, col:splashCol||'255,235,180'}); } function killEnemy(e){ if(e.dead) return; e.dead = true; G.kills++; G.gold += e.gold; G.score += 20; floatText(e.x, e.y-14, '+'+e.gold, '255,210,102'); addFx('poof', e.x, e.y, {life:.4, r:e.r}); AU.coin(); } function leakEnemy(e){ e.dead = true; G.baseHP -= e.leak; G.shake = Math.min(10, 4+e.leak*2); addFx('text', BASE.x, BASE.y-44, {text:'-'+e.leak, col:'255,110,130'}); AU.err(); if(G.baseHP<=0){ G.baseHP=0; endBattle(false); } } /* ---------------- update ---------------- */ function update(dt){ if(G.phase==='prep' && G.prepLeft>0){ G.prepLeft -= dt; if(G.prepLeft<=0) startNextWave(false); } if(G.phase==='running'){ G.waveTime += dt; while(G.queue.length && G.queue[0].t <= G.waveTime){ const q = G.queue.shift(); spawnEnemy(q.type); } } // enemies for(const e of G.enemies){ if(e.dead) continue; if(e.hitFlash>0) e.hitFlash -= dt; if(e.boost>0) e.boost -= dt; // ---- boss skills ---- if(e.boss && e.frozen<=0){ e.roarCd -= dt; if(e.roarCd <= 0){ e.roarCd = 7; addFx('ring', e.x, e.y, { r0:12, r1:130, col:'255,46,154', life:.6 }); floatText(e.x, e.y-46, 'ROAR!', '255,120,200'); AU.tone(150, 70, 0.35, 'sawtooth', 0.13); for(const o of G.enemies){ if(o===e || o.dead) continue; if(Math.hypot(o.x-e.x, o.y-e.y) < 140) o.boost = 3; } } if(!e.summoned && e.hp < e.maxHp*0.5){ e.summoned = true; for(let i=0;i<3;i++) spawnEnemy('wolf', Math.max(0, e.d - 26 - i*20)); addFx('ring', e.x, e.y, { r0:8, r1:70, col:'255,120,200', life:.55 }); floatText(e.x, e.y-56, 'SUMMON', '255,120,200'); AU.tone(300, 120, 0.3, 'square', 0.1); } } let spd = e.spd * (e.boost>0 ? 1.35 : 1); if(e.frozen>0){ e.frozen -= dt; spd = 0; } e.d += spd*dt; const p = posAt(e.d); e.px = e.x; e.py = e.y; e.x = p.x; e.y = p.y; e.ang = p.ang; if(e.d >= PATH_LEN){ leakEnemy(e); continue; } e.bob = Math.sin((G.time*6) + e.seed)*1.6; } G.enemies = G.enemies.filter(e=>!e.dead); // towers for(const t of G.towers){ if(t.flash>0) t.flash -= dt; if(t.recoil>0) t.recoil -= dt*4; const st = towerStats(t); t.cd -= dt; if(t.cd>0) continue; const target = findTarget(t, st); if(!target) continue; t.angle = Math.atan2(target.y-t.y, target.x-t.x); t.cd = st.rate; t.flash = .08; t.recoil = 1; fire(t, st, target); } // projectiles for(const p of G.projs){ if(p.type==='shell'){ p.t += dt; const k = Math.min(1, p.t/p.dur); p.x = lerp(p.x0,p.x1,k); p.y = lerp(p.y0,p.y1,k); p.h = Math.sin(k*Math.PI)*46; if(k>=1){ p.done = true; explode(p.x1,p.y1,p.splash,p.dmg,p.pierce); } } else { const tgt = p.target; if(!tgt || tgt.dead){ p.done = true; continue; } const dx=tgt.x-p.x, dy=tgt.y-p.y, d=Math.hypot(dx,dy)||1; const step = p.speed*dt; p.ang = Math.atan2(dy,dx); if(d <= step+4){ p.x = tgt.x; p.y = tgt.y; p.done = true; damageEnemy(tgt, p.dmg, p.pierce, p.col); } else { p.x += dx/d*step; p.y += dy/d*step; } } } G.projs = G.projs.filter(p=>!p.done); // fx for(const f of G.fx){ f.t += dt; } G.fx = G.fx.filter(f=>f.t < f.life); // wave clear if(G.phase==='running' && !G.queue.length && !G.enemies.length){ G.phase='prep'; if(G.mode==='campaign' && G.wave>=G.totalWaves){ endBattle(true); return; } G.prepLeft = 2.4; if(G.mode==='endless'){ G.score += 150; G.gold += 20; floatText(BASE.x, BASE.y-60, 'WAVE CLEAR +20', '255,235,180'); } else G.gold += 15; AU.wave(); updateHUD(true); } if(G.shake>0) G.shake = Math.max(0, G.shake - dt*22); if(G.flash>0) G.flash = Math.max(0, G.flash - dt*2.4); G.time += dt; } function spawnEnemy(type, atD){ const b = ENEMIES[type]; const hp = Math.round(b.hp * G.hpMul); const d0 = Math.max(0, atD||0); const p = posAt(d0); G.enemies.push({ type, hp, maxHp:hp, spd:b.spd, armor:b.armor, gold:b.gold, leak:b.leak, r:b.r, air:b.air, boss:!!b.boss, d:d0, x:p.x, y:p.y, px:p.x, py:p.y, ang:0, frozen:0, hitFlash:0, bob:0, seed:Math.random()*6, roarCd: b.boss ? 5.5 : 0, summoned:false, boost:0 }); } function findTarget(t, st){ let best=null, bestD=-1; for(const e of G.enemies){ if(e.dead) continue; if(e.air && !st.air) continue; const d = Math.hypot(e.x-t.x, e.y-t.y); if(d > st.range + e.r) continue; if(e.d > bestD){ bestD = e.d; best = e; } } return best; } function fire(t, st, target){ AU.shoot(st.proj==='hitscan' ? 'rifle' : (st.proj==='bullet'?'pistol':(st.proj==='shell'?'mortar':'arrow'))); const mx = t.x + Math.cos(t.angle)*16, my = t.y + Math.sin(t.angle)*16; addFx('muzzle', mx, my, {life:.12, ang:t.angle}); if(st.proj==='hitscan'){ damageEnemy(target, st.dmg, st.pierce, '255,180,200'); addFx('beam', 0,0,{life:.09, x1:mx, y1:my, x2:target.x, y2:target.y, col:'255,200,160'}); return; } if(st.proj==='shell'){ const lead = target.spd * (Math.hypot(target.x-t.x,target.y-t.y)/st.pspeed) * 0.55; const pp = posAt(target.d + lead); G.projs.push({ type:'shell', x0:t.x, y0:t.y, x1:pp.x, y1:pp.y, x:t.x, y:t.y, h:0, t:0, dur: Math.max(.32, Math.hypot(pp.x-t.x,pp.y-t.y)/st.pspeed), splash:st.splash, dmg:st.dmg, pierce:st.pierce }); return; } G.projs.push({ type:st.proj, x:mx, y:my, target, dmg:st.dmg, pierce:st.pierce, speed:st.pspeed, ang:t.angle, col: st.proj==='bullet'?'255,220,120':(st.proj==='bolt'?'255,210,102':'255,235,180') }); } function explode(x,y,radius,dmg,pierce){ addFx('boom', x, y, {life:.5, r:radius}); AU.boom(); G.shake = Math.max(G.shake, 4.5); G.flash = Math.max(G.flash, .35); for(const e of G.enemies){ if(e.dead || e.air) continue; if(Math.hypot(e.x-x,e.y-y) <= radius + e.r) damageEnemy(e, dmg, pierce, '255,160,90'); } } /* ---------------- rendering ---------------- */ function draw(){ const c = ctx; c.setTransform(DPR,0,0,DPR,0,0); c.clearRect(0,0,FW,FH); c.save(); if(G.shake>0) c.translate(rnd(-G.shake,G.shake)*.5, rnd(-G.shake,G.shake)*.5); c.drawImage(bgCanvas, 0,0, FW, FH); drawPortal(c); drawSlots(c); drawBase(c); if(G.selTower) drawRange(c, G.selTower); drawComboLinks(c); // towers (sorted by y for depth) [...G.towers].sort((a,b)=>a.y-b.y).forEach(t=>drawTower(c,t)); // enemies: ground then air const air = G.enemies.filter(e=>e.air); G.enemies.filter(e=>!e.air).forEach(e=>drawEnemy(c,e)); air.forEach(e=>drawEnemy(c,e)); // projectiles G.projs.forEach(p=>drawProj(c,p)); // fx G.fx.forEach(f=>drawFx(c,f)); if(G.armed==='air') drawAim(c); c.restore(); if(G.flash>0){ c.fillStyle = `rgba(255,226,170,${G.flash*.30})`; c.fillRect(0,0,FW,FH); } } function drawSlots(c){ SLOTS.forEach(s=>{ if(s.tower) return; const pulse = .5 + .5*Math.sin(G.time*2 + s.id); c.save(); c.translate(s.x, s.y); const tg = c.createLinearGradient(0,-SLOT_R,0,SLOT_R); tg.addColorStop(0,'rgba(255,238,196,.34)'); tg.addColorStop(1,'rgba(126,74,32,.34)'); rr(c, -SLOT_R+2, -SLOT_R+2, SLOT_R*2-4, SLOT_R*2-4, 10); c.fillStyle = tg; c.fill(); c.strokeStyle='rgba(90,50,20,.35)'; c.lineWidth=1.4; c.stroke(); c.lineWidth = 2; c.setLineDash([6,5]); c.lineDashOffset = -G.time*10; c.strokeStyle = `rgba(255,214,110,${.5+pulse*.4})`; c.stroke(); c.setLineDash([]); c.strokeStyle = 'rgba(255,248,214,.75)'; c.lineWidth = 1.6; c.lineCap='round'; c.beginPath(); c.moveTo(-6,0); c.lineTo(6,0); c.moveTo(0,-6); c.lineTo(0,6); c.stroke(); c.restore(); }); } function drawComboLinks(c){ if(!G.comboLinks || !G.comboLinks.length) return; const a = .35+.2*Math.sin(G.time*3); c.save(); c.setLineDash([4,5]); c.lineDashOffset = -G.time*16; c.lineWidth = 2; G.comboLinks.forEach(l=>{ c.strokeStyle = `rgba(255,214,110,${a})`; c.beginPath(); c.moveTo(l.a.x,l.a.y); c.lineTo(l.b.x,l.b.y); c.stroke(); }); c.restore(); } function drawRange(c, t){ const st = towerStats(t); c.save(); c.beginPath(); c.arc(t.x,t.y,st.range,0,TAU); c.fillStyle='rgba(255,210,102,.08)'; c.fill(); c.strokeStyle='rgba(255,210,102,.55)'; c.lineWidth=1.6; c.setLineDash([6,5]); c.lineDashOffset = -G.time*14; c.stroke(); c.restore(); } function drawBase(c){ const {x,y} = BASE; const hpK = G.baseHP/G.maxHP; c.save(); c.translate(x,y); // glow const gl = c.createRadialGradient(0,0,4,0,0,62); gl.addColorStop(0,`rgba(255,150,60,${.30+.15*Math.sin(G.time*2)})`); gl.addColorStop(1,'rgba(255,150,60,0)'); c.fillStyle=gl; c.beginPath(); c.arc(0,0,62,0,TAU); c.fill(); // ground shadow c.fillStyle='rgba(60,24,10,.35)'; c.beginPath(); c.ellipse(0,26,34,13,0,0,TAU); c.fill(); // stone footing c.fillStyle='#8C7358'; rr(c,-30,10,60,20,7); c.fill(); c.strokeStyle='#4E3A26'; c.lineWidth=2; c.stroke(); // palisade wall c.fillStyle='#A9712F'; rr(c,-27,-20,54,34,5); c.fill(); c.strokeStyle='#5A3216'; c.lineWidth=2.4; c.stroke(); c.fillStyle='#C99049'; for(let i=0;i<5;i++){ rr(c,-25+i*11,-18,8,30,3); c.fill(); c.strokeStyle='rgba(90,50,20,.55)'; c.lineWidth=1.4; c.stroke(); } // gate c.fillStyle='#4A2408'; rr(c,-8,2,16,12,3); c.fill(); c.fillStyle='#FFD34D'; c.beginPath(); c.arc(0,8,2.2,0,TAU); c.fill(); // roof c.fillStyle='#7A3E9E'; c.beginPath(); c.moveTo(-34,-20); c.lineTo(0,-42); c.lineTo(34,-20); c.closePath(); c.fill(); c.strokeStyle='#3E1B52'; c.lineWidth=2.4; c.stroke(); c.fillStyle='rgba(255,255,255,.14)'; c.beginPath(); c.moveTo(-34,-20); c.lineTo(0,-42); c.lineTo(0,-20); c.closePath(); c.fill(); // banner pole + flag c.strokeStyle='#4A2408'; c.lineWidth=2.6; c.beginPath(); c.moveTo(0,-42); c.lineTo(0,-60); c.stroke(); const wave = Math.sin(G.time*3)*1.6; c.fillStyle='#FFC21F'; c.beginPath(); c.moveTo(1,-60); c.quadraticCurveTo(10,-57+wave,19,-59); c.lineTo(19,-49); c.quadraticCurveTo(10,-47-wave,1,-50); c.closePath(); c.fill(); c.strokeStyle='#8A4A00'; c.lineWidth=1.2; c.stroke(); // HP bar c.fillStyle='rgba(24,8,18,.65)'; rr(c,-32,34,64,8,4); c.fill(); c.fillStyle = hpK>.5 ? '#4BE38A' : hpK>.25 ? '#FFD34D' : '#FF4D6A'; rr(c,-30,35.6,60*clamp(hpK,0,1),4.8,2.4); c.fill(); c.strokeStyle='rgba(255,255,255,.35)'; c.lineWidth=.8; rr(c,-30,35.6,60*clamp(hpK,0,1),4.8,2.4); c.stroke(); c.restore(); } function drawPortal(c){ const p = posAt(0); const pulse = .5+.5*Math.sin(G.time*2.4); c.save(); c.translate(p.x+4, p.y); const g1 = c.createRadialGradient(0,0,2,0,0,34); g1.addColorStop(0,`rgba(255,120,200,${.55+pulse*.25})`); g1.addColorStop(.55,'rgba(150,60,220,.35)'); g1.addColorStop(1,'rgba(150,60,220,0)'); c.fillStyle=g1; c.beginPath(); c.arc(0,0,34,0,TAU); c.fill(); for(let i=0;i<3;i++){ c.strokeStyle=`rgba(255,210,255,${.55-i*.14})`; c.lineWidth=2.4-i*.6; c.beginPath(); c.ellipse(0,0,12+i*5, 20+i*6, 0, 0, TAU); c.stroke(); } c.fillStyle='rgba(30,6,40,.7)'; c.beginPath(); c.ellipse(0,0,8,16,0,0,TAU); c.fill(); c.restore(); } function starPath(c, cx, cy, R, r, rot){ c.beginPath(); for(let i=0;i<10;i++){ const rad = (i%2===0) ? R : r; const a = rot + i*Math.PI/5; const x = cx + Math.cos(a)*rad, y = cy + Math.sin(a)*rad; i ? c.lineTo(x,y) : c.moveTo(x,y); } c.closePath(); } function drawTower(c,t){ const d = TOWERS[t.type]; c.save(); c.translate(t.x, t.y); // shadow c.fillStyle='rgba(50,20,10,.30)'; c.beginPath(); c.ellipse(0,11,21,9.5,0,0,TAU); c.fill(); // platform const pg = c.createLinearGradient(0,-21,0,21); pg.addColorStop(0,'#F6D7A6'); pg.addColorStop(.55,'#DCAE74'); pg.addColorStop(1,'#A97C46'); c.fillStyle=pg; c.beginPath(); c.arc(0,0,21,0,TAU); c.fill(); c.strokeStyle='#7A4A20'; c.lineWidth=2.6; c.stroke(); c.strokeStyle='rgba(255,244,206,.6)'; c.lineWidth=1.3; c.beginPath(); c.arc(0,0,17.4,0,TAU); c.stroke(); // combo aura if(t.combos.length){ c.strokeStyle=`rgba(255,210,102,${.55+.3*Math.sin(G.time*4)})`; c.lineWidth=2.4; c.beginPath(); c.arc(0,0,23.5,0,TAU); c.stroke(); c.strokeStyle=`rgba(255,240,180,${.25+.2*Math.sin(G.time*4+1)})`; c.lineWidth=5; c.beginPath(); c.arc(0,0,23.5,0,TAU); c.stroke(); } // weapon c.save(); c.scale(1.12,1.12); c.shadowColor='rgba(44,16,8,.45)'; c.shadowBlur=3; c.shadowOffsetY=1.5; const rec = Math.max(0,t.recoil)*3; if(t.type==='archer'){ c.rotate(t.angle); // bow c.strokeStyle='#7A4522'; c.lineWidth=2.6; c.beginPath(); c.arc(4,0,10,-1.1,1.1); c.stroke(); c.strokeStyle='rgba(255,240,200,.85)'; c.lineWidth=1; c.beginPath(); c.moveTo(8.4,-8.9); c.lineTo(8.4,8.9); c.stroke(); c.rotate(-t.angle); // body c.fillStyle='#2FA968'; rr(c,-8,-6,16,16,6); c.fill(); c.strokeStyle='#1E7A4A'; c.lineWidth=1.6; c.stroke(); c.fillStyle='#4BE38A'; c.beginPath(); c.arc(0,-9,6,0,TAU); c.fill(); c.strokeStyle='#1E7A4A'; c.stroke(); c.fillStyle='#12321F'; c.beginPath(); c.arc(-2,-9,1.2,0,TAU); c.arc(2.4,-9,1.2,0,TAU); c.fill(); } else if(t.type==='crossbow'){ c.rotate(t.angle); c.translate(-rec,0); c.strokeStyle='#7A4522'; c.lineWidth=3; c.beginPath(); c.moveTo(-2,-11); c.quadraticCurveTo(8,-4,8,0); c.quadraticCurveTo(8,4,-2,11); c.stroke(); c.strokeStyle='rgba(255,240,200,.8)'; c.lineWidth=1.1; c.beginPath(); c.moveTo(-2,-11); c.lineTo(-2,11); c.stroke(); c.fillStyle='#6E4222'; rr(c,-12,-4,20,8,3); c.fill(); c.fillStyle='#FFD34D'; c.beginPath(); c.moveTo(12,0); c.lineTo(4,-4); c.lineTo(4,4); c.closePath(); c.fill(); } else if(t.type==='pistol'){ c.rotate(t.angle); c.translate(-rec,0); c.fillStyle='#8FA3B8'; rr(c,-6,-5,14,10,3); c.fill(); c.strokeStyle='#4A5C70'; c.lineWidth=1.4; c.stroke(); c.fillStyle='#5B6B80'; rr(c,-9,-6,6,12,2); c.fill(); c.fillStyle='#FFD34D'; rr(c,8,-2,5,4,1.6); c.fill(); } else if(t.type==='rifle'){ c.rotate(t.angle); c.translate(-rec,0); c.fillStyle='#7A4522'; rr(c,-10,-4,14,8,3); c.fill(); c.fillStyle='#9FB0C4'; rr(c,2,-2.4,18,4.8,2); c.fill(); c.fillStyle='#3B4A5A'; rr(c,-2,-7,8,3.6,1.6); c.fill(); c.fillStyle='#8FE9FF'; c.beginPath(); c.arc(3,-5.2,1.3,0,TAU); c.fill(); c.fillStyle='#3B4A5A'; c.beginPath(); c.moveTo(-6,3); c.lineTo(-9,9); c.lineTo(-5,9); c.closePath(); c.fill(); } else { // mortar — fixed, tube tilted up c.rotate(-Math.PI/2.6 + Math.sin(G.time*1.2)*0.03); c.translate(-rec*1.4,0); const mg = c.createLinearGradient(-10,-8,10,8); mg.addColorStop(0,'#C7D3E0'); mg.addColorStop(1,'#5B6B80'); c.fillStyle=mg; rr(c,-10,-7,22,14,5); c.fill(); c.strokeStyle='#33414F'; c.lineWidth=1.8; c.stroke(); c.fillStyle='#22303E'; c.beginPath(); c.ellipse(12,0,3,7,0,0,TAU); c.fill(); c.rotate(Math.PI/2.6); c.fillStyle='#8A5A2E'; rr(c,-9,4,18,8,3); c.fill(); } c.restore(); c.shadowColor='transparent'; c.shadowBlur=0; c.shadowOffsetY=0; // ---- star badge under the platform (still inside tower translate) ---- c.save(); rr(c, -13.5, 18.5, 27, 11, 5.5); c.fillStyle = 'rgba(36,14,6,.66)'; c.fill(); c.strokeStyle = t.lv>=3 ? 'rgba(255,210,102,.85)' : 'rgba(255,210,102,.45)'; c.lineWidth = 1.1; c.stroke(); for(let i=0;i<3;i++){ const sx = -7.6 + i*7.6, sy = 24; if(i < t.lv){ starPath(c, sx, sy, 3.6, 1.6, -Math.PI/2); c.fillStyle = '#FFD34D'; c.fill(); c.strokeStyle = '#7A4200'; c.lineWidth = 0.8; c.stroke(); c.fillStyle = 'rgba(255,255,235,.85)'; c.beginPath(); c.arc(sx-0.9, sy-1.3, 0.75, 0, TAU); c.fill(); } else { starPath(c, sx, sy, 3.0, 1.35, -Math.PI/2); c.fillStyle = 'rgba(255,235,190,.10)'; c.fill(); c.strokeStyle = 'rgba(255,225,170,.34)'; c.lineWidth = 0.8; c.stroke(); } } c.restore(); // muzzle flash if(t.flash>0){ c.save(); c.rotate(t.angle); c.translate(14,0); const a = t.flash/.08; c.fillStyle=`rgba(255,240,180,${a*.9})`; c.beginPath(); c.arc(0,0,5*a+2,0,TAU); c.fill(); c.restore(); } c.restore(); } /* enemy drawing */ function drawEnemy(c,e){ const flip = Math.cos(e.ang) < 0 ? -1 : 1; const bounce = e.air ? Math.sin(G.time*8+e.seed)*3 : (e.spd>0 ? Math.abs(Math.sin(G.time*7+e.seed))*2 : 0); const R = e.r; c.save(); // shadow c.fillStyle = e.air ? 'rgba(50,20,10,.16)' : 'rgba(50,20,10,.32)'; c.beginPath(); c.ellipse(e.x, e.y+e.r*0.9, e.r*0.9, e.r*0.36, 0,0,TAU); c.fill(); c.translate(e.x, e.y - bounce - (e.air?15:0)); c.scale(flip,1); c.shadowColor='rgba(44,16,8,.42)'; c.shadowBlur=3.5; c.shadowOffsetY=2; const body = null; if(e.type==='rabbit'){ c.fillStyle=body||'#E8C9A0'; c.beginPath(); c.ellipse(0,0,R*.95,R*.8,0,0,TAU); c.fill(); c.fillStyle=body||'#D9B487'; c.beginPath(); c.ellipse(-R*.72,-R*.1,R*.42,R*.34,0,0,TAU); c.fill(); c.fillStyle=body||'#E8C9A0'; c.beginPath(); c.ellipse(R*.62,-R*.5,R*.46,R*.42,0,0,TAU); c.fill(); c.beginPath(); c.ellipse(R*.5,-R*1.3,R*.14,R*.44,-.2,0,TAU); c.fill(); c.beginPath(); c.ellipse(R*.82,-R*1.25,R*.14,R*.42,.2,0,TAU); c.fill(); c.shadowColor='transparent'; c.fillStyle='#3A2410'; c.beginPath(); c.arc(R*.8,-R*.55,1.5,0,TAU); c.fill(); c.fillStyle='#C9552E'; c.beginPath(); c.arc(R*1.0,-R*.42,1.2,0,TAU); c.fill(); } else if(e.type==='bison'||e.type==='king'){ const big = e.type==='king'; if(big){ const aura = c.createRadialGradient(0,0,4,0,0,R*1.9); aura.addColorStop(0,'rgba(255,46,154,.42)'); aura.addColorStop(1,'rgba(255,46,154,0)'); c.fillStyle=aura; c.beginPath(); c.arc(0,0,R*1.9,0,TAU); c.fill(); } c.fillStyle=body||(big?'#5A2E6E':'#8A5A30'); c.beginPath(); c.ellipse(0,0,R*1.15,R*.86,0,0,TAU); c.fill(); c.fillStyle=body||(big?'#7A3E9E':'#9A6A3A'); c.beginPath(); c.ellipse(R*.1,-R*.58,R*.92,R*.44,0,0,TAU); c.fill(); c.fillStyle=body||(big?'#3E1B52':'#6E3E1C'); [-.55,.55].forEach((o,i)=>{ const sw = Math.sin(G.time*7+e.seed+i*2)*2; c.beginPath(); c.ellipse(R*o+sw, R*.82, R*.2, R*.34, 0,0,TAU); c.fill(); }); c.fillStyle=body||(big?'#7A3E9E':'#9A6A3A'); c.beginPath(); c.ellipse(R*.95,-R*.1,R*.62,R*.56,0,0,TAU); c.fill(); c.shadowColor='transparent'; c.strokeStyle='#F0E0C0'; c.lineWidth=big?4.2:3.2; c.lineCap='round'; c.beginPath(); c.moveTo(R*1.1,-R*.5); c.quadraticCurveTo(R*1.72,-R*1.0,R*1.5,-R*1.38); c.stroke(); c.beginPath(); c.moveTo(R*1.1,-R*.5); c.quadraticCurveTo(R*1.56,-R*.9,R*1.2,-R*1.32); c.stroke(); c.fillStyle='#FFD34D'; c.beginPath(); c.arc(R*1.15,-R*.2,R*.17,0,TAU); c.fill(); c.fillStyle='#2A0B04'; c.beginPath(); c.arc(R*1.18,-R*.2,R*.075,0,TAU); c.fill(); if(big){ c.fillStyle='#FFC21F'; c.beginPath(); c.moveTo(-R*.5,-R*1.12); c.lineTo(-R*.3,-R*1.52); c.lineTo(-R*.1,-R*1.14); c.lineTo(R*.1,-R*1.58); c.lineTo(R*.3,-R*1.12); c.closePath(); c.fill(); c.strokeStyle='#8A4A00'; c.lineWidth=1.2; c.stroke(); } } else if(e.type==='wolf'){ c.fillStyle=body||'#8C97A8'; c.beginPath(); c.ellipse(0,0,R*1.15,R*.7,0,0,TAU); c.fill(); c.fillStyle=body||'#7A8598'; c.beginPath(); c.ellipse(R*.95,-R*.3,R*.52,R*.44,0,0,TAU); c.fill(); c.beginPath(); c.moveTo(R*1.3,-R*.5); c.lineTo(R*1.78,-R*.28); c.lineTo(R*1.3,-R*.08); c.closePath(); c.fill(); c.beginPath(); c.moveTo(R*.75,-R*.62); c.lineTo(R*.72,-R*1.08); c.lineTo(R*1.0,-R*.64); c.closePath(); c.fill(); c.fillStyle=body||'#8C97A8'; c.beginPath(); c.moveTo(-R*1.1,-R*.1); c.quadraticCurveTo(-R*1.85,-R*.75,-R*1.72,R*.12); c.quadraticCurveTo(-R*1.42,-R*.05,-R*1.1,R*.18); c.closePath(); c.fill(); c.shadowColor='transparent'; c.fillStyle='#2A0B04'; c.beginPath(); c.arc(R*1.12,-R*.35,R*.1,0,TAU); c.fill(); c.fillStyle='#fff'; c.beginPath(); c.moveTo(R*1.42,-R*.16); c.lineTo(R*1.54,-R*.02); c.lineTo(R*1.34,-R*.06); c.closePath(); c.fill(); } else if(e.type==='vulture'){ const flap = Math.sin(G.time*10+e.seed); c.fillStyle=body||'#5A4468'; c.beginPath(); c.ellipse(-R*.2,0,R*.55,R*.74,0,0,TAU); c.fill(); c.fillStyle='#6E5A78'; c.beginPath(); c.ellipse(-R*.1,-R*.92,R*.92,Math.max(1,R*.3+flap*4),-.15,0,TAU); c.fill(); c.beginPath(); c.ellipse(-R*.1,R*.52,R*.82,Math.max(1,R*.26-flap*3),.15,0,TAU); c.fill(); c.shadowColor='transparent'; c.fillStyle='#C9552E'; c.beginPath(); c.ellipse(R*.44,-R*.56,R*.32,R*.28,0,0,TAU); c.fill(); c.fillStyle='#FFC21F'; c.beginPath(); c.moveTo(R*.7,-R*.56); c.lineTo(R*1.0,-R*.48); c.lineTo(R*.7,-R*.4); c.closePath(); c.fill(); c.fillStyle='#2A0B04'; c.beginPath(); c.arc(R*.52,-R*.62,R*.085,0,TAU); c.fill(); } else if(e.type==='scorpion'){ c.fillStyle=body||'#B04A2E'; c.beginPath(); c.ellipse(0,0,R*1.1,R*.72,0,0,TAU); c.fill(); c.shadowColor='transparent'; c.strokeStyle='#7A2A18'; c.lineWidth=2; for(let i=-1;i<2;i++){ c.beginPath(); c.ellipse(i*R*.45,0,R*.3,R*.64,0,0,TAU); c.stroke(); } c.strokeStyle=body||'#B04A2E'; c.lineWidth=3.6; c.lineCap='round'; c.beginPath(); c.moveTo(R*.9,-R*.2); c.lineTo(R*1.52,-R*.56); c.stroke(); c.beginPath(); c.moveTo(R*.9,R*.2); c.lineTo(R*1.52,R*.5); c.stroke(); c.beginPath(); c.moveTo(-R*.9,0); c.quadraticCurveTo(-R*1.72,-R*.2,-R*1.5,-R*1.02); c.stroke(); c.fillStyle='#FFD34D'; c.beginPath(); c.arc(-R*1.45,-R*1.08,2.6,0,TAU); c.fill(); c.fillStyle='#2A0B04'; c.beginPath(); c.arc(R*.55,-R*.15,R*.1,0,TAU); c.fill(); } if(e.hitFlash>0){ c.globalAlpha = Math.min(.45, e.hitFlash*4); c.fillStyle='#FFF6E6'; c.beginPath(); c.ellipse(0,0,R*1.05,R*.78,0,0,TAU); c.fill(); c.globalAlpha = 1; } if(e.frozen>0){ c.fillStyle='rgba(120,220,255,.34)'; c.beginPath(); c.arc(0,0,R*1.2,0,TAU); c.fill(); c.strokeStyle='rgba(210,248,255,.95)'; c.lineWidth=1.8; c.stroke(); } c.restore(); // hp bar if(e.hp < e.maxHp){ const w = e.boss? 46 : 24, x = e.x-w/2, y = e.y - e.r*1.42 - (e.air?18:4) - 4; c.fillStyle='rgba(24,8,18,.7)'; rr(c,x-1,y-1,w+2,5.6,2.8); c.fill(); c.fillStyle = e.hp/e.maxHp>.5?'#4BE38A':e.hp/e.maxHp>.22?'#FFD34D':'#FF4D6A'; rr(c,x,y,w*clamp(e.hp/e.maxHp,0,1),3.6,1.8); c.fill(); } } function drawProj(c,p){ c.save(); if(p.type==='shell'){ c.fillStyle='rgba(50,20,10,.2)'; c.beginPath(); c.ellipse(p.x, p.y, 5, 2.4, 0,0,TAU); c.fill(); c.fillStyle='#3B4A5A'; c.beginPath(); c.arc(p.x, p.y - p.h, 4.4, 0, TAU); c.fill(); c.fillStyle='#FFB04D'; c.beginPath(); c.arc(p.x-1, p.y-p.h-1.4, 1.6,0,TAU); c.fill(); } else if(p.type==='bullet'){ c.strokeStyle='rgba(255,220,120,.75)'; c.lineWidth=2; c.beginPath(); c.moveTo(p.x-Math.cos(p.ang)*9, p.y-Math.sin(p.ang)*9); c.lineTo(p.x,p.y); c.stroke(); c.fillStyle='#FFF3C0'; c.beginPath(); c.arc(p.x,p.y,1.9,0,TAU); c.fill(); } else { c.translate(p.x,p.y); c.rotate(p.ang); c.strokeStyle= p.type==='bolt' ? '#FFD34D' : '#E8D9C0'; c.lineWidth = p.type==='bolt' ? 2.6 : 1.9; c.beginPath(); c.moveTo(-10,0); c.lineTo(4,0); c.stroke(); c.fillStyle= p.type==='bolt' ? '#FFF0BF' : '#FFE9A8'; c.beginPath(); c.moveTo(9,0); c.lineTo(3,-3); c.lineTo(3,3); c.closePath(); c.fill(); } c.restore(); } function drawFx(c,f){ const k = f.t/f.life; c.save(); if(f.kind==='ring'){ c.strokeStyle=`rgba(${f.col},${1-k})`; c.lineWidth=3*(1-k)+1; c.beginPath(); c.arc(f.x,f.y, lerp(f.r0,f.r1,k),0,TAU); c.stroke(); } else if(f.kind==='boom'){ const r = f.r*(0.35+k*0.85); // outer scorch c.fillStyle=`rgba(60,20,10,${.35*(1-k)})`; c.beginPath(); c.arc(f.x,f.y,f.r*1.02,0,TAU); c.fill(); // fireball const g = c.createRadialGradient(f.x,f.y,0,f.x,f.y,r); g.addColorStop(0,`rgba(255,255,240,${.98*(1-k)})`); g.addColorStop(.28,`rgba(255,214,120,${.92*(1-k)})`); g.addColorStop(.6,`rgba(255,120,40,${.7*(1-k)})`); g.addColorStop(1,'rgba(200,60,20,0)'); c.fillStyle=g; c.beginPath(); c.arc(f.x,f.y,r,0,TAU); c.fill(); // shock ring c.strokeStyle=`rgba(255,245,200,${.85*(1-k)})`; c.lineWidth=3*(1-k)+.6; c.beginPath(); c.arc(f.x,f.y,r*1.12,0,TAU); c.stroke(); // debris for(let i=0;i<8;i++){ const a=i*.79+f.t*3, rr2=r*(0.7+((i%3)*0.16)); c.fillStyle=`rgba(255,190,90,${.8*(1-k)})`; c.beginPath(); c.arc(f.x+Math.cos(a)*rr2, f.y+Math.sin(a)*rr2*.8, 2.6*(1-k)+.6,0,TAU); c.fill(); } } else if(f.kind==='spark'){ c.fillStyle=`rgba(${f.col||'255,235,180'},${1-k})`; for(let i=0;i<3;i++){ const a=i*2.1+f.t*9, r=k*11; c.beginPath(); c.arc(f.x+Math.cos(a)*r, f.y+Math.sin(a)*r, 1.6*(1-k),0,TAU); c.fill(); } } else if(f.kind==='poof'){ c.fillStyle=`rgba(240,220,190,${.55*(1-k)})`; for(let i=0;i<6;i++){ const a=i*1.05, r=k*(f.r+8); c.beginPath(); c.arc(f.x+Math.cos(a)*r, f.y+Math.sin(a)*r*.7, (1-k)*4,0,TAU); c.fill(); } } else if(f.kind==='muzzle'){ c.save(); c.translate(f.x,f.y); c.rotate(f.ang); c.fillStyle=`rgba(255,245,200,${1-k})`; c.beginPath(); c.moveTo(0,-4*(1-k)-1); c.lineTo(9*(1-k)+3,0); c.lineTo(0,4*(1-k)+1); c.closePath(); c.fill(); c.restore(); } else if(f.kind==='beam'){ c.strokeStyle=`rgba(${f.col},${1-k})`; c.lineWidth=2.2*(1-k)+.6; c.beginPath(); c.moveTo(f.x1,f.y1); c.lineTo(f.x2,f.y2); c.stroke(); } else if(f.kind==='text'){ c.globalAlpha = 1-k; c.font='900 13px ui-rounded, "Segoe UI", sans-serif'; c.textAlign='center'; c.lineWidth=3; c.strokeStyle='rgba(40,10,20,.75)'; c.strokeText(f.text, f.x, f.y - k*22); c.fillStyle=`rgba(${f.col},1)`; c.fillText(f.text, f.x, f.y - k*22); } else if(f.kind==='stars'){ for(let i=0;i{ const d = TOWERS[el.dataset.type]; el.classList.toggle('is-poor', G.gold < d.cost); }); if(G.selTower) openTowerPanel(G.selTower); } if(force || hudCache.hp!==G.baseHP){ document.getElementById('hudBase').textContent = G.baseHP; hudCache.hp=G.baseHP; } const sTxt = G.score; if(force || hudCache.s!==sTxt){ document.getElementById('hudScore').textContent = fmt(sTxt); hudCache.s=sTxt; } const prog = G.phase==='running' ? (1 - (G.queue.length + G.enemies.length) / Math.max(1, G.waveTotalCount||1)) : (G.phase==='prep' ? 1 : 0); document.getElementById('waveProg').style.width = clamp(prog*100,0,100) + '%'; } /* ---------------- battle end ---------------- */ function endBattle(win){ if(G.phase==='done') return; G.phase='done'; G.running=false; closeTowerPanel(); const cleared = win ? (G.mode==='campaign' ? G.totalWaves : G.wave) : Math.max(0, G.wave-1); state.stats.kills += G.kills; state.stats.waves += cleared; state.stats.towers += (G.towersBuilt||0); if(G.mode==='campaign'){ G.score = cleared*150 + G.kills*20 + G.baseHP*100; const firstClear = !(state.stars[G.level] > 0); const reward = win ? Math.round(levelReward(G.level) * (firstClear ? 1 : 0.4) / 5) * 5 : 0; G.firstClear = firstClear; if(win){ const stars = G.baseHP>=20?3:(G.baseHP>=12?2:1); state.stars[G.level] = Math.max(state.stars[G.level]||0, stars); if(G.level > state.cleared) state.cleared = G.level; state.coins += reward; G.coinsEarned = reward; save(); } save(); showResult(win, cleared, reward, false); } else { G.score = cleared*150 + G.kills*20 + G.baseHP*100; const prevBest = state.best.wave||0; let reward = cleared*45; if(cleared > prevBest) reward += (cleared-prevBest)*100; state.coins += reward; G.coinsEarned = reward; state.best = { score:Math.max(G.score,state.best.score||0), wave:Math.max(cleared,state.best.wave||0) }; submitScore(G.score, cleared); save(); showResult(true, cleared, reward, true); } if(win) AU.win(); else AU.lose(); } function showResult(win, waves, coins, endless){ const t = document.getElementById('resTitle'); t.textContent = endless ? 'RUN OVER' : (win ? 'VICTORY' : 'DEFEAT'); t.className = win ? '' : 'lose'; document.getElementById('resLead').textContent = endless ? `You held for ${waves} waves. Score ${fmt(G.score)}.` : (win ? (G.firstClear ? `Outpost ${G.level} secured.` : `Outpost ${G.level} replayed · 40% reward.`) : `The stampede broke through on wave ${waves}.`); const stars = win ? (G.baseHP>=20?3:(G.baseHP>=12?2:1)) : 0; document.querySelectorAll('#resStars svg').forEach((s,i)=>s.classList.toggle('on', i startBattle('endless',0); } else if(win && G.level<20){ next.textContent = 'NEXT LEVEL'; next.onclick = ()=> startBattle('campaign', G.level+1); } else if(win){ next.textContent = 'REPLAY'; next.onclick = ()=> startBattle('campaign', G.level); } else { next.textContent = 'RETRY'; next.onclick = ()=> startBattle('campaign', G.level); } document.getElementById('resLobby').onclick = ()=>{ closeAllSheets(); showView(G.mode==='campaign'?'levels':'lobby'); }; openSheet('sheetResult'); renderLobby(); } /* ---------------- input ---------------- */ field.addEventListener('pointerdown', ev=>{ if(G.phase==='done') return; const r = field.getBoundingClientRect(); const x = (ev.clientX - r.left) * (FW / r.width); const y = (ev.clientY - r.top) * (FH / r.height); if(G.armed==='air'){ state.items.air--; save(); G.armed=null; document.querySelectorAll('.item').forEach(el=>el.classList.remove('is-arm')); renderItemDock(); addFx('boom', x, y, {life:.55, r:78}); AU.strike(); G.shake = 9; G.enemies.forEach(e=>{ if(Math.hypot(e.x-x,e.y-y) <= 78+e.r) damageEnemy(e, 400, true, '255,160,90'); }); return; } const slot = slotAt(x,y); if(slot && slot.tower){ openTowerPanel(slot.tower); return; } if(slot && G.selType){ buildTower(slot, G.selType); return; } if(slot && !slot.tower){ toast('Pick a tower card first'); return; } closeTowerPanel(); }); document.getElementById('buyConfirm').onclick = ()=> confirmBuy(); document.getElementById('tpClose').onclick = closeTowerPanel; document.getElementById('tpUpgrade').onclick = ()=>{ if(G.selTower) upgradeTower(G.selTower); }; document.getElementById('tpSell').onclick = ()=>{ if(G.selTower) sellTower(G.selTower); }; document.getElementById('btnPause').onclick = ()=>{ G.paused = true; openSheet('sheetPause'); }; document.getElementById('btnResume').onclick = ()=>{ G.paused=false; closeSheet('sheetPause'); }; document.getElementById('btnRestart').onclick = ()=>{ closeAllSheets(); startBattle(G.mode, G.level); }; document.getElementById('btnQuit').onclick = ()=>{ closeAllSheets(); G.phase='done'; G.running=false; showView(G.mode==='campaign'?'levels':'lobby'); }; document.getElementById('btnNextWave').onclick = ()=>{ if(G.phase==='prep'){ G.prepLeft = 0; G.gold += 25; floatText(BASE.x, BASE.y-70, '+25 EARLY', '255,235,180'); AU.wave(); } else toast('Wave in progress'); }; document.querySelectorAll('#spdBox button').forEach(b=>{ b.onclick = ()=>{ G.speed = Number(b.dataset.spd); document.querySelectorAll('#spdBox button').forEach(x=>x.classList.toggle('is-on', x===b)); }; }); addEventListener('keydown', e=>{ if(e.key!=='Escape') return; const open = [...document.querySelectorAll('.sheet.is-open')].pop(); if(open && open.id==='sheetResult') return; if(open){ open.classList.remove('is-open'); if(open.id==='sheetPause' || open.id==='sheetBuy') G.paused=false; return; } if(currentView==='battle'){ G.paused = !G.paused; if(G.paused) openSheet('sheetPause'); } }); /* ---------------- coach ---------------- */ let coachTimer=null; function showCoach(text){ const el = document.getElementById('coach'); document.getElementById('coachText').textContent = text; el.classList.add('is-on'); clearTimeout(coachTimer); coachTimer = setTimeout(()=>el.classList.remove('is-on'), 5200); } /* ---------------- loop ---------------- */ let lastT = performance.now(), loopRunning = true; function loop(now){ const raw = Math.min(0.05, (now - lastT)/1000 || 0); lastT = now; if(currentView==='battle' && G.running && !G.paused && G.phase!=='done'){ let steps = G.speed; for(let i=0;i