app.js 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241
  1. /* ============================================================
  2. BUFFALO SIEGE · Desert Defense — app core
  3. ============================================================ */
  4. 'use strict';
  5. const device = document.getElementById('device');
  6. const screenEl = document.getElementById('screen');
  7. const canvasRoot = document.getElementById('canvasRoot');
  8. const W = 430, H = 932;
  9. function fit(){
  10. const s = Math.min(screenEl.clientWidth / W, screenEl.clientHeight / H);
  11. canvasRoot.style.transform = `scale(${s})`;
  12. }
  13. addEventListener('resize', fit);
  14. /* ---------------- utils ---------------- */
  15. const fmt = n => Number(n).toLocaleString('en-US');
  16. const todayKey = () => {
  17. const d = new Date();
  18. return d.getFullYear() + '-' + String(d.getMonth()+1).padStart(2,'0') + '-' + String(d.getDate()).padStart(2,'0');
  19. };
  20. const clamp = (v,a,b) => Math.max(a, Math.min(b, v));
  21. const lerp = (a,b,t) => a + (b-a)*t;
  22. const rnd = (a,b) => a + Math.random()*(b-a);
  23. const pick = arr => arr[(Math.random()*arr.length)|0];
  24. const TAU = Math.PI*2;
  25. function rr(c,x,y,w,h,r){ r=Math.min(r,w/2,h/2); c.beginPath();
  26. 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);
  27. c.arcTo(x,y+h,x,y,r); c.arcTo(x,y,x+w,y,r); c.closePath(); }
  28. function seedRnd(seed){ let s=seed>>>0; return ()=>{ s=(s*1664525+1013904223)>>>0; return s/4294967296; }; }
  29. /* ---------------- audio ---------------- */
  30. const AU = {
  31. ctx:null,
  32. get on(){ return state.sfx; },
  33. init(){ if(!this.ctx){ try{ this.ctx = new (window.AudioContext||window.webkitAudioContext)(); }catch(e){} } },
  34. tone(f0,f1,dur,type,vol){
  35. if(!this.on) return; this.init(); const c=this.ctx; if(!c) return;
  36. const t=c.currentTime, o=c.createOscillator(), g=c.createGain();
  37. o.type=type||'square'; o.frequency.setValueAtTime(f0,t);
  38. o.frequency.exponentialRampToValueAtTime(Math.max(30,f1),t+dur);
  39. g.gain.setValueAtTime(0.0001,t);
  40. g.gain.exponentialRampToValueAtTime(vol||0.12,t+0.012);
  41. g.gain.exponentialRampToValueAtTime(0.0001,t+dur);
  42. o.connect(g); g.connect(c.destination); o.start(t); o.stop(t+dur+0.02);
  43. },
  44. noise(dur,vol,f){
  45. if(!this.on) return; this.init(); const c=this.ctx; if(!c) return;
  46. const n=Math.floor(c.sampleRate*dur), buf=c.createBuffer(1,n,c.sampleRate), d=buf.getChannelData(0);
  47. for(let i=0;i<n;i++) d[i]=(Math.random()*2-1)*(1-i/n);
  48. const src=c.createBufferSource(); src.buffer=buf;
  49. const bp=c.createBiquadFilter(); bp.type='lowpass'; bp.frequency.value=f||900;
  50. const g=c.createGain(); g.gain.value=vol||0.16; g.gain.exponentialRampToValueAtTime(0.0001,c.currentTime+dur);
  51. src.connect(bp); bp.connect(g); g.connect(c.destination); src.start();
  52. },
  53. shoot(kind){
  54. if(kind==='rifle') this.tone(760,180,0.07,'square',0.07);
  55. else if(kind==='pistol') this.tone(620,260,0.05,'square',0.05);
  56. else if(kind==='mortar'){ this.tone(180,60,0.16,'sawtooth',0.1); }
  57. else this.tone(520,300,0.045,'triangle',0.05);
  58. },
  59. boom(){ this.noise(0.28,0.2,700); this.tone(120,40,0.24,'sine',0.14); },
  60. hit(){ this.tone(300,180,0.03,'square',0.03); },
  61. build(){ this.tone(420,760,0.1,'triangle',0.1); },
  62. upgrade(){ this.tone(560,980,0.14,'triangle',0.11); },
  63. coin(){ this.tone(880,1320,0.08,'sine',0.09); },
  64. err(){ this.tone(220,150,0.12,'sawtooth',0.09); },
  65. wave(){ this.tone(330,520,0.16,'triangle',0.1); },
  66. win(){ [0,90,180,300].forEach((d,i)=>setTimeout(()=>this.tone([520,660,780,1040][i],[520,660,780,1040][i],0.22,'triangle',0.11),d)); },
  67. lose(){ [0,140,300].forEach((d,i)=>setTimeout(()=>this.tone([360,280,180][i],[300,200,90][i],0.3,'sawtooth',0.1),d)); },
  68. freeze(){ this.tone(1200,300,0.4,'sine',0.09); },
  69. strike(){ this.noise(0.5,0.24,500); this.tone(200,50,0.4,'sawtooth',0.13); }
  70. };
  71. /* ---------------- background music ---------------- */
  72. const BGM = {
  73. nodes:null, oscs:[],
  74. start(){
  75. if(this.nodes) return;
  76. AU.init();
  77. const c = AU.ctx; if(!c) return;
  78. const master = c.createGain();
  79. master.gain.value = 0.0001;
  80. master.connect(c.destination);
  81. // wind: filtered noise loop
  82. const len = Math.floor(c.sampleRate*2);
  83. const buf = c.createBuffer(1, len, c.sampleRate);
  84. const d = buf.getChannelData(0);
  85. let last = 0;
  86. for(let i=0;i<len;i++){ last = (last + (Math.random()*2-1)*0.03) * 0.985; d[i] = last*2.6; }
  87. const src = c.createBufferSource(); src.buffer = buf; src.loop = true;
  88. const bp = c.createBiquadFilter(); bp.type='bandpass'; bp.frequency.value=480; bp.Q.value=0.8;
  89. const wg = c.createGain(); wg.gain.value = 0.45;
  90. src.connect(bp); bp.connect(wg); wg.connect(master);
  91. // low drone pad
  92. const pad = c.createGain(); pad.gain.value = 0.05; pad.connect(master);
  93. [98, 146.8, 196].forEach((f,i)=>{
  94. const o = c.createOscillator(); o.type = i===2 ? 'triangle' : 'sine';
  95. o.frequency.value = f;
  96. const g = c.createGain(); g.gain.value = i===2 ? 0.16 : 0.42;
  97. o.connect(g); g.connect(pad); o.start();
  98. const lfo = c.createOscillator(); lfo.frequency.value = 0.05 + i*0.017;
  99. const lg = c.createGain(); lg.gain.value = 0.18;
  100. lfo.connect(lg); lg.connect(g.gain); lfo.start();
  101. this.oscs.push(o, lfo);
  102. });
  103. src.start();
  104. master.gain.exponentialRampToValueAtTime(0.06, c.currentTime + 2.0);
  105. this.nodes = { master, src };
  106. },
  107. stop(){
  108. if(!this.nodes) return;
  109. const c = AU.ctx, { master, src } = this.nodes;
  110. try{ master.gain.cancelScheduledValues(c.currentTime);
  111. master.gain.setValueAtTime(master.gain.value, c.currentTime);
  112. master.gain.exponentialRampToValueAtTime(0.0001, c.currentTime + 0.5); }catch(e){}
  113. const oscs = this.oscs;
  114. setTimeout(()=>{ try{ src.stop(); }catch(e){} oscs.forEach(o=>{ try{o.stop();}catch(e){} }); }, 600);
  115. this.oscs = []; this.nodes = null;
  116. },
  117. sync(){ state.music ? this.start() : this.stop(); }
  118. };
  119. /* ---------------- save ---------------- */
  120. const SAVE_KEY = 'buffalo_siege_style_a_preview_v1';
  121. const BOTS = [
  122. {name:'DustDevil',score:48200,wave:34},{name:'PrairieKing',score:41500,wave:31},
  123. {name:'MesaRanger',score:36900,wave:28},{name:'VultureEye',score:31400,wave:26},
  124. {name:'BisonBane',score:27800,wave:24},{name:'CactusJack',score:23100,wave:21},
  125. {name:'RedDune',score:18700,wave:19},{name:'SilverSpur',score:14200,wave:16},
  126. {name:'Tumbleweed',score:9800,wave:13},{name:'RookieRanger',score:5600,wave:10}
  127. ];
  128. function defaults(){
  129. return {
  130. coins:1500,
  131. items:{air:1,frost:0,repair:0,gold:1},
  132. cleared:0,
  133. stars:{},
  134. best:{score:0,wave:0},
  135. board:BOTS.map(b=>({...b})),
  136. armory:{archer:1,pistol:1,crossbow:1,rifle:1,mortar:1},
  137. player:{ name:'Desert Ranger', id:'', avatar:'bison' },
  138. stats:{ kills:0, towers:0, waves:0 },
  139. checkin:{ day:1, last:'' },
  140. sfx:true,
  141. music:false,
  142. tutorial:0
  143. };
  144. }
  145. let state = defaults();
  146. function save(){ try{ localStorage.setItem(SAVE_KEY, JSON.stringify(state)); }catch(e){} }
  147. function load(){
  148. try{
  149. const raw = localStorage.getItem(SAVE_KEY);
  150. if(!raw) return;
  151. const p = JSON.parse(raw);
  152. state = Object.assign(defaults(), p);
  153. state.items = Object.assign(defaults().items, p.items||{});
  154. state.armory = Object.assign(defaults().armory, p.armory||{});
  155. state.player = Object.assign(defaults().player, p.player||{});
  156. state.stats = Object.assign(defaults().stats, p.stats||{});
  157. state.checkin = Object.assign(defaults().checkin, p.checkin||{});
  158. state.best = Object.assign({score:0,wave:0}, p.best||{});
  159. if(!Array.isArray(state.board) || !state.board.length) state.board = BOTS.map(b=>({...b}));
  160. }catch(e){ state = defaults(); }
  161. }
  162. /* ---------------- data ---------------- */
  163. const TOWERS = {
  164. archer:{ key:'archer', name:'Archer', cost:100, icon:'t-archer', proj:'arrow', pspeed:520, air:false,
  165. lv:[{dmg:11,rate:.75,range:108},{dmg:18,rate:.68,range:116},{dmg:29,rate:.60,range:124}],
  166. up:[90,150], tint:'#4BE38A', tag:'Rapid single target' },
  167. crossbow:{ key:'crossbow', name:'Crossbow', cost:170, icon:'t-crossbow', proj:'bolt', pspeed:620, air:false, pierce:true,
  168. lv:[{dmg:46,rate:2.0,range:150},{dmg:74,rate:1.85,range:160},{dmg:118,rate:1.70,range:172}],
  169. up:[150,240], tint:'#FFD34D', tag:'Armor piercing sniper' },
  170. pistol:{ key:'pistol', name:'Pistol', cost:130, icon:'t-pistol', proj:'bullet', pspeed:760, air:false,
  171. lv:[{dmg:7,rate:.38,range:92},{dmg:11,rate:.33,range:98},{dmg:17,rate:.29,range:105}],
  172. up:[110,180], tint:'#8FE9FF', tag:'Cheap rapid fire' },
  173. rifle:{ key:'rifle', name:'Rifle', cost:250, icon:'t-rifle', proj:'hitscan', air:true,
  174. lv:[{dmg:38,rate:1.30,range:180},{dmg:62,rate:1.20,range:192},{dmg:98,rate:1.10,range:205}],
  175. up:[220,340], tint:'#FF8FA6', tag:'Long range · hits air' },
  176. mortar:{ key:'mortar', name:'Mortar', cost:320, icon:'t-mortar', proj:'shell', pspeed:300, air:false, splash:1,
  177. 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}],
  178. up:[280,430], tint:'#FFA24D', tag:'Splash · ground only' }
  179. };
  180. const TOWER_ORDER = ['archer','pistol','crossbow','rifle','mortar'];
  181. const ENEMIES = {
  182. rabbit: { key:'rabbit', name:'Jackrabbit', hp:30, spd:118, armor:0, gold:10, leak:1, r:12, air:false, col:'#E8C9A0' },
  183. bison: { key:'bison', name:'Bison', hp:84, spd:70, armor:0, gold:14, leak:1, r:16, air:false, col:'#9A6A3A' },
  184. wolf: { key:'wolf', name:'Wolf', hp:104, spd:92, armor:2, gold:16, leak:1, r:14, air:false, col:'#8C97A8' },
  185. vulture: { key:'vulture', name:'Vulture', hp:68, spd:104, armor:0, gold:18, leak:1, r:13, air:true, col:'#6E5A78' },
  186. scorpion:{ key:'scorpion',name:'Scorpion', hp:176, spd:58, armor:9, gold:26, leak:2, r:16, air:false, col:'#B04A2E' },
  187. king: { key:'king', name:'Buffalo King',hp:1200,spd:50, armor:6, gold:150,leak:5, r:27, air:false, col:'#7A3E9E', boss:true }
  188. };
  189. const COMBOS = [
  190. { a:'archer', b:'crossbow', name:'Volley', desc:'+15% range, +10% fire rate' },
  191. { a:'pistol', b:'rifle', name:'Suppression', desc:'+25% fire rate' },
  192. { a:'rifle', b:'mortar', name:'Siege Line', desc:'+25% splash, +10% damage' },
  193. { a:'crossbow', b:'mortar', name:'Pierce Shell', desc:'+20% damage, splash ignores armor' }
  194. ];
  195. const ITEMS = {
  196. air: { key:'air', name:'Airstrike', price:800, icon:'it-air', desc:'Tap the field: 400 damage in a wide blast.' },
  197. frost: { key:'frost', name:'Frost Nova', price:600, icon:'it-frost', desc:'Freeze every enemy on the map for 4 seconds.' },
  198. repair: { key:'repair', name:'Repair Kit', price:1200, icon:'it-heal', desc:'Restore 3 base HP (max 20).' },
  199. gold: { key:'gold', name:'Gold Rush', price:500, icon:'it-gold', desc:'Instantly add 300 battle gold.' }
  200. };
  201. const ITEM_ORDER = ['air','frost','repair','gold'];
  202. const AVATARS = [
  203. { key:'bison', icon:'a-bison', col:'#FFC21F' },
  204. { key:'wolf', icon:'a-wolf', col:'#8FE9FF' },
  205. { key:'eagle', icon:'a-eagle', col:'#FF6B8A' },
  206. { key:'scorpion', icon:'a-scorpion', col:'#FF8A4D' },
  207. { key:'rabbit', icon:'a-rabbit', col:'#4BE38A' },
  208. { key:'bear', icon:'a-bear', col:'#B98AFF' },
  209. { key:'horse', icon:'a-horse', col:'#FFD98A' },
  210. { key:'snake', icon:'a-snake', col:'#34E0FF' }
  211. ];
  212. function avatarOf(key){ return AVATARS.find(a=>a.key===key) || AVATARS[0]; }
  213. function newPlayerId(){
  214. return String(Math.floor(10000000 + Math.random()*89999999));
  215. }
  216. /* 7 天签到:5 天金币 + 2 天道具 */
  217. const CHECKIN = [
  218. { type:'coins', amt:300 },
  219. { type:'item', key:'air', amt:1 },
  220. { type:'coins', amt:600 },
  221. { type:'coins', amt:1000 },
  222. { type:'item', key:'repair', amt:1 },
  223. { type:'coins', amt:1500 },
  224. { type:'coins', amt:2500 }
  225. ];
  226. function checkinIndex(){ return (state.checkin.day - 1) % 7; }
  227. function canCheckin(){ return state.checkin.last !== todayKey(); }
  228. function renderCheckin(){
  229. const idx = checkinIndex();
  230. const day = state.checkin.day;
  231. document.getElementById('ckStreak').textContent = 'DAY ' + day + ' / 7';
  232. document.getElementById('ckBar').style.width = (day/7*100) + '%';
  233. const list = document.getElementById('ckList');
  234. list.innerHTML = '';
  235. CHECKIN.forEach((r,i)=>{
  236. const done = i < idx, today = i === idx;
  237. const icon = r.type==='coins' ? 'i-coin' : ITEMS[r.key].icon;
  238. const label = r.type==='coins' ? fmt(r.amt) + ' coins' : ITEMS[r.key].name + ' ×' + r.amt;
  239. const row = document.createElement('div');
  240. row.className = 'ck-row' + (done?' is-done':'') + (today?' is-today':'') + (!done&&!today?' is-lock':'');
  241. row.innerHTML = `
  242. <div class="ck-ic"><svg><use href="#${icon}"/></svg></div>
  243. <div class="ck-main"><b>DAY ${i+1}</b><span>${label}</span></div>
  244. <div class="ck-pill ${done?'done':today?'today':'lock'}">${done?'CLAIMED':today?'TODAY':'LOCKED'}</div>`;
  245. list.appendChild(row);
  246. });
  247. const ok = canCheckin();
  248. const btn = document.getElementById('ckClaim');
  249. btn.disabled = !ok;
  250. btn.textContent = ok ? 'CLAIM DAY ' + day : 'CLAIMED TODAY';
  251. document.getElementById('ckHint').textContent = ok
  252. ? 'One claim per day · resets every 7 days'
  253. : 'Already claimed today · next reward tomorrow';
  254. document.getElementById('checkinDot').classList.toggle('is-on', ok);
  255. }
  256. function claimCheckin(){
  257. if(!canCheckin()){ AU.err(); toast('Already claimed today'); return; }
  258. const r = CHECKIN[checkinIndex()];
  259. if(r.type==='coins'){ state.coins += r.amt; }
  260. else { state.items[r.key] = (state.items[r.key]||0) + r.amt; }
  261. const day = state.checkin.day;
  262. state.checkin.day = (day % 7) + 1;
  263. state.checkin.last = todayKey();
  264. save(); AU.upgrade();
  265. renderCheckin(); renderLobby();
  266. toast('Day ' + day + ' claimed · ' + (r.type==='coins' ? fmt(r.amt)+' coins' : ITEMS[r.key].name+' ×'+r.amt));
  267. }
  268. function ensurePlayer(){
  269. if(!state.player) state.player = defaults().player;
  270. if(!state.player.id) state.player.id = newPlayerId();
  271. if(!state.player.name) state.player.name = 'Desert Ranger';
  272. if(!state.player.avatar) state.player.avatar = 'bison';
  273. if(!state.stats) state.stats = defaults().stats;
  274. }
  275. const ARMORY_MAX = 5;
  276. const ARMORY_DMG = 0.08; // +8% damage per level
  277. const ARMORY_RNG = 0.02; // +2% range per level
  278. const ARMORY_MULT = [2, 3.5, 5.5, 8];
  279. function armoryLv(type){ return clamp(state.armory[type]||1, 1, ARMORY_MAX); }
  280. function armoryBonus(type){
  281. const lv = armoryLv(type);
  282. return { lv, dmg:1+ARMORY_DMG*(lv-1), range:1+ARMORY_RNG*(lv-1) };
  283. }
  284. function armoryCost(type){
  285. const lv = armoryLv(type);
  286. if(lv >= ARMORY_MAX) return 0;
  287. return Math.round(TOWERS[type].cost * ARMORY_MULT[lv-1] / 10) * 10;
  288. }
  289. function upgradeArmory(type){
  290. const lv = armoryLv(type), cost = armoryCost(type);
  291. if(lv >= ARMORY_MAX){ AU.err(); toast('Already max level'); return false; }
  292. if(state.coins < cost){ AU.err(); toast('Need ' + (cost-state.coins) + ' more coins'); return false; }
  293. state.coins -= cost;
  294. state.armory[type] = lv + 1;
  295. save(); AU.upgrade();
  296. toast(`${TOWERS[type].name} upgraded to Lv.${lv+1}`);
  297. renderArmory(type); renderLobby();
  298. if(currentView==='levels') document.getElementById('levelCoins').textContent = fmt(state.coins);
  299. return true;
  300. }
  301. const levelReward = n => 250 + n*135;
  302. const recArmory = n => Math.min(ARMORY_MAX, 1 + Math.floor((n-1)/4));
  303. const levelWaves = n => 4 + Math.floor(n/2);
  304. /* 关卡血量倍率:二次曲线 + 新手保护(1–4 关 ×0.66,5–6 关 ×0.72) */
  305. const levelHpMul = n => {
  306. const base = 1 + 0.20*(n-1) + 0.0125*(n-1)*(n-1);
  307. const ease = n<=4 ? 0.66 : (n<=6 ? 0.72 : 1);
  308. return base*ease;
  309. };
  310. /* ---------------- navigation ---------------- */
  311. let currentView = 'loading';
  312. function showView(name){
  313. document.querySelectorAll('.view').forEach(v=>v.classList.toggle('is-active', v.dataset.view===name));
  314. currentView = name;
  315. if(name==='lobby') renderLobby();
  316. if(name==='levels') renderLevels();
  317. }
  318. function openSheet(id){ document.getElementById(id).classList.add('is-open'); }
  319. function closeSheet(id){ document.getElementById(id).classList.remove('is-open'); }
  320. function closeAllSheets(){ document.querySelectorAll('.sheet').forEach(s=>s.classList.remove('is-open')); }
  321. let toastTimer = null;
  322. function toast(msg){
  323. const el = document.getElementById('toast');
  324. el.textContent = msg; el.classList.add('is-on');
  325. clearTimeout(toastTimer);
  326. toastTimer = setTimeout(()=>el.classList.remove('is-on'), 1600);
  327. }
  328. /* ---------------- start / mesa art ---------------- */
  329. function paintDesert(c, w, h, opts){
  330. opts = opts||{};
  331. const rnd = seedRnd(opts.seed||7);
  332. const sky = c.createLinearGradient(0,0,0,h*0.72);
  333. sky.addColorStop(0,'#3B0F52'); sky.addColorStop(.28,'#7A1A56');
  334. sky.addColorStop(.52,'#C4392C'); sky.addColorStop(.74,'#F07A28'); sky.addColorStop(1,'#F7BE63');
  335. c.fillStyle = sky; c.fillRect(0,0,w,h*0.72);
  336. // sun
  337. const sx=w*0.5, sy=h*0.34, sr=Math.min(w,h)*0.24;
  338. const sg=c.createRadialGradient(sx,sy,0,sx,sy,sr*1.9);
  339. sg.addColorStop(0,'rgba(255,236,170,.95)'); sg.addColorStop(.34,'rgba(255,190,90,.55)');
  340. sg.addColorStop(.62,'rgba(255,120,50,.18)'); sg.addColorStop(1,'rgba(255,120,50,0)');
  341. c.fillStyle=sg; c.beginPath(); c.arc(sx,sy,sr*1.9,0,TAU); c.fill();
  342. // mesa silhouettes
  343. for(let layer=0;layer<3;layer++){
  344. const baseY = h*(0.56+layer*0.09);
  345. const col = ['rgba(96,32,60,.55)','rgba(120,44,50,.65)','rgba(72,26,40,.9)'][layer];
  346. c.fillStyle = col; c.beginPath(); c.moveTo(0,h);
  347. let x=0;
  348. while(x<w){
  349. const bw = w*(0.12+rnd()*0.22), bh = h*(0.05+rnd()*0.11)*(1-layer*0.15);
  350. c.lineTo(x, baseY-bh*0.35); c.lineTo(x+bw*0.12, baseY-bh); c.lineTo(x+bw*0.8, baseY-bh);
  351. c.lineTo(x+bw*0.92, baseY-bh*0.3); c.lineTo(x+bw, baseY); x+=bw;
  352. }
  353. c.lineTo(w,h); c.closePath(); c.fill();
  354. }
  355. // ground
  356. const gg = c.createLinearGradient(0,h*0.6,0,h);
  357. gg.addColorStop(0,'#C97A38'); gg.addColorStop(.45,'#E09A45'); gg.addColorStop(1,'#B9702E');
  358. c.fillStyle=gg; c.beginPath(); c.moveTo(0,h*0.68); c.lineTo(w,h*0.66); c.lineTo(w,h); c.lineTo(0,h); c.closePath(); c.fill();
  359. // dunes
  360. for(let i=0;i<4;i++){
  361. c.fillStyle = `rgba(${210+i*8},${150+i*6},${80},${0.35-i*0.05})`;
  362. c.beginPath(); c.ellipse(w*(0.15+rnd()*0.7), h*(0.72+rnd()*0.24), w*0.35, h*0.05, 0,0,TAU); c.fill();
  363. }
  364. // grass tufts + rocks
  365. for(let i=0;i<46;i++){
  366. const gx=rnd()*w, gy=h*(0.72+rnd()*0.27);
  367. c.strokeStyle='rgba(120,86,40,.55)'; c.lineWidth=1;
  368. c.beginPath(); c.moveTo(gx,gy); c.lineTo(gx-2,gy-4); c.moveTo(gx,gy); c.lineTo(gx+2,gy-5); c.stroke();
  369. }
  370. if(opts.towers!==false){
  371. // a couple of cacti
  372. for(let i=0;i<3;i++){
  373. const cx=w*(0.1+rnd()*0.8), cy=h*(0.78+rnd()*0.16);
  374. c.strokeStyle='#4E6B33'; c.lineWidth=5; c.lineCap='round';
  375. c.beginPath(); c.moveTo(cx,cy); c.lineTo(cx,cy-18); c.moveTo(cx,cy-10); c.lineTo(cx-6,cy-15);
  376. c.moveTo(cx,cy-13); c.lineTo(cx+6,cy-19); c.stroke();
  377. }
  378. }
  379. // vignette
  380. const vg=c.createRadialGradient(w/2,h*0.5,h*0.2,w/2,h*0.5,h*0.9);
  381. vg.addColorStop(0,'rgba(0,0,0,0)'); vg.addColorStop(1,'rgba(20,4,20,.55)');
  382. c.fillStyle=vg; c.fillRect(0,0,w,h);
  383. }
  384. function drawModeArt(){
  385. document.querySelectorAll('canvas[data-art]').forEach(cv=>{
  386. const c = cv.getContext('2d'), w=cv.width, h=cv.height;
  387. paintDesert(c,w,h,{seed: cv.dataset.art==='campaign'?11:29, towers:true});
  388. c.save();
  389. // buffalo head emblem
  390. c.globalAlpha=.95;
  391. const img = new Path2D();
  392. // simple emblem: shield + horns silhouette
  393. const cx=w/2, cy=h*0.44;
  394. c.fillStyle='rgba(20,4,20,.28)'; c.beginPath(); c.arc(cx,cy,h*0.3,0,TAU); c.fill();
  395. c.restore();
  396. });
  397. }
  398. function paintStartLandscape(){
  399. const cv = document.getElementById('mesaCanvas');
  400. if(!cv) return;
  401. const c = cv.getContext('2d'), w = cv.width, h = cv.height;
  402. const rnd = seedRnd(913);
  403. c.clearRect(0,0,w,h);
  404. // ---- distant mesa ranges (atmospheric perspective) ----
  405. const ranges = [
  406. { y:h*0.40, col:'#8A3E6E', hi:'#B25C86', hh:0.13, n:4 },
  407. { y:h*0.50, col:'#6E2A52', hi:'#93426C', hh:0.17, n:5 },
  408. { y:h*0.61, col:'#4A1836', hi:'#6B2848', hh:0.20, n:6 }
  409. ];
  410. ranges.forEach((R,ri)=>{
  411. c.fillStyle=R.col;
  412. c.beginPath();
  413. c.moveTo(0,h);
  414. let y = R.y - h*R.hh*0.55;
  415. c.lineTo(0,y);
  416. let x = 0;
  417. while(x < w+20){
  418. const seg = w*(0.055+rnd()*0.075);
  419. const topMin = R.y - h*R.hh, topMax = R.y - h*R.hh*0.18;
  420. const dy = (rnd()-0.5)*h*R.hh*0.55;
  421. y = Math.max(topMin, Math.min(topMax, y + dy));
  422. c.lineTo(x + seg*0.14, y);
  423. c.lineTo(x + seg*0.86, y);
  424. const drop = h*R.hh*(0.10+rnd()*0.28);
  425. c.lineTo(x + seg, Math.min(R.y, y + drop));
  426. x += seg;
  427. }
  428. c.lineTo(w,h); c.closePath(); c.fill();
  429. // faint top rim
  430. c.strokeStyle=`rgba(255,186,132,${0.22-ri*0.05})`; c.lineWidth=1.4;
  431. c.stroke();
  432. });
  433. // ---- sand floor ----
  434. const gg = c.createLinearGradient(0,h*0.64,0,h);
  435. gg.addColorStop(0,'#D98A3E'); gg.addColorStop(.4,'#C0702E'); gg.addColorStop(1,'#7E401C');
  436. 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();
  437. // horizon glow
  438. const rg = c.createLinearGradient(0,h*0.56,0,h*0.74);
  439. rg.addColorStop(0,'rgba(255,190,110,.55)'); rg.addColorStop(1,'rgba(255,150,60,0)');
  440. c.fillStyle=rg; c.fillRect(0,h*0.56,w,h*0.18);
  441. // dunes
  442. for(let i=0;i<6;i++){
  443. c.fillStyle=`rgba(${214+i*5},${142+i*7},${70},.32)`;
  444. 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();
  445. }
  446. // ground shadow under everything
  447. const sg = c.createLinearGradient(0,h*0.86,0,h);
  448. sg.addColorStop(0,'rgba(60,20,12,0)'); sg.addColorStop(1,'rgba(50,14,26,.55)');
  449. c.fillStyle=sg; c.fillRect(0,h*0.86,w,h*0.14);
  450. // ---- stampede silhouettes on the horizon ----
  451. const drawBeast = (bx,by,s)=>{
  452. c.save(); c.translate(bx,by); c.scale(s,s);
  453. c.fillStyle='rgba(44,12,26,.82)';
  454. c.beginPath(); c.ellipse(0,0,13,7.5,0,0,TAU); c.fill();
  455. c.beginPath(); c.ellipse(6,-3.4,7,5,0,0,TAU); c.fill();
  456. c.beginPath(); c.ellipse(11,-1,4.4,3.4,0,0,TAU); c.fill();
  457. c.strokeStyle='rgba(44,12,26,.82)'; c.lineWidth=2.2; c.lineCap='round';
  458. c.beginPath(); c.moveTo(10,-3); c.quadraticCurveTo(13,-7,11.5,-9); c.stroke();
  459. c.beginPath(); c.moveTo(-9,5); c.lineTo(-9,11); c.moveTo(5,5); c.lineTo(5,11); c.stroke();
  460. c.restore();
  461. };
  462. for(let i=0;i<5;i++) drawBeast(w*(0.5+i*0.115), h*0.655+rnd()*4, 0.72+rnd()*0.4);
  463. // ---- outpost silhouette (left) ----
  464. c.save(); c.translate(w*0.13, h*0.87); c.scale(0.72,0.72);
  465. c.fillStyle='rgba(42,12,30,.92)';
  466. c.fillRect(-24,-18,48,38);
  467. for(let i=0;i<5;i++) c.fillRect(-22+i*9, -26, 6, 46);
  468. c.beginPath(); c.moveTo(-30,-20); c.lineTo(0,-40); c.lineTo(30,-20); c.closePath(); c.fill();
  469. c.fillRect(-1.4,-58,2.8,18);
  470. c.beginPath(); c.moveTo(1,-58); c.lineTo(16,-53); c.lineTo(1,-48); c.closePath(); c.fill();
  471. c.restore();
  472. // ---- cacti / scrub ----
  473. for(let i=0;i<9;i++){
  474. const cx=rnd()*w, cy=h*(0.75+rnd()*0.2), s=6+rnd()*9;
  475. c.strokeStyle='rgba(36,16,14,.8)'; c.lineWidth=3; c.lineCap='round';
  476. c.beginPath(); c.moveTo(cx,cy); c.lineTo(cx,cy-s*1.6);
  477. c.moveTo(cx,cy-s); c.lineTo(cx-s*0.5,cy-s*1.2);
  478. c.moveTo(cx,cy-s*1.2); c.lineTo(cx+s*0.5,cy-s*1.6); c.stroke();
  479. }
  480. }
  481. /* ---------------- lobby ---------------- */
  482. function renderLobby(){
  483. ensurePlayer();
  484. const av = avatarOf(state.player.avatar);
  485. const lav = document.getElementById('lobbyAva');
  486. if(lav) lav.innerHTML = `<svg style="color:${av.col}" fill="currentColor"><use href="#${av.icon}"/></svg>`;
  487. const lnm = document.getElementById('lobbyName');
  488. if(lnm) lnm.textContent = state.player.name;
  489. const lid = document.getElementById('lobbyId');
  490. if(lid) lid.textContent = state.player.id;
  491. const cdot = document.getElementById('checkinDot');
  492. if(cdot) cdot.classList.toggle('is-on', canCheckin());
  493. document.getElementById('lobbyCoinVal').textContent = fmt(state.coins);
  494. document.getElementById('lobbyBest').textContent = fmt(state.best.score);
  495. document.getElementById('campaignGo').textContent = state.cleared>=20 ? 'ALL 20 DONE' : 'LEVEL ' + (state.cleared+1);
  496. document.getElementById('lobbyCleared').innerHTML = state.cleared + '<i>/20</i>';
  497. const stars = Object.keys(state.stars).reduce((a,k)=>a+(state.stars[k]||0),0);
  498. document.getElementById('lobbyStars').innerHTML = stars + '<i>/60</i>';
  499. document.getElementById('lobbyWave').innerHTML = (state.best.wave||0) + '<i>W</i>';
  500. const ars = document.getElementById('arsenalRow');
  501. ars.innerHTML = '';
  502. TOWER_ORDER.forEach(k=>{
  503. const d = TOWERS[k], lv = armoryLv(k);
  504. const el = document.createElement('div');
  505. el.className = 'ars' + (lv>=ARMORY_MAX?' is-max':'');
  506. let pips = '';
  507. for(let i=0;i<ARMORY_MAX;i++) pips += `<i class="${i<lv?'on':''}"></i>`;
  508. el.innerHTML = `<div class="ars__lv">Lv.${lv}</div>
  509. <svg><use href="#${d.icon}"/></svg><b>${d.name}</b>
  510. <div class="ars__pips">${pips}</div>`;
  511. el.onclick = ()=> openArmory(k);
  512. ars.appendChild(el);
  513. });
  514. renderLobbyBoard();
  515. drawModeArt();
  516. }
  517. function renderLobbyBoard(){
  518. const wrap = document.getElementById('lobbyBoard');
  519. const list = [...state.board].sort((a,b)=>b.score-a.score);
  520. const top = list.slice(0,5);
  521. const mine = list.find(r=>r.me);
  522. const rows = top.map((r,i)=>boardRow(r, i+1));
  523. if(mine && !top.includes(mine)) rows[4] = boardRow(mine, list.indexOf(mine)+1);
  524. wrap.innerHTML = rows.join('');
  525. }
  526. function boardRow(r, rank){
  527. const cls = ['r1','r2','r3'][rank-1] || '';
  528. return `<div class="brow ${r.me?'me':''}">
  529. <div class="rk ${cls}">${rank}</div>
  530. <div class="nm">${r.name}${r.me?'<em>YOU</em>':''}</div>
  531. <div class="sc">${fmt(r.score)}</div>
  532. <div class="wv">W${r.wave}</div>
  533. </div>`;
  534. }
  535. /* ---------------- profile ---------------- */
  536. let profView = 'main';
  537. function openProfile(){ profView='main'; renderProfile(); openSheet('sheetProfile'); }
  538. function profShow(v){
  539. profView = v;
  540. document.getElementById('profMain').hidden = v!=='main';
  541. document.getElementById('profAvatar').hidden = v!=='avatar';
  542. document.getElementById('profRename').hidden = v!=='rename';
  543. if(v==='rename'){
  544. const inp = document.getElementById('nameInput');
  545. inp.value = state.player.name;
  546. document.getElementById('nameMsg').className = 'msg';
  547. document.getElementById('nameMsg').textContent = '3–20 characters · letters, numbers, - and _ · must start with a letter';
  548. setTimeout(()=>{ inp.focus(); inp.select(); }, 60);
  549. }
  550. }
  551. function renderProfile(){
  552. ensurePlayer();
  553. const av = avatarOf(state.player.avatar);
  554. document.getElementById('profAva').innerHTML = `<svg style="color:${av.col}" fill="currentColor"><use href="#${av.icon}"/></svg>`;
  555. document.getElementById('profName').textContent = state.player.name;
  556. document.getElementById('profId').textContent = state.player.id;
  557. document.getElementById('profCoins').textContent = fmt(state.coins);
  558. document.getElementById('profBest').textContent = fmt(state.best.score||0);
  559. document.getElementById('profKills').textContent = fmt(state.stats.kills||0);
  560. document.getElementById('profCleared').textContent = state.cleared + ' / 20';
  561. const stars = Object.keys(state.stars).reduce((a,k)=>a+(state.stars[k]||0),0);
  562. document.getElementById('profStars').textContent = stars + ' / 60 stars';
  563. document.getElementById('profXp').style.width = (state.cleared/20*100) + '%';
  564. document.getElementById('profEndless').textContent =
  565. 'best wave ' + (state.best.wave||0) + ' · ' + fmt(state.best.score||0) + ' pts';
  566. document.getElementById('profEndlessXp').style.width =
  567. clamp((state.best.wave||0)/30*100, 0, 100) + '%';
  568. const ars = document.getElementById('profArsenal');
  569. ars.innerHTML = TOWER_ORDER.map(k=>
  570. `<div class="cg-item" data-arm="${k}"><svg><use href="#${TOWERS[k].icon}"/></svg>
  571. <span>${TOWERS[k].name}</span><b>Lv.${armoryLv(k)}</b></div>`
  572. ).join('');
  573. ars.querySelectorAll('[data-arm]').forEach(el=>{
  574. el.onclick = ()=>{ closeSheet('sheetProfile'); openArmory(el.dataset.arm); };
  575. });
  576. document.getElementById('profArmoryLink').onclick = ()=>{ closeSheet('sheetProfile'); openArmory(); };
  577. const bag = document.getElementById('profBag');
  578. bag.innerHTML = ITEM_ORDER.map(k=>
  579. `<div class="cg-item ${state.items[k]?'':'is-empty'}"><svg><use href="#${ITEMS[k].icon}"/></svg>
  580. <span>${ITEMS[k].name.split(' ')[0]}</span><b>×${state.items[k]||0}</b></div>`
  581. ).join('');
  582. document.getElementById('profShopLink').onclick = ()=>{ closeSheet('sheetProfile'); renderShop(); openSheet('sheetShop'); };
  583. renderAvatarGrid();
  584. profShow(profView);
  585. }
  586. function renderAvatarGrid(){
  587. const g = document.getElementById('avGrid');
  588. g.innerHTML = '';
  589. AVATARS.forEach(a=>{
  590. const el = document.createElement('div');
  591. el.className = 'av-cell' + (state.player.avatar===a.key?' is-sel':'');
  592. el.setAttribute('aria-label',a.name||a.key); el.dataset.avatar=a.key;
  593. el.innerHTML = `<svg style="color:${a.col}" fill="currentColor"><use href="#${a.icon}"/></svg>`;
  594. el.onclick = ()=>{
  595. state.player.avatar = a.key;
  596. save(); AU.hit();
  597. renderAvatarGrid(); renderProfile(); renderLobby();
  598. toast('Avatar updated');
  599. };
  600. g.appendChild(el);
  601. });
  602. }
  603. function validName(n){
  604. if(!/^[A-Za-z][A-Za-z0-9_-]{2,19}$/.test(n))
  605. return '3–20 chars · start with a letter · letters, numbers, - and _ only';
  606. if(['admin','system','buffalo','king','you','player'].includes(n.toLowerCase()))
  607. return 'That name is reserved';
  608. return null;
  609. }
  610. function saveName(){
  611. const inp = document.getElementById('nameInput');
  612. const msg = document.getElementById('nameMsg');
  613. const v = inp.value.trim();
  614. const err = validName(v);
  615. if(err){ msg.className='msg bad'; msg.textContent = err; AU.err(); return; }
  616. state.player.name = v;
  617. save(); AU.upgrade();
  618. msg.className='msg ok'; msg.textContent = 'Saved';
  619. renderProfile(); renderLobby();
  620. toast('Name updated to ' + v);
  621. setTimeout(()=>{ if(profView==='rename') profShow('main'); }, 550);
  622. }
  623. async function copyPlayerId(){
  624. const id = state.player.id;
  625. try{
  626. await navigator.clipboard.writeText(id);
  627. toast('ID copied · ' + id);
  628. }catch(e){
  629. toast('Your ID · ' + id);
  630. }
  631. AU.coin();
  632. }
  633. /* ---------------- armory ---------------- */
  634. function openArmory(type){
  635. renderArmory(type);
  636. openSheet('sheetArmory');
  637. }
  638. function renderArmory(focus){
  639. document.getElementById('armoryCoins').textContent = fmt(state.coins);
  640. const body = document.getElementById('armoryBody');
  641. body.innerHTML = '';
  642. TOWER_ORDER.forEach(k=>{
  643. const d = TOWERS[k], lv = armoryLv(k), maxed = lv>=ARMORY_MAX;
  644. const cost = armoryCost(k);
  645. let pips = '';
  646. for(let i=0;i<ARMORY_MAX;i++) pips += `<i class="${i<lv?'on':''}"></i>`;
  647. const dmgPct = Math.round(ARMORY_DMG*(lv-1)*100);
  648. const rngPct = Math.round(ARMORY_RNG*(lv-1)*100);
  649. const ds = maxed
  650. ? 'Fully upgraded · <b>+'+dmgPct+'% DMG</b> · +'+rngPct+'% RNG'
  651. : (lv===1
  652. ? 'Base stats · next <b>+'+(ARMORY_DMG*100).toFixed(0)+'% DMG</b> · +2% RNG'
  653. : 'DMG <b>+'+dmgPct+'%</b> · RNG <b>+'+rngPct+'%</b> · next <b>+'+(dmgPct+ARMORY_DMG*100).toFixed(0)+'%</b>');
  654. const row = document.createElement('div');
  655. row.className = 'arm-row' + (maxed?' is-max':'') + (focus===k?' is-focus':'');
  656. row.innerHTML = `
  657. <div class="arm-row__ic"><svg><use href="#${d.icon}"/></svg></div>
  658. <div style="min-width:0">
  659. <div class="arm-row__nm">${d.name} <span class="arm-row__lv">LV.${lv}/${ARMORY_MAX}</span></div>
  660. <div class="arm-row__meta"><div class="arm-pips">${pips}</div></div>
  661. <div class="arm-row__ds">${ds}</div>
  662. </div>
  663. <div class="arm-row__buy">
  664. ${maxed ? '<div class="price" style="color:#8B739E">MAX</div>'
  665. : `<div class="price"><svg style="width:13px;height:13px"><use href="#i-coin"/></svg>${fmt(cost)}</div>`}
  666. <button class="btn btn--sm" data-arm="${k}" ${maxed||state.coins<cost?'disabled':''}>
  667. ${maxed?'MAXED':'UPGRADE'}</button>
  668. </div>`;
  669. body.appendChild(row);
  670. });
  671. body.querySelectorAll('[data-arm]').forEach(btn=>{
  672. btn.onclick = ()=> upgradeArmory(btn.dataset.arm);
  673. });
  674. }
  675. function renderLevels(){
  676. document.getElementById('levelCoins').textContent = fmt(state.coins);
  677. document.getElementById('levelSub').textContent = `${state.cleared} / 20 cleared`;
  678. const grid = document.getElementById('lvGrid');
  679. grid.innerHTML = '';
  680. for(let n=1;n<=20;n++){
  681. const st = state.stars[n]||0;
  682. const locked = n > state.cleared+1;
  683. const done = n <= state.cleared;
  684. const el = document.createElement('div');
  685. el.className = 'lv' + (done?' lv--done':'') + (n===state.cleared+1?' lv--next':'') + (locked?' lv--lock':'');
  686. el.innerHTML = `<b>${n}</b><span>${done?'CLEARED':'WAVES '+levelWaves(n)}</span>
  687. <div class="lv__stars"><i class="${st>0?'on':''}"></i><i class="${st>1?'on':''}"></i><i class="${st>2?'on':''}"></i></div>
  688. <div class="lv__rec">REC Lv.${recArmory(n)}</div>
  689. ${(n%5===0||n===20)?'<div class="lv__boss">BOSS</div>':''}`;
  690. if(!locked) el.onclick = ()=>{ closeAllSheets(); startBattle('campaign', n); };
  691. else el.onclick = ()=> toast('Clear level ' + (state.cleared+1) + ' first');
  692. grid.appendChild(el);
  693. }
  694. }
  695. /* ---------------- shop ---------------- */
  696. function renderShop(){
  697. document.getElementById('shopCoins').textContent = fmt(state.coins);
  698. const body = document.getElementById('shopBody');
  699. body.innerHTML = '';
  700. ITEM_ORDER.forEach(k=>{
  701. const it = ITEMS[k], own = state.items[k]||0;
  702. const row = document.createElement('div');
  703. row.className = 'shop-row';
  704. row.innerHTML = `
  705. <div class="shop-row__ic"><svg><use href="#${it.icon}"/></svg></div>
  706. <div style="min-width:0">
  707. <div class="shop-row__nm">${it.name}</div>
  708. <div class="shop-row__ds">${it.desc}</div>
  709. <div class="shop-row__own">OWNED ×${own}</div>
  710. </div>
  711. <div class="shop-row__buy">
  712. <div class="price"><svg style="width:13px;height:13px"><use href="#i-coin"/></svg>${fmt(it.price)}</div>
  713. <button class="btn btn--sm" data-buy="${k}" ${state.coins<it.price?'disabled':''}>BUY</button>
  714. </div>`;
  715. body.appendChild(row);
  716. });
  717. body.querySelectorAll('[data-buy]').forEach(b=>{
  718. b.onclick = ()=>{
  719. const k=b.dataset.buy, it=ITEMS[k];
  720. if(state.coins < it.price){ AU.err(); toast('Not enough coins'); return; }
  721. state.coins -= it.price;
  722. state.items[k] = (state.items[k]||0)+1;
  723. save(); AU.coin(); renderShop(); renderLobby();
  724. toast(`${it.name} ×1 purchased`);
  725. if(currentView==='levels') document.getElementById('levelCoins').textContent = fmt(state.coins);
  726. };
  727. });
  728. }
  729. /* ---------------- leaderboard ---------------- */
  730. function renderBoard(){
  731. const body = document.getElementById('boardBody');
  732. const list = [...state.board].sort((a,b)=>b.score-a.score).slice(0,10);
  733. const meIn = list.some(r=>r.me);
  734. let html = '';
  735. list.forEach((r,i)=>{
  736. html += `<div class="lb-row ${r.me?'me':''}">
  737. <div class="rk ${i<3?'top':''}">${i+1}</div>
  738. <div class="nm">${r.name}${r.me?' <em>YOU</em>':''}${r.me?'':'<em>RANGER</em>'}</div>
  739. <div class="sc">${fmt(r.score)}</div><div class="wv">W${r.wave}</div></div>`;
  740. });
  741. if(!meIn && state.best.score>0){
  742. const mine = state.board.find(r=>r.me);
  743. if(mine){
  744. html += `<div style="padding:10px 4px 7px;font:800 7px/1 var(--font-d);letter-spacing:.16em;color:#8B739E;text-transform:uppercase">— YOUR BEST —</div>
  745. <div class="lb-row me"><div class="rk">—</div>
  746. <div class="nm">${mine.name} <em>YOU</em></div>
  747. <div class="sc">${fmt(mine.score)}</div><div class="wv">W${mine.wave}</div></div>`;
  748. }
  749. }
  750. body.innerHTML = html;
  751. }
  752. function submitScore(score, wave){
  753. state.board = state.board.filter(r=>!r.me);
  754. state.board.push({ name:'Desert Ranger', score, wave, me:true });
  755. state.board.sort((a,b)=>b.score-a.score);
  756. state.board = state.board.slice(0,12);
  757. save();
  758. }
  759. /* ---------------- help / settings ---------------- */
  760. const FAQ = [
  761. ['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.'],
  762. ['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.'],
  763. ['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.'],
  764. ['Which towers hit air?','Only the Rifle can shoot flying Vultures. Ground-only towers will never target them.'],
  765. ['How does armor work?','Armor subtracts flat damage from every hit. Crossbow bolts ignore armor completely.'],
  766. ['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.'],
  767. ['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.'],
  768. ['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.'],
  769. ['Does the game save?','Progress, coins, items and the leaderboard live in this browser only. There is no account and no cross-device sync.'],
  770. ['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.']
  771. ];
  772. function renderHelp(){
  773. const body = document.getElementById('helpBody');
  774. body.innerHTML = FAQ.map((q,i)=>`<details class="qa" ${i<2?'open':''}>
  775. <summary>${q[0]}</summary><p>${q[1]}</p></details>`).join('');
  776. }
  777. function renderSettings(){
  778. document.getElementById('tglSfx').classList.toggle('on', !!state.sfx);
  779. document.getElementById('tglMusic').classList.toggle('on', !!state.music);
  780. }
  781. const DOCS = {
  782. terms: {
  783. title: 'TERMS OF SERVICE',
  784. html: `<div class="doc">
  785. <p>Buffalo Siege is a single-player tower defense game. By playing you agree to the points below.</p>
  786. <h4>1. License</h4>
  787. <p>You may play this build for personal entertainment. Do not redistribute it as your own product or resell it.</p>
  788. <h4>2. No purchases</h4>
  789. <p>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.</p>
  790. <h4>3. Local save</h4>
  791. <p>Progress is stored in this browser only. Clearing browser data or resetting the save erases progress permanently — this cannot be undone.</p>
  792. <h4>4. Changes</h4>
  793. <p>Balance values, level layouts and item prices may change between versions without notice.</p>
  794. </div>`
  795. },
  796. privacy: {
  797. title: 'PRIVACY POLICY',
  798. html: `<div class="doc">
  799. <p>Buffalo Siege does not collect, transmit or sell any personal data.</p>
  800. <h4>What is stored</h4>
  801. <p>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.</p>
  802. <h4>What is NOT collected</h4>
  803. <p>No account, no email, no phone number, no location, no contacts, no device identifiers, no analytics and no third-party SDKs.</p>
  804. <h4>Network</h4>
  805. <p>The game runs fully offline. Nothing is uploaded anywhere; the leaderboard is a local list with simulated entries.</p>
  806. <h4>Deleting your data</h4>
  807. <p>Settings → Reset local save removes everything stored by the game.</p>
  808. </div>`
  809. }
  810. };
  811. function openDoc(key){
  812. const d = DOCS[key]; if(!d) return;
  813. document.getElementById('docTitle').textContent = d.title;
  814. document.getElementById('docBody').innerHTML = d.html;
  815. openSheet('sheetDoc');
  816. }
  817. let resetArmed = false, resetTimer = null;
  818. /* ---------------- boot ---------------- */
  819. function boot(){
  820. fit();
  821. load();
  822. ensurePlayer();
  823. paintStartLandscape();
  824. const fill = document.getElementById('bootFill'), pct = document.getElementById('bootPct');
  825. let p = 0;
  826. const tick = setInterval(()=>{
  827. p += 9 + Math.random()*13;
  828. if(p>=100){ p=100; clearInterval(tick); setTimeout(()=>{ showView('start'); }, 420); }
  829. fill.style.width = p+'%'; pct.textContent = 'LOADING… ' + Math.round(p) + '%';
  830. }, 130);
  831. }
  832. /* ---------------- global wiring ---------------- */
  833. document.getElementById('btnStart').onclick = ()=>{ AU.init(); AU.coin(); BGM.sync(); showView('lobby'); };
  834. document.querySelectorAll('[data-open]').forEach(el=>{
  835. el.onclick = ()=>{
  836. const k = el.dataset.open;
  837. if(k==='shop'){ renderShop(); openSheet('sheetShop'); }
  838. if(k==='leaderboard'){ renderBoard(); openSheet('sheetBoard'); }
  839. if(k==='help'){ renderHelp(); openSheet('sheetHelp'); }
  840. if(k==='settings'){ renderSettings(); openSheet('sheetSettings'); }
  841. };
  842. });
  843. document.querySelectorAll('[data-close]').forEach(el=>{
  844. el.onclick = ()=>{
  845. closeSheet(el.dataset.close);
  846. };
  847. });
  848. document.querySelectorAll('[data-back]').forEach(el=>{
  849. el.onclick = ()=> showView(el.dataset.back);
  850. });
  851. document.querySelectorAll('.mode').forEach(el=>{
  852. el.onclick = ()=>{
  853. const m = el.dataset.mode;
  854. if(m==='campaign') showView('levels');
  855. else startBattle('endless', 0);
  856. };
  857. });
  858. document.getElementById('lobbyCoins').onclick = ()=>{ renderShop(); openSheet('sheetShop'); };
  859. document.getElementById('armoryMore').onclick = ()=> openArmory();
  860. document.getElementById('lobbyPlayer').onclick = ()=> openProfile();
  861. document.getElementById('btnCheckin').onclick = ()=>{ renderCheckin(); openSheet('sheetCheckin'); AU.hit(); };
  862. document.getElementById('ckClaim').onclick = ()=> claimCheckin();
  863. document.getElementById('btnAvatar').onclick = ()=>{ AU.hit(); profShow('avatar'); };
  864. document.getElementById('btnRename').onclick = ()=>{ AU.hit(); profShow('rename'); };
  865. document.getElementById('btnCopyId').onclick = ()=> copyPlayerId();
  866. document.getElementById('btnNameCancel').onclick = ()=> profShow('main');
  867. document.getElementById('btnAvatarBack').onclick = ()=> profShow('main');
  868. document.getElementById('btnNameSave').onclick = ()=> saveName();
  869. document.getElementById('nameInput').addEventListener('keydown', e=>{
  870. if(e.key==='Enter') saveName();
  871. });
  872. document.getElementById('pstatCoins').classList.add('is-link');
  873. document.getElementById('pstatCoins').onclick = ()=>{ closeSheet('sheetProfile'); renderShop(); openSheet('sheetShop'); };
  874. document.getElementById('boardMore').onclick = ()=>{ renderBoard(); openSheet('sheetBoard'); };
  875. document.getElementById('tglSfx').onclick = ()=>{ state.sfx=!state.sfx; save(); renderSettings(); AU.coin(); };
  876. document.getElementById('tglMusic').onclick = ()=>{
  877. state.music = !state.music; save(); BGM.sync(); renderSettings(); AU.coin();
  878. toast(state.music ? 'Music on' : 'Music off');
  879. };
  880. document.getElementById('setShop').onclick = ()=>{ closeSheet('sheetSettings'); renderShop(); openSheet('sheetShop'); };
  881. document.getElementById('setHelp').onclick = ()=>{ closeSheet('sheetSettings'); renderHelp(); openSheet('sheetHelp'); };
  882. document.querySelectorAll('[data-doc]').forEach(el=>{
  883. el.onclick = ()=> openDoc(el.dataset.doc);
  884. });
  885. document.getElementById('setReset').onclick = ()=>{
  886. if(!resetArmed){
  887. resetArmed = true;
  888. const el = document.getElementById('setResetState');
  889. el.textContent = 'TAP AGAIN TO ERASE EVERYTHING'; el.style.color = '#FF4D6A';
  890. resetTimer = setTimeout(()=>{ resetArmed=false; el.textContent='Erase progress, coins and scores'; el.style.color=''; }, 3000);
  891. return;
  892. }
  893. clearTimeout(resetTimer); resetArmed=false;
  894. state = defaults(); save();
  895. document.getElementById('setResetState').textContent='Erase progress, coins and scores';
  896. document.getElementById('setResetState').style.color='';
  897. renderSettings(); renderLobby(); renderArmory(); toast('Local save erased');
  898. };
  899. // Boot follows local artwork preload in style-a.js.
  900. /* ============================================================
  901. BUFFALO SIEGE — battle engine + renderer
  902. ============================================================ */
  903. /* ---------------- field geometry ---------------- */
  904. const FW = 430, FH = 600;
  905. const PATH_W = 44;
  906. const SLOT_R = 24;
  907. /* 每关不同地图:路径折返方式 + 建造格行/列布局不同 */
  908. const MAP_DEFS = [
  909. {
  910. key:'serpentine', name:'Serpentine',
  911. path:[[-30,80],[300,80],[300,210],[110,210],[110,340],[300,340],[300,470],[110,470],[110,545],[336,545]],
  912. base:{x:368,y:545},
  913. rows:[26,145,275,405], cols:[34,90,146,202,258,314,370], minD:53
  914. },
  915. {
  916. key:'longhorn', name:'Long Horn',
  917. path:[[-30,85],[330,85],[330,225],[60,225],[60,365],[330,365],[330,505],[368,505]],
  918. base:{x:384,y:505},
  919. rows:[25,155,295,435], cols:[34,90,146,202,258,314,370], minD:53
  920. },
  921. {
  922. key:'switchback', name:'Switchback',
  923. path:[[-30,70],[350,70],[350,190],[150,190],[150,310],[350,310],[350,430],[150,430],[150,540],[376,540]],
  924. base:{x:390,y:540},
  925. rows:[24,130,250,370,470], cols:[40,100,160,220,280,340,392], minD:53
  926. },
  927. {
  928. key:'chokepoint', name:'Chokepoint',
  929. path:[[-30,90],[330,90],[330,230],[50,230],[50,370],[330,370],[330,500],[368,500]],
  930. base:{x:384,y:500},
  931. rows:[28,160,300,440], cols:[30,90,150,210,270,330,390], minD:53
  932. }
  933. ];
  934. function mapForLevel(level){ return MAP_DEFS[((level||1)-1) % MAP_DEFS.length]; }
  935. let SEGS = [], PATH_LEN = 0, SLOTS = [], BASE = { x:368, y:545 }, CUR_MAP = MAP_DEFS[0];
  936. function segDist(px,py,x1,y1,x2,y2){
  937. const dx=x2-x1, dy=y2-y1, l=dx*dx+dy*dy;
  938. let t = l ? ((px-x1)*dx + (py-y1)*dy)/l : 0;
  939. t = Math.max(0, Math.min(1, t));
  940. return Math.hypot(px-(x1+t*dx), py-(y1+t*dy));
  941. }
  942. function distToPath(px,py){
  943. let m = 1e9;
  944. for(const sg of SEGS) m = Math.min(m, segDist(px,py,sg.x1,sg.y1,sg.x2,sg.y2));
  945. return m;
  946. }
  947. function posAt(d){
  948. d = clamp(d,0,PATH_LEN);
  949. let s = SEGS[SEGS.length-1];
  950. for(const sg of SEGS){ if(d <= sg.acc+sg.len){ s=sg; break; } }
  951. const t = (d - s.acc)/s.len;
  952. return { x: lerp(s.x1,s.x2,t), y: lerp(s.y1,s.y2,t), ang: s.ang };
  953. }
  954. function applyMap(level){
  955. const def = mapForLevel(level);
  956. CUR_MAP = def;
  957. BASE = { x:def.base.x, y:def.base.y };
  958. SEGS = []; PATH_LEN = 0;
  959. for(let i=0;i<def.path.length-1;i++){
  960. const [x1,y1]=def.path[i], [x2,y2]=def.path[i+1];
  961. const len = Math.hypot(x2-x1, y2-y1);
  962. SEGS.push({x1,y1,x2,y2,len,acc:PATH_LEN,ang:Math.atan2(y2-y1,x2-x1)});
  963. PATH_LEN += len;
  964. }
  965. SLOTS = [];
  966. def.rows.forEach(y=>def.cols.forEach(x=>{
  967. if(x<24||x>406||y<18||y>580) return;
  968. if(distToPath(x,y) < def.minD) return;
  969. if(Math.hypot(x-BASE.x, y-BASE.y) < 80) return;
  970. SLOTS.push({ id:SLOTS.length, x, y, tower:null });
  971. }));
  972. buildGround();
  973. }
  974. /* ---------------- battle state ---------------- */
  975. const G = {
  976. running:false, paused:false, mode:'campaign', level:1,
  977. wave:0, totalWaves:0, phase:'prep', // prep | running | done
  978. prepLeft:0, gold:0, baseHP:20, maxHP:20, kills:0, score:0,
  979. speed:1, time:0, waveTime:0, queue:[], enemies:[], towers:[], projs:[], fx:[],
  980. selType:null, selTower:null, armed:null, shake:0, coinsEarned:0, hpMul:1,
  981. bossWave:false, flash:0
  982. };
  983. const field = document.getElementById('field');
  984. const ctx = field.getContext('2d');
  985. const DPR = Math.min(2, window.devicePixelRatio||2);
  986. field.width = FW*DPR; field.height = FH*DPR;
  987. ctx.setTransform(DPR,0,0,DPR,0,0);
  988. /* background cache */
  989. const bgCanvas = document.createElement('canvas');
  990. bgCanvas.width = FW*DPR; bgCanvas.height = FH*DPR;
  991. const bgc = bgCanvas.getContext('2d');
  992. bgc.setTransform(DPR,0,0,DPR,0,0);
  993. function buildGround(){
  994. const c = bgc, rnd = seedRnd(20261026);
  995. // sand base
  996. const g = c.createLinearGradient(0,0,0,FH);
  997. g.addColorStop(0,'#C8843F'); g.addColorStop(.42,'#D6994F'); g.addColorStop(1,'#A9662E');
  998. c.fillStyle=g; c.fillRect(0,0,FW,FH);
  999. // warm horizon haze
  1000. const sky=c.createLinearGradient(0,0,0,150);
  1001. sky.addColorStop(0,'rgba(255,176,96,.35)'); sky.addColorStop(1,'rgba(255,176,96,0)');
  1002. c.fillStyle=sky; c.fillRect(0,0,FW,150);
  1003. // dune blobs
  1004. for(let i=0;i<30;i++){
  1005. const x=rnd()*FW, y=rnd()*FH, rx=40+rnd()*90, ry=16+rnd()*34;
  1006. c.fillStyle = `rgba(${196+((rnd()*34)|0)},${140+((rnd()*44)|0)},${78+((rnd()*34)|0)},.34)`;
  1007. c.beginPath(); c.ellipse(x,y,rx,ry,rnd()*3,0,TAU); c.fill();
  1008. }
  1009. // dry grass / pebbles
  1010. for(let i=0;i<170;i++){
  1011. const x=rnd()*FW, y=rnd()*FH;
  1012. if(rnd()<.6){
  1013. c.strokeStyle='rgba(108,74,36,.42)'; c.lineWidth=1.1;
  1014. 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();
  1015. }else{
  1016. c.fillStyle='rgba(104,72,44,.32)'; c.beginPath(); c.arc(x,y,1.2+rnd()*1.8,0,TAU); c.fill();
  1017. }
  1018. }
  1019. // rocks
  1020. for(let i=0;i<10;i++){
  1021. const x=rnd()*FW, y=70+rnd()*(FH-110), r=5+rnd()*7;
  1022. c.fillStyle='#7A5A44'; c.beginPath(); c.ellipse(x,y,r,r*0.72,0,0,TAU); c.fill();
  1023. 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();
  1024. }
  1025. // bones + skull props
  1026. for(let i=0;i<5;i++){
  1027. const x=20+rnd()*(FW-40), y=90+rnd()*(FH-160);
  1028. c.strokeStyle='rgba(240,226,196,.6)'; c.lineWidth=2; c.lineCap='round';
  1029. c.beginPath(); c.moveTo(x-6,y+3); c.lineTo(x+6,y-3); c.stroke();
  1030. c.beginPath(); c.arc(x-7,y+3,1.6,0,TAU); c.arc(x+7,y-3,1.6,0,TAU); c.fill();
  1031. }
  1032. // path
  1033. const stroke = (w,col)=>{
  1034. c.strokeStyle=col; c.lineWidth=w; c.lineJoin='round'; c.lineCap='round';
  1035. c.beginPath(); c.moveTo(SEGS[0].x1, SEGS[0].y1);
  1036. for(const sg of SEGS) c.lineTo(sg.x2, sg.y2);
  1037. c.stroke();
  1038. };
  1039. stroke(PATH_W+11,'rgba(86,48,20,.55)');
  1040. stroke(PATH_W+4,'#8A5522');
  1041. stroke(PATH_W,'#D9A566');
  1042. stroke(PATH_W-15,'#EEC58B');
  1043. // path pebbles
  1044. for(let i=0;i<140;i++){
  1045. const d=rnd()*PATH_LEN, p=posAt(d), off=(rnd()-.5)*(PATH_W-12);
  1046. const x=p.x+Math.cos(p.ang+Math.PI/2)*off, y=p.y+Math.sin(p.ang+Math.PI/2)*off;
  1047. c.fillStyle=`rgba(${150+rnd()*40|0},${108+rnd()*30|0},${66+rnd()*22|0},.42)`;
  1048. c.beginPath(); c.arc(x,y,.9+rnd()*1.5,0,TAU); c.fill();
  1049. }
  1050. // vignette
  1051. const vg=c.createRadialGradient(FW/2,FH/2,150,FW/2,FH/2,430);
  1052. vg.addColorStop(0,'rgba(0,0,0,0)'); vg.addColorStop(1,'rgba(46,10,38,.52)');
  1053. c.fillStyle=vg; c.fillRect(0,0,FW,FH);
  1054. }
  1055. applyMap(1);
  1056. /* ---------------- wave generation ---------------- */
  1057. function campaignWaves(level){
  1058. const total = levelWaves(level);
  1059. /* 路径长度补偿:短路径 = 敌人通过快 = 输出窗口短,按 1520px 基准等比降血 */
  1060. const lenScale = clamp(PATH_LEN / 1520, 0.86, 1.12);
  1061. const hpMul = levelHpMul(level) * lenScale;
  1062. const rng = seedRnd(4200+level*137);
  1063. const out = [];
  1064. for(let w=1; w<=total; w++){
  1065. const pool = ['rabbit','bison'];
  1066. if(level>=3) pool.push('wolf');
  1067. if(level>=5) pool.push('vulture');
  1068. if(level>=8) pool.push('scorpion');
  1069. if(level>=13) pool.push('wolf','scorpion');
  1070. const kinds = 1 + Math.min(3, Math.floor((w-1)/3));
  1071. const baseCount = 2 + Math.round(w*1.15) + Math.floor(level*0.5);
  1072. const groups = [];
  1073. for(let i=0;i<kinds;i++){
  1074. groups.push({
  1075. type: pool[Math.floor(rng()*pool.length)],
  1076. /* 第 1 波减量 25%:让玩家能靠首波滚起金币雪球 */
  1077. count: Math.max(2, Math.round(baseCount/kinds * (w===1 ? 0.75 : 1))),
  1078. gap: Math.max(.34, .66 - w*0.02),
  1079. delay: i*1.5
  1080. });
  1081. }
  1082. if((level%5===0 || level===20) && w===total){
  1083. groups.push({ type:'king', count: level>=15?2:1, gap:3.2, delay:.6 });
  1084. }
  1085. out.push({ groups, hpMul: hpMul*(1+(w-1)*0.05) });
  1086. }
  1087. return out;
  1088. }
  1089. function endlessWave(w){
  1090. const pool = ['rabbit','bison'];
  1091. if(w>=3) pool.push('wolf');
  1092. if(w>=5) pool.push('vulture');
  1093. if(w>=7) pool.push('scorpion');
  1094. const kinds = 1 + Math.min(3, Math.floor(w/4));
  1095. const baseCount = 4 + Math.round(w*1.45);
  1096. const groups = [];
  1097. const rng = seedRnd(900+w*53);
  1098. for(let i=0;i<kinds;i++){
  1099. groups.push({
  1100. type: pool[Math.floor(rng()*pool.length)],
  1101. count: Math.max(2, Math.round(baseCount/kinds)),
  1102. gap: Math.max(.3, .62 - w*0.012),
  1103. delay: i*1.3
  1104. });
  1105. }
  1106. if(w%5===0) groups.push({ type:'king', count: 1+Math.floor(w/15), gap:2.6, delay:.5 });
  1107. return { groups, hpMul: (1 + (w-1)*0.27) * Math.pow(1.15, Math.floor((w-1)/10)) };
  1108. }
  1109. /* ---------------- battle lifecycle ---------------- */
  1110. function startBattle(mode, level){
  1111. AU.init();
  1112. G.mode = mode; G.level = level;
  1113. G.running = true; G.paused = false;
  1114. G.wave = 0; G.kills = 0; G.score = 0; G.coinsEarned = 0;
  1115. G.maxHP = 20; G.baseHP = 20;
  1116. G.enemies = []; G.towers = []; G.projs = []; G.fx = []; G.queue = [];
  1117. G.selType = null; G.selTower = null; G.armed = null; G.shake = 0; G.flash = 0;
  1118. G.time = 0; G.speed = 1; G.towersBuilt = 0;
  1119. applyMap(mode==='campaign' ? level : 1);
  1120. G.gold = mode==='campaign' ? 760 : 780;
  1121. G.totalWaves = mode==='campaign' ? levelWaves(level) : Infinity;
  1122. G.waves = mode==='campaign' ? campaignWaves(level) : null;
  1123. document.getElementById('hudMode').textContent = mode==='campaign' ? 'STAGE '+level : 'ENDLESS';
  1124. document.getElementById('hudScoreLabel').textContent = mode==='campaign' ? 'SCORE' : 'SCORE';
  1125. document.querySelectorAll('#spdBox button').forEach(b=>b.classList.toggle('is-on', b.dataset.spd==='1'));
  1126. closeAllSheets(); closeTowerPanel();
  1127. showView('battle');
  1128. renderDock(); renderItemDock();
  1129. startNextWave(true);
  1130. updateHUD(true);
  1131. if(state.tutorial===0) showCoach('Tap a tower card, then tap a gold slot');
  1132. lastT = performance.now();
  1133. if(!loopRunning){ loopRunning = true; requestAnimationFrame(loop); }
  1134. }
  1135. function startNextWave(first){
  1136. G.wave++;
  1137. if(G.mode==='campaign' && G.wave > G.totalWaves){ endBattle(true); return; }
  1138. const cfg = G.mode==='campaign' ? G.waves[G.wave-1] : endlessWave(G.wave);
  1139. G.hpMul = cfg.hpMul;
  1140. G.bossWave = cfg.groups.some(g=>g.type==='king');
  1141. const q = [];
  1142. cfg.groups.forEach(gr=>{
  1143. for(let i=0;i<gr.count;i++) q.push({ t: gr.delay + i*gr.gap, type: gr.type });
  1144. });
  1145. q.sort((a,b)=>a.t-b.t);
  1146. G.queue = q; G.waveTime = 0; G.phase = 'running';
  1147. G.waveTotalCount = q.length;
  1148. if(!first) AU.wave();
  1149. if(G.bossWave && !first){ toast('BOSS WAVE · Buffalo King'); G.shake = 8; }
  1150. updateHUD(true);
  1151. }
  1152. /* ---------------- towers ---------------- */
  1153. function towerStats(t){
  1154. const def = TOWERS[t.type], s = def.lv[t.lv-1], ab = armoryBonus(t.type);
  1155. let dmg = s.dmg * ab.dmg, rate = s.rate, range = s.range * ab.range;
  1156. let splash = s.splash||0, pierce = !!def.pierce;
  1157. t.combos.forEach(c=>{
  1158. if(c==='Volley'){ range*=1.15; rate/=1.10; }
  1159. if(c==='Suppression'){ rate/=1.25; }
  1160. if(c==='Siege Line' && t.type==='mortar'){ splash*=1.25; dmg*=1.10; }
  1161. if(c==='Pierce Shell'){ if(t.type==='crossbow') dmg*=1.20; if(t.type==='mortar') pierce=true; }
  1162. });
  1163. return { dmg, rate, range, splash, pierce, air:def.air, proj:def.proj, pspeed:def.pspeed };
  1164. }
  1165. function recomputeCombos(){
  1166. G.towers.forEach(t=>t.combos=[]);
  1167. G.comboLinks = [];
  1168. for(let i=0;i<G.towers.length;i++){
  1169. for(let j=i+1;j<G.towers.length;j++){
  1170. const a=G.towers[i], b=G.towers[j];
  1171. if(Math.hypot(a.x-b.x,a.y-b.y) > 132) continue;
  1172. COMBOS.forEach(cb=>{
  1173. const m = (cb.a===a.type&&cb.b===b.type) || (cb.a===b.type&&cb.b===a.type);
  1174. if(m){ if(!a.combos.includes(cb.name)) a.combos.push(cb.name);
  1175. if(!b.combos.includes(cb.name)) b.combos.push(cb.name);
  1176. G.comboLinks.push({a,b}); }
  1177. });
  1178. }
  1179. }
  1180. }
  1181. function slotAt(x,y){
  1182. let best=null, bd=1e9;
  1183. SLOTS.forEach(s=>{ const d=Math.hypot(s.x-x,s.y-y); if(d<SLOT_R+8 && d<bd){ bd=d; best=s; } });
  1184. return best;
  1185. }
  1186. function buildTower(slot, type){
  1187. const def = TOWERS[type];
  1188. if(slot.tower){ toast('Slot occupied'); return; }
  1189. if(G.gold < def.cost){ AU.err(); toast('Need ' + (def.cost-G.gold) + ' more gold'); return; }
  1190. G.gold -= def.cost;
  1191. const t = { slot, type, lv:1, cd:0, invested:def.cost, x:slot.x, y:slot.y, angle:-Math.PI/2, combos:[], recoil:0, flash:0 };
  1192. slot.tower = t; G.towers.push(t);
  1193. G.towersBuilt = (G.towersBuilt||0) + 1;
  1194. recomputeCombos();
  1195. AU.build(); addFx('ring', t.x, t.y, {r0:8, r1:34, col:'255,210,102', life:.5});
  1196. floatText(t.x, t.y-22, TOWERS[type].name, '255,235,180');
  1197. if(state.tutorial===0){ state.tutorial=1; save(); showCoach('Tap a built tower to upgrade · combos buff neighbours'); }
  1198. updateHUD();
  1199. }
  1200. function upgradeTower(t){
  1201. if(t.lv>=3){ toast('Already 3 stars'); return; }
  1202. const cost = TOWERS[t.type].up[t.lv-1];
  1203. if(G.gold < cost){ AU.err(); toast('Need ' + (cost-G.gold) + ' more gold'); return; }
  1204. G.gold -= cost; t.invested += cost; t.lv++;
  1205. recomputeCombos(); AU.upgrade();
  1206. addFx('ring', t.x, t.y, {r0:10, r1:38, col:'255,227,138', life:.55});
  1207. floatText(t.x, t.y - 30, '★'.repeat(t.lv), '255,214,110');
  1208. addFx('stars', t.x, t.y, {life:.65, lv:t.lv});
  1209. openTowerPanel(t); updateHUD();
  1210. }
  1211. function sellTower(t){
  1212. const back = Math.round(t.invested*0.6);
  1213. G.gold += back; t.slot.tower = null;
  1214. G.towers = G.towers.filter(x=>x!==t);
  1215. recomputeCombos(); AU.coin();
  1216. addFx('text', t.x, t.y-10, {text:'+'+back, col:'255,210,102'});
  1217. closeTowerPanel(); updateHUD();
  1218. }
  1219. /* ---------------- tower panel ---------------- */
  1220. function openTowerPanel(t){
  1221. G.selTower = t;
  1222. document.getElementById('coach').classList.remove('is-on');
  1223. const el = document.getElementById('towerPanel');
  1224. el.classList.add('is-open');
  1225. const st = towerStats(t);
  1226. document.getElementById('tpName').textContent = TOWERS[t.type].name;
  1227. let stars = '';
  1228. for(let i=0;i<3;i++) stars += `<i class="${i<t.lv?'on':''}">★</i>`;
  1229. document.getElementById('tpLevel').innerHTML = stars;
  1230. document.getElementById('tpLevel').title = 'Star ' + t.lv + ' of 3';
  1231. document.getElementById('tpDmg').textContent = Math.round(st.dmg);
  1232. document.getElementById('tpRate').textContent = (1/st.rate).toFixed(1)+'/s';
  1233. document.getElementById('tpRange').textContent = Math.round(st.range);
  1234. document.getElementById('tpDps').textContent = Math.round(st.dmg/st.rate);
  1235. const ab = armoryBonus(t.type);
  1236. const armEl = document.getElementById('tpArm');
  1237. if(ab.lv > 1){
  1238. armEl.style.display = 'flex';
  1239. armEl.innerHTML = '★ ARMORY LV.'+ab.lv+' · <b>+'+Math.round((ab.dmg-1)*100)+'% DMG</b> · +'+Math.round((ab.range-1)*100)+'% RNG';
  1240. } else armEl.style.display = 'none';
  1241. const comboEl = document.getElementById('tpCombo');
  1242. if(t.combos.length){ comboEl.style.display='flex'; comboEl.innerHTML = '★ COMBO · ' + t.combos.join(' + '); }
  1243. else comboEl.style.display='none';
  1244. const upBtn = document.getElementById('tpUpgrade');
  1245. if(t.lv>=3){ upBtn.textContent='★★★ MAX'; upBtn.disabled=true; }
  1246. else { const c = TOWERS[t.type].up[t.lv-1]; upBtn.textContent='★ UPGRADE · '+c; upBtn.disabled = G.gold<c; }
  1247. document.getElementById('tpSell').textContent = 'SELL '+Math.round(t.invested*0.6);
  1248. }
  1249. function closeTowerPanel(){
  1250. G.selTower = null;
  1251. document.getElementById('towerPanel').classList.remove('is-open');
  1252. }
  1253. /* ---------------- dock ---------------- */
  1254. function renderDock(){
  1255. const dock = document.getElementById('dockTowers');
  1256. dock.innerHTML = '';
  1257. TOWER_ORDER.forEach(k=>{
  1258. const d = TOWERS[k];
  1259. const el = document.createElement('div');
  1260. el.className='tcard'; el.dataset.type=k;
  1261. el.innerHTML = `<div class="tcard__lvl">★1</div>
  1262. <div class="tcard__art"><svg><use href="#${d.icon}"/></svg></div>
  1263. <div class="tcard__nm">${d.name}</div>
  1264. <div class="tcard__cost"><svg style="width:9px;height:9px"><use href="#i-coin"/></svg>${d.cost}</div>`;
  1265. el.onclick = ()=>{
  1266. if(G.selType===k){ G.selType=null; }
  1267. else { G.selType=k; closeTowerPanel(); }
  1268. document.querySelectorAll('.tcard').forEach(c=>c.classList.toggle('is-sel', c.dataset.type===G.selType));
  1269. document.getElementById('dockHint').innerHTML = G.selType
  1270. ? `Tap a gold slot to build <b>${d.name}</b> · ${d.tag}`
  1271. : 'Pick a tower · tap an empty <b>gold slot</b> to build';
  1272. AU.hit();
  1273. };
  1274. dock.appendChild(el);
  1275. });
  1276. }
  1277. function renderItemDock(){
  1278. const dock = document.getElementById('dockItems');
  1279. dock.innerHTML='';
  1280. ITEM_ORDER.forEach(k=>{
  1281. const it = ITEMS[k], n = state.items[k]||0;
  1282. const el = document.createElement('div');
  1283. el.className='item'+(n<=0?' is-empty':'');
  1284. el.dataset.item=k;
  1285. el.innerHTML = `<div class="item__ic"><svg><use href="#${it.icon}"/></svg></div>
  1286. <b>${it.name.split(' ')[0]}</b>` + (n>0
  1287. ? `<div class="cnt">${n}</div>`
  1288. : `<i class="plus" title="Buy">+</i>`);
  1289. el.onclick = ()=> useItem(k);
  1290. dock.appendChild(el);
  1291. });
  1292. }
  1293. let buyKey = null;
  1294. function openBuy(k){
  1295. buyKey = k;
  1296. const it = ITEMS[k];
  1297. document.getElementById('buyIcon').setAttribute('href', '#'+it.icon);
  1298. document.getElementById('buyName').textContent = it.name;
  1299. document.getElementById('buyDesc').textContent = it.desc;
  1300. document.getElementById('buyOwn').textContent = 'OWNED ×' + (state.items[k]||0);
  1301. document.getElementById('buyPrice').textContent = fmt(it.price);
  1302. document.getElementById('buyCoins').textContent = fmt(state.coins);
  1303. const btn = document.getElementById('buyConfirm');
  1304. btn.disabled = state.coins < it.price;
  1305. btn.textContent = state.coins < it.price ? 'NEED MORE COINS' : 'BUY & USE';
  1306. G.paused = true;
  1307. openSheet('sheetBuy');
  1308. }
  1309. function confirmBuy(){
  1310. const it = ITEMS[buyKey];
  1311. if(!it) return;
  1312. if(state.coins < it.price){ AU.err(); toast('Need ' + (it.price-state.coins) + ' more coins'); return; }
  1313. state.coins -= it.price;
  1314. state.items[buyKey] = (state.items[buyKey]||0) + 1;
  1315. save(); AU.coin();
  1316. closeSheet('sheetBuy'); G.paused = false;
  1317. renderItemDock();
  1318. toast(it.name + ' purchased');
  1319. useItem(buyKey);
  1320. }
  1321. function useItem(k){
  1322. const n = state.items[k]||0;
  1323. if(n<=0){ openBuy(k); return; }
  1324. if(G.phase==='done'){ return; }
  1325. if(k==='air'){
  1326. G.armed = G.armed==='air' ? null : 'air';
  1327. document.querySelectorAll('.item').forEach(el=>el.classList.toggle('is-arm', el.dataset.item===G.armed));
  1328. if(G.armed) toast('Tap the field to call the airstrike');
  1329. return;
  1330. }
  1331. if(k==='frost'){
  1332. state.items[k]--; save();
  1333. G.enemies.forEach(e=>{ e.frozen = 4; });
  1334. addFx('frost', 0,0,{life:.8}); AU.freeze();
  1335. toast('Frost Nova · all enemies frozen');
  1336. }
  1337. if(k==='repair'){
  1338. if(G.baseHP>=G.maxHP){ AU.err(); toast('Base is already at full HP'); return; }
  1339. state.items[k]--; save();
  1340. G.baseHP = Math.min(G.maxHP, G.baseHP+3);
  1341. addFx('heal', BASE.x, BASE.y, {life:.9}); AU.upgrade();
  1342. toast('Base repaired +3 HP');
  1343. }
  1344. if(k==='gold'){
  1345. state.items[k]--; save();
  1346. G.gold += 300;
  1347. addFx('text', BASE.x, BASE.y-40, {text:'+300', col:'255,210,102'});
  1348. AU.coin(); toast('Gold Rush · +300 gold');
  1349. }
  1350. renderItemDock(); updateHUD();
  1351. }
  1352. /* ---------------- fx ---------------- */
  1353. function addFx(kind,x,y,opt){
  1354. opt=opt||{};
  1355. G.fx.push({kind,x,y,t:0,life:opt.life||.5,...opt});
  1356. }
  1357. function floatText(x,y,text,col){ addFx('text',x,y,{text,col:col||'255,235,180',life:.85}); }
  1358. /* ---------------- damage ---------------- */
  1359. function damageEnemy(e, dmg, pierce, splashCol){
  1360. const armor = pierce ? 0 : e.armor;
  1361. const real = Math.max(1, dmg - armor);
  1362. e.hp -= real; e.hitFlash = .12;
  1363. if(e.hp<=0) killEnemy(e);
  1364. else if(Math.random()<.35) addFx('spark', e.x, e.y, {life:.22, col:splashCol||'255,235,180'});
  1365. }
  1366. function killEnemy(e){
  1367. if(e.dead) return;
  1368. e.dead = true;
  1369. G.kills++;
  1370. G.gold += e.gold;
  1371. G.score += 20;
  1372. floatText(e.x, e.y-14, '+'+e.gold, '255,210,102');
  1373. addFx('poof', e.x, e.y, {life:.4, r:e.r});
  1374. AU.coin();
  1375. }
  1376. function leakEnemy(e){
  1377. e.dead = true;
  1378. G.baseHP -= e.leak;
  1379. G.shake = Math.min(10, 4+e.leak*2);
  1380. addFx('text', BASE.x, BASE.y-44, {text:'-'+e.leak, col:'255,110,130'});
  1381. AU.err();
  1382. if(G.baseHP<=0){ G.baseHP=0; endBattle(false); }
  1383. }
  1384. /* ---------------- update ---------------- */
  1385. function update(dt){
  1386. if(G.phase==='prep' && G.prepLeft>0){
  1387. G.prepLeft -= dt;
  1388. if(G.prepLeft<=0) startNextWave(false);
  1389. }
  1390. if(G.phase==='running'){
  1391. G.waveTime += dt;
  1392. while(G.queue.length && G.queue[0].t <= G.waveTime){
  1393. const q = G.queue.shift();
  1394. spawnEnemy(q.type);
  1395. }
  1396. }
  1397. // enemies
  1398. for(const e of G.enemies){
  1399. if(e.dead) continue;
  1400. if(e.hitFlash>0) e.hitFlash -= dt;
  1401. if(e.boost>0) e.boost -= dt;
  1402. // ---- boss skills ----
  1403. if(e.boss && e.frozen<=0){
  1404. e.roarCd -= dt;
  1405. if(e.roarCd <= 0){
  1406. e.roarCd = 7;
  1407. addFx('ring', e.x, e.y, { r0:12, r1:130, col:'255,46,154', life:.6 });
  1408. floatText(e.x, e.y-46, 'ROAR!', '255,120,200');
  1409. AU.tone(150, 70, 0.35, 'sawtooth', 0.13);
  1410. for(const o of G.enemies){
  1411. if(o===e || o.dead) continue;
  1412. if(Math.hypot(o.x-e.x, o.y-e.y) < 140) o.boost = 3;
  1413. }
  1414. }
  1415. if(!e.summoned && e.hp < e.maxHp*0.5){
  1416. e.summoned = true;
  1417. for(let i=0;i<3;i++) spawnEnemy('wolf', Math.max(0, e.d - 26 - i*20));
  1418. addFx('ring', e.x, e.y, { r0:8, r1:70, col:'255,120,200', life:.55 });
  1419. floatText(e.x, e.y-56, 'SUMMON', '255,120,200');
  1420. AU.tone(300, 120, 0.3, 'square', 0.1);
  1421. }
  1422. }
  1423. let spd = e.spd * (e.boost>0 ? 1.35 : 1);
  1424. if(e.frozen>0){ e.frozen -= dt; spd = 0; }
  1425. e.d += spd*dt;
  1426. const p = posAt(e.d);
  1427. e.px = e.x; e.py = e.y;
  1428. e.x = p.x; e.y = p.y; e.ang = p.ang;
  1429. if(e.d >= PATH_LEN){ leakEnemy(e); continue; }
  1430. e.bob = Math.sin((G.time*6) + e.seed)*1.6;
  1431. }
  1432. G.enemies = G.enemies.filter(e=>!e.dead);
  1433. // towers
  1434. for(const t of G.towers){
  1435. if(t.flash>0) t.flash -= dt;
  1436. if(t.recoil>0) t.recoil -= dt*4;
  1437. const st = towerStats(t);
  1438. t.cd -= dt;
  1439. if(t.cd>0) continue;
  1440. const target = findTarget(t, st);
  1441. if(!target) continue;
  1442. t.angle = Math.atan2(target.y-t.y, target.x-t.x);
  1443. t.cd = st.rate;
  1444. t.flash = .08; t.recoil = 1;
  1445. fire(t, st, target);
  1446. }
  1447. // projectiles
  1448. for(const p of G.projs){
  1449. if(p.type==='shell'){
  1450. p.t += dt;
  1451. const k = Math.min(1, p.t/p.dur);
  1452. p.x = lerp(p.x0,p.x1,k); p.y = lerp(p.y0,p.y1,k);
  1453. p.h = Math.sin(k*Math.PI)*46;
  1454. if(k>=1){
  1455. p.done = true;
  1456. explode(p.x1,p.y1,p.splash,p.dmg,p.pierce);
  1457. }
  1458. } else {
  1459. const tgt = p.target;
  1460. if(!tgt || tgt.dead){ p.done = true; continue; }
  1461. const dx=tgt.x-p.x, dy=tgt.y-p.y, d=Math.hypot(dx,dy)||1;
  1462. const step = p.speed*dt;
  1463. p.ang = Math.atan2(dy,dx);
  1464. if(d <= step+4){
  1465. p.x = tgt.x; p.y = tgt.y; p.done = true;
  1466. damageEnemy(tgt, p.dmg, p.pierce, p.col);
  1467. } else { p.x += dx/d*step; p.y += dy/d*step; }
  1468. }
  1469. }
  1470. G.projs = G.projs.filter(p=>!p.done);
  1471. // fx
  1472. for(const f of G.fx){ f.t += dt; }
  1473. G.fx = G.fx.filter(f=>f.t < f.life);
  1474. // wave clear
  1475. if(G.phase==='running' && !G.queue.length && !G.enemies.length){
  1476. G.phase='prep';
  1477. if(G.mode==='campaign' && G.wave>=G.totalWaves){ endBattle(true); return; }
  1478. G.prepLeft = 2.4;
  1479. if(G.mode==='endless'){ G.score += 150; G.gold += 20; floatText(BASE.x, BASE.y-60, 'WAVE CLEAR +20', '255,235,180'); }
  1480. else G.gold += 15;
  1481. AU.wave();
  1482. updateHUD(true);
  1483. }
  1484. if(G.shake>0) G.shake = Math.max(0, G.shake - dt*22);
  1485. if(G.flash>0) G.flash = Math.max(0, G.flash - dt*2.4);
  1486. G.time += dt;
  1487. }
  1488. function spawnEnemy(type, atD){
  1489. const b = ENEMIES[type];
  1490. const hp = Math.round(b.hp * G.hpMul);
  1491. const d0 = Math.max(0, atD||0);
  1492. const p = posAt(d0);
  1493. G.enemies.push({
  1494. type, hp, maxHp:hp, spd:b.spd, armor:b.armor, gold:b.gold, leak:b.leak,
  1495. 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,
  1496. frozen:0, hitFlash:0, bob:0, seed:Math.random()*6,
  1497. roarCd: b.boss ? 5.5 : 0, summoned:false, boost:0
  1498. });
  1499. }
  1500. function findTarget(t, st){
  1501. let best=null, bestD=-1;
  1502. for(const e of G.enemies){
  1503. if(e.dead) continue;
  1504. if(e.air && !st.air) continue;
  1505. const d = Math.hypot(e.x-t.x, e.y-t.y);
  1506. if(d > st.range + e.r) continue;
  1507. if(e.d > bestD){ bestD = e.d; best = e; }
  1508. }
  1509. return best;
  1510. }
  1511. function fire(t, st, target){
  1512. AU.shoot(st.proj==='hitscan' ? 'rifle' : (st.proj==='bullet'?'pistol':(st.proj==='shell'?'mortar':'arrow')));
  1513. const mx = t.x + Math.cos(t.angle)*16, my = t.y + Math.sin(t.angle)*16;
  1514. addFx('muzzle', mx, my, {life:.12, ang:t.angle});
  1515. if(st.proj==='hitscan'){
  1516. damageEnemy(target, st.dmg, st.pierce, '255,180,200');
  1517. addFx('beam', 0,0,{life:.09, x1:mx, y1:my, x2:target.x, y2:target.y, col:'255,200,160'});
  1518. return;
  1519. }
  1520. if(st.proj==='shell'){
  1521. const lead = target.spd * (Math.hypot(target.x-t.x,target.y-t.y)/st.pspeed) * 0.55;
  1522. const pp = posAt(target.d + lead);
  1523. 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,
  1524. 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 });
  1525. return;
  1526. }
  1527. G.projs.push({ type:st.proj, x:mx, y:my, target, dmg:st.dmg, pierce:st.pierce,
  1528. speed:st.pspeed, ang:t.angle, col: st.proj==='bullet'?'255,220,120':(st.proj==='bolt'?'255,210,102':'255,235,180') });
  1529. }
  1530. function explode(x,y,radius,dmg,pierce){
  1531. addFx('boom', x, y, {life:.5, r:radius});
  1532. AU.boom(); G.shake = Math.max(G.shake, 4.5); G.flash = Math.max(G.flash, .35);
  1533. for(const e of G.enemies){
  1534. if(e.dead || e.air) continue;
  1535. if(Math.hypot(e.x-x,e.y-y) <= radius + e.r) damageEnemy(e, dmg, pierce, '255,160,90');
  1536. }
  1537. }
  1538. /* ---------------- rendering ---------------- */
  1539. function draw(){
  1540. const c = ctx;
  1541. c.setTransform(DPR,0,0,DPR,0,0);
  1542. c.clearRect(0,0,FW,FH);
  1543. c.save();
  1544. if(G.shake>0) c.translate(rnd(-G.shake,G.shake)*.5, rnd(-G.shake,G.shake)*.5);
  1545. c.drawImage(bgCanvas, 0,0, FW, FH);
  1546. drawPortal(c);
  1547. drawSlots(c);
  1548. drawBase(c);
  1549. if(G.selTower) drawRange(c, G.selTower);
  1550. drawComboLinks(c);
  1551. // towers (sorted by y for depth)
  1552. [...G.towers].sort((a,b)=>a.y-b.y).forEach(t=>drawTower(c,t));
  1553. // enemies: ground then air
  1554. const air = G.enemies.filter(e=>e.air);
  1555. G.enemies.filter(e=>!e.air).forEach(e=>drawEnemy(c,e));
  1556. air.forEach(e=>drawEnemy(c,e));
  1557. // projectiles
  1558. G.projs.forEach(p=>drawProj(c,p));
  1559. // fx
  1560. G.fx.forEach(f=>drawFx(c,f));
  1561. if(G.armed==='air') drawAim(c);
  1562. c.restore();
  1563. if(G.flash>0){
  1564. c.fillStyle = `rgba(255,226,170,${G.flash*.30})`;
  1565. c.fillRect(0,0,FW,FH);
  1566. }
  1567. }
  1568. function drawSlots(c){
  1569. SLOTS.forEach(s=>{
  1570. if(s.tower) return;
  1571. const pulse = .5 + .5*Math.sin(G.time*2 + s.id);
  1572. c.save();
  1573. c.translate(s.x, s.y);
  1574. const tg = c.createLinearGradient(0,-SLOT_R,0,SLOT_R);
  1575. tg.addColorStop(0,'rgba(255,238,196,.34)'); tg.addColorStop(1,'rgba(126,74,32,.34)');
  1576. rr(c, -SLOT_R+2, -SLOT_R+2, SLOT_R*2-4, SLOT_R*2-4, 10);
  1577. c.fillStyle = tg; c.fill();
  1578. c.strokeStyle='rgba(90,50,20,.35)'; c.lineWidth=1.4; c.stroke();
  1579. c.lineWidth = 2;
  1580. c.setLineDash([6,5]); c.lineDashOffset = -G.time*10;
  1581. c.strokeStyle = `rgba(255,214,110,${.5+pulse*.4})`;
  1582. c.stroke();
  1583. c.setLineDash([]);
  1584. c.strokeStyle = 'rgba(255,248,214,.75)'; c.lineWidth = 1.6; c.lineCap='round';
  1585. c.beginPath(); c.moveTo(-6,0); c.lineTo(6,0); c.moveTo(0,-6); c.lineTo(0,6); c.stroke();
  1586. c.restore();
  1587. });
  1588. }
  1589. function drawComboLinks(c){
  1590. if(!G.comboLinks || !G.comboLinks.length) return;
  1591. const a = .35+.2*Math.sin(G.time*3);
  1592. c.save();
  1593. c.setLineDash([4,5]); c.lineDashOffset = -G.time*16;
  1594. c.lineWidth = 2;
  1595. G.comboLinks.forEach(l=>{
  1596. c.strokeStyle = `rgba(255,214,110,${a})`;
  1597. c.beginPath(); c.moveTo(l.a.x,l.a.y); c.lineTo(l.b.x,l.b.y); c.stroke();
  1598. });
  1599. c.restore();
  1600. }
  1601. function drawRange(c, t){
  1602. const st = towerStats(t);
  1603. c.save();
  1604. c.beginPath(); c.arc(t.x,t.y,st.range,0,TAU);
  1605. c.fillStyle='rgba(255,210,102,.08)'; c.fill();
  1606. c.strokeStyle='rgba(255,210,102,.55)'; c.lineWidth=1.6; c.setLineDash([6,5]);
  1607. c.lineDashOffset = -G.time*14; c.stroke();
  1608. c.restore();
  1609. }
  1610. function drawBase(c){
  1611. const {x,y} = BASE;
  1612. const hpK = G.baseHP/G.maxHP;
  1613. c.save(); c.translate(x,y);
  1614. // glow
  1615. const gl = c.createRadialGradient(0,0,4,0,0,62);
  1616. gl.addColorStop(0,`rgba(255,150,60,${.30+.15*Math.sin(G.time*2)})`);
  1617. gl.addColorStop(1,'rgba(255,150,60,0)');
  1618. c.fillStyle=gl; c.beginPath(); c.arc(0,0,62,0,TAU); c.fill();
  1619. // ground shadow
  1620. c.fillStyle='rgba(60,24,10,.35)';
  1621. c.beginPath(); c.ellipse(0,26,34,13,0,0,TAU); c.fill();
  1622. // stone footing
  1623. c.fillStyle='#8C7358'; rr(c,-30,10,60,20,7); c.fill();
  1624. c.strokeStyle='#4E3A26'; c.lineWidth=2; c.stroke();
  1625. // palisade wall
  1626. c.fillStyle='#A9712F';
  1627. rr(c,-27,-20,54,34,5); c.fill();
  1628. c.strokeStyle='#5A3216'; c.lineWidth=2.4; c.stroke();
  1629. c.fillStyle='#C99049';
  1630. 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(); }
  1631. // gate
  1632. c.fillStyle='#4A2408'; rr(c,-8,2,16,12,3); c.fill();
  1633. c.fillStyle='#FFD34D'; c.beginPath(); c.arc(0,8,2.2,0,TAU); c.fill();
  1634. // roof
  1635. c.fillStyle='#7A3E9E'; c.beginPath();
  1636. c.moveTo(-34,-20); c.lineTo(0,-42); c.lineTo(34,-20); c.closePath(); c.fill();
  1637. c.strokeStyle='#3E1B52'; c.lineWidth=2.4; c.stroke();
  1638. c.fillStyle='rgba(255,255,255,.14)'; c.beginPath();
  1639. c.moveTo(-34,-20); c.lineTo(0,-42); c.lineTo(0,-20); c.closePath(); c.fill();
  1640. // banner pole + flag
  1641. c.strokeStyle='#4A2408'; c.lineWidth=2.6;
  1642. c.beginPath(); c.moveTo(0,-42); c.lineTo(0,-60); c.stroke();
  1643. const wave = Math.sin(G.time*3)*1.6;
  1644. c.fillStyle='#FFC21F';
  1645. 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();
  1646. c.strokeStyle='#8A4A00'; c.lineWidth=1.2; c.stroke();
  1647. // HP bar
  1648. c.fillStyle='rgba(24,8,18,.65)'; rr(c,-32,34,64,8,4); c.fill();
  1649. c.fillStyle = hpK>.5 ? '#4BE38A' : hpK>.25 ? '#FFD34D' : '#FF4D6A';
  1650. rr(c,-30,35.6,60*clamp(hpK,0,1),4.8,2.4); c.fill();
  1651. 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();
  1652. c.restore();
  1653. }
  1654. function drawPortal(c){
  1655. const p = posAt(0);
  1656. const pulse = .5+.5*Math.sin(G.time*2.4);
  1657. c.save(); c.translate(p.x+4, p.y);
  1658. const g1 = c.createRadialGradient(0,0,2,0,0,34);
  1659. g1.addColorStop(0,`rgba(255,120,200,${.55+pulse*.25})`);
  1660. g1.addColorStop(.55,'rgba(150,60,220,.35)');
  1661. g1.addColorStop(1,'rgba(150,60,220,0)');
  1662. c.fillStyle=g1; c.beginPath(); c.arc(0,0,34,0,TAU); c.fill();
  1663. for(let i=0;i<3;i++){
  1664. c.strokeStyle=`rgba(255,210,255,${.55-i*.14})`; c.lineWidth=2.4-i*.6;
  1665. c.beginPath(); c.ellipse(0,0,12+i*5, 20+i*6, 0, 0, TAU); c.stroke();
  1666. }
  1667. c.fillStyle='rgba(30,6,40,.7)'; c.beginPath(); c.ellipse(0,0,8,16,0,0,TAU); c.fill();
  1668. c.restore();
  1669. }
  1670. function starPath(c, cx, cy, R, r, rot){
  1671. c.beginPath();
  1672. for(let i=0;i<10;i++){
  1673. const rad = (i%2===0) ? R : r;
  1674. const a = rot + i*Math.PI/5;
  1675. const x = cx + Math.cos(a)*rad, y = cy + Math.sin(a)*rad;
  1676. i ? c.lineTo(x,y) : c.moveTo(x,y);
  1677. }
  1678. c.closePath();
  1679. }
  1680. function drawTower(c,t){
  1681. const d = TOWERS[t.type];
  1682. c.save();
  1683. c.translate(t.x, t.y);
  1684. // shadow
  1685. c.fillStyle='rgba(50,20,10,.30)';
  1686. c.beginPath(); c.ellipse(0,11,21,9.5,0,0,TAU); c.fill();
  1687. // platform
  1688. const pg = c.createLinearGradient(0,-21,0,21);
  1689. pg.addColorStop(0,'#F6D7A6'); pg.addColorStop(.55,'#DCAE74'); pg.addColorStop(1,'#A97C46');
  1690. c.fillStyle=pg; c.beginPath(); c.arc(0,0,21,0,TAU); c.fill();
  1691. c.strokeStyle='#7A4A20'; c.lineWidth=2.6; c.stroke();
  1692. c.strokeStyle='rgba(255,244,206,.6)'; c.lineWidth=1.3;
  1693. c.beginPath(); c.arc(0,0,17.4,0,TAU); c.stroke();
  1694. // combo aura
  1695. if(t.combos.length){
  1696. c.strokeStyle=`rgba(255,210,102,${.55+.3*Math.sin(G.time*4)})`;
  1697. c.lineWidth=2.4; c.beginPath(); c.arc(0,0,23.5,0,TAU); c.stroke();
  1698. c.strokeStyle=`rgba(255,240,180,${.25+.2*Math.sin(G.time*4+1)})`;
  1699. c.lineWidth=5; c.beginPath(); c.arc(0,0,23.5,0,TAU); c.stroke();
  1700. }
  1701. // weapon
  1702. c.save();
  1703. c.scale(1.12,1.12);
  1704. c.shadowColor='rgba(44,16,8,.45)'; c.shadowBlur=3; c.shadowOffsetY=1.5;
  1705. const rec = Math.max(0,t.recoil)*3;
  1706. if(t.type==='archer'){
  1707. c.rotate(t.angle);
  1708. // bow
  1709. c.strokeStyle='#7A4522'; c.lineWidth=2.6; c.beginPath(); c.arc(4,0,10,-1.1,1.1); c.stroke();
  1710. 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();
  1711. c.rotate(-t.angle);
  1712. // body
  1713. c.fillStyle='#2FA968'; rr(c,-8,-6,16,16,6); c.fill();
  1714. c.strokeStyle='#1E7A4A'; c.lineWidth=1.6; c.stroke();
  1715. c.fillStyle='#4BE38A'; c.beginPath(); c.arc(0,-9,6,0,TAU); c.fill();
  1716. c.strokeStyle='#1E7A4A'; c.stroke();
  1717. c.fillStyle='#12321F'; c.beginPath(); c.arc(-2,-9,1.2,0,TAU); c.arc(2.4,-9,1.2,0,TAU); c.fill();
  1718. } else if(t.type==='crossbow'){
  1719. c.rotate(t.angle);
  1720. c.translate(-rec,0);
  1721. 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();
  1722. c.strokeStyle='rgba(255,240,200,.8)'; c.lineWidth=1.1; c.beginPath(); c.moveTo(-2,-11); c.lineTo(-2,11); c.stroke();
  1723. c.fillStyle='#6E4222'; rr(c,-12,-4,20,8,3); c.fill();
  1724. c.fillStyle='#FFD34D'; c.beginPath(); c.moveTo(12,0); c.lineTo(4,-4); c.lineTo(4,4); c.closePath(); c.fill();
  1725. } else if(t.type==='pistol'){
  1726. c.rotate(t.angle);
  1727. c.translate(-rec,0);
  1728. c.fillStyle='#8FA3B8'; rr(c,-6,-5,14,10,3); c.fill();
  1729. c.strokeStyle='#4A5C70'; c.lineWidth=1.4; c.stroke();
  1730. c.fillStyle='#5B6B80'; rr(c,-9,-6,6,12,2); c.fill();
  1731. c.fillStyle='#FFD34D'; rr(c,8,-2,5,4,1.6); c.fill();
  1732. } else if(t.type==='rifle'){
  1733. c.rotate(t.angle);
  1734. c.translate(-rec,0);
  1735. c.fillStyle='#7A4522'; rr(c,-10,-4,14,8,3); c.fill();
  1736. c.fillStyle='#9FB0C4'; rr(c,2,-2.4,18,4.8,2); c.fill();
  1737. c.fillStyle='#3B4A5A'; rr(c,-2,-7,8,3.6,1.6); c.fill();
  1738. c.fillStyle='#8FE9FF'; c.beginPath(); c.arc(3,-5.2,1.3,0,TAU); c.fill();
  1739. c.fillStyle='#3B4A5A'; c.beginPath(); c.moveTo(-6,3); c.lineTo(-9,9); c.lineTo(-5,9); c.closePath(); c.fill();
  1740. } else {
  1741. // mortar — fixed, tube tilted up
  1742. c.rotate(-Math.PI/2.6 + Math.sin(G.time*1.2)*0.03);
  1743. c.translate(-rec*1.4,0);
  1744. const mg = c.createLinearGradient(-10,-8,10,8);
  1745. mg.addColorStop(0,'#C7D3E0'); mg.addColorStop(1,'#5B6B80');
  1746. c.fillStyle=mg; rr(c,-10,-7,22,14,5); c.fill();
  1747. c.strokeStyle='#33414F'; c.lineWidth=1.8; c.stroke();
  1748. c.fillStyle='#22303E'; c.beginPath(); c.ellipse(12,0,3,7,0,0,TAU); c.fill();
  1749. c.rotate(Math.PI/2.6);
  1750. c.fillStyle='#8A5A2E'; rr(c,-9,4,18,8,3); c.fill();
  1751. }
  1752. c.restore();
  1753. c.shadowColor='transparent'; c.shadowBlur=0; c.shadowOffsetY=0;
  1754. // ---- star badge under the platform (still inside tower translate) ----
  1755. c.save();
  1756. rr(c, -13.5, 18.5, 27, 11, 5.5);
  1757. c.fillStyle = 'rgba(36,14,6,.66)'; c.fill();
  1758. c.strokeStyle = t.lv>=3 ? 'rgba(255,210,102,.85)' : 'rgba(255,210,102,.45)';
  1759. c.lineWidth = 1.1; c.stroke();
  1760. for(let i=0;i<3;i++){
  1761. const sx = -7.6 + i*7.6, sy = 24;
  1762. if(i < t.lv){
  1763. starPath(c, sx, sy, 3.6, 1.6, -Math.PI/2);
  1764. c.fillStyle = '#FFD34D'; c.fill();
  1765. c.strokeStyle = '#7A4200'; c.lineWidth = 0.8; c.stroke();
  1766. c.fillStyle = 'rgba(255,255,235,.85)';
  1767. c.beginPath(); c.arc(sx-0.9, sy-1.3, 0.75, 0, TAU); c.fill();
  1768. } else {
  1769. starPath(c, sx, sy, 3.0, 1.35, -Math.PI/2);
  1770. c.fillStyle = 'rgba(255,235,190,.10)'; c.fill();
  1771. c.strokeStyle = 'rgba(255,225,170,.34)'; c.lineWidth = 0.8; c.stroke();
  1772. }
  1773. }
  1774. c.restore();
  1775. // muzzle flash
  1776. if(t.flash>0){
  1777. c.save(); c.rotate(t.angle); c.translate(14,0);
  1778. const a = t.flash/.08;
  1779. c.fillStyle=`rgba(255,240,180,${a*.9})`;
  1780. c.beginPath(); c.arc(0,0,5*a+2,0,TAU); c.fill();
  1781. c.restore();
  1782. }
  1783. c.restore();
  1784. }
  1785. /* enemy drawing */
  1786. function drawEnemy(c,e){
  1787. const flip = Math.cos(e.ang) < 0 ? -1 : 1;
  1788. 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);
  1789. const R = e.r;
  1790. c.save();
  1791. // shadow
  1792. c.fillStyle = e.air ? 'rgba(50,20,10,.16)' : 'rgba(50,20,10,.32)';
  1793. 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();
  1794. c.translate(e.x, e.y - bounce - (e.air?15:0));
  1795. c.scale(flip,1);
  1796. c.shadowColor='rgba(44,16,8,.42)'; c.shadowBlur=3.5; c.shadowOffsetY=2;
  1797. const body = null;
  1798. if(e.type==='rabbit'){
  1799. c.fillStyle=body||'#E8C9A0';
  1800. c.beginPath(); c.ellipse(0,0,R*.95,R*.8,0,0,TAU); c.fill();
  1801. c.fillStyle=body||'#D9B487';
  1802. c.beginPath(); c.ellipse(-R*.72,-R*.1,R*.42,R*.34,0,0,TAU); c.fill();
  1803. c.fillStyle=body||'#E8C9A0';
  1804. c.beginPath(); c.ellipse(R*.62,-R*.5,R*.46,R*.42,0,0,TAU); c.fill();
  1805. c.beginPath(); c.ellipse(R*.5,-R*1.3,R*.14,R*.44,-.2,0,TAU); c.fill();
  1806. c.beginPath(); c.ellipse(R*.82,-R*1.25,R*.14,R*.42,.2,0,TAU); c.fill();
  1807. c.shadowColor='transparent';
  1808. c.fillStyle='#3A2410'; c.beginPath(); c.arc(R*.8,-R*.55,1.5,0,TAU); c.fill();
  1809. c.fillStyle='#C9552E'; c.beginPath(); c.arc(R*1.0,-R*.42,1.2,0,TAU); c.fill();
  1810. } else if(e.type==='bison'||e.type==='king'){
  1811. const big = e.type==='king';
  1812. if(big){
  1813. const aura = c.createRadialGradient(0,0,4,0,0,R*1.9);
  1814. aura.addColorStop(0,'rgba(255,46,154,.42)'); aura.addColorStop(1,'rgba(255,46,154,0)');
  1815. c.fillStyle=aura; c.beginPath(); c.arc(0,0,R*1.9,0,TAU); c.fill();
  1816. }
  1817. c.fillStyle=body||(big?'#5A2E6E':'#8A5A30');
  1818. c.beginPath(); c.ellipse(0,0,R*1.15,R*.86,0,0,TAU); c.fill();
  1819. c.fillStyle=body||(big?'#7A3E9E':'#9A6A3A');
  1820. c.beginPath(); c.ellipse(R*.1,-R*.58,R*.92,R*.44,0,0,TAU); c.fill();
  1821. c.fillStyle=body||(big?'#3E1B52':'#6E3E1C');
  1822. [-.55,.55].forEach((o,i)=>{
  1823. const sw = Math.sin(G.time*7+e.seed+i*2)*2;
  1824. c.beginPath(); c.ellipse(R*o+sw, R*.82, R*.2, R*.34, 0,0,TAU); c.fill();
  1825. });
  1826. c.fillStyle=body||(big?'#7A3E9E':'#9A6A3A');
  1827. c.beginPath(); c.ellipse(R*.95,-R*.1,R*.62,R*.56,0,0,TAU); c.fill();
  1828. c.shadowColor='transparent';
  1829. c.strokeStyle='#F0E0C0'; c.lineWidth=big?4.2:3.2; c.lineCap='round';
  1830. 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();
  1831. c.beginPath(); c.moveTo(R*1.1,-R*.5); c.quadraticCurveTo(R*1.56,-R*.9,R*1.2,-R*1.32); c.stroke();
  1832. c.fillStyle='#FFD34D'; c.beginPath(); c.arc(R*1.15,-R*.2,R*.17,0,TAU); c.fill();
  1833. c.fillStyle='#2A0B04'; c.beginPath(); c.arc(R*1.18,-R*.2,R*.075,0,TAU); c.fill();
  1834. if(big){
  1835. c.fillStyle='#FFC21F';
  1836. c.beginPath();
  1837. c.moveTo(-R*.5,-R*1.12); c.lineTo(-R*.3,-R*1.52); c.lineTo(-R*.1,-R*1.14);
  1838. c.lineTo(R*.1,-R*1.58); c.lineTo(R*.3,-R*1.12); c.closePath(); c.fill();
  1839. c.strokeStyle='#8A4A00'; c.lineWidth=1.2; c.stroke();
  1840. }
  1841. } else if(e.type==='wolf'){
  1842. c.fillStyle=body||'#8C97A8';
  1843. c.beginPath(); c.ellipse(0,0,R*1.15,R*.7,0,0,TAU); c.fill();
  1844. c.fillStyle=body||'#7A8598';
  1845. c.beginPath(); c.ellipse(R*.95,-R*.3,R*.52,R*.44,0,0,TAU); c.fill();
  1846. 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();
  1847. 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();
  1848. c.fillStyle=body||'#8C97A8';
  1849. c.beginPath(); c.moveTo(-R*1.1,-R*.1); c.quadraticCurveTo(-R*1.85,-R*.75,-R*1.72,R*.12);
  1850. c.quadraticCurveTo(-R*1.42,-R*.05,-R*1.1,R*.18); c.closePath(); c.fill();
  1851. c.shadowColor='transparent';
  1852. c.fillStyle='#2A0B04'; c.beginPath(); c.arc(R*1.12,-R*.35,R*.1,0,TAU); c.fill();
  1853. 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();
  1854. } else if(e.type==='vulture'){
  1855. const flap = Math.sin(G.time*10+e.seed);
  1856. c.fillStyle=body||'#5A4468';
  1857. c.beginPath(); c.ellipse(-R*.2,0,R*.55,R*.74,0,0,TAU); c.fill();
  1858. c.fillStyle='#6E5A78';
  1859. c.beginPath(); c.ellipse(-R*.1,-R*.92,R*.92,Math.max(1,R*.3+flap*4),-.15,0,TAU); c.fill();
  1860. c.beginPath(); c.ellipse(-R*.1,R*.52,R*.82,Math.max(1,R*.26-flap*3),.15,0,TAU); c.fill();
  1861. c.shadowColor='transparent';
  1862. c.fillStyle='#C9552E'; c.beginPath(); c.ellipse(R*.44,-R*.56,R*.32,R*.28,0,0,TAU); c.fill();
  1863. 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();
  1864. c.fillStyle='#2A0B04'; c.beginPath(); c.arc(R*.52,-R*.62,R*.085,0,TAU); c.fill();
  1865. } else if(e.type==='scorpion'){
  1866. c.fillStyle=body||'#B04A2E';
  1867. c.beginPath(); c.ellipse(0,0,R*1.1,R*.72,0,0,TAU); c.fill();
  1868. c.shadowColor='transparent';
  1869. c.strokeStyle='#7A2A18'; c.lineWidth=2;
  1870. for(let i=-1;i<2;i++){ c.beginPath(); c.ellipse(i*R*.45,0,R*.3,R*.64,0,0,TAU); c.stroke(); }
  1871. c.strokeStyle=body||'#B04A2E'; c.lineWidth=3.6; c.lineCap='round';
  1872. c.beginPath(); c.moveTo(R*.9,-R*.2); c.lineTo(R*1.52,-R*.56); c.stroke();
  1873. c.beginPath(); c.moveTo(R*.9,R*.2); c.lineTo(R*1.52,R*.5); c.stroke();
  1874. c.beginPath(); c.moveTo(-R*.9,0); c.quadraticCurveTo(-R*1.72,-R*.2,-R*1.5,-R*1.02); c.stroke();
  1875. c.fillStyle='#FFD34D'; c.beginPath(); c.arc(-R*1.45,-R*1.08,2.6,0,TAU); c.fill();
  1876. c.fillStyle='#2A0B04'; c.beginPath(); c.arc(R*.55,-R*.15,R*.1,0,TAU); c.fill();
  1877. }
  1878. if(e.hitFlash>0){
  1879. c.globalAlpha = Math.min(.45, e.hitFlash*4);
  1880. c.fillStyle='#FFF6E6';
  1881. c.beginPath(); c.ellipse(0,0,R*1.05,R*.78,0,0,TAU); c.fill();
  1882. c.globalAlpha = 1;
  1883. }
  1884. if(e.frozen>0){
  1885. c.fillStyle='rgba(120,220,255,.34)';
  1886. c.beginPath(); c.arc(0,0,R*1.2,0,TAU); c.fill();
  1887. c.strokeStyle='rgba(210,248,255,.95)'; c.lineWidth=1.8; c.stroke();
  1888. }
  1889. c.restore();
  1890. // hp bar
  1891. if(e.hp < e.maxHp){
  1892. const w = e.boss? 46 : 24, x = e.x-w/2, y = e.y - e.r*1.42 - (e.air?18:4) - 4;
  1893. c.fillStyle='rgba(24,8,18,.7)'; rr(c,x-1,y-1,w+2,5.6,2.8); c.fill();
  1894. c.fillStyle = e.hp/e.maxHp>.5?'#4BE38A':e.hp/e.maxHp>.22?'#FFD34D':'#FF4D6A';
  1895. rr(c,x,y,w*clamp(e.hp/e.maxHp,0,1),3.6,1.8); c.fill();
  1896. }
  1897. }
  1898. function drawProj(c,p){
  1899. c.save();
  1900. if(p.type==='shell'){
  1901. c.fillStyle='rgba(50,20,10,.2)';
  1902. c.beginPath(); c.ellipse(p.x, p.y, 5, 2.4, 0,0,TAU); c.fill();
  1903. c.fillStyle='#3B4A5A';
  1904. c.beginPath(); c.arc(p.x, p.y - p.h, 4.4, 0, TAU); c.fill();
  1905. c.fillStyle='#FFB04D'; c.beginPath(); c.arc(p.x-1, p.y-p.h-1.4, 1.6,0,TAU); c.fill();
  1906. } else if(p.type==='bullet'){
  1907. c.strokeStyle='rgba(255,220,120,.75)'; c.lineWidth=2;
  1908. 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();
  1909. c.fillStyle='#FFF3C0'; c.beginPath(); c.arc(p.x,p.y,1.9,0,TAU); c.fill();
  1910. } else {
  1911. c.translate(p.x,p.y); c.rotate(p.ang);
  1912. c.strokeStyle= p.type==='bolt' ? '#FFD34D' : '#E8D9C0';
  1913. c.lineWidth = p.type==='bolt' ? 2.6 : 1.9;
  1914. c.beginPath(); c.moveTo(-10,0); c.lineTo(4,0); c.stroke();
  1915. c.fillStyle= p.type==='bolt' ? '#FFF0BF' : '#FFE9A8';
  1916. c.beginPath(); c.moveTo(9,0); c.lineTo(3,-3); c.lineTo(3,3); c.closePath(); c.fill();
  1917. }
  1918. c.restore();
  1919. }
  1920. function drawFx(c,f){
  1921. const k = f.t/f.life;
  1922. c.save();
  1923. if(f.kind==='ring'){
  1924. c.strokeStyle=`rgba(${f.col},${1-k})`; c.lineWidth=3*(1-k)+1;
  1925. c.beginPath(); c.arc(f.x,f.y, lerp(f.r0,f.r1,k),0,TAU); c.stroke();
  1926. } else if(f.kind==='boom'){
  1927. const r = f.r*(0.35+k*0.85);
  1928. // outer scorch
  1929. c.fillStyle=`rgba(60,20,10,${.35*(1-k)})`;
  1930. c.beginPath(); c.arc(f.x,f.y,f.r*1.02,0,TAU); c.fill();
  1931. // fireball
  1932. const g = c.createRadialGradient(f.x,f.y,0,f.x,f.y,r);
  1933. g.addColorStop(0,`rgba(255,255,240,${.98*(1-k)})`);
  1934. g.addColorStop(.28,`rgba(255,214,120,${.92*(1-k)})`);
  1935. g.addColorStop(.6,`rgba(255,120,40,${.7*(1-k)})`);
  1936. g.addColorStop(1,'rgba(200,60,20,0)');
  1937. c.fillStyle=g; c.beginPath(); c.arc(f.x,f.y,r,0,TAU); c.fill();
  1938. // shock ring
  1939. c.strokeStyle=`rgba(255,245,200,${.85*(1-k)})`; c.lineWidth=3*(1-k)+.6;
  1940. c.beginPath(); c.arc(f.x,f.y,r*1.12,0,TAU); c.stroke();
  1941. // debris
  1942. for(let i=0;i<8;i++){
  1943. const a=i*.79+f.t*3, rr2=r*(0.7+((i%3)*0.16));
  1944. c.fillStyle=`rgba(255,190,90,${.8*(1-k)})`;
  1945. 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();
  1946. }
  1947. } else if(f.kind==='spark'){
  1948. c.fillStyle=`rgba(${f.col||'255,235,180'},${1-k})`;
  1949. for(let i=0;i<3;i++){
  1950. const a=i*2.1+f.t*9, r=k*11;
  1951. c.beginPath(); c.arc(f.x+Math.cos(a)*r, f.y+Math.sin(a)*r, 1.6*(1-k),0,TAU); c.fill();
  1952. }
  1953. } else if(f.kind==='poof'){
  1954. c.fillStyle=`rgba(240,220,190,${.55*(1-k)})`;
  1955. for(let i=0;i<6;i++){
  1956. const a=i*1.05, r=k*(f.r+8);
  1957. c.beginPath(); c.arc(f.x+Math.cos(a)*r, f.y+Math.sin(a)*r*.7, (1-k)*4,0,TAU); c.fill();
  1958. }
  1959. } else if(f.kind==='muzzle'){
  1960. c.save(); c.translate(f.x,f.y); c.rotate(f.ang);
  1961. c.fillStyle=`rgba(255,245,200,${1-k})`;
  1962. 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();
  1963. c.restore();
  1964. } else if(f.kind==='beam'){
  1965. c.strokeStyle=`rgba(${f.col},${1-k})`; c.lineWidth=2.2*(1-k)+.6;
  1966. c.beginPath(); c.moveTo(f.x1,f.y1); c.lineTo(f.x2,f.y2); c.stroke();
  1967. } else if(f.kind==='text'){
  1968. c.globalAlpha = 1-k;
  1969. c.font='900 13px ui-rounded, "Segoe UI", sans-serif';
  1970. c.textAlign='center';
  1971. c.lineWidth=3; c.strokeStyle='rgba(40,10,20,.75)';
  1972. c.strokeText(f.text, f.x, f.y - k*22);
  1973. c.fillStyle=`rgba(${f.col},1)`;
  1974. c.fillText(f.text, f.x, f.y - k*22);
  1975. } else if(f.kind==='stars'){
  1976. for(let i=0;i<f.lv;i++){
  1977. const a = -Math.PI/2 + (i-(f.lv-1)/2)*0.55;
  1978. const r = 10 + k*26;
  1979. const sx = f.x + Math.cos(a)*r, sy = f.y + Math.sin(a)*r;
  1980. starPath(c, sx, sy, 3.2*(1-k*0.4), 1.4*(1-k*0.4), -Math.PI/2);
  1981. c.fillStyle = `rgba(255,214,110,${1-k})`;
  1982. c.fill();
  1983. }
  1984. } else if(f.kind==='frost'){
  1985. c.fillStyle=`rgba(140,230,255,${.30*(1-k)})`; c.fillRect(0,0,FW,FH);
  1986. for(let i=0;i<20;i++){
  1987. const a=i*.31, r=lerp(20,300,k);
  1988. c.strokeStyle=`rgba(200,245,255,${.5*(1-k)})`; c.lineWidth=1.4;
  1989. c.beginPath(); c.arc(FW/2,FH/2,r,a,a+.22); c.stroke();
  1990. }
  1991. } else if(f.kind==='heal'){
  1992. c.strokeStyle=`rgba(120,255,180,${1-k})`; c.lineWidth=3;
  1993. c.beginPath(); c.arc(f.x,f.y, lerp(10,50,k),0,TAU); c.stroke();
  1994. }
  1995. c.restore();
  1996. }
  1997. function drawAim(c){
  1998. const a = .5+.5*Math.sin(G.time*6);
  1999. c.save();
  2000. c.fillStyle=`rgba(255,120,60,${.10+a*.08})`; c.fillRect(0,0,FW,FH);
  2001. c.strokeStyle=`rgba(255,180,80,${.6+a*.3})`; c.lineWidth=2; c.setLineDash([8,6]);
  2002. c.strokeRect(6,6,FW-12,FH-12);
  2003. c.restore();
  2004. }
  2005. /* ---------------- HUD ---------------- */
  2006. let hudCache = {};
  2007. function updateHUD(force){
  2008. const wTxt = G.mode==='campaign' ? `${Math.min(G.wave,G.totalWaves)}/${G.totalWaves}` : `${G.wave}`;
  2009. if(force || hudCache.w!==wTxt){ document.getElementById('hudWave').textContent = wTxt; hudCache.w=wTxt; }
  2010. const gTxt = Math.floor(G.gold);
  2011. if(force || hudCache.g!==gTxt){ document.getElementById('hudGold').textContent = gTxt; hudCache.g=gTxt;
  2012. document.querySelectorAll('.tcard').forEach(el=>{
  2013. const d = TOWERS[el.dataset.type];
  2014. el.classList.toggle('is-poor', G.gold < d.cost);
  2015. });
  2016. if(G.selTower) openTowerPanel(G.selTower);
  2017. }
  2018. if(force || hudCache.hp!==G.baseHP){ document.getElementById('hudBase').textContent = G.baseHP; hudCache.hp=G.baseHP; }
  2019. const sTxt = G.score;
  2020. if(force || hudCache.s!==sTxt){ document.getElementById('hudScore').textContent = fmt(sTxt); hudCache.s=sTxt; }
  2021. const prog = G.phase==='running'
  2022. ? (1 - (G.queue.length + G.enemies.length) / Math.max(1, G.waveTotalCount||1))
  2023. : (G.phase==='prep' ? 1 : 0);
  2024. document.getElementById('waveProg').style.width = clamp(prog*100,0,100) + '%';
  2025. }
  2026. /* ---------------- battle end ---------------- */
  2027. function endBattle(win){
  2028. if(G.phase==='done') return;
  2029. G.phase='done';
  2030. G.running=false;
  2031. closeTowerPanel();
  2032. const cleared = win ? (G.mode==='campaign' ? G.totalWaves : G.wave) : Math.max(0, G.wave-1);
  2033. state.stats.kills += G.kills;
  2034. state.stats.waves += cleared;
  2035. state.stats.towers += (G.towersBuilt||0);
  2036. if(G.mode==='campaign'){
  2037. G.score = cleared*150 + G.kills*20 + G.baseHP*100;
  2038. const firstClear = !(state.stars[G.level] > 0);
  2039. const reward = win ? Math.round(levelReward(G.level) * (firstClear ? 1 : 0.4) / 5) * 5 : 0;
  2040. G.firstClear = firstClear;
  2041. if(win){
  2042. const stars = G.baseHP>=20?3:(G.baseHP>=12?2:1);
  2043. state.stars[G.level] = Math.max(state.stars[G.level]||0, stars);
  2044. if(G.level > state.cleared) state.cleared = G.level;
  2045. state.coins += reward;
  2046. G.coinsEarned = reward;
  2047. save();
  2048. }
  2049. save();
  2050. showResult(win, cleared, reward, false);
  2051. } else {
  2052. G.score = cleared*150 + G.kills*20 + G.baseHP*100;
  2053. const prevBest = state.best.wave||0;
  2054. let reward = cleared*45;
  2055. if(cleared > prevBest) reward += (cleared-prevBest)*100;
  2056. state.coins += reward;
  2057. G.coinsEarned = reward;
  2058. state.best = { score:Math.max(G.score,state.best.score||0), wave:Math.max(cleared,state.best.wave||0) };
  2059. submitScore(G.score, cleared);
  2060. save();
  2061. showResult(true, cleared, reward, true);
  2062. }
  2063. if(win) AU.win(); else AU.lose();
  2064. }
  2065. function showResult(win, waves, coins, endless){
  2066. const t = document.getElementById('resTitle');
  2067. t.textContent = endless ? 'RUN OVER' : (win ? 'VICTORY' : 'DEFEAT');
  2068. t.className = win ? '' : 'lose';
  2069. document.getElementById('resLead').textContent = endless
  2070. ? `You held for ${waves} waves. Score ${fmt(G.score)}.`
  2071. : (win ? (G.firstClear ? `Outpost ${G.level} secured.`
  2072. : `Outpost ${G.level} replayed · 40% reward.`)
  2073. : `The stampede broke through on wave ${waves}.`);
  2074. const stars = win ? (G.baseHP>=20?3:(G.baseHP>=12?2:1)) : 0;
  2075. document.querySelectorAll('#resStars svg').forEach((s,i)=>s.classList.toggle('on', i<stars));
  2076. document.getElementById('resStars').style.display = endless ? 'none' : 'flex';
  2077. document.getElementById('resWaves').textContent = waves;
  2078. document.getElementById('resKills').textContent = G.kills;
  2079. document.getElementById('resScore').textContent = fmt(G.score);
  2080. document.getElementById('resCoins').textContent = '+'+fmt(coins);
  2081. const next = document.getElementById('resNext');
  2082. if(endless){ next.textContent = 'PLAY AGAIN'; next.onclick = ()=> startBattle('endless',0); }
  2083. else if(win && G.level<20){ next.textContent = 'NEXT LEVEL'; next.onclick = ()=> startBattle('campaign', G.level+1); }
  2084. else if(win){ next.textContent = 'REPLAY'; next.onclick = ()=> startBattle('campaign', G.level); }
  2085. else { next.textContent = 'RETRY'; next.onclick = ()=> startBattle('campaign', G.level); }
  2086. document.getElementById('resLobby').onclick = ()=>{ closeAllSheets(); showView(G.mode==='campaign'?'levels':'lobby'); };
  2087. openSheet('sheetResult');
  2088. renderLobby();
  2089. }
  2090. /* ---------------- input ---------------- */
  2091. field.addEventListener('pointerdown', ev=>{
  2092. if(G.phase==='done') return;
  2093. const r = field.getBoundingClientRect();
  2094. const x = (ev.clientX - r.left) * (FW / r.width);
  2095. const y = (ev.clientY - r.top) * (FH / r.height);
  2096. if(G.armed==='air'){
  2097. state.items.air--; save(); G.armed=null;
  2098. document.querySelectorAll('.item').forEach(el=>el.classList.remove('is-arm'));
  2099. renderItemDock();
  2100. addFx('boom', x, y, {life:.55, r:78}); AU.strike(); G.shake = 9;
  2101. G.enemies.forEach(e=>{ if(Math.hypot(e.x-x,e.y-y) <= 78+e.r) damageEnemy(e, 400, true, '255,160,90'); });
  2102. return;
  2103. }
  2104. const slot = slotAt(x,y);
  2105. if(slot && slot.tower){ openTowerPanel(slot.tower); return; }
  2106. if(slot && G.selType){ buildTower(slot, G.selType); return; }
  2107. if(slot && !slot.tower){ toast('Pick a tower card first'); return; }
  2108. closeTowerPanel();
  2109. });
  2110. document.getElementById('buyConfirm').onclick = ()=> confirmBuy();
  2111. document.getElementById('tpClose').onclick = closeTowerPanel;
  2112. document.getElementById('tpUpgrade').onclick = ()=>{ if(G.selTower) upgradeTower(G.selTower); };
  2113. document.getElementById('tpSell').onclick = ()=>{ if(G.selTower) sellTower(G.selTower); };
  2114. document.getElementById('btnPause').onclick = ()=>{ G.paused = true; openSheet('sheetPause'); };
  2115. document.getElementById('btnResume').onclick = ()=>{ G.paused=false; closeSheet('sheetPause'); };
  2116. document.getElementById('btnRestart').onclick = ()=>{ closeAllSheets(); startBattle(G.mode, G.level); };
  2117. document.getElementById('btnQuit').onclick = ()=>{ closeAllSheets(); G.phase='done'; G.running=false;
  2118. showView(G.mode==='campaign'?'levels':'lobby'); };
  2119. document.getElementById('btnNextWave').onclick = ()=>{
  2120. if(G.phase==='prep'){
  2121. G.prepLeft = 0; G.gold += 25;
  2122. floatText(BASE.x, BASE.y-70, '+25 EARLY', '255,235,180');
  2123. AU.wave();
  2124. } else toast('Wave in progress');
  2125. };
  2126. document.querySelectorAll('#spdBox button').forEach(b=>{
  2127. b.onclick = ()=>{
  2128. G.speed = Number(b.dataset.spd);
  2129. document.querySelectorAll('#spdBox button').forEach(x=>x.classList.toggle('is-on', x===b));
  2130. };
  2131. });
  2132. addEventListener('keydown', e=>{
  2133. if(e.key!=='Escape') return;
  2134. const open = [...document.querySelectorAll('.sheet.is-open')].pop();
  2135. if(open && open.id==='sheetResult') return;
  2136. if(open){ open.classList.remove('is-open');
  2137. if(open.id==='sheetPause' || open.id==='sheetBuy') G.paused=false;
  2138. return; }
  2139. if(currentView==='battle'){ G.paused = !G.paused; if(G.paused) openSheet('sheetPause'); }
  2140. });
  2141. /* ---------------- coach ---------------- */
  2142. let coachTimer=null;
  2143. function showCoach(text){
  2144. const el = document.getElementById('coach');
  2145. document.getElementById('coachText').textContent = text;
  2146. el.classList.add('is-on');
  2147. clearTimeout(coachTimer);
  2148. coachTimer = setTimeout(()=>el.classList.remove('is-on'), 5200);
  2149. }
  2150. /* ---------------- loop ---------------- */
  2151. let lastT = performance.now(), loopRunning = true;
  2152. function loop(now){
  2153. const raw = Math.min(0.05, (now - lastT)/1000 || 0);
  2154. lastT = now;
  2155. if(currentView==='battle' && G.running && !G.paused && G.phase!=='done'){
  2156. let steps = G.speed;
  2157. for(let i=0;i<steps;i++) update(raw);
  2158. updateHUD();
  2159. }
  2160. if(currentView==='battle') draw();
  2161. requestAnimationFrame(loop);
  2162. }
  2163. requestAnimationFrame(loop);