codekeep 0.2.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +14 -16
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import{Command as Oa}from"commander";import{render as Ua}from"ink";import{useState as Re,useCallback as Yt,useEffect as Pa,useRef as Bs}from"react";import{Box as Lt,Text as Me,useApp as Da,useInput as La,useStdout as $a}from"ink";var B={gold:"\u25CF",wood:"\u2663",stone:"\u25A0"};var I=16,cr=8,ur=2400;var St={gold:80,wood:40,stone:20},no={gold:200,wood:120,stone:80},fe={wall:"#",trap:"%",treasury:"$",ward:"@",watchtower:"^",archerTower:"!",vault:"&"},tt={wall:"Stone Wall",trap:"Bear Trap",treasury:"Treasury",ward:"Ward",watchtower:"Watchtower",archerTower:"Archer Tower",vault:"Vault"},Ot="\xB7",ot={wall:{1:{gold:12,wood:0,stone:2},2:{gold:10,wood:0,stone:4},3:{gold:14,wood:0,stone:6}},trap:{1:{gold:8,wood:4,stone:6},2:{gold:8,wood:4,stone:6},3:{gold:10,wood:6,stone:8}},treasury:{1:{gold:6,wood:14,stone:2},2:{gold:6,wood:18,stone:4},3:{gold:8,wood:24,stone:6}},ward:{1:{gold:10,wood:10,stone:0},2:{gold:12,wood:12,stone:0},3:{gold:16,wood:16,stone:0}},watchtower:{1:{gold:6,wood:2,stone:12},2:{gold:6,wood:4,stone:14},3:{gold:8,wood:6,stone:18}},archerTower:{1:{gold:14,wood:6,stone:8},2:{gold:16,wood:8,stone:10},3:{gold:20,wood:12,stone:14}},vault:{1:{gold:20,wood:20,stone:15},2:{gold:35,wood:35,stone:25},3:{gold:55,wood:55,stone:40}}},ao={1:40,2:70,3:110},io={1:25,2:40,3:60},lo={1:20,2:35,3:50},pr={1:4,2:6,3:9},fr={1:16,2:12,3:8},mr={1:80,2:160,3:280},gr={1:.15,2:.28,3:.4},bt={1:1,2:2,3:3},hr={1:4,2:7,3:10},co={1:2,2:2,3:3},Tr={1:4,2:3,3:2};var Le={raider:{hp:30,damage:8,loot:3,speed:1},scout:{hp:14,damage:4,loot:2,speed:2},brute:{hp:55,damage:14,loot:5,speed:1}},xr=6e4,uo={gold:2,wood:4,stone:1},po={gold:1,wood:0,stone:3},fo={build_success:{gold:12,wood:0,stone:4},tests_pass:{gold:0,wood:8,stone:4},git_commit:{gold:5,wood:5,stone:10},session_reward:{gold:8,wood:3,stone:6},daily_login:{gold:5,wood:5,stone:10}},yr={build_success:"Miners returned",tests_pass:"Harvest complete",git_commit:"Trade caravan arrived",session_reward:"Tax collection",daily_login:"Morning tribute"},qt=9e5,wr=5,Ut=10,Rr=.5,zt=[{id:"first_structure",name:"Builder",desc:"Place your first structure",bonus:"+20 gold"},{id:"defense_win_5",name:"Warden",desc:"Win 5 defense raids",bonus:"+25 gold, +15 wood, +15 stone"},{id:"win_streak_3",name:"Rallying Cry",desc:"Achieve a 3-win streak",bonus:"+10 all resources"},{id:"win_streak_5",name:"Unstoppable",desc:"Achieve a 5-win streak",bonus:"+30 all resources"},{id:"all_types",name:"Master Builder",desc:"Place every structure type",bonus:"+15 all resources"},{id:"max_level",name:"Fortifier",desc:"Upgrade a structure to Level 3",bonus:"+20 gold, +10 stone"},{id:"archer_kills_10",name:"Marksman",desc:"Kill 10 raiders with archers",bonus:"+20 gold, +10 wood, +10 stone"},{id:"structures_20",name:"Architect",desc:"Place 20 structures total",bonus:"+10 all resources"},{id:"raids_10",name:"Veteran",desc:"Complete 10 raids",bonus:"+15 all resources"},{id:"hoarder",name:"Treasure Keeper",desc:"Hold 500+ total resources",bonus:"+25 gold"}],Zt={gold_nugget:{symbol:"~",color:"cyan",yield:{gold:4,wood:0,stone:0},weight:35},timber:{symbol:"~",color:"yellow",yield:{gold:0,wood:4,stone:0},weight:35},ore:{symbol:"~",color:"green",yield:{gold:0,wood:0,stone:4},weight:20},gem:{symbol:"~",color:"white",yield:{gold:2,wood:2,stone:2},weight:10}},$o=6,Sr=35e3,br=18e4,kr=.25,vr=2,ct=["wall","trap","treasury","ward","watchtower","archerTower","vault"],mo={1:60,2:90,3:130};var Er=1;var Ka={defense_win:7200*1e3,partial_breach:14400*1e3,full_breach:480*60*1e3},go={raider:{gold:8,wood:4,stone:2},scout:{gold:6,wood:6,stone:0},brute:{gold:15,wood:8,stone:8}},Ar={raider:120*1e3,scout:120*1e3,brute:300*1e3};var Ha=1440*60*1e3,Fa=2880*60*1e3,Va=672*60*60*1e3;var Ya=336*60*60*1e3,ja=2880*60*1e3;var qa=720*60*1e3;import{writeFileSync as Oo,readFileSync as wn,mkdirSync as Rn,existsSync as Fo,renameSync as Sn,unlinkSync as bn}from"fs";import{join as Zr,dirname as kn}from"path";import{homedir as vn}from"os";function Js(e){return e.x>=0&&e.x<I&&e.y>=0&&e.y<I}function Go(e,t){return e.structures.find(o=>o.pos.x===t.x&&o.pos.y===t.y)}function Xs(e,t,o){return Js(t)?Go(e,t)?{ok:!1,reason:"Cell is occupied"}:{ok:!0}:{ok:!1,reason:"Out of bounds"}}function Nr(e,t){return e.gold>=t.gold&&e.wood>=t.wood&&e.stone>=t.stone}function Br(e,t,o){let s=Xs(e.grid,t,o);if(!s.ok)return{ok:!1,reason:s.reason};let r=ot[o][1];if(!Nr(e.resources,r))return{ok:!1,reason:Gr(e.resources,r)};let a={id:`${o}-${t.x}-${t.y}-${Date.now()}`,kind:o,level:1,pos:{...t},placedAtUnixMs:Date.now()};return{ok:!0,keep:{...e,resources:Wr(e.resources,r),grid:{...e.grid,structures:[...e.grid.structures,a]},updatedAtUnixMs:Date.now()}}}function Or(e,t){let o=Go(e.grid,t);if(!o)return{ok:!1,reason:"No structure at this position"};if(o.level>=3)return{ok:!1,reason:"Already at max level"};let s=o.level+1,r=ot[o.kind][s];if(!Nr(e.resources,r))return{ok:!1,reason:Gr(e.resources,r)};let a={...o,level:s};return{ok:!0,keep:{...e,resources:Wr(e.resources,r),grid:{...e.grid,structures:e.grid.structures.map(T=>T.id===o.id?a:T)},updatedAtUnixMs:Date.now()}}}function Ur(e,t){let o=Go(e.grid,t);if(!o)return{ok:!1,reason:"No structure at this position"};let s=Qs(o);return{ok:!0,keep:{...e,resources:Oe(e.resources,s),grid:{...e.grid,structures:e.grid.structures.filter(r=>r.id!==o.id)},updatedAtUnixMs:Date.now()}}}function Qs(e){let t=0,o=0,s=0;for(let r=1;r<=e.level;r++){let a=ot[e.kind][r];t+=a.gold,o+=a.wood,s+=a.stone}return{gold:Math.floor(t*.5),wood:Math.floor(o*.5),stone:Math.floor(s*.5)}}function Gr(e,t){let o=[];return t.gold>e.gold&&o.push(`${t.gold-e.gold} more gold`),t.wood>e.wood&&o.push(`${t.wood-e.wood} more wood`),t.stone>e.stone&&o.push(`${t.stone-e.stone} more stone`),o.length>0?`Need ${o.join(", ")}`:"Not enough resources"}function Wr(e,t){return{gold:e.gold-t.gold,wood:e.wood-t.wood,stone:e.stone-t.stone}}function Oe(e,t){return{gold:e.gold+t.gold,wood:e.wood+t.wood,stone:e.stone+t.stone}}function Wo(e,t){let o=t.grants??fo[t.type]??{gold:0,wood:0,stone:0},s=Oe(e.resources,o);return{...e,resources:rt(s),updatedAtUnixMs:Date.now()}}function rt(e){return{gold:Math.min(e.gold,no.gold*10),wood:Math.min(e.wood,no.wood*10),stone:Math.min(e.stone,no.stone*10)}}function Ko(e,t){let o=Math.min(Math.floor(t/xr),60),s=e.structures.filter(a=>a.kind==="treasury").length,r=e.structures.filter(a=>a.kind==="watchtower").length;return{gold:o*(s*uo.gold+r*po.gold),wood:o*(s*uo.wood+r*po.wood),stone:o*(s*uo.stone+r*po.stone)}}function Kr(){let e=["build_success","tests_pass","git_commit","session_reward"],t=e[Math.floor(Math.random()*e.length)];return{type:t,timestamp:Date.now(),grants:fo[t]}}function en(e){return ao[e]}function tn(e){return io[e]}function on(e){return lo[e]}function rn(e){return mo[e]}function Cr(e){return pr[e]}function _r(e){return fr[e]}function No(e){return mr[e]}function sn(e){return gr[e]}function nn(e){return bt[e]}function an(e){return hr[e]}function ln(e){return co[e]}function dn(e){return Tr[e]}function Mr(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function _e(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}function cn(e,t){let o=e.structures.filter(a=>a.kind==="ward"),s=e.structures.filter(a=>a.kind==="watchtower"),r=0;for(let a of o){let T=1;for(let f of s)Mr(a.pos,f.pos)<=1&&(T=Math.max(T,1+nn(f.level)));Mr(a.pos,t)<=T&&(r=Math.max(r,sn(a.level)))}return r}function Hr(e){let t=e|0;return()=>{t=t+1831565813|0;let o=Math.imul(t^t>>>15,1|t);return o=o+Math.imul(o^o>>>7,61|o)^o,((o^o>>>14)>>>0)/4294967296}}function Fr(e){let t=0;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);t=(t<<5)-t+s|0}return t}function un(e,t){switch(e){case"N":return{x:t,y:0};case"S":return{x:t,y:I-1};case"E":return{x:I-1,y:t};case"W":return{x:0,y:t}}}function Vr(e,t){return t.x<0||t.x>=I||t.y<0||t.y>=I?!1:e.grid[t.y][t.x]}function Yr(e){for(let t=0;t<I;t++)for(let o=0;o<I;o++)e.grid[t][o]=!0;for(let t of e.solids)t.destroyed||(e.grid[t.pos.y][t.pos.x]=!1)}function jr(e,t,o){if(e.x===t.x&&e.y===t.y)return null;let s=l=>`${l.x},${l.y}`,r=new Map,a=new Set,T=l=>Math.abs(l.x-t.x)+Math.abs(l.y-t.y),f=s(e);r.set(f,{pos:e,g:0,f:T(e),parent:null});let d=new Map;for(;r.size>0;){let l="",x=1/0;for(let[m,p]of r)p.f<x&&(x=p.f,l=m);let k=r.get(l);if(r.delete(l),k.pos.x===t.x&&k.pos.y===t.y){let m=s(t),p=d.get(m);for(;p&&p!==f;)m=p,p=d.get(m);let[b,c]=m.split(",").map(Number);return{x:b,y:c}}a.add(l);let R=[{x:k.pos.x-1,y:k.pos.y},{x:k.pos.x+1,y:k.pos.y},{x:k.pos.x,y:k.pos.y-1},{x:k.pos.x,y:k.pos.y+1}];for(let m of R){let p=s(m);if(a.has(p)||!Vr(o,m)&&!(m.x===t.x&&m.y===t.y))continue;let b=k.g+1,c=r.get(p);c&&b>=c.g||(d.set(p,l),r.set(p,{pos:m,g:b,f:b+T(m),parent:l}))}}return null}function pn(e,t){switch(e){case"wall":return en(t);case"archerTower":return tn(t);case"watchtower":return on(t);case"vault":return rn(t);default:return 0}}var fn=["archerTower","watchtower"];function Ir(e,t){return e.solids.find(o=>!o.destroyed&&_e(o.pos,t)===1)}function ho(e,t,o){o.hp-=Le[t.raiderType].damage;let s=o.hp<=0;if(s){o.destroyed=!0,Yr(e);let r=e.archers.find(a=>a.structureId===o.structureId);r&&(r.destroyed=!0)}o.kind==="wall"?e.events.push({t:e.tick,type:"wall_damaged",structureId:o.structureId,hpRemaining:Math.max(0,o.hp),destroyed:s}):e.events.push({t:e.tick,type:"structure_damaged",structureId:o.structureId,structureKind:o.kind,hpRemaining:Math.max(0,o.hp),destroyed:s})}function Pr(e,t,o){let r=[{x:o.pos.x-1,y:o.pos.y},{x:o.pos.x+1,y:o.pos.y},{x:o.pos.x,y:o.pos.y-1},{x:o.pos.x,y:o.pos.y+1}].filter(f=>Vr(e,f)).sort((f,d)=>{let l=_e(f,t.pos),x=_e(d,t.pos);return l-x})[0];if(!r||_e(t.pos,r)===0)return!1;let a=jr(t.pos,r,e);if(!a)return!1;let T={...t.pos};return t.pos={...a},e.events.push({t:e.tick,type:"raider_move",probeId:t.id,from:T,to:{...t.pos}}),!0}function mn(e,t){return e.solids.filter(s=>!s.destroyed&&fn.includes(s.kind)).sort((s,r)=>{let a=s.kind==="archerTower"?0:1,T=r.kind==="archerTower"?0:1;return a!==T?a-T:_e(s.pos,t.pos)-_e(r.pos,t.pos)})[0]??null}function gn(e,t){let o=e.solids.filter(s=>!s.destroyed&&_e(s.pos,t.pos)===1);return o.length===0?null:o.sort((s,r)=>s.hp-r.hp)[0]}function ut(e){let t=Hr(Fr(e.seed)),{keepGrid:o}=e,s=["wall","archerTower","watchtower","vault"],r=o.structures.filter(c=>s.includes(c.kind)).sort((c,$)=>c.id.localeCompare($.id)).map(c=>({structureId:c.id,kind:c.kind,pos:{...c.pos},hp:pn(c.kind,c.level),destroyed:!1})),a=o.structures.filter(c=>c.kind==="trap").sort((c,$)=>c.id.localeCompare($.id)).map(c=>({structureId:c.id,pos:{...c.pos},level:c.level,cooldownRemaining:0})),T=o.structures.filter(c=>c.kind==="archerTower").sort((c,$)=>c.id.localeCompare($.id)).map(c=>({structureId:c.id,pos:{...c.pos},level:c.level,cooldownRemaining:0,destroyed:!1})),f=o.structures.filter(c=>c.kind==="treasury").sort((c,$)=>c.id.localeCompare($.id)).map(c=>({structureId:c.id,pos:{...c.pos},level:c.level,storedResources:No(c.level)}));f.length===0&&(f=[{structureId:"__virtual_center_treasury",pos:{x:8,y:8},level:1,storedResources:No(1)}]);let d={tick:0,raiders:[],solids:r,traps:a,archers:T,treasuries:f,events:[],grid:Array.from({length:I},()=>Array(I).fill(!0)),totalLoot:{gold:0,wood:0,stone:0}};Yr(d);let l=[],x=["N","S","E","W"];for(let c=0;c<e.probeCount;c++){let $=e.spawnSpecs?.[c],z=$?.edge??x[Math.floor(t()*x.length)],U=$?.offset??Math.floor(t()*I),u=$?.raiderType??e.probeTypes?.[c]??"raider",K=$?.waveDelay??0;l.push({id:c,edge:z,offset:U,raiderType:u,spawnAtTick:K})}function k(c,$){let z=un(c.edge,c.offset),U=null,u=1/0;for(let K of f){let w=_e(K.pos,z);w<u&&(u=w,U=K)}d.raiders.push({id:c.id,pos:{...z},hp:Le[c.raiderType].hp,raiderType:c.raiderType,stunRemaining:0,targetId:U?.structureId??null,alive:!0,looted:{gold:0,wood:0,stone:0}}),d.events.push({t:$,type:"raider_spawn",probeId:c.id,edge:c.edge,pos:{...z},raiderType:c.raiderType,maxHp:Le[c.raiderType].hp})}for(let c of l)c.spawnAtTick===0&&k(c,0);for(;d.tick<ur;){d.tick++;for(let u of l)u.spawnAtTick===d.tick&&k(u,d.tick);for(let u of d.traps)u.cooldownRemaining>0&&u.cooldownRemaining--;for(let u of d.archers)u.cooldownRemaining>0&&u.cooldownRemaining--;let c=d.raiders.filter(u=>u.alive).sort((u,K)=>u.id-K.id),$=l.some(u=>u.spawnAtTick>d.tick);if(c.length===0&&!$)break;for(let u of d.archers){if(u.destroyed||u.cooldownRemaining>0)continue;let K=ln(u.level),w=an(u.level),H=c.filter(h=>h.alive&&_e(u.pos,h.pos)<=K),y=H.length===0?void 0:H.sort((h,E)=>{let C=h.stunRemaining>0?0:1,N=E.stunRemaining>0?0:1;if(C!==N)return C-N;let A=d.treasuries.find(Se=>Se.structureId===h.targetId),O=d.treasuries.find(Se=>Se.structureId===E.targetId),W=A?_e(h.pos,A.pos):1/0,ue=O?_e(E.pos,O.pos):1/0;return W-ue})[0];y&&(y.hp-=w,u.cooldownRemaining=dn(u.level),y.hp<=0?(y.alive=!1,d.events.push({t:d.tick,type:"arrow_hit",probeId:y.id,archerId:u.structureId,damage:w,hpRemaining:0}),d.events.push({t:d.tick,type:"raider_destroyed",probeId:y.id,pos:{...y.pos}})):d.events.push({t:d.tick,type:"arrow_hit",probeId:y.id,archerId:u.structureId,damage:w,hpRemaining:y.hp}))}for(let u of c){if(!u.alive)continue;if(u.stunRemaining>0){u.stunRemaining--;continue}let K=Le[u.raiderType].speed;for(let w=0;w<K&&u.alive;w++){if(u.raiderType==="brute"){let N=mn(d,u);if(N){if(_e(u.pos,N.pos)===1){ho(d,u,N);break}if(Pr(d,u,N)){let O=d.traps.find(W=>W.pos.x===u.pos.x&&W.pos.y===u.pos.y&&W.cooldownRemaining===0);if(O){u.stunRemaining=Cr(O.level),O.cooldownRemaining=_r(O.level),d.events.push({t:d.tick,type:"raider_stunned",probeId:u.id,pos:{...u.pos},trapId:O.structureId,stunTicks:u.stunRemaining});break}continue}let A=Ir(d,u.pos);if(A){ho(d,u,A);break}}}let H=d.treasuries.find(N=>N.structureId===u.targetId);if(!H||H.storedResources<=0){let N=d.treasuries.filter(A=>A.storedResources>0).sort((A,O)=>{let W=_e(A.pos,u.pos),ue=_e(O.pos,u.pos);return W-ue||A.structureId.localeCompare(O.structureId)})[0];if(!N){u.alive=!1,d.events.push({t:d.tick,type:"raider_destroyed",probeId:u.id,pos:{...u.pos}});break}u.targetId=N.structureId}let y=d.treasuries.find(N=>N.structureId===u.targetId);if(u.pos.x===y.pos.x&&u.pos.y===y.pos.y){let N=cn(o,y.pos),A=Math.max(1,Math.floor(Le[u.raiderType].loot*y.level*(1-N))),O=Math.min(A,y.storedResources);y.storedResources-=O;let W=Math.ceil(O*.4),ue=Math.ceil(O*.35),Se=Math.max(0,O-W-ue),nt={gold:W,wood:ue,stone:Se};u.looted.gold+=W,u.looted.wood+=ue,u.looted.stone+=Se,d.totalLoot.gold+=W,d.totalLoot.wood+=ue,d.totalLoot.stone+=Se,d.events.push({t:d.tick,type:"treasury_breach",structureId:y.structureId,lootTaken:nt});break}let h=jr(u.pos,y.pos,d);if(!h){if(u.raiderType==="scout"){let A=gn(d,u);if(A){ho(d,u,A);break}}let N=Ir(d,u.pos);if(N)ho(d,u,N);else{let A=d.solids.filter(O=>!O.destroyed).sort((O,W)=>_e(O.pos,u.pos)-_e(W.pos,u.pos))[0];A&&Pr(d,u,A)}break}let E={...u.pos};u.pos={...h},d.events.push({t:d.tick,type:"raider_move",probeId:u.id,from:E,to:{...u.pos}});let C=d.traps.find(N=>N.pos.x===u.pos.x&&N.pos.y===u.pos.y&&N.cooldownRemaining===0);if(C){let N=Cr(C.level);u.stunRemaining=N,C.cooldownRemaining=_r(C.level),d.events.push({t:d.tick,type:"raider_stunned",probeId:u.id,pos:{...u.pos},trapId:C.structureId,stunTicks:N});break}}}let z=d.raiders.every(u=>!u.alive||u.stunRemaining>100),U=l.some(u=>u.spawnAtTick>d.tick);if(z&&!U)break}let R=d.treasuries.reduce((c,$)=>c+$.storedResources,0),m=d.treasuries.reduce((c,$)=>c+No($.level),0),p,b=d.totalLoot.gold+d.totalLoot.wood+d.totalLoot.stone;return b===0?p="defense_win":R>0&&b<m*.5?p="partial_breach":p="full_breach",d.events.push({t:d.tick,type:"raid_end",outcome:p}),{tickRateHz:cr,maxTicks:d.tick,events:d.events}}function Bo(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}function hn(e){let t=Object.entries(Zt),o=t.reduce((r,[,a])=>r+a.weight,0),s=e()*o;for(let[r,a]of t)if(s-=a.weight,s<=0)return r;return"gold_nugget"}function Tn(e,t,o){return!!(t.structures.some(s=>s.pos.x===e.x&&s.pos.y===e.y)||o.some(s=>s.pos.x===e.x&&s.pos.y===e.y))}function qr(e,t,o,s){if(e.length>=$o)return e;let r=t.structures.filter(l=>l.kind==="archerTower").length,a=Math.min(r,2),T=1+(s()<.4?1:0),f=Math.min(T+a,$o-e.length),d=[];for(let l=0;l<f;l++){let x=null;for(let k=0;k<30;k++){let R=Math.floor(s()*I),m=Math.floor(s()*I),p={x:R,y:m};if(!Tn(p,t,[...e,...d])){x=p;break}}if(!x)break;d.push({id:`frag-${o}-${l}`,type:hn(s),pos:x,spawnedAtMs:o})}return[...e,...d]}function Ho(e,t,o){let s=e.findIndex(l=>l.pos.x===t.x&&l.pos.y===t.y);if(s===-1)return null;let r=[e[s]],a=o.structures.filter(l=>l.kind==="watchtower"),T=0;for(let l of a)Bo(l.pos,t)<=bt[l.level]&&(T=Math.max(T,l.level));if(T>0)for(let l of e)r.includes(l)||Bo(t,l.pos)<=T&&r.push(l);let f=new Set(r.map(l=>l.id)),d={gold:0,wood:0,stone:0};for(let l of r){let x=Zt[l.type].yield,k=1;o.structures.some(m=>m.kind==="treasury"&&Bo(m.pos,l.pos)<=vr)&&(k+=kr),d={gold:d.gold+Math.ceil(x.gold*k),wood:d.wood+Math.ceil(x.wood*k),stone:d.stone+Math.ceil(x.stone*k)}}return{yield:d,updatedFragments:e.filter(l=>!f.has(l.id)),collected:r}}function zr(e,t){return e.filter(o=>t-o.spawnedAtMs<br)}var Dr=[{level:1,structureCount:4,maxUpgradeLevel:1,probeCount:3},{level:2,structureCount:8,maxUpgradeLevel:1,probeCount:4},{level:3,structureCount:12,maxUpgradeLevel:2,probeCount:5},{level:4,structureCount:16,maxUpgradeLevel:2,probeCount:6},{level:5,structureCount:22,maxUpgradeLevel:3,probeCount:8}];function To(e,t){let o=Dr[Math.max(0,Math.min(t-1,Dr.length-1))],s=Hr(Fr(e)),r=[],a=new Set,T=Math.max(1,Math.floor(o.structureCount/5));for(let R=0;R<T;R++){let m=Lr(s,a);if(!m)break;r.push(kt("treasury",m,vt(s,o.maxUpgradeLevel))),a.add(`${m.x},${m.y}`)}let f=Math.floor(o.structureCount*.35);for(let R=0;R<f;R++){let m=$r(s,a,r);if(!m)break;r.push(kt("wall",m,vt(s,o.maxUpgradeLevel))),a.add(`${m.x},${m.y}`)}let d=Math.floor(o.structureCount*.2);for(let R=0;R<d;R++){let m=xn(s,a);if(!m)break;r.push(kt("trap",m,vt(s,o.maxUpgradeLevel))),a.add(`${m.x},${m.y}`)}let l=Math.max(1,Math.floor(o.structureCount*.15));for(let R=0;R<l;R++){let m=r.filter(c=>c.kind==="treasury"),p=m.length>0?m[Math.floor(s()*m.length)]:void 0;if(!p)break;let b=[{x:p.pos.x-1,y:p.pos.y},{x:p.pos.x+1,y:p.pos.y},{x:p.pos.x,y:p.pos.y-1},{x:p.pos.x,y:p.pos.y+1}].filter(c=>c.x>=0&&c.x<I&&c.y>=0&&c.y<I&&!a.has(`${c.x},${c.y}`));if(b.length>0){let c=b[Math.floor(s()*b.length)];r.push(kt("ward",c,vt(s,o.maxUpgradeLevel))),a.add(`${c.x},${c.y}`)}}let x=Math.max(0,Math.floor(o.structureCount*.1));for(let R=0;R<x;R++){let m=$r(s,a,r);if(!m)break;r.push(kt("archerTower",m,vt(s,o.maxUpgradeLevel))),a.add(`${m.x},${m.y}`)}for(let R=0;R<Er;R++){let m=Lr(s,a);if(!m)break;r.push(kt("vault",m,vt(s,o.maxUpgradeLevel))),a.add(`${m.x},${m.y}`)}let k=o.structureCount-r.length;for(let R=0;R<k;R++){let m=yn(s,a);if(!m)break;r.push(kt("watchtower",m,vt(s,o.maxUpgradeLevel))),a.add(`${m.x},${m.y}`)}return{id:`npc-${e}-${t}`,name:`NPC Keep (Lv.${o.level})`,ownerPlayerId:"npc",grid:{width:16,height:16,structures:r},resources:{...St},createdAtUnixMs:Date.now(),updatedAtUnixMs:Date.now()}}function kt(e,t,o){return{id:`${e}-${t.x}-${t.y}`,kind:e,level:o,pos:{...t},placedAtUnixMs:Date.now()}}function vt(e,t){let o=Math.floor(e()*t)+1;return Math.min(t,o)}function Lr(e,t){for(let o=0;o<50;o++){let s=4+Math.floor(e()*(I-8)),r=4+Math.floor(e()*(I-8));if(!t.has(`${s},${r}`))return{x:s,y:r}}return null}function $r(e,t,o){for(let s=0;s<50;s++){let r=o[Math.floor(e()*o.length)],a=Math.floor(e()*3)-1,T=Math.floor(e()*3)-1,f=r.pos.x+a,d=r.pos.y+T;if(f>=0&&f<I&&d>=0&&d<I&&!t.has(`${f},${d}`))return{x:f,y:d}}return null}function xn(e,t){for(let o=0;o<50;o++){let s=Math.floor(e()*4),r,a;if(s===0?(r=Math.floor(e()*I),a=Math.floor(e()*3)):s===1?(r=Math.floor(e()*I),a=I-1-Math.floor(e()*3)):s===2?(r=Math.floor(e()*3),a=Math.floor(e()*I)):(r=I-1-Math.floor(e()*3),a=Math.floor(e()*I)),!t.has(`${r},${a}`))return{x:r,y:a}}return null}function yn(e,t){for(let o=0;o<50;o++){let s=Math.floor(e()*I),r=Math.floor(e()*I);if(!t.has(`${s},${r}`))return{x:s,y:r}}return null}var Uo=1;function En(){return Zr(vn(),".config","codekeep")}function Vo(){return Zr(En(),"game.json")}function Jr(e){let t=`player-${Date.now()}`;return{schemaVersion:Uo,savedAtUnixMs:Date.now(),player:{id:t,displayName:e,settings:{asciiMode:!1}},keep:{id:`keep-${t}-${Date.now()}`,name:`${e}'s Keep`,ownerPlayerId:t,grid:{width:16,height:16,structures:[]},resources:{...St},createdAtUnixMs:Date.now(),updatedAtUnixMs:Date.now()},raidHistory:[],tutorialCompleted:!1,lastPlayedAtUnixMs:Date.now(),progression:{totalBuildsToday:0,totalCommitsToday:0,lastDailyResetDay:Math.floor(Date.now()/864e5),totalRaidsWon:0,totalRaidsLost:0,totalStructuresPlaced:0,currentWinStreak:0,bestWinStreak:0,achievements:[],totalRaidersKilledByArcher:0}}}function Et(e){let t=Vo(),o=kn(t);Fo(o)||Rn(o,{recursive:!0});let s=t+".tmp",r=JSON.stringify({...e,savedAtUnixMs:Date.now()},null,2);Oo(s,r,"utf-8"),Sn(s,t)}function Gt(){let e=Vo();if(!Fo(e))return null;let t;try{t=wn(e,"utf-8")}catch{return null}let o;try{o=JSON.parse(t)}catch{let s=e+".bak";try{Oo(s,t,"utf-8")}catch{}return process.stderr.write(`[codekeep] Corrupted save backed up to ${s}
3
- `),null}if(o.schemaVersion!==Uo){let s=e+`.v${o.schemaVersion}.bak`;try{Oo(s,t,"utf-8")}catch{}return process.stderr.write(`[codekeep] Save version mismatch (got ${o.schemaVersion}, need ${Uo}), backed up to ${s}
4
- `),null}return o}function Xr(){let e=Vo();if(!Fo(e))return!1;try{return bn(e),!0}catch{return!1}}import{Box as Qr,Text as qe}from"ink";import{jsx as ze,jsxs as es}from"react/jsx-runtime";var An={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"},Cn={wall:"whiteBright",trap:"magentaBright",treasury:"yellowBright",ward:"cyanBright",watchtower:"greenBright",archerTower:"redBright"},_n=Object.fromEntries(Object.entries(Zt).map(([e,t])=>[e,t.color]));function Mn(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}function Yo(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function In(e,t){let o=new Set;if(e.kind==="archerTower"){let s=co[e.level];for(let r=0;r<I;r++)for(let a=0;a<I;a++)Mn(e.pos,{x:a,y:r})<=s&&!(a===e.pos.x&&r===e.pos.y)&&o.add(`${a},${r}`);return{tiles:o,color:"red"}}if(e.kind==="watchtower"){let s=bt[e.level];for(let r=0;r<I;r++)for(let a=0;a<I;a++)Yo(e.pos,{x:a,y:r})<=s&&!(a===e.pos.x&&r===e.pos.y)&&o.add(`${a},${r}`);return{tiles:o,color:"green"}}if(e.kind==="ward"){let s=1,r=t.filter(a=>a.kind==="watchtower");for(let a of r)Yo(e.pos,a.pos)<=1&&(s=Math.max(s,1+bt[a.level]));s=Math.min(s,5);for(let a=0;a<I;a++)for(let T=0;T<I;T++)Yo(e.pos,{x:T,y:a})<=s&&!(T===e.pos.x&&a===e.pos.y)&&o.add(`${T},${a}`);return{tiles:o,color:"cyan"}}return null}function ts({grid:e,cursor:t,asciiMode:o,compact:s,fragments:r=[]}){let a=o?"-":"\u2500",T=o?"|":"\u2502",f=o?"+":"\u250C",d=o?"+":"\u2510",l=o?"+":"\u2514",x=o?"+":"\u2518",k=s?1:2,R=(s?" ":" ")+Array.from({length:I},(u,K)=>s?K.toString(16).toUpperCase():K.toString(16).toUpperCase()+" ").join(""),m=(s?" ":" ")+f+a.repeat(I*k)+d,p=(s?" ":" ")+l+a.repeat(I*k)+x,b=new Map;for(let u of e.structures)b.set(`${u.pos.x},${u.pos.y}`,u);let c=new Map;for(let u of r)c.set(`${u.pos.x},${u.pos.y}`,u);let $=b.get(`${t.x},${t.y}`),z=$?In($,e.structures):null,U=[];for(let u=0;u<I;u++){let K=s?u.toString(16).toUpperCase():" "+u.toString(16).toUpperCase(),w=[];for(let H=0;H<I;H++){let y=t.x===H&&t.y===u,h=b.get(`${H},${u}`),E=`${H},${u}`,C=z?.tiles.has(E)??!1,N,A,O=!1,W=c.get(E);h?(N=fe[h.kind],A=An[h.kind],h.level>=2&&(O=!0),h.level===3&&(A=Cn[h.kind])):W?(N="~",A=_n[W.type]??"cyan",O=!0):(N=Ot,A=void 0);let ue=s?"":h&&h.level>1?String(h.level):" ";y?w.push(ze(qe,{backgroundColor:"white",color:"black",bold:!0,children:N+ue},H)):C&&!h&&!W?w.push(ze(qe,{color:z.color,children:"\u2591"+(s?"":" ")},H)):C&&h?w.push(ze(qe,{color:A,bold:O,backgroundColor:z.color==="red"?"red":void 0,children:N+ue},H)):A?w.push(ze(qe,{color:A,bold:O,children:N+ue},H)):w.push(ze(qe,{dimColor:!0,children:N+(s?"":" ")},H))}U.push(es(Qr,{children:[ze(qe,{dimColor:!0,children:K}),ze(qe,{dimColor:!0,children:T}),w,ze(qe,{dimColor:!0,children:T})]},u))}return es(Qr,{flexDirection:"column",children:[ze(qe,{dimColor:!0,children:R}),ze(qe,{dimColor:!0,children:m}),U,ze(qe,{dimColor:!0,children:p})]})}import{Box as jo,Text as ce}from"ink";import{Fragment as Ln,jsx as ve,jsxs as Ve}from"react/jsx-runtime";var Pn={wall:"WL",trap:"TR",treasury:"TY",ward:"WD",watchtower:"WT",archerTower:"AT"};function Dn(e){let t=[];return e.gold>0&&t.push(`${B.gold}${e.gold}`),e.wood>0&&t.push(`${B.wood}${e.wood}`),e.stone>0&&t.push(`${B.stone}${e.stone}`),t.join(" ")}function os({resources:e,selectedStructure:t,message:o,compact:s,structureAtCursor:r,fragmentCount:a=0,dryRun:T}){if(s){let d=Pn[t];return ve(jo,{flexDirection:"column",marginBottom:0,children:Ve(ce,{children:[ve(ce,{bold:!0,color:"yellow",children:"\u25C6"}),ve(ce,{dimColor:!0,children:" \u2502 "}),Ve(ce,{color:"yellow",children:[B.gold,e.gold]}),ve(ce,{children:" "}),Ve(ce,{color:"green",children:[B.wood,e.wood]}),ve(ce,{children:" "}),Ve(ce,{color:"white",children:[B.stone,e.stone]}),ve(ce,{dimColor:!0,children:" \u2502 "}),ve(ce,{bold:!0,children:d}),o?ve(ce,{dimColor:!0,children:" \u2502 "}):null,o?ve(ce,{color:o.startsWith("!")?"red":"yellow",children:o}):null]})})}let f=r?`${tt[r.kind]} Lv.${r.level}`+(r.level<3?` \u2192 Lv.${r.level+1}: ${Dn(ot[r.kind][r.level+1])}`:" (MAX)"):"";return Ve(jo,{flexDirection:"column",marginBottom:1,children:[Ve(jo,{flexDirection:"row",gap:1,children:[ve(ce,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep"}),T&&ve(ce,{color:"magenta",bold:!0,children:" [DRY RUN]"}),ve(ce,{dimColor:!0,children:"\u2502"}),Ve(ce,{color:"yellow",children:[B.gold," ",e.gold]}),Ve(ce,{color:"green",children:[B.wood," ",e.wood]}),Ve(ce,{color:"white",children:[B.stone," ",e.stone]}),ve(ce,{dimColor:!0,children:"\u2502"}),Ve(ce,{children:["Sel: ",ve(ce,{bold:!0,children:tt[t]})]}),a>0&&Ve(Ln,{children:[ve(ce,{dimColor:!0,children:"\u2502"}),Ve(ce,{color:"cyan",bold:!0,children:["~ ",a," on ground"]})]})]}),ve(ce,{color:o.startsWith("!")?"red":"yellow",children:o||" "}),ve(ce,{dimColor:!0,children:f||" "})]})}import{Box as $n,Text as _}from"ink";import{jsx as F,jsxs as pe}from"react/jsx-runtime";function Wt(e){let t=[];return e.gold>0&&t.push(`${B.gold}${e.gold}`),e.wood>0&&t.push(`${B.wood}${e.wood}`),e.stone>0&&t.push(`${B.stone}${e.stone}`),t.join(" ")}function rs(){let e=Le,t=ot;return pe($n,{flexDirection:"column",padding:1,children:[F(_,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep \u2014 Help"}),F(_,{children:" "}),F(_,{bold:!0,children:"Navigation"}),F(_,{children:" h/j/k/l or WASD or Arrows Move cursor"}),F(_,{children:" g + hex coords + Enter Jump to coordinate (e.g. g 5,3)"}),F(_,{children:" Tab Jump to next structure"}),F(_,{children:" Esc Back to menu"}),F(_,{children:" "}),F(_,{bold:!0,children:"Building"}),pe(_,{children:[" ","[ / ] Cycle structure type"]}),F(_,{children:" 1-6 Select structure by number"}),F(_,{children:" Enter or e Place structure at cursor"}),F(_,{children:" u Upgrade structure (Lv.1\u21922\u21923)"}),F(_,{children:" x Demolish structure (50% refund)"}),F(_,{children:" "}),F(_,{bold:!0,children:"Foraging"}),F(_,{children:" c Collect forage at cursor (~ on the grid)"}),pe(_,{children:[" "," Archer towers improve spawn rate; treasuries improve yield"]}),pe(_,{children:[" "," Watchtowers auto-gather nearby forage"]}),F(_,{children:" "}),F(_,{bold:!0,children:"Combat"}),F(_,{children:" r Quick defend (instant result)"}),F(_,{children:" v View last quick-defend replay"}),F(_,{children:" Defend Keep (menu) Watch raiders assault your grid"}),F(_,{children:" Attack NPC (menu) Raid an NPC keep for loot"}),F(_,{children:" "}),F(_,{bold:!0,children:"Other"}),F(_,{children:" f Kingdom boon (+resources)"}),F(_,{children:" ? Toggle this help (works on any screen)"}),F(_,{children:" q Save and quit"}),F(_,{children:" "}),F(_,{bold:!0,children:"Structures (cost Lv.1 \u2192 Lv.2 \u2192 Lv.3)"}),pe(_,{children:[" ",pe(_,{color:"white",children:["1 ",fe.wall]})," Stone Wall Blocks raiders, has HP ",Wt(t.wall[1])]}),pe(_,{children:[" ",pe(_,{color:"magenta",children:["2 ",fe.trap]})," Bear Trap Stuns raiders on contact ",Wt(t.trap[1])]}),pe(_,{children:[" ",pe(_,{color:"yellow",children:["3 ",fe.treasury]})," Treasury Stores loot, generates income ",Wt(t.treasury[1])]}),pe(_,{children:[" ",pe(_,{color:"cyan",children:["4 ",fe.ward]})," Ward Reduces loot stolen nearby ",Wt(t.ward[1])]}),pe(_,{children:[" ",pe(_,{color:"green",children:["5 ",fe.watchtower]})," Watchtower Extends ward range, auto-gathers ",Wt(t.watchtower[1])]}),pe(_,{children:[" ",pe(_,{color:"redBright",children:["6 ",fe.archerTower]})," Archer Tower Fires arrows at raiders in range ",Wt(t.archerTower[1])]}),F(_,{children:" "}),F(_,{bold:!0,children:"Resources"}),pe(_,{children:[" ",F(_,{color:"yellow",children:B.gold})," Gold Earned from events, foraging, and raids"]}),pe(_,{children:[" ",F(_,{color:"green",children:B.wood})," Wood Earned from treasuries and events"]}),pe(_,{children:[" ",F(_,{color:"white",children:B.stone})," Stone Earned from watchtowers and events"]}),F(_,{children:" Treasuries and watchtowers generate passive income over time."}),F(_,{children:" "}),F(_,{bold:!0,children:"Raider Types"}),pe(_,{children:[" Raider HP ",e.raider.hp,", dmg ",e.raider.damage,", speed ",e.raider.speed," \u2014 standard foot soldier"]}),pe(_,{children:[" Scout HP ",e.scout.hp,", dmg ",e.scout.damage,", speed ",e.scout.speed," \u2014 fast, moves twice per tick"]}),pe(_,{children:[" Brute HP ",e.brute.hp,", dmg ",e.brute.damage,", speed ",e.brute.speed," \u2014 heavy hitter, hard to kill"]}),F(_,{children:" "}),F(_,{bold:!0,children:"Raid Difficulty"}),F(_,{children:" Difficulty scales with total raids completed (Lv.1\u20135)."}),F(_,{children:" Higher levels bring more raiders, scouts, and brutes."}),pe(_,{children:[" Outcomes: ",F(_,{color:"green",children:"Defense Win"})," \xB7 ",F(_,{color:"yellow",children:"Partial Breach"})," \xB7 ",F(_,{color:"red",children:"Full Breach"})]}),F(_,{children:" "}),F(_,{dimColor:!0,children:"Press any key to close"})]})}import{useState as Nn}from"react";import{Box as ss,Text as Ze,useInput as Bn}from"ink";import{jsx as Jt,jsxs as xt}from"react/jsx-runtime";function On(e){let t=[{key:"keep",label:"Build Keep",desc:"Place and upgrade structures",disabled:!1},{key:"defend",label:"Defend Keep",desc:"Watch NPCs attack YOUR defenses",disabled:!1},{key:"attack",label:"Attack NPC",desc:"Raid an NPC keep for resources",disabled:!1}];return e?t.push({key:"pvp",label:"\u2694 PvP Arena",desc:"Fight real players for trophies",disabled:!1}):t.push({key:"pvp-locked",label:"\u2694 PvP Arena",desc:"Coming soon \u2014 use --online to connect",disabled:!0}),t.push({key:"friendRaid",label:"Raid Rival Keep",desc:"Plunder a rival lord's fortress",disabled:!1},{key:"raidLog",label:"Raid Log",desc:"View recent raid history",disabled:!1},{key:"settings",label:"Settings",desc:"Game options and reset",disabled:!1},{key:"quit",label:"Rest for the Night",desc:"Save and exit",disabled:!1}),t}function ns({gameSave:e,onlineMode:t,onKeep:o,onAttack:s,onDefend:r,onFriendRaid:a,onPvp:T,onRaidLog:f,onSettings:d,onQuit:l}){let x=On(!!t),[k,R]=Nn(0);Bn((U,u)=>{if(U==="k"||U==="w"||u.upArrow)R(K=>{let w=K-1;for(;w>=0&&x[w].disabled;)w--;return w>=0?w:K});else if(U==="j"||U==="s"||u.downArrow)R(K=>{let w=K+1;for(;w<x.length&&x[w].disabled;)w++;return w<x.length?w:K});else if(u.return){let K=x[k];if(K.disabled)return;K.key==="keep"?o():K.key==="defend"?r():K.key==="attack"?s():K.key==="pvp"?T?.():K.key==="friendRaid"?a():K.key==="raidLog"?f():K.key==="settings"?d():K.key==="quit"&&l()}else U==="q"&&l()});let m=e.keep.grid.structures.length,p=e.progression,b=p.totalRaidsWon+p.totalRaidsLost,c=Math.max(1,Math.floor((Date.now()-e.keep.createdAtUnixMs)/864e5)),$=e.keep.grid.structures.filter(U=>U.kind==="treasury").length,z=e.keep.grid.structures.filter(U=>U.kind==="archerTower").length;return xt(ss,{flexDirection:"column",padding:1,children:[Jt(Ze,{bold:!0,color:"yellow",children:`
2
+ import{Command as el}from"commander";import{render as tl}from"ink";import{useState as Ce,useCallback as ao,useEffect as ji,useRef as Wn}from"react";import{Box as Mt,Text as ae,useApp as qi,useInput as zi,useStdout as Xi}from"ink";var W={gold:"\u25CF",wood:"\u2663",stone:"\u25A0"};var I=16,es=8,ts=2400;var kt={gold:80,wood:40,stone:20},Co={gold:200,wood:120,stone:80},ye={wall:"#",trap:"%",treasury:"$",ward:"@",watchtower:"^",archerTower:"!",vault:"&"},Je={wall:"Stone Wall",trap:"Bear Trap",treasury:"Treasury",ward:"Ward",watchtower:"Watchtower",archerTower:"Archer Tower",vault:"Vault"},yt="\xB7",wt={wall:{1:{gold:12,wood:0,stone:2},2:{gold:10,wood:0,stone:4},3:{gold:14,wood:0,stone:6}},trap:{1:{gold:8,wood:4,stone:6},2:{gold:8,wood:4,stone:6},3:{gold:10,wood:6,stone:8}},treasury:{1:{gold:6,wood:14,stone:2},2:{gold:6,wood:18,stone:4},3:{gold:8,wood:24,stone:6}},ward:{1:{gold:10,wood:10,stone:0},2:{gold:12,wood:12,stone:0},3:{gold:16,wood:16,stone:0}},watchtower:{1:{gold:6,wood:2,stone:12},2:{gold:6,wood:4,stone:14},3:{gold:8,wood:6,stone:18}},archerTower:{1:{gold:14,wood:6,stone:8},2:{gold:16,wood:8,stone:10},3:{gold:20,wood:12,stone:14}},vault:{1:{gold:20,wood:20,stone:15},2:{gold:35,wood:35,stone:25},3:{gold:55,wood:55,stone:40}}},Eo={1:40,2:70,3:110},Ao={1:25,2:40,3:60},Mo={1:20,2:35,3:50},os={1:4,2:6,3:9},rs={1:16,2:12,3:8},ss={1:80,2:160,3:280},ns={1:.15,2:.28,3:.4},Ot={1:1,2:2,3:3},as={1:4,2:7,3:10},_o={1:2,2:2,3:3},is={1:4,2:3,3:2};var Qe={raider:{hp:30,damage:8,loot:3,speed:1},scout:{hp:14,damage:4,loot:2,speed:2},brute:{hp:55,damage:14,loot:5,speed:1}},ls=6e4,Io={gold:2,wood:4,stone:1},Po={gold:1,wood:0,stone:3},Do={build_success:{gold:12,wood:0,stone:4},tests_pass:{gold:0,wood:8,stone:4},git_commit:{gold:5,wood:5,stone:10},session_reward:{gold:8,wood:3,stone:6},daily_login:{gold:5,wood:5,stone:10}},ds={build_success:"Miners returned",tests_pass:"Harvest complete",git_commit:"Trade caravan arrived",session_reward:"Tax collection",daily_login:"Morning tribute"},io=9e5,cs=5,zt=6,us=.5,lo=[{id:"first_structure",name:"Builder",desc:"Place your first structure",bonus:"+20 gold"},{id:"defense_win_5",name:"Warden",desc:"Win 5 defense raids",bonus:"+25 gold, +15 wood, +15 stone"},{id:"win_streak_3",name:"Rallying Cry",desc:"Achieve a 3-win streak",bonus:"+10 all resources"},{id:"win_streak_5",name:"Unstoppable",desc:"Achieve a 5-win streak",bonus:"+30 all resources"},{id:"all_types",name:"Master Builder",desc:"Place every structure type",bonus:"+15 all resources"},{id:"max_level",name:"Fortifier",desc:"Upgrade a structure to Level 3",bonus:"+20 gold, +10 stone"},{id:"archer_kills_10",name:"Marksman",desc:"Kill 10 raiders with archers",bonus:"+20 gold, +10 wood, +10 stone"},{id:"structures_20",name:"Architect",desc:"Place 20 structures total",bonus:"+10 all resources"},{id:"raids_10",name:"Veteran",desc:"Complete 10 raids",bonus:"+15 all resources"},{id:"hoarder",name:"Treasure Keeper",desc:"Hold 500+ total resources",bonus:"+25 gold"}],co={gold_nugget:{symbol:"~",color:"cyan",yield:{gold:4,wood:0,stone:0},weight:35},timber:{symbol:"~",color:"yellow",yield:{gold:0,wood:4,stone:0},weight:35},ore:{symbol:"~",color:"green",yield:{gold:0,wood:0,stone:4},weight:20},gem:{symbol:"~",color:"white",yield:{gold:2,wood:2,stone:2},weight:10}},Sr=6,ps=35e3,fs=18e4,ms=.25,gs=2,qe=["wall","trap","treasury","ward","watchtower","archerTower","vault"],Lo={1:60,2:90,3:130},$o={1:{gold:50,wood:30,stone:20},2:{gold:100,wood:60,stone:40},3:{gold:180,wood:110,stone:75}},br=1;var sl={defense_win:7200*1e3,partial_breach:14400*1e3,full_breach:480*60*1e3},Bo={raider:{gold:8,wood:4,stone:2},scout:{gold:6,wood:6,stone:0},brute:{gold:15,wood:8,stone:8}},hs={raider:120*1e3,scout:120*1e3,brute:300*1e3};var nl=1440*60*1e3,al=2880*60*1e3,il=672*60*60*1e3;var xs=[{id:"fog_of_war",name:"Fog of War",description:"Watchtower range halved",icon:"\u{1F32B}",modifiers:{watchtowerRangeMult:.5}},{id:"speed_raid",name:"Speed Raid",description:"Raiders move 50% faster",icon:"\u26A1",modifiers:{raiderSpeedMult:1.5}},{id:"fortified",name:"Fortified",description:"Raiders have +40% HP, double loot",icon:"\u{1F6E1}",modifiers:{raiderHpMult:1.4,lootMult:2}},{id:"swarm",name:"Swarm",description:"+50% raiders, \u221230% HP each",icon:"\u{1F41D}",modifiers:{raiderCountMult:1.5,raiderHpMult:.7}},{id:"piercing",name:"Piercing",description:"Ward mitigation halved",icon:"\u{1F5E1}",modifiers:{wardMitigationMult:.5}},{id:"siege",name:"Siege",description:"Double brute chance",icon:"\u{1F3F0}",modifiers:{bruteChanceMult:2}},{id:"flanking",name:"Flanking",description:"All raiders from one edge",icon:"\u27A1",modifiers:{singleEdge:!0}},{id:"ironwall",name:"Iron Wall",description:"Walls have +50% HP",icon:"\u{1F9F1}",modifiers:{wallHpMult:1.5}},{id:"sharpshooter",name:"Sharpshooter",description:"Archers deal +30% damage",icon:"\u{1F3AF}",modifiers:{archerDamageMult:1.3}},{id:"sticky_traps",name:"Sticky Traps",description:"Traps stun 50% longer",icon:"\u{1F578}",modifiers:{trapStunMult:1.5}}],Ts=2,ys=6,ws=[{id:"wall_fortify",name:"Fortified Walls",raidsRemaining:3,modifiers:{wallHpMult:1.25}},{id:"archer_focus",name:"Archer Focus",raidsRemaining:3,modifiers:{archerDamageMult:1.2}},{id:"trap_mastery",name:"Trap Mastery",raidsRemaining:3,modifiers:{trapStunMult:1.3}},{id:"ward_power",name:"Ward Power",raidsRemaining:3,modifiers:{wardMitigationMult:1.3}},{id:"scout_shield",name:"Scout Shield",raidsRemaining:2,modifiers:{wallHpMult:1.4,archerDamageMult:1.15}}],Xt=[{id:"starting_resources_boost",name:"War Chest",description:"Start with 2x resources",ascensionLevel:1},{id:"structures_lv2",name:"Veteran Builder",description:"New structures start at Lv.2",ascensionLevel:2},{id:"extra_faucet",name:"Deep Wells",description:"+3 faucet uses before diminishing",ascensionLevel:3},{id:"passive_income_boost",name:"Trade Routes",description:"+50% passive income",ascensionLevel:4},{id:"anomaly_choice",name:"Oracle",description:"Choose from 2 anomalies before each raid (coming soon)",ascensionLevel:5}],Zt=50,ll=336*60*60*1e3,dl=2880*60*1e3;var cl=720*60*1e3;import{writeFileSync as Er,readFileSync as Ea,mkdirSync as Aa,existsSync as Lr,renameSync as Ma,unlinkSync as _a}from"fs";import{join as Ws,dirname as Ia}from"path";import{homedir as Pa}from"os";function ea(e){return e.x>=0&&e.x<I&&e.y>=0&&e.y<I}function Mr(e,t){return e.structures.find(o=>o.pos.x===t.x&&o.pos.y===t.y)}function ta(e,t,o){return ea(t)?Mr(e,t)?{ok:!1,reason:"Cell is occupied"}:{ok:!0}:{ok:!1,reason:"Out of bounds"}}function _s(e,t){return e.gold>=t.gold&&e.wood>=t.wood&&e.stone>=t.stone}function Oo(e,t,o,s){let r=ta(e.grid,t,o);if(!r.ok)return{ok:!1,reason:r.reason};let n=wt[o][1];if(!_s(e.resources,n))return{ok:!1,reason:Is(e.resources,n)};let c=s?.startingLevel??1,d={id:`${o}-${t.x}-${t.y}-${Date.now()}`,kind:o,level:c,pos:{...t},placedAtUnixMs:Date.now()};return{ok:!0,keep:{...e,resources:Ps(e.resources,n),grid:{...e.grid,structures:[...e.grid.structures,d]},updatedAtUnixMs:Date.now()}}}function Uo(e,t){let o=Mr(e.grid,t);if(!o)return{ok:!1,reason:"No structure at this position"};if(o.level>=3)return{ok:!1,reason:"Already at max level"};let s=o.level+1,r=wt[o.kind][s];if(!_s(e.resources,r))return{ok:!1,reason:Is(e.resources,r)};let n={...o,level:s};return{ok:!0,keep:{...e,resources:Ps(e.resources,r),grid:{...e.grid,structures:e.grid.structures.map(c=>c.id===o.id?n:c)},updatedAtUnixMs:Date.now()}}}function Go(e,t){let o=Mr(e.grid,t);if(!o)return{ok:!1,reason:"No structure at this position"};let s=oa(o);return{ok:!0,keep:{...e,resources:He(e.resources,s),grid:{...e.grid,structures:e.grid.structures.filter(r=>r.id!==o.id)},updatedAtUnixMs:Date.now()}}}function oa(e){let t=0,o=0,s=0;for(let r=1;r<=e.level;r++){let n=wt[e.kind][r];t+=n.gold,o+=n.wood,s+=n.stone}return{gold:Math.floor(t*.5),wood:Math.floor(o*.5),stone:Math.floor(s*.5)}}function Is(e,t){let o=[];return t.gold>e.gold&&o.push(`${t.gold-e.gold} more gold`),t.wood>e.wood&&o.push(`${t.wood-e.wood} more wood`),t.stone>e.stone&&o.push(`${t.stone-e.stone} more stone`),o.length>0?`Need ${o.join(", ")}`:"Not enough resources"}function Ps(e,t){return{gold:e.gold-t.gold,wood:e.wood-t.wood,stone:e.stone-t.stone}}function He(e,t){return{gold:e.gold+t.gold,wood:e.wood+t.wood,stone:e.stone+t.stone}}function _r(e,t){let o=t.grants??Do[t.type]??{gold:0,wood:0,stone:0},s=He(e.resources,o);return{...e,resources:nt(s),updatedAtUnixMs:Date.now()}}function nt(e){return{gold:Math.min(e.gold,Co.gold*10),wood:Math.min(e.wood,Co.wood*10),stone:Math.min(e.stone,Co.stone*10)}}function Ir(e,t){let o=Math.min(Math.floor(t/ls),60),s=e.structures.filter(d=>d.kind==="treasury"),r=e.structures.filter(d=>d.kind==="watchtower"),n=s.reduce((d,g)=>d+g.level,0),c=r.reduce((d,g)=>d+g.level,0);return{gold:o*(n*Io.gold+c*Po.gold),wood:o*(n*Io.wood+c*Po.wood),stone:o*(n*Io.stone+c*Po.stone)}}function Ds(){let e=["build_success","tests_pass","git_commit","session_reward"],t=e[Math.floor(Math.random()*e.length)];return{type:t,timestamp:Date.now(),grants:Do[t]}}function ra(e){return Eo[e]}function sa(e){return Ao[e]}function na(e){return Mo[e]}function aa(e){return Lo[e]}function Rs(e){return os[e]}function Ss(e){return rs[e]}function kr(e){return ss[e]}function ia(e){return ns[e]}function la(e){return Ot[e]}function da(e){return as[e]}function ca(e){return _o[e]}function ua(e){return is[e]}function bs(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function De(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}function pa(e,t,o=1){let s=e.structures.filter(c=>c.kind==="ward"),r=e.structures.filter(c=>c.kind==="watchtower"),n=0;for(let c of s){let d=1;for(let g of r)bs(c.pos,g.pos)<=1&&(d=Math.max(d,1+Math.floor(la(g.level)*o)));bs(c.pos,t)<=d&&(n=Math.max(n,ia(c.level)))}return n}function vr(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function Pr(e){let t=[],o=e.structures,s=o.filter(u=>u.kind==="trap"),r=o.filter(u=>u.kind==="archerTower"),n=o.filter(u=>u.kind==="wall"),c=o.filter(u=>u.kind==="ward"),d=o.filter(u=>u.kind==="treasury"),g=o.filter(u=>u.kind==="watchtower");for(let u of s)for(let i of r)if(vr(u.pos,i.pos)<=1){let y=t.find(w=>w.id==="killbox"&&w.affectedStructureIds.includes(i.id));y?y.affectedStructureIds.includes(u.id)||y.affectedStructureIds.push(u.id):t.push({id:"killbox",name:"Killbox",affectedStructureIds:[u.id,i.id]})}let l=new Set(n.map(u=>`${u.pos.x},${u.pos.y}`)),T=new Map(n.map(u=>[`${u.pos.x},${u.pos.y}`,u])),R=new Set;for(let u of n){if(R.has(u.id))continue;let i=[u];for(let w=1;l.has(`${u.pos.x+w},${u.pos.y}`);w++)i.push(T.get(`${u.pos.x+w},${u.pos.y}`));if(i.length>=3){let w=i.map(h=>h.id);w.forEach(h=>R.add(h)),t.push({id:"fortress",name:"Fortress",affectedStructureIds:w})}let y=[u];for(let w=1;l.has(`${u.pos.x},${u.pos.y+w}`);w++)y.push(T.get(`${u.pos.x},${u.pos.y+w}`));if(y.length>=3){let w=y.map(h=>h.id);w.forEach(h=>R.add(h)),t.push({id:"fortress",name:"Fortress",affectedStructureIds:w})}}for(let u of c){let i=d.filter(w=>vr(u.pos,w.pos)<=1),y=g.filter(w=>vr(u.pos,w.pos)<=1);if(i.length>0&&y.length>0){let w=[u.id,...i.map(h=>h.id),...y.map(h=>h.id)];t.push({id:"sanctum",name:"Sanctum",affectedStructureIds:[...new Set(w)]})}}for(let u=0;u<s.length;u++){let i=s.filter((y,w)=>w!==u&&De(s[u].pos,y.pos)<=3);if(i.length>=1){let y=[s[u].id,...i.map(x=>x.id)],w=[...new Set(y)].sort(),h=w.join(",");t.some(x=>x.id==="gauntlet"&&x.affectedStructureIds.sort().join(",")===h)||t.push({id:"gauntlet",name:"Gauntlet",affectedStructureIds:w})}}return t}function Wo(e){let t=e|0;return()=>{t=t+1831565813|0;let o=Math.imul(t^t>>>15,1|t);return o=o+Math.imul(o^o>>>7,61|o)^o,((o^o>>>14)>>>0)/4294967296}}function It(e){let t=0;for(let o=0;o<e.length;o++){let s=e.charCodeAt(o);t=(t<<5)-t+s|0}return t}function fa(e,t){switch(e){case"N":return{x:t,y:0};case"S":return{x:t,y:I-1};case"E":return{x:I-1,y:t};case"W":return{x:0,y:t}}}function Ls(e,t){return t.x<0||t.x>=I||t.y<0||t.y>=I?!1:e.grid[t.y][t.x]}function $s(e){for(let t=0;t<I;t++)for(let o=0;o<I;o++)e.grid[t][o]=!0;for(let t of e.solids)t.destroyed||(e.grid[t.pos.y][t.pos.x]=!1)}function Bs(e,t,o){if(e.x===t.x&&e.y===t.y)return null;let s=l=>`${l.x},${l.y}`,r=new Map,n=new Set,c=l=>Math.abs(l.x-t.x)+Math.abs(l.y-t.y),d=s(e);r.set(d,{pos:e,g:0,f:c(e),parent:null});let g=new Map;for(;r.size>0;){let l="",T=1/0;for(let[i,y]of r)y.f<T&&(T=y.f,l=i);let R=r.get(l);if(r.delete(l),R.pos.x===t.x&&R.pos.y===t.y){let i=s(t),y=g.get(i);for(;y&&y!==d;)i=y,y=g.get(i);let[w,h]=i.split(",").map(Number);return{x:w,y:h}}n.add(l);let u=[{x:R.pos.x-1,y:R.pos.y},{x:R.pos.x+1,y:R.pos.y},{x:R.pos.x,y:R.pos.y-1},{x:R.pos.x,y:R.pos.y+1}];for(let i of u){let y=s(i);if(n.has(y)||!Ls(o,i)&&!(i.x===t.x&&i.y===t.y))continue;let w=R.g+1,h=r.get(y);h&&w>=h.g||(g.set(y,l),r.set(y,{pos:i,g:w,f:w+c(i),parent:l}))}}return null}function ma(e,t){switch(e){case"wall":return ra(t);case"archerTower":return sa(t);case"watchtower":return na(t);case"vault":return aa(t);default:return 0}}var ga=["archerTower","watchtower"];function ks(e,t){return e.solids.find(o=>!o.destroyed&&De(o.pos,t)===1)}function No(e,t,o,s=1){o.hp-=Math.floor(Qe[t.raiderType].damage*s);let r=o.hp<=0;if(r){o.destroyed=!0,$s(e);let n=e.archers.find(c=>c.structureId===o.structureId);n&&(n.destroyed=!0)}o.kind==="wall"?e.events.push({t:e.tick,type:"wall_damaged",structureId:o.structureId,hpRemaining:Math.max(0,o.hp),destroyed:r}):e.events.push({t:e.tick,type:"structure_damaged",structureId:o.structureId,structureKind:o.kind,hpRemaining:Math.max(0,o.hp),destroyed:r})}function vs(e,t,o){let r=[{x:o.pos.x-1,y:o.pos.y},{x:o.pos.x+1,y:o.pos.y},{x:o.pos.x,y:o.pos.y-1},{x:o.pos.x,y:o.pos.y+1}].filter(d=>Ls(e,d)).sort((d,g)=>{let l=De(d,t.pos),T=De(g,t.pos);return l-T})[0];if(!r||De(t.pos,r)===0)return!1;let n=Bs(t.pos,r,e);if(!n)return!1;let c={...t.pos};return t.pos={...n},e.events.push({t:e.tick,type:"raider_move",probeId:t.id,from:c,to:{...t.pos}}),!0}function ha(e,t){return e.solids.filter(s=>!s.destroyed&&ga.includes(s.kind)).sort((s,r)=>{let n=s.kind==="archerTower"?0:1,c=r.kind==="archerTower"?0:1;return n!==c?n-c:De(s.pos,t.pos)-De(r.pos,t.pos)})[0]??null}function xa(e,t){let o=e.solids.filter(s=>!s.destroyed&&De(s.pos,t.pos)===1);return o.length===0?null:o.sort((s,r)=>s.hp-r.hp)[0]}function Fe(e,t){let o=e[t];return typeof o=="number"?o:1}function ut(e){let t=Wo(It(e.seed)),{keepGrid:o}=e,s=e.modifiers??{},r=["wall","archerTower","watchtower","vault"],n=o.structures.filter(m=>r.includes(m.kind)).sort((m,P)=>m.id.localeCompare(P.id)).map(m=>{let P=ma(m.kind,m.level);return m.kind==="wall"&&(P=Math.floor(P*Fe(s,"wallHpMult"))),{structureId:m.id,kind:m.kind,pos:{...m.pos},hp:P,destroyed:!1}}),c=o.structures.filter(m=>m.kind==="trap").sort((m,P)=>m.id.localeCompare(P.id)).map(m=>({structureId:m.id,pos:{...m.pos},level:m.level,cooldownRemaining:0})),d=o.structures.filter(m=>m.kind==="archerTower").sort((m,P)=>m.id.localeCompare(P.id)).map(m=>({structureId:m.id,pos:{...m.pos},level:m.level,cooldownRemaining:0,destroyed:!1})),l=o.structures.filter(m=>m.kind==="vault").reduce((m,P)=>m+$o[P.level].gold+$o[P.level].wood+$o[P.level].stone,0),T=o.structures.filter(m=>m.kind==="treasury"),R=T.length>0?Math.floor(l/T.length):0,u=T.sort((m,P)=>m.id.localeCompare(P.id)).map(m=>({structureId:m.id,pos:{...m.pos},level:m.level,storedResources:Math.max(0,kr(m.level)-R)}));u.length===0&&(u=[{structureId:"__virtual_center_treasury",pos:{x:8,y:8},level:1,storedResources:kr(1)}]);let i={tick:0,raiders:[],solids:n,traps:c,archers:d,treasuries:u,events:[],grid:Array.from({length:I},()=>Array(I).fill(!0)),totalLoot:{gold:0,wood:0,stone:0}};$s(i);let y=Pr(o),w=new Set(y.filter(m=>m.id==="killbox").flatMap(m=>m.affectedStructureIds)),h=new Set(y.filter(m=>m.id==="gauntlet").flatMap(m=>m.affectedStructureIds)),x=new Set(y.filter(m=>m.id==="fortress").flatMap(m=>m.affectedStructureIds));for(let m of i.solids)m.kind==="wall"&&x.has(m.structureId)&&(m.hp=Math.floor(m.hp*1.25));let _=[],j=["N","S","E","W"],K=s.singleEdge?j[Math.floor(t()*j.length)]:null,N=Math.round(e.probeCount*Fe(s,"raiderCountMult"));for(let m=0;m<N;m++){let P=e.spawnSpecs?.[m],Y=K??P?.edge??j[Math.floor(t()*j.length)],se=P?.offset??Math.floor(t()*I),v=P?.raiderType??e.probeTypes?.[m%(e.probeTypes?.length||1)]??"raider",oe=P?.waveDelay??0;_.push({id:m,edge:Y,offset:se,raiderType:v,spawnAtTick:oe})}function $(m,P){let Y=fa(m.edge,m.offset),se=null,v=1/0;for(let fe of u){let be=De(fe.pos,Y);be<v&&(v=be,se=fe)}let oe=Math.floor(Qe[m.raiderType].hp*Fe(s,"raiderHpMult"));i.raiders.push({id:m.id,pos:{...Y},hp:oe,raiderType:m.raiderType,stunRemaining:0,targetId:se?.structureId??null,alive:!0,looted:{gold:0,wood:0,stone:0}}),i.events.push({t:P,type:"raider_spawn",probeId:m.id,edge:m.edge,pos:{...Y},raiderType:m.raiderType,maxHp:oe})}for(let m of _)m.spawnAtTick===0&&$(m,0);for(;i.tick<ts;){i.tick++;for(let v of _)v.spawnAtTick===i.tick&&$(v,i.tick);for(let v of i.traps)v.cooldownRemaining>0&&v.cooldownRemaining--;for(let v of i.archers)v.cooldownRemaining>0&&v.cooldownRemaining--;let m=i.raiders.filter(v=>v.alive).sort((v,oe)=>v.id-oe.id),P=_.some(v=>v.spawnAtTick>i.tick);if(m.length===0&&!P)break;for(let v of i.archers){if(v.destroyed||v.cooldownRemaining>0)continue;let oe=Math.floor(ca(v.level)*Fe(s,"archerRangeMult")),fe=Math.floor(da(v.level)*Fe(s,"archerDamageMult")),be=m.filter(Te=>Te.alive&&De(v.pos,Te.pos)<=oe),me=be.length===0?void 0:be.sort((Te,Ve)=>{let C=Te.stunRemaining>0?1:0,B=Ve.stunRemaining>0?1:0;if(C!==B)return C-B;let E=i.treasuries.find(H=>H.structureId===Te.targetId),F=i.treasuries.find(H=>H.structureId===Ve.targetId),D=E?De(Te.pos,E.pos):1/0,q=F?De(Ve.pos,F.pos):1/0;return D-q})[0];if(me){let Te=fe;w.has(v.structureId)&&me.stunRemaining>0&&(Te=Math.floor(fe*1.3)),me.hp-=Te,v.cooldownRemaining=ua(v.level),me.hp<=0?(me.alive=!1,i.events.push({t:i.tick,type:"arrow_hit",probeId:me.id,archerId:v.structureId,damage:Te,hpRemaining:0}),i.events.push({t:i.tick,type:"raider_destroyed",probeId:me.id,pos:{...me.pos}})):i.events.push({t:i.tick,type:"arrow_hit",probeId:me.id,archerId:v.structureId,damage:Te,hpRemaining:me.hp})}}for(let v of m){if(!v.alive)continue;if(v.stunRemaining>0){v.stunRemaining--;continue}let oe=Math.max(1,Math.round(Qe[v.raiderType].speed*Fe(s,"raiderSpeedMult")));for(let fe=0;fe<oe&&v.alive;fe++){if(v.raiderType==="brute"){let B=ha(i,v);if(B){if(De(v.pos,B.pos)===1){No(i,v,B,Fe(s,"raiderDamageMult"));break}if(vs(i,v,B)){let F=i.traps.find(D=>D.pos.x===v.pos.x&&D.pos.y===v.pos.y&&D.cooldownRemaining===0);if(F){let D=Math.floor(Rs(F.level)*Fe(s,"trapStunMult"));v.stunRemaining=h.has(F.structureId)?D+2:D,F.cooldownRemaining=Ss(F.level),i.events.push({t:i.tick,type:"raider_stunned",probeId:v.id,pos:{...v.pos},trapId:F.structureId,stunTicks:v.stunRemaining});break}continue}let E=ks(i,v.pos);if(E){No(i,v,E,Fe(s,"raiderDamageMult"));break}}}let be=i.treasuries.find(B=>B.structureId===v.targetId);if(!be||be.storedResources<=0){let B=i.treasuries.filter(E=>E.storedResources>0).sort((E,F)=>{let D=De(E.pos,v.pos),q=De(F.pos,v.pos);return D-q||E.structureId.localeCompare(F.structureId)})[0];if(!B){v.alive=!1,i.events.push({t:i.tick,type:"raider_destroyed",probeId:v.id,pos:{...v.pos}});break}v.targetId=B.structureId}let me=i.treasuries.find(B=>B.structureId===v.targetId);if(v.pos.x===me.pos.x&&v.pos.y===me.pos.y){let B=pa(o,me.pos,Fe(s,"watchtowerRangeMult")),E=Math.min(1,B*Fe(s,"wardMitigationMult")),F=Math.max(1,Math.floor(Qe[v.raiderType].loot*me.level*(1-E)*Fe(s,"lootMult"))),D=Math.min(F,me.storedResources);me.storedResources-=D;let q=Math.ceil(D*.4),H=Math.ceil(D*.35),Z=Math.max(0,D-q-H),Ee={gold:q,wood:H,stone:Z};v.looted.gold+=q,v.looted.wood+=H,v.looted.stone+=Z,i.totalLoot.gold+=q,i.totalLoot.wood+=H,i.totalLoot.stone+=Z,i.events.push({t:i.tick,type:"treasury_breach",structureId:me.structureId,lootTaken:Ee});break}let Te=Bs(v.pos,me.pos,i);if(!Te){if(v.raiderType==="scout"){let E=xa(i,v);if(E){No(i,v,E,Fe(s,"raiderDamageMult"));break}}let B=ks(i,v.pos);if(B)No(i,v,B,Fe(s,"raiderDamageMult"));else{let E=i.solids.filter(F=>!F.destroyed).sort((F,D)=>De(F.pos,v.pos)-De(D.pos,v.pos))[0];E&&vs(i,v,E)}break}let Ve={...v.pos};v.pos={...Te},i.events.push({t:i.tick,type:"raider_move",probeId:v.id,from:Ve,to:{...v.pos}});let C=i.traps.find(B=>B.pos.x===v.pos.x&&B.pos.y===v.pos.y&&B.cooldownRemaining===0);if(C){let B=Math.floor(Rs(C.level)*Fe(s,"trapStunMult")),E=h.has(C.structureId)?B+2:B;v.stunRemaining=E,C.cooldownRemaining=Ss(C.level),i.events.push({t:i.tick,type:"raider_stunned",probeId:v.id,pos:{...v.pos},trapId:C.structureId,stunTicks:E});break}}}let Y=i.raiders.every(v=>!v.alive||v.stunRemaining>100),se=_.some(v=>v.spawnAtTick>i.tick);if(Y&&!se)break}let U=i.treasuries.reduce((m,P)=>m+P.storedResources,0),k=i.treasuries.reduce((m,P)=>m+kr(P.level),0),b,L=i.totalLoot.gold+i.totalLoot.wood+i.totalLoot.stone;return L===0?b="defense_win":U>0&&L<k*.5?b="partial_breach":b="full_breach",i.events.push({t:i.tick,type:"raid_end",outcome:b}),{tickRateHz:es,maxTicks:i.tick,events:i.events}}function Cr(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}function Ta(e){let t=Object.entries(co),o=t.reduce((r,[,n])=>r+n.weight,0),s=e()*o;for(let[r,n]of t)if(s-=n.weight,s<=0)return r;return"gold_nugget"}function ya(e,t,o){return!!(t.structures.some(s=>s.pos.x===e.x&&s.pos.y===e.y)||o.some(s=>s.pos.x===e.x&&s.pos.y===e.y))}function Ns(e,t,o,s){if(e.length>=Sr)return e;let r=t.structures.filter(l=>l.kind==="archerTower").length,n=Math.min(r,2),c=1+(s()<.4?1:0),d=Math.min(c+n,Sr-e.length),g=[];for(let l=0;l<d;l++){let T=null;for(let R=0;R<30;R++){let u=Math.floor(s()*I),i=Math.floor(s()*I),y={x:u,y:i};if(!ya(y,t,[...e,...g])){T=y;break}}if(!T)break;g.push({id:`frag-${o}-${l}`,type:Ta(s),pos:T,spawnedAtMs:o})}return[...e,...g]}function Dr(e,t,o){let s=e.findIndex(l=>l.pos.x===t.x&&l.pos.y===t.y);if(s===-1)return null;let r=[e[s]],n=o.structures.filter(l=>l.kind==="watchtower"),c=0;for(let l of n)Cr(l.pos,t)<=Ot[l.level]&&(c=Math.max(c,l.level));if(c>0)for(let l of e)r.includes(l)||Cr(t,l.pos)<=c&&r.push(l);let d=new Set(r.map(l=>l.id)),g={gold:0,wood:0,stone:0};for(let l of r){let T=co[l.type].yield,R=1;o.structures.some(i=>i.kind==="treasury"&&Cr(i.pos,l.pos)<=gs)&&(R+=ms),g={gold:g.gold+Math.ceil(T.gold*R),wood:g.wood+Math.ceil(T.wood*R),stone:g.stone+Math.ceil(T.stone*R)}}return{yield:g,updatedFragments:e.filter(l=>!d.has(l.id)),collected:r}}function Os(e,t){return e.filter(o=>t-o.spawnedAtMs<fs)}function Us(e){let t=e.progression.totalRaidsWon;return t<Zt?{eligible:!1,reason:`Need ${Zt} raid wins (have ${t})`}:{eligible:!0}}function wa(e){return e.prestige?.ascensionLevel??0}function Ra(e){return Xt.filter(t=>t.ascensionLevel<=e).map(t=>t.id)}function Ko(e,t){let o=wa(e);return Xt.some(s=>s.id===t&&s.ascensionLevel<=o)}function Gs(e){let t=e.prestige??{ascensionLevel:0,permanentUnlocks:[],lifetimeRaidsWon:0,lifetimeRaidsLost:0,lifetimeBestStreak:0},o=t.ascensionLevel+1,s=Ra(o),r={...kt};return s.includes("starting_resources_boost")&&(r={gold:r.gold*2,wood:r.wood*2,stone:r.stone*2}),{...e,keep:{...e.keep,grid:{width:16,height:16,structures:[]},resources:r},raidHistory:[],progression:{totalBuildsToday:0,totalCommitsToday:0,lastDailyResetDay:e.progression.lastDailyResetDay,totalRaidsWon:0,totalRaidsLost:0,totalStructuresPlaced:0,currentWinStreak:0,bestWinStreak:0,achievements:e.progression.achievements,totalRaidersKilledByArcher:0,dailyChallenges:e.progression.dailyChallenges},activeBuffs:[],prestige:{ascensionLevel:o,permanentUnlocks:s,lifetimeRaidsWon:t.lifetimeRaidsWon+e.progression.totalRaidsWon,lifetimeRaidsLost:t.lifetimeRaidsLost+e.progression.totalRaidsLost,lifetimeBestStreak:Math.max(t.lifetimeBestStreak,e.progression.bestWinStreak)},savedAtUnixMs:Date.now()}}var Cs=[{level:1,structureCount:4,maxUpgradeLevel:1,probeCount:3},{level:2,structureCount:8,maxUpgradeLevel:1,probeCount:4},{level:3,structureCount:12,maxUpgradeLevel:2,probeCount:5},{level:4,structureCount:16,maxUpgradeLevel:2,probeCount:6},{level:5,structureCount:22,maxUpgradeLevel:3,probeCount:8},{level:6,structureCount:26,maxUpgradeLevel:3,probeCount:9},{level:7,structureCount:30,maxUpgradeLevel:3,probeCount:10},{level:8,structureCount:34,maxUpgradeLevel:3,probeCount:11},{level:9,structureCount:38,maxUpgradeLevel:3,probeCount:12},{level:10,structureCount:42,maxUpgradeLevel:3,probeCount:13}],Sa={maze:"Maze",sniper_nest:"Sniper Nest",trap_garden:"Trap Garden",fortress:"Fortress",balanced:"Outpost"},ba={maze:{wall:.55,trap:.1,ward:.1,archer:.05,watchtower:.05},sniper_nest:{wall:.15,trap:.1,ward:.1,archer:.35,watchtower:.1},trap_garden:{wall:.15,trap:.4,ward:.1,archer:.05,watchtower:.1},fortress:{wall:.3,trap:.1,ward:.2,archer:.1,watchtower:.05},balanced:{wall:.35,trap:.2,ward:.15,archer:.1,watchtower:.05}},Es=["maze","sniper_nest","trap_garden","fortress","balanced"];function ka(e){return Es[Math.floor(e()*Es.length)]}function Fo(e,t){let o=Cs[Math.max(0,Math.min(t-1,Cs.length-1))],s=Wo(It(e)),r=ka(s),n=ba[r],c=[],d=new Set,g=Math.max(1,Math.floor(o.structureCount/5));for(let h=0;h<g;h++){let x=As(s,d);if(!x)break;c.push(Ut("treasury",x,Gt(s,o.maxUpgradeLevel))),d.add(`${x.x},${x.y}`)}let l=o.structureCount-g-br,T=Math.max(0,Math.round(l*n.wall));for(let h=0;h<T;h++){let x=Ms(s,d,c);if(!x)break;c.push(Ut("wall",x,Gt(s,o.maxUpgradeLevel))),d.add(`${x.x},${x.y}`)}let R=Math.max(0,Math.round(l*n.trap));for(let h=0;h<R;h++){let x=va(s,d);if(!x)break;c.push(Ut("trap",x,Gt(s,o.maxUpgradeLevel))),d.add(`${x.x},${x.y}`)}let u=Math.max(1,Math.round(l*n.ward));for(let h=0;h<u;h++){let x=c.filter(K=>K.kind==="treasury"),_=x.length>0?x[Math.floor(s()*x.length)]:void 0;if(!_)break;let j=[{x:_.pos.x-1,y:_.pos.y},{x:_.pos.x+1,y:_.pos.y},{x:_.pos.x,y:_.pos.y-1},{x:_.pos.x,y:_.pos.y+1}].filter(K=>K.x>=0&&K.x<I&&K.y>=0&&K.y<I&&!d.has(`${K.x},${K.y}`));if(j.length>0){let K=j[Math.floor(s()*j.length)];c.push(Ut("ward",K,Gt(s,o.maxUpgradeLevel))),d.add(`${K.x},${K.y}`)}}let i=Math.max(0,Math.round(l*n.archer));for(let h=0;h<i;h++){let x=Ms(s,d,c);if(!x)break;c.push(Ut("archerTower",x,Gt(s,o.maxUpgradeLevel))),d.add(`${x.x},${x.y}`)}for(let h=0;h<br;h++){let x=As(s,d);if(!x)break;c.push(Ut("vault",x,Gt(s,o.maxUpgradeLevel))),d.add(`${x.x},${x.y}`)}let y=o.structureCount-c.length;for(let h=0;h<y;h++){let x=Ca(s,d);if(!x)break;c.push(Ut("watchtower",x,Gt(s,o.maxUpgradeLevel))),d.add(`${x.x},${x.y}`)}let w=Sa[r];return{id:`npc-${e}-${t}`,name:`${w} (Lv.${o.level})`,ownerPlayerId:"npc",grid:{width:16,height:16,structures:c},resources:{...kt},createdAtUnixMs:Date.now(),updatedAtUnixMs:Date.now()}}function Ut(e,t,o){return{id:`${e}-${t.x}-${t.y}`,kind:e,level:o,pos:{...t},placedAtUnixMs:Date.now()}}function Gt(e,t){let o=Math.floor(e()*t)+1;return Math.min(t,o)}function As(e,t){for(let o=0;o<50;o++){let s=4+Math.floor(e()*(I-8)),r=4+Math.floor(e()*(I-8));if(!t.has(`${s},${r}`))return{x:s,y:r}}return null}function Ms(e,t,o){for(let s=0;s<50;s++){let r=o[Math.floor(e()*o.length)],n=Math.floor(e()*3)-1,c=Math.floor(e()*3)-1,d=r.pos.x+n,g=r.pos.y+c;if(d>=0&&d<I&&g>=0&&g<I&&!t.has(`${d},${g}`))return{x:d,y:g}}return null}function va(e,t){for(let o=0;o<50;o++){let s=Math.floor(e()*4),r,n;if(s===0?(r=Math.floor(e()*I),n=Math.floor(e()*3)):s===1?(r=Math.floor(e()*I),n=I-1-Math.floor(e()*3)):s===2?(r=Math.floor(e()*3),n=Math.floor(e()*I)):(r=I-1-Math.floor(e()*3),n=Math.floor(e()*I)),!t.has(`${r},${n}`))return{x:r,y:n}}return null}function Ca(e,t){for(let o=0;o<50;o++){let s=Math.floor(e()*I),r=Math.floor(e()*I);if(!t.has(`${s},${r}`))return{x:s,y:r}}return null}var Ar=1;function Da(){return Ws(Pa(),".config","codekeep")}function $r(){return Ws(Da(),"game.json")}function Ks(e){let t=`player-${Date.now()}`;return{schemaVersion:Ar,savedAtUnixMs:Date.now(),player:{id:t,displayName:e,settings:{asciiMode:!1}},keep:{id:`keep-${t}-${Date.now()}`,name:`${e}'s Keep`,ownerPlayerId:t,grid:{width:16,height:16,structures:[]},resources:{...kt},createdAtUnixMs:Date.now(),updatedAtUnixMs:Date.now()},raidHistory:[],tutorialCompleted:!1,lastPlayedAtUnixMs:Date.now(),progression:{totalBuildsToday:0,totalCommitsToday:0,lastDailyResetDay:Math.floor(Date.now()/864e5),totalRaidsWon:0,totalRaidsLost:0,totalStructuresPlaced:0,currentWinStreak:0,bestWinStreak:0,achievements:[],totalRaidersKilledByArcher:0}}}function Pt(e){let t=$r(),o=Ia(t);Lr(o)||Aa(o,{recursive:!0});let s=t+".tmp",r=JSON.stringify({...e,savedAtUnixMs:Date.now()},null,2);Er(s,r,"utf-8"),Ma(s,t)}function Jt(){let e=$r();if(!Lr(e))return null;let t;try{t=Ea(e,"utf-8")}catch{return null}let o;try{o=JSON.parse(t)}catch{let s=e+".bak";try{Er(s,t,"utf-8")}catch{}return process.stderr.write(`[codekeep] Corrupted save backed up to ${s}
3
+ `),null}if(o.schemaVersion!==Ar){let s=e+`.v${o.schemaVersion}.bak`;try{Er(s,t,"utf-8")}catch{}return process.stderr.write(`[codekeep] Save version mismatch (got ${o.schemaVersion}, need ${Ar}), backed up to ${s}
4
+ `),null}return o}function Fs(){let e=$r();if(!Lr(e))return!1;try{return _a(e),!0}catch{return!1}}import{Box as Hs,Text as pt}from"ink";import{jsx as ft,jsxs as Ys}from"react/jsx-runtime";var La={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"},$a={wall:"whiteBright",trap:"magentaBright",treasury:"yellowBright",ward:"cyanBright",watchtower:"greenBright",archerTower:"redBright"},Ba=Object.fromEntries(Object.entries(co).map(([e,t])=>[e,t.color]));function Na(e,t){return Math.abs(e.x-t.x)+Math.abs(e.y-t.y)}function Br(e,t){return Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))}function Oa(e,t){let o=new Set;if(e.kind==="archerTower"){let s=_o[e.level];for(let r=0;r<I;r++)for(let n=0;n<I;n++)Na(e.pos,{x:n,y:r})<=s&&!(n===e.pos.x&&r===e.pos.y)&&o.add(`${n},${r}`);return{tiles:o,color:"red"}}if(e.kind==="watchtower"){let s=Ot[e.level];for(let r=0;r<I;r++)for(let n=0;n<I;n++)Br(e.pos,{x:n,y:r})<=s&&!(n===e.pos.x&&r===e.pos.y)&&o.add(`${n},${r}`);return{tiles:o,color:"green"}}if(e.kind==="ward"){let s=1,r=t.filter(n=>n.kind==="watchtower");for(let n of r)Br(e.pos,n.pos)<=1&&(s=Math.max(s,1+Ot[n.level]));s=Math.min(s,5);for(let n=0;n<I;n++)for(let c=0;c<I;c++)Br(e.pos,{x:c,y:n})<=s&&!(c===e.pos.x&&n===e.pos.y)&&o.add(`${c},${n}`);return{tiles:o,color:"cyan"}}return null}function Vs({grid:e,cursor:t,asciiMode:o,compact:s,fragments:r=[],synergyStructureIds:n}){let c=o?"-":"\u2500",d=o?"|":"\u2502",g=o?"+":"\u250C",l=o?"+":"\u2510",T=o?"+":"\u2514",R=o?"+":"\u2518",u=s?1:2,i=(s?" ":" ")+Array.from({length:I},(N,$)=>s?$.toString(16).toUpperCase():$.toString(16).toUpperCase()+" ").join(""),y=(s?" ":" ")+g+c.repeat(I*u)+l,w=(s?" ":" ")+T+c.repeat(I*u)+R,h=new Map;for(let N of e.structures)h.set(`${N.pos.x},${N.pos.y}`,N);let x=new Map;for(let N of r)x.set(`${N.pos.x},${N.pos.y}`,N);let _=h.get(`${t.x},${t.y}`),j=_?Oa(_,e.structures):null,K=[];for(let N=0;N<I;N++){let $=s?N.toString(16).toUpperCase():" "+N.toString(16).toUpperCase(),U=[];for(let k=0;k<I;k++){let b=t.x===k&&t.y===N,L=h.get(`${k},${N}`),m=`${k},${N}`,P=j?.tiles.has(m)??!1,Y,se,v=!1,oe=x.get(m),fe=L&&n?.has(L.id);L?(Y=ye[L.kind],se=La[L.kind],(L.level>=2||fe)&&(v=!0),L.level===3&&(se=$a[L.kind])):oe?(Y="~",se=Ba[oe.type]??"cyan",v=!0):(Y=yt,se=void 0);let be=s?"":L&&L.level>1?String(L.level):" ";b?U.push(ft(pt,{backgroundColor:"white",color:"black",bold:!0,children:Y+be},k)):P&&!L&&!oe?U.push(ft(pt,{color:j.color,children:"\u2591"+(s?"":" ")},k)):P&&L?U.push(ft(pt,{color:se,bold:v,backgroundColor:j.color==="red"?"red":void 0,children:Y+be},k)):se?U.push(ft(pt,{color:se,bold:v,children:Y+be},k)):U.push(ft(pt,{dimColor:!0,children:Y+(s?"":" ")},k))}K.push(Ys(Hs,{children:[ft(pt,{dimColor:!0,children:$}),ft(pt,{dimColor:!0,children:d}),U,ft(pt,{dimColor:!0,children:d})]},N))}return Ys(Hs,{flexDirection:"column",children:[ft(pt,{dimColor:!0,children:i}),ft(pt,{dimColor:!0,children:y}),K,ft(pt,{dimColor:!0,children:w})]})}import{Box as Ho,Text as ue}from"ink";import{Fragment as js,jsx as Ie,jsxs as Ue}from"react/jsx-runtime";var Ua={wall:"WL",trap:"TR",treasury:"TY",ward:"WD",watchtower:"WT",archerTower:"AT"};function Ga(e){let t=[];return e.gold>0&&t.push(`${W.gold}${e.gold}`),e.wood>0&&t.push(`${W.wood}${e.wood}`),e.stone>0&&t.push(`${W.stone}${e.stone}`),t.join(" ")}function qs({resources:e,selectedStructure:t,message:o,compact:s,structureAtCursor:r,fragmentCount:n=0,dryRun:c,siegeForecast:d,flowMultiplier:g,raidAnomalies:l,activeBuffs:T}){if(s){let u=Ua[t];return Ie(Ho,{flexDirection:"column",marginBottom:0,children:Ue(ue,{children:[Ie(ue,{bold:!0,color:"yellow",children:"\u25C6"}),Ie(ue,{dimColor:!0,children:" \u2502 "}),Ue(ue,{color:"yellow",children:[W.gold,e.gold]}),Ie(ue,{children:" "}),Ue(ue,{color:"green",children:[W.wood,e.wood]}),Ie(ue,{children:" "}),Ue(ue,{color:"white",children:[W.stone,e.stone]}),Ie(ue,{dimColor:!0,children:" \u2502 "}),Ie(ue,{bold:!0,children:u}),o?Ie(ue,{dimColor:!0,children:" \u2502 "}):null,o?Ie(ue,{color:o.startsWith("!")?"red":"yellow",children:o}):null]})})}let R=r?`${Je[r.kind]} Lv.${r.level}`+(r.level<3?` \u2192 Lv.${r.level+1}: ${Ga(wt[r.kind][r.level+1])}`:" (MAX)"):"";return Ue(Ho,{flexDirection:"column",marginBottom:1,children:[Ue(Ho,{flexDirection:"row",gap:1,children:[Ie(ue,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep"}),c&&Ie(ue,{color:"magenta",bold:!0,children:" [DRY RUN]"}),Ie(ue,{dimColor:!0,children:"\u2502"}),Ue(ue,{color:"yellow",children:[W.gold," ",e.gold]}),Ue(ue,{color:"green",children:[W.wood," ",e.wood]}),Ue(ue,{color:"white",children:[W.stone," ",e.stone]}),Ie(ue,{dimColor:!0,children:"\u2502"}),Ue(ue,{children:["Sel: ",Ie(ue,{bold:!0,children:Je[t]})]}),n>0&&Ue(js,{children:[Ie(ue,{dimColor:!0,children:"\u2502"}),Ue(ue,{color:"cyan",bold:!0,children:["~ ",n," on ground"]})]})]}),Ue(Ho,{flexDirection:"row",gap:1,children:[Ie(ue,{color:o.startsWith("!")?"red":"yellow",children:o||" "}),g!=null&&g>1&&Ue(js,{children:[Ie(ue,{dimColor:!0,children:"\u2502"}),Ue(ue,{color:g>=2?"magenta":g>=1.5?"cyan":"green",bold:!0,children:["Flow: ",g.toFixed(1),"x"]})]})]}),Ie(ue,{dimColor:!0,children:d?`${R?R+" \u2502 ":""}${d}`:R||" "}),T&&T.length>0&&Ue(ue,{color:"cyan",children:["\u2605 Buffs: ",T.map(u=>`${u.name} (${u.raidsRemaining}r)`).join(", ")]})]})}import{Box as Wa,Text as O}from"ink";import{jsx as z,jsxs as Re}from"react/jsx-runtime";function Qt(e){let t=[];return e.gold>0&&t.push(`${W.gold}${e.gold}`),e.wood>0&&t.push(`${W.wood}${e.wood}`),e.stone>0&&t.push(`${W.stone}${e.stone}`),t.join(" ")}function zs(){let e=Qe,t=wt;return Re(Wa,{flexDirection:"column",padding:1,children:[z(O,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep \u2014 Help"}),z(O,{children:" "}),z(O,{bold:!0,children:"Navigation"}),z(O,{children:" h/j/k/l or WASD or Arrows Move cursor"}),z(O,{children:" g + hex coords + Enter Jump to coordinate (e.g. g 5,3)"}),z(O,{children:" Tab Jump to next structure"}),z(O,{children:" Esc Back to menu"}),z(O,{children:" "}),z(O,{bold:!0,children:"Building"}),Re(O,{children:[" ","[ / ] Cycle structure type"]}),z(O,{children:" 1-6 Select structure by number"}),z(O,{children:" Enter or e Place structure at cursor"}),z(O,{children:" u Upgrade structure (Lv.1\u21922\u21923)"}),z(O,{children:" x Demolish structure (50% refund)"}),z(O,{children:" "}),z(O,{bold:!0,children:"Foraging"}),z(O,{children:" c Collect forage at cursor (~ on the grid)"}),Re(O,{children:[" "," Archer towers improve spawn rate; treasuries improve yield"]}),Re(O,{children:[" "," Watchtowers auto-gather nearby forage"]}),z(O,{children:" "}),z(O,{bold:!0,children:"Combat"}),z(O,{children:" r Quick defend (instant result)"}),z(O,{children:" v View last quick-defend replay"}),z(O,{children:" Defend Keep (menu) Watch raiders assault your grid"}),z(O,{children:" Attack NPC (menu) Raid an NPC keep for loot"}),z(O,{children:" "}),z(O,{bold:!0,children:"Other"}),z(O,{children:" f Kingdom boon (+resources)"}),z(O,{children:" ? Toggle this help (works on any screen)"}),z(O,{children:" q Save and quit"}),z(O,{children:" "}),z(O,{bold:!0,children:"Structures (cost Lv.1 \u2192 Lv.2 \u2192 Lv.3)"}),Re(O,{children:[" ",Re(O,{color:"white",children:["1 ",ye.wall]})," Stone Wall Blocks raiders, has HP ",Qt(t.wall[1])]}),Re(O,{children:[" ",Re(O,{color:"magenta",children:["2 ",ye.trap]})," Bear Trap Stuns raiders on contact ",Qt(t.trap[1])]}),Re(O,{children:[" ",Re(O,{color:"yellow",children:["3 ",ye.treasury]})," Treasury Stores loot, generates income ",Qt(t.treasury[1])]}),Re(O,{children:[" ",Re(O,{color:"cyan",children:["4 ",ye.ward]})," Ward Reduces loot stolen nearby ",Qt(t.ward[1])]}),Re(O,{children:[" ",Re(O,{color:"green",children:["5 ",ye.watchtower]})," Watchtower Extends ward range, auto-gathers ",Qt(t.watchtower[1])]}),Re(O,{children:[" ",Re(O,{color:"redBright",children:["6 ",ye.archerTower]})," Archer Tower Fires arrows at raiders in range ",Qt(t.archerTower[1])]}),z(O,{children:" "}),z(O,{bold:!0,children:"Resources"}),Re(O,{children:[" ",z(O,{color:"yellow",children:W.gold})," Gold Earned from events, foraging, and raids"]}),Re(O,{children:[" ",z(O,{color:"green",children:W.wood})," Wood Earned from treasuries and events"]}),Re(O,{children:[" ",z(O,{color:"white",children:W.stone})," Stone Earned from watchtowers and events"]}),z(O,{children:" Treasuries and watchtowers generate passive income over time."}),z(O,{children:" "}),z(O,{bold:!0,children:"Raider Types"}),Re(O,{children:[" Raider HP ",e.raider.hp,", dmg ",e.raider.damage,", speed ",e.raider.speed," \u2014 standard foot soldier"]}),Re(O,{children:[" Scout HP ",e.scout.hp,", dmg ",e.scout.damage,", speed ",e.scout.speed," \u2014 fast, moves twice per tick"]}),Re(O,{children:[" Brute HP ",e.brute.hp,", dmg ",e.brute.damage,", speed ",e.brute.speed," \u2014 heavy hitter, hard to kill"]}),z(O,{children:" "}),z(O,{bold:!0,children:"Raid Difficulty"}),z(O,{children:" Difficulty scales with total raids completed (Lv.1\u20135)."}),z(O,{children:" Higher levels bring more raiders, scouts, and brutes."}),Re(O,{children:[" Outcomes: ",z(O,{color:"green",children:"Defense Win"})," \xB7 ",z(O,{color:"yellow",children:"Partial Breach"})," \xB7 ",z(O,{color:"red",children:"Full Breach"})]}),z(O,{children:" "}),z(O,{dimColor:!0,children:"Press any key to close"})]})}import{useState as Ha}from"react";import{Box as on,Text as mt,useInput as Ya}from"ink";function Dt(e){return e<=2?1:e<=5?2:e<=9?3:e<=14?4:e<=19?5:e<=29?6:e<=44?7:e<=64?8:e<=99?9:10}function Lt(e,t,o,s=1){let r=Math.min(.8,(t>=8?.4:t>=6?.3:t>=3?.2:0)*s),n=t>=2?.3:0,c=[];for(let d=0;d<e;d++){let g=o();g<r?c.push("brute"):g<r+n?c.push("scout"):c.push("raider")}return c}function at(e){let t=e|0;return()=>{t=t+1831565813|0;let o=Math.imul(t^t>>>15,1|t);return o=o+Math.imul(o^o>>>7,61|o)^o,((o^o>>>14)>>>0)/4294967296}}function Xs(e){let t=e.progression;return{...e,progression:{...t,totalRaidsWon:t.totalRaidsWon??0,totalRaidsLost:t.totalRaidsLost??0,totalStructuresPlaced:t.totalStructuresPlaced??0,currentWinStreak:t.currentWinStreak??0,bestWinStreak:t.bestWinStreak??0,achievements:t.achievements??[],totalRaidersKilledByArcher:t.totalRaidersKilledByArcher??t.totalProbesKilledByScanner??0}}}var Ka={first_structure:{gold:20,wood:0,stone:0},defense_win_5:{gold:25,wood:15,stone:15},win_streak_3:{gold:10,wood:10,stone:10},win_streak_5:{gold:30,wood:30,stone:30},all_types:{gold:15,wood:15,stone:15},max_level:{gold:20,wood:0,stone:10},archer_kills_10:{gold:20,wood:10,stone:10},structures_20:{gold:10,wood:10,stone:10},raids_10:{gold:15,wood:15,stone:15},hoarder:{gold:25,wood:0,stone:0}};function Nr(e){return Ka[e]??null}function Or(e){let t=e.progression,o=new Set(t.achievements),s=[],r=(c,d)=>{!o.has(c)&&d&&s.push(c)};r("first_structure",t.totalStructuresPlaced>=1),r("defense_win_5",t.totalRaidsWon>=5),r("win_streak_3",t.bestWinStreak>=3),r("win_streak_5",t.bestWinStreak>=5),r("structures_20",t.totalStructuresPlaced>=20),r("raids_10",t.totalRaidsWon+t.totalRaidsLost>=10),r("archer_kills_10",t.totalRaidersKilledByArcher>=10),r("hoarder",e.keep.resources.gold+e.keep.resources.wood+e.keep.resources.stone>=500);let n=new Set(e.keep.grid.structures.map(c=>c.kind));return r("all_types",n.size>=qe.length),r("max_level",e.keep.grid.structures.some(c=>c.level===3)),s}function Zs(e,t,o){let r=Dt(t),n=3+r,c=Fa(e,t),d=at(c),g=Lt(n,r,d),l=g.filter(h=>h==="raider").length,T=g.filter(h=>h==="scout").length,R=g.filter(h=>h==="brute").length,u={raiders:l,scouts:T,brutes:R},i;n<=5?i="Small force approaching":n<=8?i="Moderate force approaching":n<=11?i="Strong force approaching":i="Massive force approaching";let y=[];R>0&&y.push(`${R}B`),l>0&&y.push(`${l}R`),T>0&&y.push(`${T}S`);let w=`Next raid: ${y.join(" ")} (Lv.${r})`;return{difficulty:r,probeCount:n,composition:u,vague:i,detailed:w}}function Fa(e,t){let o=`${e}-forecast-${t+1}`,s=0;for(let r=0;r<o.length;r++)s=(s<<5)-s+o.charCodeAt(r)|0;return s}function Js(e,t){if(e<Ts)return[];let o=xs.filter(n=>!(n.id==="siege"&&e<4||n.id==="piercing"&&e<3));if(o.length===0)return[];let s=[],r=Math.floor(t()*o.length);if(s.push(o[r]),e>=ys&&t()<.5){let n=o.filter((c,d)=>d!==r);n.length>0&&s.push(n[Math.floor(t()*n.length)])}return s}function Qs(e,t){let o=e.map(r=>r.modifiers);if(t)for(let r of t)o.push(r.modifiers);let s={};for(let r of o)for(let[n,c]of Object.entries(r))n==="singleEdge"?s.singleEdge=s.singleEdge||c:s[n]=(s[n]??1)*c;return s}function Yo(e,t){let o=[],s=1+(e-1)*.3,r=Math.floor(15*s),n=Math.floor(10*s),c=Math.floor(8*s);o.push({id:"resources_gold",type:"resources",name:"Gold Cache",description:`+${r*2} gold`,icon:"\u25CF",resources:{gold:r*2,wood:0,stone:0}}),o.push({id:"resources_balanced",type:"resources",name:"Supply Crate",description:`+${r} gold, +${n} wood, +${c} stone`,icon:"\u25A0",resources:{gold:r,wood:n,stone:c}});let d=[...ws],g=Math.floor(t()*d.length),l={...d[g],modifiers:{...d[g].modifiers}};return o.push({id:`buff_${l.id}`,type:"buff",name:l.name,description:`${l.name} for ${l.raidsRemaining} raids`,icon:"\u2605",buff:l}),o}function en(e){return e.map(t=>({...t,raidsRemaining:t.raidsRemaining-1})).filter(t=>t.raidsRemaining>0)}function tn(e,t){if(t<=zt)return e;let o=Math.pow(us,Math.floor((t-zt)/zt)+1);return{gold:Math.max(1,Math.floor(e.gold*o)),wood:Math.max(1,Math.floor(e.wood*o)),stone:Math.max(1,Math.floor(e.stone*o))}}import{jsx as uo,jsxs as $t}from"react/jsx-runtime";function Va(e){let t=[{key:"keep",label:"Build Keep",desc:"Place and upgrade structures",disabled:!1},{key:"defend",label:"Defend Keep",desc:"Watch NPCs attack YOUR defenses",disabled:!1},{key:"attack",label:"Attack NPC",desc:"Raid an NPC keep for resources",disabled:!1}];return e?t.push({key:"pvp",label:"\u2694 PvP Arena",desc:"Fight real players for trophies",disabled:!1}):t.push({key:"pvp-locked",label:"\u2694 PvP Arena",desc:"Coming soon \u2014 use --online to connect",disabled:!0}),t.push({key:"dailyChallenge",label:"\u2605 Daily Challenge",desc:"Date-seeded escalating waves",disabled:!1},{key:"prestige",label:"\u2191 Prestige",desc:"Ascend \u2014 reset keep, gain permanents",disabled:!1},{key:"friendRaid",label:"Raid Rival Keep",desc:"Plunder a rival lord's fortress",disabled:!1},{key:"raidLog",label:"Raid Log",desc:"View recent raid history",disabled:!1},{key:"settings",label:"Settings",desc:"Game options and reset",disabled:!1},{key:"quit",label:"Rest for the Night",desc:"Save and exit",disabled:!1}),t}function rn({gameSave:e,onlineMode:t,onKeep:o,onAttack:s,onDefend:r,onFriendRaid:n,onPvp:c,onDailyChallenge:d,onPrestige:g,onRaidLog:l,onSettings:T,onQuit:R}){let u=Va(!!t),[i,y]=Ha(0);Ya((N,$)=>{if(N==="k"||N==="w"||$.upArrow)y(U=>{let k=U-1;for(;k>=0&&u[k].disabled;)k--;return k>=0?k:U});else if(N==="j"||N==="s"||$.downArrow)y(U=>{let k=U+1;for(;k<u.length&&u[k].disabled;)k++;return k<u.length?k:U});else if($.return){let U=u[i];if(U.disabled)return;U.key==="keep"?o():U.key==="defend"?r():U.key==="attack"?s():U.key==="pvp"?c?.():U.key==="dailyChallenge"?d():U.key==="prestige"?g():U.key==="friendRaid"?n():U.key==="raidLog"?l():U.key==="settings"?T():U.key==="quit"&&R()}else N==="q"&&R()});let w=e.keep.grid.structures.length,h=e.progression,x=h.totalRaidsWon+h.totalRaidsLost,_=Math.max(1,Math.floor((Date.now()-e.keep.createdAtUnixMs)/864e5)),j=e.keep.grid.structures.filter(N=>N.kind==="treasury").length,K=e.keep.grid.structures.filter(N=>N.kind==="archerTower").length;return $t(on,{flexDirection:"column",padding:1,children:[uo(mt,{bold:!0,color:"yellow",children:`
5
5
  \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2557 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2557
6
6
  \u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2551 \u2588\u2588\u2554\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2550\u2550\u255D\u2588\u2588\u2554\u2550\u2550\u2588\u2588\u2557
7
7
  \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2554\u255D \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2557 \u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D
8
8
  \u2588\u2588\u2551 \u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2551 \u2588\u2588\u2551\u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2588\u2588\u2557 \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u255D \u2588\u2588\u2554\u2550\u2550\u2550\u255D
9
9
  \u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u255A\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2554\u255D\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551 \u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2557\u2588\u2588\u2551
10
- \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D`}),Jt(Ze,{children:" "}),xt(Ze,{dimColor:!0,children:[" ",e.player.displayName,"'s Keep \u2014 ",c,"d old"]}),xt(Ze,{dimColor:!0,children:[" ",m," structures (",$,"$ ",z,"!) \xB7 Raids ",p.totalRaidsWon,"W / ",p.totalRaidsLost,"L \xB7 Streak ",p.currentWinStreak," (best ",p.bestWinStreak,")"]}),xt(Ze,{dimColor:!0,children:[" Difficulty: Lv.",b<=2?1:b<=5?2:b<=9?3:b<=14?4:5]}),xt(Ze,{dimColor:!0,children:[" Achievements: ",e.progression.achievements?.length||0,"/",10]}),Jt(Ze,{children:" "}),x.map((U,u)=>xt(ss,{children:[xt(Ze,{color:U.disabled?void 0:u===k?"yellow":void 0,bold:!U.disabled&&u===k,dimColor:U.disabled,children:[u===k&&!U.disabled?" \u25B8 ":" ",U.label]}),xt(Ze,{dimColor:!0,children:[" ",U.desc]})]},U.key)),Jt(Ze,{children:" "}),Jt(Ze,{dimColor:!0,children:" \u2191\u2193 navigate Enter select q quit"})]})}import{useState as pt,useEffect as as,useCallback as Un,useRef as Gn}from"react";import{Box as Je,Text as J,useInput as Wn}from"ink";import{jsx as se,jsxs as ye}from"react/jsx-runtime";var qo={raider:"R",scout:"S",brute:"B"};function zo(e,t){let o=e/t;return o>.6?"green":o>.3?"yellow":"red"}function Kn(e,t){let o=e/t;return o>.6?"white":o>.3?"yellow":"red"}function Zo(e,t){let o=[];return e.gold>0&&o.push(`${t}${e.gold}${B.gold}`),e.wood>0&&o.push(`${t}${e.wood}${B.wood}`),e.stone>0&&o.push(`${t}${e.stone}${B.stone}`),o.join(" ")}function Hn(e,t,o=6){let s=Math.round(e/t*o);return"\u2588".repeat(s)+"\u2591".repeat(o-s)}var Fn={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"};function Jo({replay:e,keepGrid:t,raidType:o,summary:s,initialSpeed:r,onSpeedChange:a,onDone:T}){let[f,d]=pt(0),[l,x]=pt(r??1),k=Un(v=>{x(v),a?.(v)},[a]),[R,m]=pt(!1),[p,b]=pt(new Map),[c,$]=pt(()=>{let v=new Map,q={wall:ao,archerTower:io,watchtower:lo,vault:mo};for(let Y of t.structures){let Ie=q[Y.kind];if(Ie){let L=Ie[Y.level];v.set(Y.id,{structureId:Y.id,kind:Y.kind,pos:{...Y.pos},hp:L,maxHp:L,destroyed:!1})}}return v}),[z,U]=pt([]),[u,K]=pt(new Set),[w,H]=pt([]),[y,h]=pt(null),E=Gn(-1);Wn((v,q)=>{if(v==="q"||q.escape){T();return}if(v==="p"||v===" "){m(Y=>!Y);return}v==="1"&&k(1),v==="2"&&k(2),v==="4"&&k(4),v==="8"&&k(8),(v==="n"||q.return)&&d(e.maxTicks)}),as(()=>{if(R||y)return;let v=setInterval(()=>{d(q=>{let Y=q+1;return Y>e.maxTicks?(clearInterval(v),q):Y})},1e3/e.tickRateHz/l);return()=>clearInterval(v)},[R,l,y,e]),as(()=>{if(f<=E.current)return;let v=e.events.filter(L=>L.t>E.current&&L.t<=f),q=[],Y=[],Ie=new Map;b(L=>{let Z=new Map(L);for(let G of v)switch(G.type){case"raider_spawn":{let X=G.raiderType??"raider",Ce=G.maxHp??Le[X].hp;Z.set(G.probeId,{id:G.probeId,pos:{...G.pos},alive:!0,stunned:!1,hp:Ce,maxHp:Ce,raiderType:X});break}case"raider_move":{let X=Z.get(G.probeId);X&&(X.pos={...G.to},X.stunned=!1);break}case"raider_stunned":{let X=Z.get(G.probeId);X&&(X.stunned=!0);break}case"arrow_hit":{let X=Z.get(G.probeId);X&&(X.hp=Math.max(0,G.hpRemaining));break}case"raider_destroyed":{let X=Z.get(G.probeId);X&&(X.alive=!1);break}default:break}return Ie=Z,Z}),$(L=>{let Z=new Map(L);for(let G of v)if(G.type==="wall_damaged"||G.type==="structure_damaged"){let X=Z.get(G.structureId);X&&(X.hp=Math.max(0,G.hpRemaining),X.destroyed=G.destroyed)}return Z});for(let L of v)switch(L.type){case"raider_spawn":{let Z=L.raiderType??"raider",G=qo[Z]??"R",X=L.edge==="N"?"\u2193":L.edge==="S"?"\u2191":L.edge==="W"?"\u2192":"\u2190";q.push(`${G} Raider ${L.probeId+1} enters from ${L.edge} ${X}`),Y.push({pos:{...L.pos},char:X,color:"yellowBright",bold:!0,expiresAtTick:f+3,priority:0});break}case"raider_stunned":{q.push(`\u26A1 Raider ${L.probeId+1} STUNNED ${L.stunTicks}t`),Y.push({pos:{...L.pos},char:"\u2727",color:"cyanBright",bold:!0,expiresAtTick:f+3,priority:2});break}case"wall_damaged":{if(L.destroyed){q.push("\u{1F4A5} Wall DESTROYED!");let Z=t.structures.find(G=>G.id===L.structureId);Z&&Y.push({pos:{...Z.pos},char:"\u2717",color:"redBright",bold:!0,expiresAtTick:f+4,priority:2})}else q.push(`\u2694 Wall hit (${L.hpRemaining} HP)`);break}case"structure_damaged":{let Z=tt[L.structureKind]??L.structureKind;if(L.destroyed){q.push(`\u{1F4A5} ${Z} DESTROYED!`);let G=t.structures.find(X=>X.id===L.structureId);G&&Y.push({pos:{...G.pos},char:"\u2717",color:"redBright",bold:!0,expiresAtTick:f+5,priority:3})}else q.push(`\u2694 ${Z} hit (${L.hpRemaining} HP)`);break}case"arrow_hit":{let Z=Ie.get(L.probeId),G=Z?{...Z.pos}:null;G&&Y.push({pos:G,char:"\u2020",color:"redBright",bold:!0,expiresAtTick:f+2,priority:1}),L.hpRemaining<=0?(q.push(`\u{1F3F9} Archer slew raider ${L.probeId+1}!`),G&&Y.push({pos:G,char:"\u2716",color:"redBright",bold:!0,expiresAtTick:f+4,priority:3})):q.push(`\u{1F3F9} Arrow hit raider ${L.probeId+1} (-${L.damage} \u2192 ${L.hpRemaining} HP)`);break}case"treasury_breach":{let Z=Zo(L.lootTaken,""),G=o==="attack"?"Looted":"Lost";q.push(`\u{1F4B0} TREASURY BREACHED! ${G} ${Z}`),K(Ce=>new Set([...Ce,L.structureId]));let X=t.structures.find(Ce=>Ce.id===L.structureId);X&&Y.push({pos:{...X.pos},char:"\u26A1",color:"yellowBright",bold:!0,expiresAtTick:f+5,priority:3});break}case"raider_destroyed":{v.some(G=>G.type==="arrow_hit"&&G.probeId===L.probeId&&G.hpRemaining<=0&&G.t===L.t)||q.push(`\u{1F480} Raider ${L.probeId+1} eliminated`);break}case"raid_end":{let Z=L.outcome==="defense_win"?o==="defend"?"DEFENSE VICTORY \u2014 All raiders defeated!":"ATTACK FAILED \u2014 The keep held strong":L.outcome==="partial_breach"?o==="defend"?"PARTIAL BREACH \u2014 Raiders stole some supplies":"PARTIAL SUCCESS \u2014 Some loot seized":o==="defend"?"FULL BREACH \u2014 Major losses!":"FULL SUCCESS \u2014 Major plunder!";h(Z),q.push(Z);break}default:break}U(L=>[...L.filter(Z=>Z.expiresAtTick>f),...Y]),E.current=f,q.length>0&&H(L=>[...L.slice(-10),...q])},[f,o,e,t]);let C=new Map;for(let v of t.structures)C.set(`${v.pos.x},${v.pos.y}`,v);if(!t.structures.some(v=>v.kind==="treasury")){let v={id:"__virtual_center_treasury",kind:"treasury",pos:{x:8,y:8},level:1};C.set("8,8",v)}let A=new Map;for(let[,v]of p)v.alive&&A.set(`${v.pos.x},${v.pos.y}`,v);let O=new Map;for(let[,v]of c)O.set(`${v.pos.x},${v.pos.y}`,v);let W=new Map;for(let v of z){let q=`${v.pos.x},${v.pos.y}`,Y=W.get(q);(!Y||v.priority>Y.priority||v.priority===Y.priority&&v.expiresAtTick>Y.expiresAtTick)&&W.set(q,v)}let ue=" "+Array.from({length:I},(v,q)=>q.toString(16).toUpperCase()+" ").join(""),Se=[se(J,{dimColor:!0,children:ue},"hdr")];for(let v=0;v<I;v++){let q=[se(J,{dimColor:!0,children:v.toString(16).toUpperCase()+" "},"lbl")];for(let Y=0;Y<I;Y++){let Ie=`${Y},${v}`,L=A.get(Ie),Z=C.get(Ie),G=O.get(Ie),X=W.get(Ie);if(X&&!L)q.push(se(J,{color:X.color,bold:X.bold,children:X.char+" "},Y));else if(L){let Ce=L.stunned?"\u25CA":qo[L.raiderType]??"\u25CF",Tt=L.stunned?"cyan":zo(L.hp,L.maxHp);q.push(se(J,{color:Tt,bold:!0,children:Ce+" "},Y))}else if(Z)if(G&&!G.destroyed){let Ce=Kn(G.hp,G.maxHp),Tt=fe[G.kind]??"#";q.push(se(J,{color:Ce,bold:G.hp>G.maxHp*.6,children:Tt+" "},Y))}else if(G&&G.destroyed)q.push(se(J,{color:"red",dimColor:!0,children:"x "},Y));else if(u.has(Z.id))q.push(se(J,{color:"red",bold:!0,children:"$ "},Y));else{let Ce=fe[Z.kind];q.push(se(J,{color:Fn[Z.kind]||"white",children:Ce+" "},Y))}else q.push(se(J,{dimColor:!0,children:Ot+" "},Y))}Se.push(se(Je,{children:q},v))}let nt=Array.from(p.values()).filter(v=>v.alive),$t=Array.from(p.values()).filter(v=>!v.alive);return ye(Je,{flexDirection:"column",padding:1,children:[ye(Je,{flexDirection:"row",gap:2,children:[se(J,{bold:!0,color:o==="defend"?"red":"green",children:o==="defend"?"\u2694 DEFENDING YOUR KEEP":"\u2694 ATTACKING NPC KEEP"}),ye(J,{children:["Tick: ",f,"/",e.maxTicks]}),ye(J,{children:["Speed: ",l,"x"]}),se(J,{dimColor:!0,children:R?"[PAUSED]":""})]}),se(J,{children:" "}),ye(Je,{flexDirection:"row",children:[se(Je,{flexDirection:"column",children:Se}),ye(Je,{flexDirection:"column",marginLeft:2,width:38,children:[nt.length>0&&ye(Je,{flexDirection:"column",marginBottom:1,children:[se(J,{bold:!0,children:"Raiders"}),nt.map(v=>ye(Je,{children:[ye(J,{color:zo(v.hp,v.maxHp),bold:!0,children:[qo[v.raiderType],v.id+1]}),se(J,{children:" "}),se(J,{color:zo(v.hp,v.maxHp),children:Hn(v.hp,v.maxHp)}),ye(J,{dimColor:!0,children:[" ",v.hp,"/",v.maxHp]}),v.stunned&&se(J,{color:"cyan",children:" STUN"})]},v.id)),$t.length>0&&ye(J,{dimColor:!0,children:[" ",$t.length," slain"]})]}),se(J,{bold:!0,children:"Battle Log"}),(()=>{let v=w.slice(-10);return v.map((q,Y)=>se(J,{dimColor:Y<Math.max(0,v.length-3),wrap:"truncate",children:q},Y))})()]})]}),se(J,{children:" "}),y?ye(Je,{flexDirection:"column",children:[se(J,{bold:!0,color:y.includes("VICTORY")||y.includes("SUCCESS")?"green":"red",children:y}),s&&ye(Je,{flexDirection:"column",marginTop:1,children:[se(J,{bold:!0,children:"\u2550\u2550\u2550 Raid Summary \u2550\u2550\u2550"}),ye(J,{children:["Difficulty: Lv.",s.difficulty," Raiders: ",s.raidersKilled,"/",s.raidersTotal," slain"]}),ye(J,{children:["Walls destroyed: ",s.wallsDestroyed," Archer towers: ",s.archersActive]}),s.lootGained.gold+s.lootGained.wood+s.lootGained.stone>0&&ye(J,{color:"green",children:["Resources gained: ",Zo(s.lootGained,"+")]}),s.lootLost.gold+s.lootLost.wood+s.lootLost.stone>0&&ye(J,{color:"red",children:["Resources lost: ",Zo(s.lootLost,"-")]})]}),se(J,{dimColor:!0,children:"Press q to return"})]}):ye(Je,{flexDirection:"column",children:[se(J,{dimColor:!0,children:"p pause 1/2/4/8 speed n/\u21B5 skip q back"}),ye(J,{dimColor:!0,children:[se(J,{color:"green",bold:!0,children:"R"}),"=Raider ",se(J,{color:"yellow",bold:!0,children:"S"}),"=Scout ",se(J,{color:"red",bold:!0,children:"B"}),"=Brute ",se(J,{color:"cyan",children:"\u25CA"}),"=Stunned ",se(J,{color:"red",children:"\u2716"}),"=Kill ",se(J,{color:"redBright",children:"\u2020"}),"=Arrow ",se(J,{color:"yellowBright",children:"\u2193\u2191\u2192\u2190"}),"=Spawn"]})]})]})}import{useState as Kt,useCallback as is}from"react";import{Box as xo,Text as n,useInput as Vn}from"ink";import{Fragment as Ue,jsx as i,jsxs as P}from"react/jsx-runtime";var Xt=["welcome","resources","move","place_wall","place_treasury","place_archer","place_trap","upgrade_explain","first_raid","raid_result","foraging","tips","done"],ls={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"};function ds({gameSave:e,onComplete:t}){let[o,s]=Kt("welcome"),[r,a]=Kt({x:7,y:7}),[T,f]=Kt([]),[d,l]=Kt([]),[x,k]=Kt(""),[R,m]=Kt(0),p=R>=4,b=Xt.indexOf(o),c=Xt.length-1,$=is(()=>{let w=Xt.indexOf(o);w<Xt.length-1&&s(Xt[w+1])},[o]),z=o==="place_wall"?"wall":o==="place_treasury"?"treasury":o==="place_archer"?"archerTower":o==="place_trap"?"trap":null,U=is(()=>{let w={width:16,height:16,structures:[...T]},H=ut({probeCount:2,keepGrid:w,seed:"tutorial-raid",probeTypes:["raider","scout"]}),y=[],h=0,E=0,C=!1;for(let A of H.events)A.type==="raider_spawn"?y.push(` Raider ${A.probeId+1} appears from the ${A.edge} edge`):A.type==="wall_damaged"&&A.destroyed?(E++,y.push(" A stone wall was destroyed!")):A.type==="raider_stunned"?y.push(` Raider ${A.probeId+1} stepped on a bear trap \u2014 stunned!`):A.type==="arrow_hit"&&A.hpRemaining<=0?(h++,y.push(` Archer tower eliminated raider ${A.probeId+1}!`)):A.type==="raider_destroyed"&&!y[y.length-1]?.includes(`raider ${A.probeId+1}`)?(h++,y.push(` Raider ${A.probeId+1} was destroyed`)):A.type==="treasury_breach"?(C=!0,y.push(" Raiders breached your treasury!")):A.type==="raid_end"&&(A.outcome==="defense_win"?y.push(" \u2713 DEFENSE WIN \u2014 all raiders defeated!"):y.push(" \u2717 Raiders got through \u2014 time to strengthen defenses"));if(y.length>10){let A=[...y.slice(0,3),` ... ${y.length-6} more events ...`,...y.slice(-3)];l(A)}else l(y);let N=H.events.find(A=>A.type==="raid_end");k(N?.type==="raid_end"&&N.outcome==="defense_win"?"win":"loss"),$()},[T,$]);Vn((w,H)=>{if(w==="s"&&o!=="move"){t();return}if(["welcome","resources","move","upgrade_explain","first_raid","raid_result","foraging","tips","done"].includes(o)){if(o==="move"){if(w==="h"||w==="a"||H.leftArrow){a(h=>({...h,x:Math.max(0,h.x-1)})),m(h=>h+1);return}if(w==="l"||w==="d"||H.rightArrow){a(h=>({...h,x:Math.min(I-1,h.x+1)})),m(h=>h+1);return}if(w==="k"||w==="w"||H.upArrow){a(h=>({...h,y:Math.max(0,h.y-1)})),m(h=>h+1);return}if(w==="j"||H.downArrow){a(h=>({...h,y:Math.min(I-1,h.y+1)})),m(h=>h+1);return}if((H.return||w===" ")&&p){$();return}return}if(o==="first_raid"){U();return}if(o==="done"){t();return}(H.return||w===" ")&&$();return}if(z){if(w==="h"||w==="a"||H.leftArrow)a(h=>({...h,x:Math.max(0,h.x-1)}));else if(w==="l"||w==="d"||H.rightArrow)a(h=>({...h,x:Math.min(I-1,h.x+1)}));else if(w==="k"||w==="w"||H.upArrow)a(h=>({...h,y:Math.max(0,h.y-1)}));else if(w==="j"||H.downArrow)a(h=>({...h,y:Math.min(I-1,h.y+1)}));else if(H.return||w==="e"){if(T.some(C=>C.pos.x===r.x&&C.pos.y===r.y))return;let E={id:`tut-${z}-${r.x}-${r.y}`,kind:z,level:1,pos:{...r},placedAtUnixMs:Date.now()};f(C=>[...C,E]),$()}}});let u=()=>{let h=new Map;for(let C of T)h.set(`${C.pos.x},${C.pos.y}`,C);let E=[];for(let C=3;C<13;C++){let N=[];for(let A=3;A<13;A++){let O=r.x===A&&r.y===C,W=h.get(`${A},${C}`),ue=Ot,Se;W&&(ue=fe[W.kind],Se=ls[W.kind]),O?N.push(i(n,{backgroundColor:"white",color:"black",bold:!0,children:ue+" "},A)):Se?N.push(i(n,{color:Se,bold:!0,children:ue+" "},A)):N.push(i(n,{dimColor:!0,children:ue+" "},A))}E.push(i(xo,{children:N},C))}return i(xo,{flexDirection:"column",children:E})},K=`[${b}/${c}]`;return P(xo,{flexDirection:"column",padding:1,children:[P(xo,{children:[i(n,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep \u2014 Tutorial "}),i(n,{dimColor:!0,children:K})]}),i(n,{children:" "}),o==="welcome"&&P(Ue,{children:[P(n,{bold:!0,color:"cyan",children:["Welcome to CodeKeep, ",e.player.displayName,"!"]}),i(n,{children:" "}),P(n,{children:["CodeKeep is a ",i(n,{bold:!0,children:"tower defense"})," game played in your terminal."]}),i(n,{children:" "}),P(n,{children:[" ","Build a ",i(n,{bold:!0,children:"fortress"})," on a 16\xD716 grid"]}),P(n,{children:[" ","Place ",i(n,{bold:!0,children:"walls"}),", ",i(n,{bold:!0,children:"traps"}),", and ",i(n,{bold:!0,children:"archer towers"})," to defend"]}),P(n,{children:[" ","Protect your ",i(n,{bold:!0,color:"yellow",children:"treasuries"})," from raiding parties"]}),P(n,{children:[" ","Earn resources over time and from coding activity"]}),i(n,{children:" "}),i(n,{children:"Let's learn how to play!"}),i(n,{children:" "}),i(n,{dimColor:!0,children:"Enter to continue \xB7 s to skip tutorial"})]}),o==="resources"&&P(Ue,{children:[i(n,{bold:!0,color:"cyan",children:"Resources"}),i(n,{children:" "}),i(n,{children:"You have three resources to build and upgrade structures:"}),i(n,{children:" "}),P(n,{children:[" ",P(n,{color:"yellow",bold:!0,children:[B.gold," Gold"]})," \u2014 Your main currency. Earned from events and raids."]}),P(n,{children:[" ",P(n,{color:"green",bold:!0,children:[B.wood," Wood"]})," \u2014 Building material. Earned from treasuries and events."]}),P(n,{children:[" ",P(n,{color:"white",bold:!0,children:[B.stone," Stone"]})," \u2014 Heavy material. Used for walls and towers."]}),i(n,{children:" "}),i(n,{children:"Resources grow passively and from coding activity (git commits!)."}),P(n,{children:["You can also press ",i(n,{bold:!0,children:"f"})," for a kingdom boon anytime."]}),i(n,{children:" "}),i(n,{dimColor:!0,children:"Enter to continue"})]}),o==="move"&&P(Ue,{children:[i(n,{bold:!0,color:"cyan",children:"Movement"}),i(n,{children:" "}),i(n,{children:"Move the cursor with:"}),P(n,{children:[" ",i(n,{bold:!0,children:"h j k l"})," (vim) \xB7 ",i(n,{bold:!0,children:"W A S D"})," \xB7 ",i(n,{bold:!0,children:"Arrow keys"})]}),i(n,{children:" "}),P(n,{children:["Try moving around \u2014 ",p?i(n,{color:"green",bold:!0,children:"Great! Press Enter to continue."}):i(n,{dimColor:!0,children:"move at least 4 times to proceed"})]}),i(n,{children:" "}),u()]}),o==="place_wall"&&P(Ue,{children:[P(n,{bold:!0,color:"cyan",children:["Build: Stone Wall ",i(n,{color:"white",children:"#"})]}),i(n,{children:" "}),P(n,{children:["Walls ",i(n,{bold:!0,children:"block raiders"})," and force them to find another path."]}),i(n,{children:"They have HP and will eventually break if attacked."}),i(n,{children:" "}),P(n,{children:["Move to an empty cell and press ",i(n,{bold:!0,children:"Enter"})," to place one."]}),i(n,{children:" "}),u(),i(n,{children:" "}),i(n,{dimColor:!0,children:"Move with h/j/k/l \xB7 place with Enter"})]}),o==="place_treasury"&&P(Ue,{children:[P(n,{bold:!0,color:"cyan",children:["Build: Treasury ",i(n,{color:"yellow",children:"$"})]}),i(n,{children:" "}),P(n,{children:["Treasuries are what ",i(n,{bold:!0,color:"red",children:"raiders target"}),"."]}),P(n,{children:["They also generate ",i(n,{bold:!0,children:"passive income"})," over time."]}),i(n,{children:"Place them in protected spots behind your walls!"}),i(n,{children:" "}),i(n,{children:"Place a treasury somewhere on the grid."}),i(n,{children:" "}),u(),i(n,{children:" "}),i(n,{dimColor:!0,children:"Move and press Enter to place"})]}),o==="place_archer"&&P(Ue,{children:[P(n,{bold:!0,color:"cyan",children:["Build: Archer Tower ",i(n,{color:"redBright",children:"!"})]}),i(n,{children:" "}),P(n,{children:["Archer towers ",i(n,{bold:!0,children:"shoot arrows"})," at raiders within range."]}),i(n,{children:"They fire automatically and can kill raiders before they reach your treasury."}),i(n,{children:"Place them where raiders will pass by!"}),i(n,{children:" "}),i(n,{children:"Place an archer tower on the grid."}),i(n,{children:" "}),u(),i(n,{children:" "}),i(n,{dimColor:!0,children:"Move and press Enter to place"})]}),o==="place_trap"&&P(Ue,{children:[P(n,{bold:!0,color:"cyan",children:["Build: Bear Trap ",i(n,{color:"magenta",children:"%"})]}),i(n,{children:" "}),P(n,{children:["Traps ",i(n,{bold:!0,children:"stun raiders"})," that walk over them."]}),i(n,{children:"A stunned raider can't move for several ticks \u2014 perfect for"}),i(n,{children:"your archer towers to finish them off!"}),i(n,{children:" "}),i(n,{children:"Place a bear trap on a path raiders might take."}),i(n,{children:" "}),u(),i(n,{children:" "}),i(n,{dimColor:!0,children:"Move and press Enter to place"})]}),o==="upgrade_explain"&&P(Ue,{children:[i(n,{bold:!0,color:"cyan",children:"Upgrading & More Structures"}),i(n,{children:" "}),i(n,{children:"In the full game you can:"}),i(n,{children:" "}),P(n,{children:[" ",i(n,{bold:!0,children:"u"})," Upgrade a structure (Lv.1 \u2192 2 \u2192 3) for better stats"]}),P(n,{children:[" ",i(n,{bold:!0,children:"x"})," Demolish a structure (get 50% refund)"]}),P(n,{children:[" ",i(n,{bold:!0,children:"1-6"})," Quick-select any structure type"]}),i(n,{children:" "}),i(n,{children:"Two structures you haven't placed yet:"}),i(n,{children:" "}),P(n,{children:[" ",i(n,{color:"cyan",bold:!0,children:fe.ward})," ",tt.ward," \u2014 Place next to a treasury to ",i(n,{bold:!0,children:"reduce loot"})]}),i(n,{children:" raiders can steal. Wards protect a 1-tile radius around them."}),i(n,{children:" "}),P(n,{children:[" ",i(n,{color:"green",bold:!0,children:fe.watchtower})," ",tt.watchtower," \u2014 ",i(n,{bold:!0,children:"Extends ward range"})," when adjacent."]}),i(n,{children:" Also auto-gathers forage nearby and earns passive stone."}),i(n,{children:" "}),i(n,{dimColor:!0,children:"Combo: Ward next to Treasury + Watchtower next to Ward = max protection!"}),i(n,{children:" "}),i(n,{dimColor:!0,children:"Enter to continue"})]}),o==="first_raid"&&P(Ue,{children:[i(n,{bold:!0,color:"cyan",children:"Your First Raid!"}),i(n,{children:" "}),i(n,{children:"Let's test your defenses. Two raiders will attack your layout:"}),i(n,{children:" "}),u(),i(n,{children:" "}),P(n,{children:[" You placed: ",T.map(w=>P(n,{children:[i(n,{color:ls[w.kind],bold:!0,children:fe[w.kind]})," "]},w.id))]}),i(n,{children:" "}),i(n,{bold:!0,color:"yellow",children:"Press any key to simulate the raid!"})]}),o==="raid_result"&&P(Ue,{children:[i(n,{bold:!0,color:x==="win"?"green":"yellow",children:x==="win"?"Victory! Your defenses held!":"The raiders got through \u2014 but that's okay!"}),i(n,{children:" "}),i(n,{bold:!0,children:"Raid replay:"}),d.map((w,H)=>i(n,{color:w.includes("WIN")?"green":w.includes("eliminated")||w.includes("destroyed")?"cyan":w.includes("breached")||w.includes("through")?"red":w.includes("stunned")?"magenta":void 0,children:w},H)),i(n,{children:" "}),x!=="win"&&i(n,{dimColor:!0,children:"Don't worry \u2014 you'll have plenty of resources to build better defenses!"}),i(n,{children:" "}),i(n,{dimColor:!0,children:"Enter to continue"})]}),o==="foraging"&&P(Ue,{children:[i(n,{bold:!0,color:"cyan",children:"Foraging"}),i(n,{children:" "}),P(n,{children:["Glowing ",i(n,{color:"cyan",bold:!0,children:"~"})," fragments appear on your grid over time."]}),P(n,{children:["Move your cursor over one and press ",i(n,{bold:!0,children:"c"})," to collect resources!"]}),i(n,{children:" "}),P(n,{children:[" ",i(n,{color:"cyan",children:"~"})," Gold Nugget ",i(n,{color:"yellow",children:"~"})," Timber ",i(n,{color:"green",children:"~"})," Ore ",i(n,{color:"white",children:"~"})," Gem"]}),i(n,{children:" "}),i(n,{children:"Structure synergies:"}),P(n,{children:[" ",i(n,{color:"redBright",children:"!"})," Archer Towers increase spawn rate"]}),P(n,{children:[" ",i(n,{color:"yellow",children:"$"})," Treasuries boost yield when nearby"]}),P(n,{children:[" ",i(n,{color:"green",children:"^"})," Watchtowers auto-collect nearby fragments"]}),i(n,{children:" "}),i(n,{dimColor:!0,children:"Enter to continue"})]}),o==="tips"&&P(Ue,{children:[i(n,{bold:!0,color:"cyan",children:"Pro Tips"}),i(n,{children:" "}),P(n,{children:[" ",i(n,{bold:!0,children:"?"})," Full help screen (anytime)"]}),P(n,{children:[" ",i(n,{bold:!0,children:"1-6"})," Quick-select structures"]}),P(n,{children:[" ",i(n,{bold:!0,children:"Tab"})," Jump between your structures"]}),P(n,{children:[" ",i(n,{bold:!0,children:"r"})," Quick defend (instant raid result)"]}),P(n,{children:[" ",i(n,{bold:!0,children:"v"})," Watch replay of last defense"]}),P(n,{children:[" ",i(n,{bold:!0,children:"f"})," Kingdom boon (free resources)"]}),P(n,{children:[" ",i(n,{bold:!0,children:"Esc"})," Back to main menu"]}),i(n,{children:" "}),i(n,{bold:!0,children:"Strategy:"}),P(n,{children:[" \u2022 Place walls to create ",i(n,{bold:!0,children:"chokepoints"})]}),P(n,{children:[" \u2022 Put traps in the chokepoint so raiders get ",i(n,{bold:!0,children:"stunned"})]}),P(n,{children:[" \u2022 Put archer towers nearby to ",i(n,{bold:!0,children:"finish stunned raiders"})]}),P(n,{children:[" \u2022 Hide treasuries ",i(n,{bold:!0,children:"deep inside"})," your walls"]}),P(n,{children:[" \u2022 Place wards next to treasuries to ",i(n,{bold:!0,children:"reduce loot stolen"})]}),P(n,{children:[" \u2022 ",i(n,{bold:!0,children:"Hover over"})," towers/wards to see their ",i(n,{bold:!0,color:"red",children:"range overlay"})]}),i(n,{children:" "}),i(n,{dimColor:!0,children:"Enter to continue"})]}),o==="done"&&P(Ue,{children:[i(n,{bold:!0,color:"yellow",children:"You're ready to defend your keep!"}),i(n,{children:" "}),i(n,{children:"Your structures from the tutorial won't carry over \u2014 you start"}),i(n,{children:"with a clean grid and starting resources."}),i(n,{children:" "}),i(n,{children:"Go forth, build wisely, and may your walls hold strong!"}),i(n,{children:" "}),i(n,{dimColor:!0,children:"Press Enter to start playing"})]})]})}import{Box as cs,Text as Xo}from"ink";import{jsx as qn,jsxs as yo}from"react/jsx-runtime";var Yn={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"};function jn(e){let t=[];return e.gold>0&&t.push(`${B.gold}${e.gold}`),e.wood>0&&t.push(`${B.wood}${e.wood}`),e.stone>0&&t.push(`${B.stone}${e.stone}`),t.join(" ")}function us({selected:e}){return yo(cs,{flexDirection:"column",children:[qn(Xo,{bold:!0,children:"Structures [ ]"}),ct.map((t,o)=>{let s=t===e,r=ot[t][1];return yo(cs,{children:[yo(Xo,{color:s?Yn[t]:void 0,bold:s,dimColor:!s,children:[s?"\u25B8":" "," ",o+1," ",fe[t]," ",tt[t]]}),s&&yo(Xo,{dimColor:!0,children:[" ",jn(r)]})]},t)})]})}import{useState as zn}from"react";import{Box as wo,Text as ft,useInput as Zn}from"ink";import{jsx as At,jsxs as Ht}from"react/jsx-runtime";var Qo=[{name:"Lord Ironhelm",seed:"friend-ironhelm-42",difficulty:1,tagline:"A minor lord with modest fortifications"},{name:"Lady Ashwood",seed:"friend-ashwood-99",difficulty:2,tagline:"Her archers never miss \u2014 or so she claims"},{name:"Baron Stonewatch",seed:"friend-stonewatch-256",difficulty:3,tagline:"Walls thick as legends and twice as old"}];function ps({onSelectFriend:e,onBack:t}){let[o,s]=zn(0);return Zn((r,a)=>{if(r==="k"||r==="w"||a.upArrow)s(T=>Math.max(0,T-1));else if(r==="j"||r==="s"||a.downArrow)s(T=>Math.min(Qo.length-1,T+1));else if(a.return){let T=Qo[o],f=To(T.seed,T.difficulty);f.name=`${T.name}'s Keep`,f.ownerPlayerId=T.name.toLowerCase(),e(f)}else(r==="q"||a.escape)&&t()}),Ht(wo,{flexDirection:"column",padding:1,children:[At(wo,{children:At(ft,{bold:!0,color:"cyan",children:"\u2694 Rival Keeps"})}),At(ft,{children:" "}),At(ft,{dimColor:!0,children:" Choose a rival lord's keep to raid for plunder."}),At(ft,{children:" "}),Qo.map((r,a)=>Ht(wo,{flexDirection:"column",children:[Ht(wo,{children:[Ht(ft,{color:a===o?"yellow":void 0,bold:a===o,children:[a===o?" \u25B8 ":" ",r.name]}),Ht(ft,{dimColor:!0,children:[" Lv.",r.difficulty]})]}),a===o&&Ht(ft,{dimColor:!0,children:[' "',r.tagline,'"']})]},r.name)),At(ft,{children:" "}),At(ft,{dimColor:!0,children:" \u2191\u2193 navigate Enter raid Esc back"})]})}import{useState as fs}from"react";import{Box as Qt,Text as we,useInput as Jn}from"ink";import{Fragment as ta,jsx as $e,jsxs as Xe}from"react/jsx-runtime";function Xn(e){let t=[];return e.gold>0&&t.push(`+${e.gold}${B.gold}`),e.wood>0&&t.push(`+${e.wood}${B.wood}`),e.stone>0&&t.push(`+${e.stone}${B.stone}`),t.join(" ")}function Qn(e){let t=[];return e.gold>0&&t.push(`-${e.gold}${B.gold}`),e.wood>0&&t.push(`-${e.wood}${B.wood}`),e.stone>0&&t.push(`-${e.stone}${B.stone}`),t.join(" ")}function ms({gameSave:e,onBack:t,onWatchReplay:o}){let[s,r]=fs("raids"),[a,T]=fs(0),f=[...e.raidHistory].reverse().slice(0,15);Jn((l,x)=>{if(l==="q"||x.escape){t();return}(x.tab||l==="t")&&r(k=>k==="raids"?"achievements":"raids"),s==="raids"&&f.length>0&&((l==="j"||x.downArrow)&&T(k=>Math.min(k+1,f.length-1)),(l==="k"||x.upArrow)&&T(k=>Math.max(k-1,0)),(x.return||l==="v")&&f[a]&&o&&o(f[a]))});let d=e.progression;return Xe(Qt,{flexDirection:"column",padding:1,children:[Xe(Qt,{gap:2,children:[$e(we,{bold:!0,color:s==="raids"?"yellow":void 0,underline:s==="raids",children:"Raid Log"}),$e(we,{bold:!0,color:s==="achievements"?"yellow":void 0,underline:s==="achievements",children:"Achievements"}),$e(we,{dimColor:!0,children:"(Tab to switch)"})]}),$e(we,{children:" "}),s==="raids"&&Xe(Qt,{flexDirection:"column",children:[Xe(we,{dimColor:!0,children:[" Total: ",d.totalRaidsWon,"W / ",d.totalRaidsLost,"L \xB7 Streak: ",d.currentWinStreak," (best ",d.bestWinStreak,")"]}),$e(we,{children:" "}),f.length===0?$e(we,{dimColor:!0,children:" No raids yet. Try Defend Keep or Attack NPC!"}):f.map((l,x)=>{let k=ea(l.resolvedAtUnixMs),R=l.attackerId!==e.player.id,m=l.outcome==="defense_win"?R?"\u2713":"\u2717":R?"\u2717":"\u2713",p=(R?l.outcome==="defense_win":l.outcome!=="defense_win")?"green":"red",b=R?"DEF":"ATK",c=l.lootLost.gold+l.lootLost.wood+l.lootLost.stone>0?` ${Qn(l.lootLost)}`:"",$=l.lootGained.gold+l.lootGained.wood+l.lootGained.stone>0?` ${Xn(l.lootGained)}`:"",z=x===a?">":" ";return Xe(we,{dimColor:x>4&&x!==a,bold:x===a,children:[z," ",$e(we,{color:p,children:m})," ",b," ",l.outcome.replace("_"," "),c,$," ",Xe(we,{dimColor:!0,children:["(",k,")"]})]},l.id)}),f.length>0&&Xe(ta,{children:[$e(we,{children:" "}),$e(we,{dimColor:!0,children:" j/k navigate \xB7 Enter/v watch replay"})]})]}),s==="achievements"&&Xe(Qt,{flexDirection:"column",children:[Xe(we,{dimColor:!0,children:[" ",d.achievements?.length||0," / ",zt.length," earned"]}),$e(we,{children:" "}),zt.map(l=>{let x=d.achievements?.includes(l.id);return $e(Qt,{children:Xe(we,{color:x?"green":void 0,dimColor:!x,children:[" ",x?"\u2605":"\u2606"," ",$e(we,{bold:x,children:l.name})," \u2014 ",l.desc,l.bonus&&x?Xe(we,{color:"yellow",children:[" (",l.bonus,")"]}):null]})},l.id)})]}),$e(we,{children:" "}),$e(we,{dimColor:!0,children:" Tab switch \xB7 Esc/q back"})]})}function ea(e){let t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}import{useState as So}from"react";import{Box as bo,Text as be,useInput as aa}from"ink";import{writeFileSync as oa,mkdirSync as ra,existsSync as sa}from"fs";import{join as gs}from"path";import{homedir as na}from"os";var er=gs(na(),".config","codekeep","crashes");function hs(e,t){if((e instanceof Error?e.message:String(e)).includes("Raw mode is not supported"))return"";sa(er)||ra(er,{recursive:!0});let s={timestamp:new Date().toISOString(),error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,version:globalThis.__CODEKEEP_VERSION??"unknown",nodeVersion:process.version,platform:process.platform,arch:process.arch,screen:t?.screen,gameState:t?.gameState},r=`crash-${Date.now()}.json`,a=gs(er,r);return oa(a,JSON.stringify(s,null,2),"utf-8"),a}function Ro(e){let t=encodeURIComponent(`[Crash]: ${e.error.slice(0,80)}`),o=encodeURIComponent(`## Crash Report
10
+ \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u255D \u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D \u255A\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u255D\u255A\u2550\u255D`}),uo(mt,{children:" "}),$t(mt,{dimColor:!0,children:[" ",e.player.displayName,"'s Keep \u2014 ",_,"d old"]}),$t(mt,{dimColor:!0,children:[" ",w," structures (",j,"$ ",K,"!) \xB7 Raids ",h.totalRaidsWon,"W / ",h.totalRaidsLost,"L \xB7 Streak ",h.currentWinStreak," (best ",h.bestWinStreak,")"]}),$t(mt,{dimColor:!0,children:[" Difficulty: Lv.",Dt(x),e.prestige?` \u2605 Ascension ${e.prestige.ascensionLevel}`:""]}),$t(mt,{dimColor:!0,children:[" Achievements: ",e.progression.achievements?.length||0,"/",10,e.activeBuffs&&e.activeBuffs.length>0?` Buffs: ${e.activeBuffs.length}`:""]}),uo(mt,{children:" "}),u.map((N,$)=>$t(on,{children:[$t(mt,{color:N.disabled?void 0:$===i?"yellow":void 0,bold:!N.disabled&&$===i,dimColor:N.disabled,children:[$===i&&!N.disabled?" \u25B8 ":" ",N.label]}),$t(mt,{dimColor:!0,children:[" ",N.desc]})]},N.key)),uo(mt,{children:" "}),uo(mt,{dimColor:!0,children:" \u2191\u2193 navigate Enter select q quit"})]})}import{useState as vt,useEffect as sn,useCallback as ja,useRef as qa}from"react";import{Box as gt,Text as Q,useInput as za}from"ink";import{jsx as ne,jsxs as ve}from"react/jsx-runtime";var Ur={raider:"R",scout:"S",brute:"B"};function Gr(e,t){let o=e/t;return o>.6?"green":o>.3?"yellow":"red"}function Xa(e,t){let o=e/t;return o>.6?"white":o>.3?"yellow":"red"}function Wr(e,t){let o=[];return e.gold>0&&o.push(`${t}${e.gold}${W.gold}`),e.wood>0&&o.push(`${t}${e.wood}${W.wood}`),e.stone>0&&o.push(`${t}${e.stone}${W.stone}`),o.join(" ")}function Za(e,t,o=6){let s=Math.round(e/t*o);return"\u2588".repeat(s)+"\u2591".repeat(o-s)}var Ja={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"};function Kr({replay:e,keepGrid:t,raidType:o,summary:s,anomalies:r,initialSpeed:n,onSpeedChange:c,onDone:d}){let[g,l]=vt(0),[T,R]=vt(n??1),u=ja(C=>{R(C),c?.(C)},[c]),[i,y]=vt(!1),[w,h]=vt(new Map),[x,_]=vt(()=>{let C=new Map,B={wall:Eo,archerTower:Ao,watchtower:Mo,vault:Lo};for(let E of t.structures){let F=B[E.kind];if(F){let D=F[E.level];C.set(E.id,{structureId:E.id,kind:E.kind,pos:{...E.pos},hp:D,maxHp:D,destroyed:!1})}}return C}),[j,K]=vt([]),[N,$]=vt(new Set),[U,k]=vt([]),[b,L]=vt(null),m=qa(-1);za((C,B)=>{if(C==="q"||B.escape){d();return}if(C==="p"||C===" "){y(E=>!E);return}C==="1"&&u(1),C==="2"&&u(2),C==="4"&&u(4),C==="8"&&u(8),(C==="n"||B.return)&&l(e.maxTicks)}),sn(()=>{if(i||b)return;let C=setInterval(()=>{l(B=>{let E=B+1;return E>e.maxTicks?(clearInterval(C),B):E})},1e3/e.tickRateHz/T);return()=>clearInterval(C)},[i,T,b,e]),sn(()=>{if(g<=m.current)return;let C=e.events.filter(D=>D.t>m.current&&D.t<=g),B=[],E=[],F=new Map;h(D=>{let q=new Map(D);for(let H of C)switch(H.type){case"raider_spawn":{let Z=H.raiderType??"raider",Ee=H.maxHp??Qe[Z].hp;q.set(H.probeId,{id:H.probeId,pos:{...H.pos},alive:!0,stunned:!1,hp:Ee,maxHp:Ee,raiderType:Z});break}case"raider_move":{let Z=q.get(H.probeId);Z&&(Z.pos={...H.to},Z.stunned=!1);break}case"raider_stunned":{let Z=q.get(H.probeId);Z&&(Z.stunned=!0);break}case"arrow_hit":{let Z=q.get(H.probeId);Z&&(Z.hp=Math.max(0,H.hpRemaining));break}case"raider_destroyed":{let Z=q.get(H.probeId);Z&&(Z.alive=!1);break}default:break}return F=q,q}),_(D=>{let q=new Map(D);for(let H of C)if(H.type==="wall_damaged"||H.type==="structure_damaged"){let Z=q.get(H.structureId);Z&&(Z.hp=Math.max(0,H.hpRemaining),Z.destroyed=H.destroyed)}return q});for(let D of C)switch(D.type){case"raider_spawn":{let q=D.raiderType??"raider",H=Ur[q]??"R",Z=D.edge==="N"?"\u2193":D.edge==="S"?"\u2191":D.edge==="W"?"\u2192":"\u2190";B.push(`${H} Raider ${D.probeId+1} enters from ${D.edge} ${Z}`),E.push({pos:{...D.pos},char:Z,color:"yellowBright",bold:!0,expiresAtTick:g+3,priority:0});break}case"raider_stunned":{B.push(`\u26A1 Raider ${D.probeId+1} STUNNED ${D.stunTicks}t`),E.push({pos:{...D.pos},char:"\u2727",color:"cyanBright",bold:!0,expiresAtTick:g+3,priority:2});break}case"wall_damaged":{if(D.destroyed){B.push("\u{1F4A5} Wall DESTROYED!");let q=t.structures.find(H=>H.id===D.structureId);q&&E.push({pos:{...q.pos},char:"\u2717",color:"redBright",bold:!0,expiresAtTick:g+4,priority:2})}else B.push(`\u2694 Wall hit (${D.hpRemaining} HP)`);break}case"structure_damaged":{let q=Je[D.structureKind]??D.structureKind;if(D.destroyed){B.push(`\u{1F4A5} ${q} DESTROYED!`);let H=t.structures.find(Z=>Z.id===D.structureId);H&&E.push({pos:{...H.pos},char:"\u2717",color:"redBright",bold:!0,expiresAtTick:g+5,priority:3})}else B.push(`\u2694 ${q} hit (${D.hpRemaining} HP)`);break}case"arrow_hit":{let q=F.get(D.probeId),H=q?{...q.pos}:null;H&&E.push({pos:H,char:"\u2020",color:"redBright",bold:!0,expiresAtTick:g+2,priority:1}),D.hpRemaining<=0?(B.push(`\u{1F3F9} Archer slew raider ${D.probeId+1}!`),H&&E.push({pos:H,char:"\u2716",color:"redBright",bold:!0,expiresAtTick:g+4,priority:3})):B.push(`\u{1F3F9} Arrow hit raider ${D.probeId+1} (-${D.damage} \u2192 ${D.hpRemaining} HP)`);break}case"treasury_breach":{let q=Wr(D.lootTaken,""),H=o==="attack"?"Looted":"Lost";B.push(`\u{1F4B0} TREASURY BREACHED! ${H} ${q}`),$(Ee=>new Set([...Ee,D.structureId]));let Z=t.structures.find(Ee=>Ee.id===D.structureId);Z&&E.push({pos:{...Z.pos},char:"\u26A1",color:"yellowBright",bold:!0,expiresAtTick:g+5,priority:3});break}case"raider_destroyed":{C.some(H=>H.type==="arrow_hit"&&H.probeId===D.probeId&&H.hpRemaining<=0&&H.t===D.t)||B.push(`\u{1F480} Raider ${D.probeId+1} eliminated`);break}case"raid_end":{let q=D.outcome==="defense_win"?o==="defend"?"DEFENSE VICTORY \u2014 All raiders defeated!":"ATTACK FAILED \u2014 The keep held strong":D.outcome==="partial_breach"?o==="defend"?"PARTIAL BREACH \u2014 Raiders stole some supplies":"PARTIAL SUCCESS \u2014 Some loot seized":o==="defend"?"FULL BREACH \u2014 Major losses!":"FULL SUCCESS \u2014 Major plunder!";L(q),B.push(q);break}default:break}K(D=>[...D.filter(q=>q.expiresAtTick>g),...E]),m.current=g,B.length>0&&k(D=>[...D.slice(-10),...B])},[g,o,e,t]);let P=new Map;for(let C of t.structures)P.set(`${C.pos.x},${C.pos.y}`,C);if(!t.structures.some(C=>C.kind==="treasury")){let C={id:"__virtual_center_treasury",kind:"treasury",pos:{x:8,y:8},level:1};P.set("8,8",C)}let se=new Map;for(let[,C]of w)C.alive&&se.set(`${C.pos.x},${C.pos.y}`,C);let v=new Map;for(let[,C]of x)v.set(`${C.pos.x},${C.pos.y}`,C);let oe=new Map;for(let C of j){let B=`${C.pos.x},${C.pos.y}`,E=oe.get(B);(!E||C.priority>E.priority||C.priority===E.priority&&C.expiresAtTick>E.expiresAtTick)&&oe.set(B,C)}let fe=" "+Array.from({length:I},(C,B)=>B.toString(16).toUpperCase()+" ").join(""),be=[ne(Q,{dimColor:!0,children:fe},"hdr")];for(let C=0;C<I;C++){let B=[ne(Q,{dimColor:!0,children:C.toString(16).toUpperCase()+" "},"lbl")];for(let E=0;E<I;E++){let F=`${E},${C}`,D=se.get(F),q=P.get(F),H=v.get(F),Z=oe.get(F);if(Z&&!D)B.push(ne(Q,{color:Z.color,bold:Z.bold,children:Z.char+" "},E));else if(D){let Ee=D.stunned?"\u25CA":Ur[D.raiderType]??"\u25CF",Tt=D.stunned?"cyan":Gr(D.hp,D.maxHp);B.push(ne(Q,{color:Tt,bold:!0,children:Ee+" "},E))}else if(q)if(H&&!H.destroyed){let Ee=Xa(H.hp,H.maxHp),Tt=ye[H.kind]??"#";B.push(ne(Q,{color:Ee,bold:H.hp>H.maxHp*.6,children:Tt+" "},E))}else if(H&&H.destroyed)B.push(ne(Q,{color:"red",dimColor:!0,children:"x "},E));else if(N.has(q.id))B.push(ne(Q,{color:"red",bold:!0,children:"$ "},E));else{let Ee=ye[q.kind];B.push(ne(Q,{color:Ja[q.kind]||"white",children:Ee+" "},E))}else B.push(ne(Q,{dimColor:!0,children:yt+" "},E))}be.push(ne(gt,{children:B},C))}let me=Array.from(w.values()).filter(C=>C.alive),Te=Array.from(w.values()).filter(C=>!C.alive);return ve(gt,{flexDirection:"column",padding:1,children:[ve(gt,{flexDirection:"row",gap:2,children:[ne(Q,{bold:!0,color:o==="defend"?"red":"green",children:o==="defend"?"\u2694 DEFENDING YOUR KEEP":"\u2694 ATTACKING NPC KEEP"}),ve(Q,{children:["Tick: ",g,"/",e.maxTicks]}),ve(Q,{children:["Speed: ",T,"x"]}),ne(Q,{dimColor:!0,children:i?"[PAUSED]":""})]}),r&&r.length>0&&ve(Q,{color:"yellow",bold:!0,children:["\u26A1 Anomalies: ",r.map(C=>`${C.icon} ${C.name}`).join(" ")]}),ne(Q,{children:" "}),ve(gt,{flexDirection:"row",children:[ne(gt,{flexDirection:"column",children:be}),ve(gt,{flexDirection:"column",marginLeft:2,width:38,children:[me.length>0&&ve(gt,{flexDirection:"column",marginBottom:1,children:[ne(Q,{bold:!0,children:"Raiders"}),me.map(C=>ve(gt,{children:[ve(Q,{color:Gr(C.hp,C.maxHp),bold:!0,children:[Ur[C.raiderType],C.id+1]}),ne(Q,{children:" "}),ne(Q,{color:Gr(C.hp,C.maxHp),children:Za(C.hp,C.maxHp)}),ve(Q,{dimColor:!0,children:[" ",C.hp,"/",C.maxHp]}),C.stunned&&ne(Q,{color:"cyan",children:" STUN"})]},C.id)),Te.length>0&&ve(Q,{dimColor:!0,children:[" ",Te.length," slain"]})]}),ne(Q,{bold:!0,children:"Battle Log"}),(()=>{let C=U.slice(-10);return C.map((B,E)=>ne(Q,{dimColor:E<Math.max(0,C.length-3),wrap:"truncate",children:B},E))})()]})]}),ne(Q,{children:" "}),b?ve(gt,{flexDirection:"column",children:[ne(Q,{bold:!0,color:b.includes("VICTORY")||b.includes("SUCCESS")?"green":"red",children:b}),s&&ve(gt,{flexDirection:"column",marginTop:1,children:[ne(Q,{bold:!0,children:"\u2550\u2550\u2550 Raid Summary \u2550\u2550\u2550"}),ve(Q,{children:["Difficulty: Lv.",s.difficulty," Raiders: ",s.raidersKilled,"/",s.raidersTotal," slain"]}),ve(Q,{children:["Walls destroyed: ",s.wallsDestroyed," Archer towers: ",s.archersActive]}),s.lootGained.gold+s.lootGained.wood+s.lootGained.stone>0&&ve(Q,{color:"green",children:["Resources gained: ",Wr(s.lootGained,"+")]}),s.lootLost.gold+s.lootLost.wood+s.lootLost.stone>0&&ve(Q,{color:"red",children:["Resources lost: ",Wr(s.lootLost,"-")]})]}),ne(Q,{dimColor:!0,children:"Press q to return"})]}):ve(gt,{flexDirection:"column",children:[ne(Q,{dimColor:!0,children:"p pause 1/2/4/8 speed n/\u21B5 skip q back"}),ve(Q,{dimColor:!0,children:[ne(Q,{color:"green",bold:!0,children:"R"}),"=Raider ",ne(Q,{color:"yellow",bold:!0,children:"S"}),"=Scout ",ne(Q,{color:"red",bold:!0,children:"B"}),"=Brute ",ne(Q,{color:"cyan",children:"\u25CA"}),"=Stunned ",ne(Q,{color:"red",children:"\u2716"}),"=Kill ",ne(Q,{color:"redBright",children:"\u2020"}),"=Arrow ",ne(Q,{color:"yellowBright",children:"\u2193\u2191\u2192\u2190"}),"=Spawn"]})]})]})}import{useState as eo,useCallback as nn}from"react";import{Box as Vo,Text as a,useInput as Qa}from"ink";import{Fragment as et,jsx as p,jsxs as G}from"react/jsx-runtime";var po=["welcome","resources","move","place_wall","place_treasury","place_archer","place_trap","upgrade_explain","first_raid","raid_result","foraging","tips","done"],an={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"};function ln({gameSave:e,onComplete:t}){let[o,s]=eo("welcome"),[r,n]=eo({x:7,y:7}),[c,d]=eo([]),[g,l]=eo([]),[T,R]=eo(""),[u,i]=eo(0),y=u>=4,w=po.indexOf(o),h=po.length-1,x=nn(()=>{let $=po.indexOf(o);$<po.length-1&&s(po[$+1])},[o]),_=o==="place_wall"?"wall":o==="place_treasury"?"treasury":o==="place_archer"?"archerTower":o==="place_trap"?"trap":null,j=nn(()=>{let $={width:16,height:16,structures:[...c]},U=ut({probeCount:2,keepGrid:$,seed:"tutorial-raid",probeTypes:["raider","scout"]}),k=[],b=0,L=0,m=!1;for(let Y of U.events)Y.type==="raider_spawn"?k.push(` Raider ${Y.probeId+1} appears from the ${Y.edge} edge`):Y.type==="wall_damaged"&&Y.destroyed?(L++,k.push(" A stone wall was destroyed!")):Y.type==="raider_stunned"?k.push(` Raider ${Y.probeId+1} stepped on a bear trap \u2014 stunned!`):Y.type==="arrow_hit"&&Y.hpRemaining<=0?(b++,k.push(` Archer tower eliminated raider ${Y.probeId+1}!`)):Y.type==="raider_destroyed"&&!k[k.length-1]?.includes(`raider ${Y.probeId+1}`)?(b++,k.push(` Raider ${Y.probeId+1} was destroyed`)):Y.type==="treasury_breach"?(m=!0,k.push(" Raiders breached your treasury!")):Y.type==="raid_end"&&(Y.outcome==="defense_win"?k.push(" \u2713 DEFENSE WIN \u2014 all raiders defeated!"):k.push(" \u2717 Raiders got through \u2014 time to strengthen defenses"));if(k.length>10){let Y=[...k.slice(0,3),` ... ${k.length-6} more events ...`,...k.slice(-3)];l(Y)}else l(k);let P=U.events.find(Y=>Y.type==="raid_end");R(P?.type==="raid_end"&&P.outcome==="defense_win"?"win":"loss"),x()},[c,x]);Qa(($,U)=>{if($==="s"&&o!=="move"){t();return}if(["welcome","resources","move","upgrade_explain","first_raid","raid_result","foraging","tips","done"].includes(o)){if(o==="move"){if($==="h"||$==="a"||U.leftArrow){n(b=>({...b,x:Math.max(0,b.x-1)})),i(b=>b+1);return}if($==="l"||$==="d"||U.rightArrow){n(b=>({...b,x:Math.min(I-1,b.x+1)})),i(b=>b+1);return}if($==="k"||$==="w"||U.upArrow){n(b=>({...b,y:Math.max(0,b.y-1)})),i(b=>b+1);return}if($==="j"||U.downArrow){n(b=>({...b,y:Math.min(I-1,b.y+1)})),i(b=>b+1);return}if((U.return||$===" ")&&y){x();return}return}if(o==="first_raid"){j();return}if(o==="done"){t();return}(U.return||$===" ")&&x();return}if(_){if($==="h"||$==="a"||U.leftArrow)n(b=>({...b,x:Math.max(0,b.x-1)}));else if($==="l"||$==="d"||U.rightArrow)n(b=>({...b,x:Math.min(I-1,b.x+1)}));else if($==="k"||$==="w"||U.upArrow)n(b=>({...b,y:Math.max(0,b.y-1)}));else if($==="j"||U.downArrow)n(b=>({...b,y:Math.min(I-1,b.y+1)}));else if(U.return||$==="e"){if(c.some(m=>m.pos.x===r.x&&m.pos.y===r.y))return;let L={id:`tut-${_}-${r.x}-${r.y}`,kind:_,level:1,pos:{...r},placedAtUnixMs:Date.now()};d(m=>[...m,L]),x()}}});let K=()=>{let b=new Map;for(let m of c)b.set(`${m.pos.x},${m.pos.y}`,m);let L=[];for(let m=3;m<13;m++){let P=[];for(let Y=3;Y<13;Y++){let se=r.x===Y&&r.y===m,v=b.get(`${Y},${m}`),oe=yt,fe;v&&(oe=ye[v.kind],fe=an[v.kind]),se?P.push(p(a,{backgroundColor:"white",color:"black",bold:!0,children:oe+" "},Y)):fe?P.push(p(a,{color:fe,bold:!0,children:oe+" "},Y)):P.push(p(a,{dimColor:!0,children:oe+" "},Y))}L.push(p(Vo,{children:P},m))}return p(Vo,{flexDirection:"column",children:L})},N=`[${w}/${h}]`;return G(Vo,{flexDirection:"column",padding:1,children:[G(Vo,{children:[p(a,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep \u2014 Tutorial "}),p(a,{dimColor:!0,children:N})]}),p(a,{children:" "}),o==="welcome"&&G(et,{children:[G(a,{bold:!0,color:"cyan",children:["Welcome to CodeKeep, ",e.player.displayName,"!"]}),p(a,{children:" "}),G(a,{children:["CodeKeep is a ",p(a,{bold:!0,children:"tower defense"})," game played in your terminal."]}),p(a,{children:" "}),G(a,{children:[" ","Build a ",p(a,{bold:!0,children:"fortress"})," on a 16\xD716 grid"]}),G(a,{children:[" ","Place ",p(a,{bold:!0,children:"walls"}),", ",p(a,{bold:!0,children:"traps"}),", and ",p(a,{bold:!0,children:"archer towers"})," to defend"]}),G(a,{children:[" ","Protect your ",p(a,{bold:!0,color:"yellow",children:"treasuries"})," from raiding parties"]}),G(a,{children:[" ","Earn resources over time and from coding activity"]}),p(a,{children:" "}),p(a,{children:"Let's learn how to play!"}),p(a,{children:" "}),p(a,{dimColor:!0,children:"Enter to continue \xB7 s to skip tutorial"})]}),o==="resources"&&G(et,{children:[p(a,{bold:!0,color:"cyan",children:"Resources"}),p(a,{children:" "}),p(a,{children:"You have three resources to build and upgrade structures:"}),p(a,{children:" "}),G(a,{children:[" ",G(a,{color:"yellow",bold:!0,children:[W.gold," Gold"]})," \u2014 Your main currency. Earned from events and raids."]}),G(a,{children:[" ",G(a,{color:"green",bold:!0,children:[W.wood," Wood"]})," \u2014 Building material. Earned from treasuries and events."]}),G(a,{children:[" ",G(a,{color:"white",bold:!0,children:[W.stone," Stone"]})," \u2014 Heavy material. Used for walls and towers."]}),p(a,{children:" "}),p(a,{children:"Resources grow passively and from coding activity (git commits!)."}),G(a,{children:["You can also press ",p(a,{bold:!0,children:"f"})," for a kingdom boon anytime."]}),p(a,{children:" "}),p(a,{dimColor:!0,children:"Enter to continue"})]}),o==="move"&&G(et,{children:[p(a,{bold:!0,color:"cyan",children:"Movement"}),p(a,{children:" "}),p(a,{children:"Move the cursor with:"}),G(a,{children:[" ",p(a,{bold:!0,children:"h j k l"})," (vim) \xB7 ",p(a,{bold:!0,children:"W A S D"})," \xB7 ",p(a,{bold:!0,children:"Arrow keys"})]}),p(a,{children:" "}),G(a,{children:["Try moving around \u2014 ",y?p(a,{color:"green",bold:!0,children:"Great! Press Enter to continue."}):p(a,{dimColor:!0,children:"move at least 4 times to proceed"})]}),p(a,{children:" "}),K()]}),o==="place_wall"&&G(et,{children:[G(a,{bold:!0,color:"cyan",children:["Build: Stone Wall ",p(a,{color:"white",children:"#"})]}),p(a,{children:" "}),G(a,{children:["Walls ",p(a,{bold:!0,children:"block raiders"})," and force them to find another path."]}),p(a,{children:"They have HP and will eventually break if attacked."}),p(a,{children:" "}),G(a,{children:["Move to an empty cell and press ",p(a,{bold:!0,children:"Enter"})," to place one."]}),p(a,{children:" "}),K(),p(a,{children:" "}),p(a,{dimColor:!0,children:"Move with h/j/k/l \xB7 place with Enter"})]}),o==="place_treasury"&&G(et,{children:[G(a,{bold:!0,color:"cyan",children:["Build: Treasury ",p(a,{color:"yellow",children:"$"})]}),p(a,{children:" "}),G(a,{children:["Treasuries are what ",p(a,{bold:!0,color:"red",children:"raiders target"}),"."]}),G(a,{children:["They also generate ",p(a,{bold:!0,children:"passive income"})," over time."]}),p(a,{children:"Place them in protected spots behind your walls!"}),p(a,{children:" "}),p(a,{children:"Place a treasury somewhere on the grid."}),p(a,{children:" "}),K(),p(a,{children:" "}),p(a,{dimColor:!0,children:"Move and press Enter to place"})]}),o==="place_archer"&&G(et,{children:[G(a,{bold:!0,color:"cyan",children:["Build: Archer Tower ",p(a,{color:"redBright",children:"!"})]}),p(a,{children:" "}),G(a,{children:["Archer towers ",p(a,{bold:!0,children:"shoot arrows"})," at raiders within range."]}),p(a,{children:"They fire automatically and can kill raiders before they reach your treasury."}),p(a,{children:"Place them where raiders will pass by!"}),p(a,{children:" "}),p(a,{children:"Place an archer tower on the grid."}),p(a,{children:" "}),K(),p(a,{children:" "}),p(a,{dimColor:!0,children:"Move and press Enter to place"})]}),o==="place_trap"&&G(et,{children:[G(a,{bold:!0,color:"cyan",children:["Build: Bear Trap ",p(a,{color:"magenta",children:"%"})]}),p(a,{children:" "}),G(a,{children:["Traps ",p(a,{bold:!0,children:"stun raiders"})," that walk over them."]}),p(a,{children:"A stunned raider can't move for several ticks \u2014 perfect for"}),p(a,{children:"your archer towers to finish them off!"}),p(a,{children:" "}),p(a,{children:"Place a bear trap on a path raiders might take."}),p(a,{children:" "}),K(),p(a,{children:" "}),p(a,{dimColor:!0,children:"Move and press Enter to place"})]}),o==="upgrade_explain"&&G(et,{children:[p(a,{bold:!0,color:"cyan",children:"Upgrading & More Structures"}),p(a,{children:" "}),p(a,{children:"In the full game you can:"}),p(a,{children:" "}),G(a,{children:[" ",p(a,{bold:!0,children:"u"})," Upgrade a structure (Lv.1 \u2192 2 \u2192 3) for better stats"]}),G(a,{children:[" ",p(a,{bold:!0,children:"x"})," Demolish a structure (get 50% refund)"]}),G(a,{children:[" ",p(a,{bold:!0,children:"1-6"})," Quick-select any structure type"]}),p(a,{children:" "}),p(a,{children:"Two structures you haven't placed yet:"}),p(a,{children:" "}),G(a,{children:[" ",p(a,{color:"cyan",bold:!0,children:ye.ward})," ",Je.ward," \u2014 Place next to a treasury to ",p(a,{bold:!0,children:"reduce loot"})]}),p(a,{children:" raiders can steal. Wards protect a 1-tile radius around them."}),p(a,{children:" "}),G(a,{children:[" ",p(a,{color:"green",bold:!0,children:ye.watchtower})," ",Je.watchtower," \u2014 ",p(a,{bold:!0,children:"Extends ward range"})," when adjacent."]}),p(a,{children:" Also auto-gathers forage nearby and earns passive stone."}),p(a,{children:" "}),p(a,{dimColor:!0,children:"Combo: Ward next to Treasury + Watchtower next to Ward = max protection!"}),p(a,{children:" "}),p(a,{dimColor:!0,children:"Enter to continue"})]}),o==="first_raid"&&G(et,{children:[p(a,{bold:!0,color:"cyan",children:"Your First Raid!"}),p(a,{children:" "}),p(a,{children:"Let's test your defenses. Two raiders will attack your layout:"}),p(a,{children:" "}),K(),p(a,{children:" "}),G(a,{children:[" You placed: ",c.map($=>G(a,{children:[p(a,{color:an[$.kind],bold:!0,children:ye[$.kind]})," "]},$.id))]}),p(a,{children:" "}),p(a,{bold:!0,color:"yellow",children:"Press any key to simulate the raid!"})]}),o==="raid_result"&&G(et,{children:[p(a,{bold:!0,color:T==="win"?"green":"yellow",children:T==="win"?"Victory! Your defenses held!":"The raiders got through \u2014 but that's okay!"}),p(a,{children:" "}),p(a,{bold:!0,children:"Raid replay:"}),g.map(($,U)=>p(a,{color:$.includes("WIN")?"green":$.includes("eliminated")||$.includes("destroyed")?"cyan":$.includes("breached")||$.includes("through")?"red":$.includes("stunned")?"magenta":void 0,children:$},U)),p(a,{children:" "}),T!=="win"&&p(a,{dimColor:!0,children:"Don't worry \u2014 you'll have plenty of resources to build better defenses!"}),p(a,{children:" "}),p(a,{dimColor:!0,children:"Enter to continue"})]}),o==="foraging"&&G(et,{children:[p(a,{bold:!0,color:"cyan",children:"Foraging"}),p(a,{children:" "}),G(a,{children:["Glowing ",p(a,{color:"cyan",bold:!0,children:"~"})," fragments appear on your grid over time."]}),G(a,{children:["Move your cursor over one and press ",p(a,{bold:!0,children:"c"})," to collect resources!"]}),p(a,{children:" "}),G(a,{children:[" ",p(a,{color:"cyan",children:"~"})," Gold Nugget ",p(a,{color:"yellow",children:"~"})," Timber ",p(a,{color:"green",children:"~"})," Ore ",p(a,{color:"white",children:"~"})," Gem"]}),p(a,{children:" "}),p(a,{children:"Structure synergies:"}),G(a,{children:[" ",p(a,{color:"redBright",children:"!"})," Archer Towers increase spawn rate"]}),G(a,{children:[" ",p(a,{color:"yellow",children:"$"})," Treasuries boost yield when nearby"]}),G(a,{children:[" ",p(a,{color:"green",children:"^"})," Watchtowers auto-collect nearby fragments"]}),p(a,{children:" "}),p(a,{dimColor:!0,children:"Enter to continue"})]}),o==="tips"&&G(et,{children:[p(a,{bold:!0,color:"cyan",children:"Pro Tips"}),p(a,{children:" "}),G(a,{children:[" ",p(a,{bold:!0,children:"?"})," Full help screen (anytime)"]}),G(a,{children:[" ",p(a,{bold:!0,children:"1-6"})," Quick-select structures"]}),G(a,{children:[" ",p(a,{bold:!0,children:"Tab"})," Jump between your structures"]}),G(a,{children:[" ",p(a,{bold:!0,children:"r"})," Quick defend (instant raid result)"]}),G(a,{children:[" ",p(a,{bold:!0,children:"v"})," Watch replay of last defense"]}),G(a,{children:[" ",p(a,{bold:!0,children:"f"})," Kingdom boon (free resources)"]}),G(a,{children:[" ",p(a,{bold:!0,children:"Esc"})," Back to main menu"]}),p(a,{children:" "}),p(a,{bold:!0,children:"Strategy:"}),G(a,{children:[" \u2022 Place walls to create ",p(a,{bold:!0,children:"chokepoints"})]}),G(a,{children:[" \u2022 Put traps in the chokepoint so raiders get ",p(a,{bold:!0,children:"stunned"})]}),G(a,{children:[" \u2022 Put archer towers nearby to ",p(a,{bold:!0,children:"finish stunned raiders"})]}),G(a,{children:[" \u2022 Hide treasuries ",p(a,{bold:!0,children:"deep inside"})," your walls"]}),G(a,{children:[" \u2022 Place wards next to treasuries to ",p(a,{bold:!0,children:"reduce loot stolen"})]}),G(a,{children:[" \u2022 ",p(a,{bold:!0,children:"Hover over"})," towers/wards to see their ",p(a,{bold:!0,color:"red",children:"range overlay"})]}),p(a,{children:" "}),p(a,{dimColor:!0,children:"Enter to continue"})]}),o==="done"&&G(et,{children:[p(a,{bold:!0,color:"yellow",children:"You're ready to defend your keep!"}),p(a,{children:" "}),p(a,{children:"Your structures from the tutorial won't carry over \u2014 you start"}),p(a,{children:"with a clean grid and starting resources."}),p(a,{children:" "}),p(a,{children:"Go forth, build wisely, and may your walls hold strong!"}),p(a,{children:" "}),p(a,{dimColor:!0,children:"Press Enter to start playing"})]})]})}import{Box as dn,Text as Fr}from"ink";import{jsx as oi,jsxs as jo}from"react/jsx-runtime";var ei={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"};function ti(e){let t=[];return e.gold>0&&t.push(`${W.gold}${e.gold}`),e.wood>0&&t.push(`${W.wood}${e.wood}`),e.stone>0&&t.push(`${W.stone}${e.stone}`),t.join(" ")}function cn({selected:e}){return jo(dn,{flexDirection:"column",children:[oi(Fr,{bold:!0,children:"Structures [ ]"}),qe.map((t,o)=>{let s=t===e,r=wt[t][1];return jo(dn,{children:[jo(Fr,{color:s?ei[t]:void 0,bold:s,dimColor:!s,children:[s?"\u25B8":" "," ",o+1," ",ye[t]," ",Je[t]]}),s&&jo(Fr,{dimColor:!0,children:[" ",ti(r)]})]},t)})]})}import{useState as ri}from"react";import{Box as qo,Text as Ct,useInput as si}from"ink";import{jsx as Wt,jsxs as to}from"react/jsx-runtime";var Hr=[{name:"Lord Ironhelm",seed:"friend-ironhelm-42",difficulty:1,tagline:"A minor lord with modest fortifications"},{name:"Lady Ashwood",seed:"friend-ashwood-99",difficulty:2,tagline:"Her archers never miss \u2014 or so she claims"},{name:"Baron Stonewatch",seed:"friend-stonewatch-256",difficulty:3,tagline:"Walls thick as legends and twice as old"}];function un({onSelectFriend:e,onBack:t}){let[o,s]=ri(0);return si((r,n)=>{if(r==="k"||r==="w"||n.upArrow)s(c=>Math.max(0,c-1));else if(r==="j"||r==="s"||n.downArrow)s(c=>Math.min(Hr.length-1,c+1));else if(n.return){let c=Hr[o],d=Fo(c.seed,c.difficulty);d.name=`${c.name}'s Keep`,d.ownerPlayerId=c.name.toLowerCase(),e(d)}else(r==="q"||n.escape)&&t()}),to(qo,{flexDirection:"column",padding:1,children:[Wt(qo,{children:Wt(Ct,{bold:!0,color:"cyan",children:"\u2694 Rival Keeps"})}),Wt(Ct,{children:" "}),Wt(Ct,{dimColor:!0,children:" Choose a rival lord's keep to raid for plunder."}),Wt(Ct,{children:" "}),Hr.map((r,n)=>to(qo,{flexDirection:"column",children:[to(qo,{children:[to(Ct,{color:n===o?"yellow":void 0,bold:n===o,children:[n===o?" \u25B8 ":" ",r.name]}),to(Ct,{dimColor:!0,children:[" Lv.",r.difficulty]})]}),n===o&&to(Ct,{dimColor:!0,children:[' "',r.tagline,'"']})]},r.name)),Wt(Ct,{children:" "}),Wt(Ct,{dimColor:!0,children:" \u2191\u2193 navigate Enter raid Esc back"})]})}import{useState as pn}from"react";import{Box as fo,Text as Me,useInput as ni}from"ink";import{Fragment as di,jsx as ze,jsxs as ht}from"react/jsx-runtime";function ai(e){let t=[];return e.gold>0&&t.push(`+${e.gold}${W.gold}`),e.wood>0&&t.push(`+${e.wood}${W.wood}`),e.stone>0&&t.push(`+${e.stone}${W.stone}`),t.join(" ")}function ii(e){let t=[];return e.gold>0&&t.push(`-${e.gold}${W.gold}`),e.wood>0&&t.push(`-${e.wood}${W.wood}`),e.stone>0&&t.push(`-${e.stone}${W.stone}`),t.join(" ")}function fn({gameSave:e,onBack:t,onWatchReplay:o}){let[s,r]=pn("raids"),[n,c]=pn(0),d=[...e.raidHistory].reverse().slice(0,15);ni((l,T)=>{if(l==="q"||T.escape){t();return}(T.tab||l==="t")&&r(R=>R==="raids"?"achievements":"raids"),s==="raids"&&d.length>0&&((l==="j"||T.downArrow)&&c(R=>Math.min(R+1,d.length-1)),(l==="k"||T.upArrow)&&c(R=>Math.max(R-1,0)),(T.return||l==="v")&&d[n]&&o&&o(d[n]))});let g=e.progression;return ht(fo,{flexDirection:"column",padding:1,children:[ht(fo,{gap:2,children:[ze(Me,{bold:!0,color:s==="raids"?"yellow":void 0,underline:s==="raids",children:"Raid Log"}),ze(Me,{bold:!0,color:s==="achievements"?"yellow":void 0,underline:s==="achievements",children:"Achievements"}),ze(Me,{dimColor:!0,children:"(Tab to switch)"})]}),ze(Me,{children:" "}),s==="raids"&&ht(fo,{flexDirection:"column",children:[ht(Me,{dimColor:!0,children:[" Total: ",g.totalRaidsWon,"W / ",g.totalRaidsLost,"L \xB7 Streak: ",g.currentWinStreak," (best ",g.bestWinStreak,")"]}),ze(Me,{children:" "}),d.length===0?ze(Me,{dimColor:!0,children:" No raids yet. Try Defend Keep or Attack NPC!"}):d.map((l,T)=>{let R=li(l.resolvedAtUnixMs),u=l.attackerId!==e.player.id,i=l.outcome==="defense_win"?u?"\u2713":"\u2717":u?"\u2717":"\u2713",y=(u?l.outcome==="defense_win":l.outcome!=="defense_win")?"green":"red",w=u?"DEF":"ATK",h=l.lootLost.gold+l.lootLost.wood+l.lootLost.stone>0?` ${ii(l.lootLost)}`:"",x=l.lootGained.gold+l.lootGained.wood+l.lootGained.stone>0?` ${ai(l.lootGained)}`:"",_=T===n?">":" ";return ht(Me,{dimColor:T>4&&T!==n,bold:T===n,children:[_," ",ze(Me,{color:y,children:i})," ",w," ",l.outcome.replace("_"," "),h,x," ",ht(Me,{dimColor:!0,children:["(",R,")"]})]},l.id)}),d.length>0&&ht(di,{children:[ze(Me,{children:" "}),ze(Me,{dimColor:!0,children:" j/k navigate \xB7 Enter/v watch replay"})]})]}),s==="achievements"&&ht(fo,{flexDirection:"column",children:[ht(Me,{dimColor:!0,children:[" ",g.achievements?.length||0," / ",lo.length," earned"]}),ze(Me,{children:" "}),lo.map(l=>{let T=g.achievements?.includes(l.id);return ze(fo,{children:ht(Me,{color:T?"green":void 0,dimColor:!T,children:[" ",T?"\u2605":"\u2606"," ",ze(Me,{bold:T,children:l.name})," \u2014 ",l.desc,l.bonus&&T?ht(Me,{color:"yellow",children:[" (",l.bonus,")"]}):null]})},l.id)})]}),ze(Me,{children:" "}),ze(Me,{dimColor:!0,children:" Tab switch \xB7 Esc/q back"})]})}function li(e){let t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}import{useState as mo}from"react";import{Box as go,Text as he,useInput as mi}from"ink";import{exec as gi}from"child_process";import{writeFileSync as ci,mkdirSync as ui,existsSync as pi}from"fs";import{join as mn}from"path";import{homedir as fi}from"os";var Yr=mn(fi(),".config","codekeep","crashes");function gn(e,t){if((e instanceof Error?e.message:String(e)).includes("Raw mode is not supported"))return"";pi(Yr)||ui(Yr,{recursive:!0});let s={timestamp:new Date().toISOString(),error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0,version:globalThis.__CODEKEEP_VERSION??"unknown",nodeVersion:process.version,platform:process.platform,arch:process.arch,screen:t?.screen,gameState:t?.gameState},r=`crash-${Date.now()}.json`,n=mn(Yr,r);return ci(n,JSON.stringify(s,null,2),"utf-8"),n}function zo(e){let t=encodeURIComponent(`[Crash]: ${e.error.slice(0,80)}`),o=encodeURIComponent(`## Crash Report
11
11
 
12
12
  **Error:** ${e.error}
13
13
 
@@ -22,20 +22,18 @@ ${e.stack??"N/A"}
22
22
  - OS: ${e.platform} ${e.arch}
23
23
  - Screen: ${e.screen??"unknown"}
24
24
  - Time: ${e.timestamp}
25
- `);return`https://github.com/tooyipjee/codekeep/issues/new?title=${t}&body=${o}&labels=bug,crash`}import{Fragment as ia,jsx as Ne,jsxs as mt}from"react/jsx-runtime";function Ts({onBack:e,onResetGame:t,onReplayTutorial:o,asciiMode:s,onToggleAscii:r}){let[a,T]=So(0),[f,d]=So(!1),[l,x]=So(!1),[k,R]=So(""),m=[{key:"ascii",label:`ASCII Mode: ${s?"ON":"OFF"}`,desc:"Use plain ASCII borders (for basic terminals)"},{key:"tutorial",label:"Replay Tutorial",desc:"Learn how to play again"},{key:"report",label:"Report Bug",desc:"Open a GitHub issue for bugs"},{key:"reset",label:"Reset Game",desc:"Delete save and start over"},{key:"back",label:"Back",desc:"Return to menu"}];return aa((p,b)=>{if(l){if(b.escape){x(!1),R("");return}if(b.return&&k.length>0){let c={timestamp:new Date().toISOString(),error:k,version:globalThis.__CODEKEEP_VERSION??"unknown",nodeVersion:process.version,platform:process.platform,arch:process.arch,screen:"settings"},$=Ro(c);process.stderr.write(`
26
- Open this URL to report the bug:
27
- ${$}
28
-
29
- `),x(!1),R("");return}if(b.backspace||b.delete){R(c=>c.slice(0,-1));return}p&&p.length===1&&R(c=>c+p);return}if(f){if(p==="y"||p==="Y"){t();return}d(!1);return}if(p==="q"||b.escape){e();return}if((p==="j"||p==="s"||b.downArrow)&&T(c=>Math.min(c+1,m.length-1)),(p==="k"||p==="w"||b.upArrow)&&T(c=>Math.max(c-1,0)),b.return){let c=m[a];c.key==="ascii"?r():c.key==="tutorial"?o():c.key==="report"?x(!0):c.key==="reset"?d(!0):c.key==="back"&&e()}}),mt(bo,{flexDirection:"column",padding:1,children:[Ne(be,{bold:!0,color:"yellow",children:"\u25C6 Settings"}),Ne(be,{children:" "}),l?mt(bo,{flexDirection:"column",children:[Ne(be,{bold:!0,color:"cyan",children:"Report a Bug"}),Ne(be,{children:"Describe the issue briefly:"}),mt(be,{color:"cyan",children:[k,Ne(be,{dimColor:!0,children:"_"})]}),Ne(be,{children:" "}),Ne(be,{dimColor:!0,children:"Enter to generate GitHub issue URL \xB7 Esc cancel"})]}):f?mt(bo,{flexDirection:"column",children:[Ne(be,{bold:!0,color:"red",children:"Are you sure you want to reset?"}),Ne(be,{children:"This will permanently delete your save file."}),Ne(be,{children:"All structures, resources, and achievements will be lost."}),Ne(be,{children:" "}),mt(be,{bold:!0,children:["Press ",Ne(be,{color:"red",children:"Y"})," to confirm, any other key to cancel"]})]}):mt(ia,{children:[m.map((p,b)=>mt(bo,{children:[mt(be,{color:b===a?"yellow":void 0,bold:b===a,children:[b===a?" \u25B8 ":" ",p.label]}),mt(be,{dimColor:!0,children:[" ",p.desc]})]},p.key)),Ne(be,{children:" "}),Ne(be,{dimColor:!0,children:" \u2191\u2193 navigate \xB7 Enter select \xB7 Esc back"})]})]})}import la from"react";import{Box as da,Text as Ee}from"ink";import{Fragment as xs,jsx as Ge,jsxs as Ct}from"react/jsx-runtime";var ko=class extends la.Component{constructor(t){super(t),this.state={error:null,crashFilePath:null,issueUrl:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t){try{let o=hs(t),s={timestamp:new Date().toISOString(),error:t.message,stack:t.stack,version:globalThis.__CODEKEEP_VERSION??"unknown",nodeVersion:process.version,platform:process.platform,arch:process.arch},r=Ro(s);this.setState({crashFilePath:o,issueUrl:r})}catch{}}render(){return this.state.error?Ct(da,{flexDirection:"column",padding:1,children:[Ge(Ee,{bold:!0,color:"red",children:"\u25C6 CodeKeep \u2014 Something went wrong"}),Ge(Ee,{children:" "}),Ge(Ee,{color:"red",children:this.state.error.message}),Ge(Ee,{children:" "}),Ge(Ee,{dimColor:!0,children:"Your save file is at:"}),Ct(Ee,{children:[" ","~/.config/codekeep/game.json"]}),Ge(Ee,{children:" "}),this.state.crashFilePath&&Ct(xs,{children:[Ge(Ee,{dimColor:!0,children:"Crash report saved to:"}),Ct(Ee,{children:[" ",this.state.crashFilePath]}),Ge(Ee,{children:" "})]}),this.state.issueUrl&&Ct(xs,{children:[Ge(Ee,{dimColor:!0,children:"Report this bug:"}),Ct(Ee,{color:"cyan",children:[" ",this.state.issueUrl]}),Ge(Ee,{children:" "})]}),Ge(Ee,{dimColor:!0,children:"If the game won't start, try:"}),Ct(Ee,{bold:!0,children:[" ","codekeep --tutorial"]}),Ge(Ee,{children:" "}),Ge(Ee,{dimColor:!0,children:"Press Ctrl+C to exit"})]}):this.props.children}};import{useState as ca}from"react";import{Box as vo,Text as Qe,useInput as ua}from"ink";import{jsx as yt,jsxs as _t}from"react/jsx-runtime";var pa={copper:"white",iron:"gray",silver:"whiteBright",gold:"yellow",diamond:"cyan"},fa={copper:"\u25CB",iron:"\u25CF",silver:"\u25C6",gold:"\u2605",diamond:"\u25C8"};function ys({pvpProfile:e,targets:t,isSearching:o,onSearch:s,onAttack:r,onWarCamp:a,onLeaderboard:T,onBack:f}){let[d,l]=ca(0),x=[{key:"search",label:"Find Opponent"},{key:"warcamp",label:"War Camp"},{key:"leaderboard",label:"Leaderboard"},...t.map((p,b)=>({key:`target-${b}`,label:`Attack ${p.displayName} (${p.trophies} trophies)`})),{key:"back",label:"Back"}];ua((p,b)=>{if(b.upArrow||p==="k")l(c=>Math.max(0,c-1));else if(b.downArrow||p==="j")l(c=>Math.min(x.length-1,c+1));else if(b.return){let c=x[d];if(c.key==="search")s();else if(c.key==="warcamp")a();else if(c.key==="leaderboard")T();else if(c.key==="back")f();else if(c.key.startsWith("target-")){let $=parseInt(c.key.split("-")[1]),z=t[$];z&&r(z)}}else(b.escape||p==="q")&&f()});let k=e?.league??"copper",R=pa[k]??"white",m=fa[k]??"\u25CB";return _t(vo,{flexDirection:"column",padding:1,children:[yt(Qe,{bold:!0,color:"red",children:"\u2694 PVP ARENA"}),yt(Qe,{children:" "}),e&&_t(vo,{flexDirection:"column",children:[_t(vo,{flexDirection:"row",gap:2,children:[_t(Qe,{color:R,bold:!0,children:[m," ",k.toUpperCase()," League"]}),_t(Qe,{children:["Trophies: ",yt(Qe,{bold:!0,color:"yellow",children:e.trophies})]})]}),e.shieldExpiresAt&&e.shieldExpiresAt>Date.now()&&_t(Qe,{color:"cyan",children:["Shield active (",Math.ceil((e.shieldExpiresAt-Date.now())/36e5),"h remaining)"]}),yt(Qe,{children:" "})]}),o&&yt(Qe,{color:"yellow",children:"Searching for opponents..."}),x.map((p,b)=>yt(vo,{children:_t(Qe,{color:b===d?"yellow":void 0,bold:b===d,children:[b===d?" \u25B8 ":" ",p.label]})},p.key)),yt(Qe,{children:" "}),yt(Qe,{dimColor:!0,children:"\u2191\u2193 select Enter choose Esc back"})]})}import{useState as Eo,useEffect as ma}from"react";import{Box as eo,Text as We,useInput as ga}from"ink";import{jsx as gt,jsxs as ht}from"react/jsx-runtime";var tr=[{type:"raider",name:"Raider",symbol:"R"},{type:"scout",name:"Scout",symbol:"S"},{type:"brute",name:"Brute",symbol:"B"}];function ws(e){let t=Math.ceil(e/1e3),o=Math.floor(t/60),s=t%60;return`${o}:${String(s).padStart(2,"0")}`}function Rs({warCamp:e,resources:t,onTrain:o,onBack:s}){let[r,a]=Eo(0),[T,f]=Eo(!1),[d,l]=Eo(0),[x,k]=Eo(Date.now());return ma(()=>{let R=setInterval(()=>k(Date.now()),1e3);return()=>clearInterval(R)},[]),ga((R,m)=>{if(T){m.upArrow||R==="k"?l(p=>Math.max(0,p-1)):m.downArrow||R==="j"?l(p=>Math.min(tr.length-1,p+1)):m.return?(o(r,tr[d].type),f(!1)):m.escape&&f(!1);return}m.upArrow||R==="k"?a(p=>Math.max(0,p-1)):m.downArrow||R==="j"?a(p=>Math.min(e.maxSlots-1,p+1)):m.return?e.slots[r]?.raiderType||f(!0):(m.escape||R==="q")&&s()}),ht(eo,{flexDirection:"column",padding:1,children:[gt(We,{bold:!0,color:"red",children:"\u2694 WAR CAMP"}),gt(We,{dimColor:!0,children:"Train raiders for PvP attacks"}),gt(We,{children:" "}),ht(eo,{flexDirection:"row",gap:2,children:[ht(We,{children:["Gold: ",t.gold,B.gold]}),ht(We,{children:["Wood: ",t.wood,B.wood]}),ht(We,{children:["Stone: ",t.stone,B.stone]})]}),gt(We,{children:" "}),ht(We,{bold:!0,children:["Slots (",e.slots.filter(R=>R.raiderType).length,"/",e.maxSlots,")"]}),Array.from({length:e.maxSlots},(R,m)=>{let p=e.slots[m],b=r===m,c=p?.readyAtMs?p.readyAtMs<=x:!1,$=p?.readyAtMs?p.readyAtMs>x:!1,z=$&&p?.readyAtMs?p.readyAtMs-x:0,U;return p?.raiderType?$?U=`${p.raiderType} training... ${ws(z)}`:c?U=`${p.raiderType} READY!`:U=`${p.raiderType}`:U="[ Empty ]",gt(eo,{children:ht(We,{color:b?"yellow":void 0,bold:b,children:[b?" \u25B8 ":" ","Slot ",m+1,": ",U]})},m)}),T&&ht(eo,{flexDirection:"column",marginTop:1,children:[gt(We,{bold:!0,color:"cyan",children:"Select raider type:"}),tr.map((R,m)=>{let p=go[R.type],b=Ar[R.type],c=Le[R.type],$=t.gold>=p.gold&&t.wood>=p.wood&&t.stone>=p.stone;return gt(eo,{children:ht(We,{color:d===m?"yellow":$?void 0:"red",bold:d===m,children:[d===m?" \u25B8 ":" ",R.name," \u2014 HP:",c.hp," DMG:",c.damage," SPD:",c.speed," \u2014 ",p.gold,"g ",p.wood,"w ",p.stone,"s \u2014 ",ws(b)]})},R.type)})]}),gt(We,{children:" "}),gt(We,{dimColor:!0,children:"\u2191\u2193 select Enter train Esc back"})]})}import{Box as Ao,Text as Be,useInput as ha}from"ink";import{jsx as Ke,jsxs as to}from"react/jsx-runtime";var Ta={copper:"white",iron:"gray",silver:"whiteBright",gold:"yellow",diamond:"cyan"};function Ss({entries:e,currentPlayerId:t,isLoading:o,onBack:s}){return ha((r,a)=>{(a.escape||r==="q")&&s()}),to(Ao,{flexDirection:"column",padding:1,children:[Ke(Be,{bold:!0,color:"yellow",children:"\u{1F3C6} LEADERBOARD"}),Ke(Be,{children:" "}),o&&Ke(Be,{color:"yellow",children:"Loading..."}),!o&&e.length===0&&Ke(Be,{dimColor:!0,children:"No players on the leaderboard yet."}),!o&&e.length>0&&to(Ao,{flexDirection:"column",children:[to(Ao,{children:[Ke(Be,{bold:!0,children:" # "}),Ke(Be,{bold:!0,children:"Name "}),Ke(Be,{bold:!0,children:"League "}),Ke(Be,{bold:!0,children:"Trophies"})]}),e.map(r=>{let a=r.id===t,T=a?"green":void 0,f=Ta[r.league]??"white";return to(Ao,{children:[to(Be,{color:T,bold:a,children:[String(r.rank).padStart(3," ")," "]}),Ke(Be,{color:T,bold:a,children:(r.displayName||"Unknown").padEnd(20," ")}),Ke(Be,{color:f,children:r.league.padEnd(10," ")}),Ke(Be,{color:"yellow",bold:!0,children:r.trophies})]},r.id)})]}),Ke(Be,{children:" "}),Ke(Be,{dimColor:!0,children:"Esc/q back"})]})}import{useState as or}from"react";import{Box as Co,Text as Ae,useInput as xa}from"ink";import{Fragment as ya,jsx as De,jsxs as Mt}from"react/jsx-runtime";function bs({onLogin:e,onRegister:t,onPlayOffline:o,error:s,isLoading:r}){let[a,T]=or("menu"),[f,d]=or(""),[l,x]=or(0),k=[{key:"register",label:"Register (new player)"},{key:"login",label:"Login (with API key)"},{key:"offline",label:"Play Offline"}];return xa((R,m)=>{if(!r){if(a==="menu"){if(m.upArrow||R==="k")x(p=>Math.max(0,p-1));else if(m.downArrow||R==="j")x(p=>Math.min(k.length-1,p+1));else if(m.return){let p=k[l];p.key==="register"?T("register"):p.key==="login"?T("login"):p.key==="offline"&&o()}return}if(m.escape){T("menu"),d("");return}if(m.return&&f.length>0){a==="login"?e(f):a==="register"&&t(f),d("");return}if(m.backspace||m.delete){d(p=>p.slice(0,-1));return}R&&R.length===1&&d(p=>p+R)}}),Mt(Co,{flexDirection:"column",padding:1,children:[De(Ae,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep Online"}),De(Ae,{children:" "}),s&&De(Ae,{color:"red",children:s}),r&&De(Ae,{color:"yellow",children:"Connecting..."}),a==="menu"&&!r&&Mt(ya,{children:[k.map((R,m)=>De(Co,{children:Mt(Ae,{color:m===l?"yellow":void 0,bold:m===l,children:[m===l?" \u25B8 ":" ",R.label]})},R.key)),De(Ae,{children:" "}),De(Ae,{dimColor:!0,children:"\u2191\u2193 navigate Enter select"})]}),a==="login"&&!r&&Mt(Co,{flexDirection:"column",children:[De(Ae,{children:"Enter your API key:"}),Mt(Ae,{color:"cyan",children:[f,De(Ae,{dimColor:!0,children:"_"})]}),De(Ae,{children:" "}),De(Ae,{dimColor:!0,children:"Enter to submit Esc back"})]}),a==="register"&&!r&&Mt(Co,{flexDirection:"column",children:[De(Ae,{children:"Choose a display name:"}),Mt(Ae,{color:"cyan",children:[f,De(Ae,{dimColor:!0,children:"_"})]}),De(Ae,{children:" "}),De(Ae,{dimColor:!0,children:"Enter to submit Esc back"})]})]})}import{useState as It}from"react";import{Box as Ye,Text as j,useInput as wa}from"ink";import{jsx as ee,jsxs as ke}from"react/jsx-runtime";var ks={N:"North",S:"South",E:"East",W:"West"},Ft={raider:"R",scout:"S",brute:"B"},_o={raider:"red",scout:"cyan",brute:"magenta"},vs=8;function Es(e,t){switch(e){case"N":return{x:t,y:0};case"S":return{x:t,y:I-1};case"E":return{x:I-1,y:t};case"W":return{x:0,y:t}}}function As({targetName:e,targetTrophies:t,targetGrid:o,warCamp:s,resources:r,onLaunch:a,onBack:T}){let[f,d]=It("scout"),[l,x]=It([]),[k,R]=It(0),[m,p]=It([]),[b,c]=It("N"),[$,z]=It(Math.floor(I/2)),[U,u]=It(0),K=["raider","scout","brute"];wa((y,h)=>{if(h.escape||y==="q"){if(f==="scout"){T();return}if(f==="army"){d("scout");return}if(f==="deploy"){d("army");return}if(f==="confirm"){d("deploy");return}return}if(f==="scout"){h.return&&d("army");return}if(f==="army"){h.upArrow||y==="k"?R(E=>Math.max(0,E-1)):h.downArrow||y==="j"?R(E=>Math.min(K.length-1,E+1)):h.return?l.length<vs&&x(E=>[...E,K[k]]):h.backspace||h.delete?x(E=>E.slice(0,-1)):(y==="n"||h.tab)&&l.length>0&&(p(l.map(()=>({edge:"N",offset:Math.floor(I/2)}))),u(0),d("deploy"));return}if(f==="deploy"){h.leftArrow||y==="a"?z(b==="E"||b==="W"?E=>Math.max(0,E-1):E=>Math.max(0,E-1)):h.rightArrow||y==="d"?z(E=>Math.min(I-1,E+1)):h.upArrow||y==="w"?z(E=>Math.max(0,E-1)):h.downArrow||y==="s"?z(E=>Math.min(I-1,E+1)):y==="n"?c("N"):y==="e"?c("E"):y==="z"?c("S"):y==="x"?c("W"):h.return?(p(E=>{let C=[...E];return C[U]={edge:b,offset:$},C}),U<l.length-1?u(E=>E+1):d("confirm")):h.tab&&u(E=>(E+1)%l.length);return}if(f==="confirm"){if(h.return||y==="y"){let E=l.map((C,N)=>({raiderType:C,edge:m[N]?.edge??"N",offset:m[N]?.offset??8,waveDelay:0}));a(E)}return}});let H=(()=>{let y=Array.from({length:I},()=>Array(I).fill("\xB7"));for(let C of o.structures)C.kind==="trap"||C.kind==="ward"?y[C.pos.y][C.pos.x]="?":y[C.pos.y][C.pos.x]=fe[C.kind];if(f==="deploy"||f==="confirm"){for(let C=0;C<m.length;C++){let N=m[C];if(!N)continue;let A=Es(N.edge,N.offset);y[A.y][A.x]=Ft[l[C]]}if(f==="deploy"){let C=Es(b,$);y[C.y][C.x]="\u25BC"}}let h=" "+Array.from({length:I},(C,N)=>N.toString(16).toUpperCase()).join(" "),E=y.map((C,N)=>{let A=N.toString(16).toUpperCase(),O=C.join(" ");return`${A} ${O}`});return[h,...E]})();return ke(Ye,{flexDirection:"column",padding:1,children:[ee(j,{bold:!0,color:"red",children:"\u2694 RAID PLANNER"}),ke(Ye,{gap:2,children:[ke(j,{children:["Target: ",ee(j,{bold:!0,color:"yellow",children:e})]}),ke(j,{children:["Trophies: ",ee(j,{bold:!0,children:t})]})]}),ee(j,{children:" "}),ee(Ye,{flexDirection:"column",children:H.map((y,h)=>h===0?ee(j,{dimColor:!0,children:y},h):ee(j,{children:y},h))}),ee(j,{children:" "}),ee(Ye,{gap:2,children:ee(j,{dimColor:!0,children:"# wall $ treasury ^ tower ! archer & vault ? hidden"})}),ee(j,{children:" "}),f==="scout"&&ke(Ye,{flexDirection:"column",children:[ee(j,{bold:!0,color:"cyan",children:"SCOUT PHASE"}),ee(j,{children:"Study the enemy keep. Traps and wards are hidden (?)."}),ke(j,{children:["Structures: ",o.structures.length," placed"]}),ee(j,{children:" "}),ee(j,{dimColor:!0,children:"Enter \u2192 pick your army Esc \u2192 back"})]}),f==="army"&&ke(Ye,{flexDirection:"column",children:[ke(j,{bold:!0,color:"cyan",children:["ARMY SELECTION (",l.length,"/",vs,")"]}),ee(j,{children:" "}),K.map((y,h)=>{let E=Le[y],C=go[y];return ee(Ye,{children:ke(j,{color:k===h?"yellow":void 0,bold:k===h,children:[k===h?" \u25B8 ":" ",ee(j,{color:_o[y],children:Ft[y]})," ",y.charAt(0).toUpperCase()+y.slice(1)," ","HP:",E.hp," DMG:",E.damage," SPD:",E.speed," ","(",C.gold,"g ",C.wood,"w ",C.stone,"s)"]})},y)}),ee(j,{children:" "}),ke(Ye,{gap:1,children:[ee(j,{children:"Army: "}),l.length===0?ee(j,{dimColor:!0,children:"(empty)"}):l.map((y,h)=>ee(j,{color:_o[y],bold:!0,children:Ft[y]},h))]}),ee(j,{children:" "}),ee(j,{dimColor:!0,children:"Enter add Backspace remove Tab/N \u2192 deploy Esc back"})]}),f==="deploy"&&ke(Ye,{flexDirection:"column",children:[ke(j,{bold:!0,color:"cyan",children:["DEPLOY \u2014 Placing ",Ft[l[U]]," (",l[U],") [",U+1,"/",l.length,"]"]}),ke(j,{children:["Edge: ",ee(j,{bold:!0,color:"yellow",children:ks[b]})," Position: ",ee(j,{bold:!0,children:$.toString(16).toUpperCase()})]}),ee(j,{children:" "}),ke(Ye,{gap:1,children:[ee(j,{children:"Spawns: "}),l.map((y,h)=>{let E=m[h],C=h<U||h===U&&!1;return ke(j,{color:h===U?"yellow":C?_o[y]:"gray",children:[Ft[y],E?`@${E.edge}${E.offset.toString(16)}`:"",h<l.length-1?" ":""]},h)})]}),ee(j,{children:" "}),ee(j,{dimColor:!0,children:"\u2190\u2192 / \u2191\u2193 position N/E/Z/X edge Enter place Tab next Esc back"})]}),f==="confirm"&&ke(Ye,{flexDirection:"column",children:[ee(j,{bold:!0,color:"green",children:"READY TO ATTACK"}),ee(j,{children:" "}),ee(Ye,{flexDirection:"column",children:l.map((y,h)=>{let E=m[h];return ke(j,{children:[ee(j,{color:_o[y],bold:!0,children:Ft[y]})," ",y," \u2192 ",E?`${ks[E.edge]} edge, pos ${E.offset.toString(16).toUpperCase()}`:"unplaced"]},h)})}),ee(j,{children:" "}),ke(j,{bold:!0,children:["Press ",ee(j,{color:"green",children:"Enter"})," to launch raid or ",ee(j,{color:"red",children:"Esc"})," to adjust"]})]})]})}import{useState as st,useEffect as so,useCallback as ge,useRef as Dt}from"react";import{useEffect as ba,useRef as _s,useCallback as ka}from"react";import{existsSync as Ms,statSync as Is,openSync as va,readSync as Ea,closeSync as Aa,watch as Ca}from"fs";import{existsSync as ud,mkdirSync as pd,readFileSync as fd,writeFileSync as md,unlinkSync as gd}from"fs";import{join as Cs}from"path";import{homedir as Ra}from"os";var Sa=Cs(Ra(),".config","codekeep"),Pt=Cs(Sa,"events.jsonl");var _a=2e3;function Ps(e){let t=_s(0),o=_s(e);o.current=e;let s=ka(()=>{if(!Ms(Pt))return;let r;try{r=Is(Pt).size}catch{return}if(r<t.current&&(t.current=0),r<=t.current)return;let a,T;try{let d=Buffer.alloc(r-t.current);T=va(Pt,"r"),Ea(T,d,0,d.length,t.current),a=d.toString("utf-8")}catch{return}finally{T!==void 0&&Aa(T)}t.current=r;let f=a.split(`
30
- `).filter(Boolean);for(let d of f)try{let l=JSON.parse(d);o.current(l)}catch{}},[]);ba(()=>{if(Ms(Pt))try{t.current=Is(Pt).size}catch{t.current=0}let r=null;try{r=Ca(Pt,()=>s())}catch{}let a=setInterval(s,_a);return()=>{clearInterval(a),r?.close()}},[s])}function oo(e){return e<=2?1:e<=5?2:e<=9?3:e<=14?4:5}function ro(e,t,o){let s=[];for(let r=0;r<e;r++)t>=3&&o()<.2?s.push("brute"):t>=2&&o()<.3?s.push("scout"):s.push("raider");return s}function Vt(e){let t=e|0;return()=>{t=t+1831565813|0;let o=Math.imul(t^t>>>15,1|t);return o=o+Math.imul(o^o>>>7,61|o)^o,((o^o>>>14)>>>0)/4294967296}}function Ds(e){let t=e.progression;return{...e,progression:{...t,totalRaidsWon:t.totalRaidsWon??0,totalRaidsLost:t.totalRaidsLost??0,totalStructuresPlaced:t.totalStructuresPlaced??0,currentWinStreak:t.currentWinStreak??0,bestWinStreak:t.bestWinStreak??0,achievements:t.achievements??[],totalRaidersKilledByArcher:t.totalRaidersKilledByArcher??t.totalProbesKilledByScanner??0}}}var Ma={first_structure:{gold:20,wood:0,stone:0},defense_win_5:{gold:25,wood:15,stone:15},win_streak_3:{gold:10,wood:10,stone:10},win_streak_5:{gold:30,wood:30,stone:30},all_types:{gold:15,wood:15,stone:15},max_level:{gold:20,wood:0,stone:10},archer_kills_10:{gold:20,wood:10,stone:10},structures_20:{gold:10,wood:10,stone:10},raids_10:{gold:15,wood:15,stone:15},hoarder:{gold:25,wood:0,stone:0}};function rr(e){return Ma[e]??null}function sr(e){let t=e.progression,o=new Set(t.achievements),s=[],r=(T,f)=>{!o.has(T)&&f&&s.push(T)};r("first_structure",t.totalStructuresPlaced>=1),r("defense_win_5",t.totalRaidsWon>=5),r("win_streak_3",t.bestWinStreak>=3),r("win_streak_5",t.bestWinStreak>=5),r("structures_20",t.totalStructuresPlaced>=20),r("raids_10",t.totalRaidsWon+t.totalRaidsLost>=10),r("archer_kills_10",t.totalRaidersKilledByArcher>=10),r("hoarder",e.keep.resources.gold+e.keep.resources.wood+e.keep.resources.stone>=500);let a=new Set(e.keep.grid.structures.map(T=>T.kind));return r("all_types",a.size>=ct.length),r("max_level",e.keep.grid.structures.some(T=>T.level===3)),s}function Ls(e,t){if(t<=Ut)return e;let o=Math.pow(Rr,Math.floor((t-Ut)/Ut)+1);return{gold:Math.max(1,Math.floor(e.gold*o)),wood:Math.max(1,Math.floor(e.wood*o)),stone:Math.max(1,Math.floor(e.stone*o))}}var $s=5e3,nr=6e4;function Ia(e,t){if(e.keep.grid.structures.length<3)return{save:e,results:[]};let o=Math.min(Math.floor(t/qt),wr);if(o===0)return{save:e,results:[]};let s=[],r=e;for(let a=0;a<o;a++){let T=r.progression.totalRaidsWon+r.progression.totalRaidsLost,f=oo(T),d=`bg-${r.lastPlayedAtUnixMs}-${a}`,l=3+f,x=Vt(r.lastPlayedAtUnixMs+a),k=ro(l,f,x),R=ut({probeCount:l,keepGrid:r.keep.grid,seed:d,probeTypes:k}),m=R.events[R.events.length-1];if(m?.type!=="raid_end")continue;let p=m.outcome==="defense_win",b=R.events.filter(w=>w.type==="treasury_breach").reduce((w,H)=>({gold:w.gold+H.lootTaken.gold,wood:w.wood+H.lootTaken.wood,stone:w.stone+H.lootTaken.stone}),{gold:0,wood:0,stone:0}),c=R.events.filter(w=>w.type==="arrow_hit"&&w.hpRemaining<=0).length,$=p?{gold:10+f*3,wood:5+f*2,stone:5+f*2}:{gold:0,wood:0,stone:0},z={gold:Math.max(0,r.keep.resources.gold-b.gold),wood:Math.max(0,r.keep.resources.wood-b.wood),stone:Math.max(0,r.keep.resources.stone-b.stone)},U=rt(Oe(z,$)),u=p?r.progression.currentWinStreak+1:0,K={id:d,seed:d,rulesVersion:1,attackerId:"npc-bg",defenderKeepId:r.keep.id,startedAtUnixMs:r.lastPlayedAtUnixMs+a*qt,resolvedAtUnixMs:r.lastPlayedAtUnixMs+(a+1)*qt,outcome:m.outcome,lootLost:b,lootGained:$,replay:R};r={...r,keep:{...r.keep,resources:U},raidHistory:[...r.raidHistory.slice(-19),K],progression:{...r.progression,totalRaidsWon:r.progression.totalRaidsWon+(p?1:0),totalRaidsLost:r.progression.totalRaidsLost+(p?0:1),currentWinStreak:u,bestWinStreak:Math.max(r.progression.bestWinStreak,u),totalRaidersKilledByArcher:r.progression.totalRaidersKilledByArcher+c}},s.push({won:p,lootLost:b,defenseBonus:$,difficulty:f})}return{save:r,results:s}}function Ns(e,t){let[o,s]=st(null),[r,a]=st({x:8,y:8}),[T,f]=st(0),[d,l]=st(""),[x,k]=st(null),[R,m]=st(null),[p,b]=st(null),[c,$]=st(null),[z,U]=st(null),[u,K]=st([]),w=Dt(null),H=Dt(0),y=Dt(0),h=Dt(null),E=Dt(null),C=Dt(null),N=Dt(null),A=ct[T];Ps(g=>{s(S=>{if(!S)return S;let M=Wo(S.keep,g),V={...S,keep:M,lastPlayedAtUnixMs:Date.now()};return t||Et(V),V})}),so(()=>{let g=Gt();g||(g=Jr(process.env.USER||process.env.USERNAME||"Keeper")),g=Ds(g),g.lastPlayedAtUnixMs||(g={...g,lastPlayedAtUnixMs:g.savedAtUnixMs||Date.now()});let S=Date.now()-g.lastPlayedAtUnixMs,M={gold:0,wood:0,stone:0},V=[];if(S>nr&&g.keep.grid.structures.length>0&&(M=Ko(g.keep.grid,S),(M.gold>0||M.wood>0||M.stone>0)&&(g={...g,keep:{...g.keep,resources:rt(Oe(g.keep.resources,M))}})),S>qt){let re=Ia(g,S);g=re.save,V=re.results}let Q=sr(g);if(Q.length>0){g={...g,progression:{...g.progression,achievements:[...g.progression.achievements,...Q]}};for(let re of Q){let oe=rr(re);oe&&(g={...g,keep:{...g.keep,resources:Oe(g.keep.resources,oe)}})}}(M.gold>0||M.wood>0||M.stone>0||V.length>0||Q.length>0)&&U({resources:M,raids:V,newAchievements:Q}),g={...g,lastPlayedAtUnixMs:Date.now()},e&&(g={...g,tutorialCompleted:!1}),s(g),t||Et(g)},[]),so(()=>(h.current=setInterval(()=>{s(g=>{if(!g||g.keep.grid.structures.length===0)return g;let S=Ko(g.keep.grid,nr);if(S.gold===0&&S.wood===0&&S.stone===0)return g;let M={...g,keep:{...g.keep,resources:rt(Oe(g.keep.resources,S))},lastPlayedAtUnixMs:Date.now()};return t||Et(M),M})},nr),()=>{h.current&&clearInterval(h.current)}),[t]),so(()=>(E.current=setInterval(()=>{K(g=>{if(!o)return g;let S=Vt(Date.now()),M=zr(g,Date.now());return qr(M,o.keep.grid,Date.now(),S)})},Sr),()=>{E.current&&clearInterval(E.current)}),[o]),so(()=>{let g=N.current;if(!g||!o)return;N.current=null;let S=Ho(u,g,o.keep.grid);if(!S)return;K(S.updatedFragments);let M=S.yield,V={...o,keep:{...o.keep,resources:rt(Oe(o.keep.resources,M))}};O(V);let Q=[];M.gold>0&&Q.push(`+${M.gold}${B.gold}`),M.wood>0&&Q.push(`+${M.wood}${B.wood}`),M.stone>0&&Q.push(`+${M.stone}${B.stone}`);let he=S.collected[0]?.type.replace("_"," ")??"fragment",re=S.collected.length>1?` (${S.collected.length}x)`:"";W(`${Q.join(" ")} ${he}${re}`)},[r]),so(()=>()=>{w.current&&clearTimeout(w.current)},[]);let O=ge(g=>{let S=sr(g),M={...g,lastPlayedAtUnixMs:Date.now()};if(S.length>0){M={...M,progression:{...M.progression,achievements:[...M.progression.achievements,...S]}};for(let V of S){let Q=rr(V);Q&&(M={...M,keep:{...M.keep,resources:Oe(M.keep.resources,Q)}})}}if(s(M),t||Et(M),S.length>0){let V=S.map(Q=>zt.find(he=>he.id===Q)?.name||Q);W(`\u{1F3C6} ${V.join(", ")}!`)}},[t]),W=ge(g=>{w.current&&clearTimeout(w.current),l(g),w.current=setTimeout(()=>{l(""),w.current=null},3e3)},[]),ue=ge((g,S)=>{a(M=>{let V={x:Math.max(0,Math.min(I-1,M.x+g)),y:Math.max(0,Math.min(I-1,M.y+S))};return N.current=V,V})},[]),Se=ge(g=>{f(S=>{let M=S+g;return M<0?ct.length-1:M>=ct.length?0:M})},[]),nt=ge(g=>{g>=0&&g<ct.length&&f(g)},[]),$t=ge(()=>{if(!o)return;let g=Br(o.keep,r,A);if(g.ok&&g.keep){let S={...o,keep:g.keep,progression:{...o.progression,totalStructuresPlaced:o.progression.totalStructuresPlaced+1}};O(S),W(`Placed ${A}`)}else W(`!${g.reason}`)},[o,r,A,O,W]),jt=ge(()=>{if(!o)return;let g=Or(o.keep,r);g.ok&&g.keep?(O({...o,keep:g.keep}),W("Upgraded!")):W(`!${g.reason}`)},[o,r,O,W]),v=ge(()=>{if(!o)return;let g=Ur(o.keep,r);g.ok&&g.keep?(O({...o,keep:g.keep}),W("Demolished (50% refund)")):W(`!${g.reason}`)},[o,r,O,W]),q=ge(()=>{if(!o)return;let g=o.progression.totalRaidsWon+o.progression.totalRaidsLost,S=oo(g),M=`attack-${Date.now()}-${Math.random()}`,V=To(M,S),Q=3+S,he=Vt(Date.now()),re=ro(Q,S,he),oe=ut({probeCount:Q,keepGrid:V.grid,seed:M,probeTypes:re});k(oe),m(V.grid),b("attack");let Te=oe.events[oe.events.length-1];if(Te?.type==="raid_end"){let ie=Te.outcome!=="defense_win",et=oe.events.filter(xe=>xe.type==="treasury_breach").reduce((xe,lt)=>({gold:xe.gold+lt.lootTaken.gold,wood:xe.wood+lt.lootTaken.wood,stone:xe.stone+lt.lootTaken.stone}),{gold:0,wood:0,stone:0}),He=oe.events.filter(xe=>xe.type==="raider_destroyed").length,wt=oe.events.filter(xe=>xe.type==="wall_damaged"&&xe.destroyed).length;$({won:ie,raidType:"attack",outcome:Te.outcome,lootGained:et,lootLost:{gold:0,wood:0,stone:0},raidersKilled:He,raidersTotal:Q,wallsDestroyed:wt,archersActive:V.grid.structures.filter(xe=>xe.kind==="archerTower").length,difficulty:S});let at=ie?rt(Oe(o.keep.resources,et)):o.keep.resources,it=ie?o.progression.currentWinStreak+1:0,Rt={id:M,seed:M,rulesVersion:1,attackerId:o.player.id,defenderKeepId:V.id,startedAtUnixMs:Date.now(),resolvedAtUnixMs:Date.now(),outcome:Te.outcome,lootLost:{gold:0,wood:0,stone:0},lootGained:ie?et:{gold:0,wood:0,stone:0},replay:oe,defenderGrid:V.grid};O({...o,keep:{...o.keep,resources:at},raidHistory:[...o.raidHistory.slice(-19),Rt],progression:{...o.progression,totalRaidsWon:o.progression.totalRaidsWon+(ie?1:0),totalRaidsLost:o.progression.totalRaidsLost+(ie?0:1),currentWinStreak:it,bestWinStreak:Math.max(o.progression.bestWinStreak,it)}})}},[o,O]),Y=ge(()=>{if(!o)return;let g=o.progression.totalRaidsWon+o.progression.totalRaidsLost,S=oo(g),M=`defend-${Date.now()}-${Math.random()}`,V=3+S,Q=Vt(Date.now()),he=ro(V,S,Q),re=ut({probeCount:V,keepGrid:o.keep.grid,seed:M,probeTypes:he});k(re),m(o.keep.grid),b("defend");let oe=re.events[re.events.length-1];if(oe?.type==="raid_end"){let Te=oe.outcome==="defense_win",ie=re.events.filter(te=>te.type==="treasury_breach").reduce((te,dt)=>({gold:te.gold+dt.lootTaken.gold,wood:te.wood+dt.lootTaken.wood,stone:te.stone+dt.lootTaken.stone}),{gold:0,wood:0,stone:0}),et=re.events.filter(te=>te.type==="raider_destroyed").length,He=re.events.filter(te=>te.type==="wall_damaged"&&te.destroyed).length,wt=re.events.filter(te=>te.type==="arrow_hit"&&te.hpRemaining<=0).length,at=Te?{gold:10+S*3,wood:5+S*2,stone:5+S*2}:{gold:0,wood:0,stone:0};$({won:Te,raidType:"defend",outcome:oe.outcome,lootGained:at,lootLost:ie,raidersKilled:et,raidersTotal:V,wallsDestroyed:He,archersActive:o.keep.grid.structures.filter(te=>te.kind==="archerTower").length,difficulty:S});let it={gold:Math.max(0,o.keep.resources.gold-ie.gold),wood:Math.max(0,o.keep.resources.wood-ie.wood),stone:Math.max(0,o.keep.resources.stone-ie.stone)},Rt=rt(Oe(it,at)),xe=Te?o.progression.currentWinStreak+1:0,lt={id:M,seed:M,rulesVersion:1,attackerId:"npc",defenderKeepId:o.keep.id,startedAtUnixMs:Date.now(),resolvedAtUnixMs:Date.now(),outcome:oe.outcome,lootLost:ie,lootGained:at,replay:re};O({...o,keep:{...o.keep,resources:Rt},raidHistory:[...o.raidHistory.slice(-19),lt],progression:{...o.progression,totalRaidsWon:o.progression.totalRaidsWon+(Te?1:0),totalRaidsLost:o.progression.totalRaidsLost+(Te?0:1),currentWinStreak:xe,bestWinStreak:Math.max(o.progression.bestWinStreak,xe),totalRaidersKilledByArcher:o.progression.totalRaidersKilledByArcher+wt}})}},[o,O]),Ie=ge(()=>{if(!o)return;let g=o.progression.totalRaidsWon+o.progression.totalRaidsLost,S=oo(g),M=`quick-${Date.now()}-${Math.random()}`,V=3+S,Q=Vt(Date.now()),he=ro(V,S,Q),re=ut({probeCount:V,keepGrid:o.keep.grid,seed:M,probeTypes:he}),oe=re.events[re.events.length-1];if(oe?.type==="raid_end"){let Te=oe.outcome==="defense_win",ie=re.events.filter(te=>te.type==="treasury_breach").reduce((te,dt)=>({gold:te.gold+dt.lootTaken.gold,wood:te.wood+dt.lootTaken.wood,stone:te.stone+dt.lootTaken.stone}),{gold:0,wood:0,stone:0}),et=re.events.filter(te=>te.type==="arrow_hit"&&te.hpRemaining<=0).length,He=Te?{gold:10+S*3,wood:5+S*2,stone:5+S*2}:{gold:0,wood:0,stone:0},wt={gold:Math.max(0,o.keep.resources.gold-ie.gold),wood:Math.max(0,o.keep.resources.wood-ie.wood),stone:Math.max(0,o.keep.resources.stone-ie.stone)},at=rt(Oe(wt,He)),it=Te?o.progression.currentWinStreak+1:0,Rt={id:M,seed:M,rulesVersion:1,attackerId:"npc",defenderKeepId:o.keep.id,startedAtUnixMs:Date.now(),resolvedAtUnixMs:Date.now(),outcome:oe.outcome,lootLost:ie,lootGained:He,replay:re};O({...o,keep:{...o.keep,resources:at},raidHistory:[...o.raidHistory.slice(-19),Rt],progression:{...o.progression,totalRaidsWon:o.progression.totalRaidsWon+(Te?1:0),totalRaidsLost:o.progression.totalRaidsLost+(Te?0:1),currentWinStreak:it,bestWinStreak:Math.max(o.progression.bestWinStreak,it),totalRaidersKilledByArcher:o.progression.totalRaidersKilledByArcher+et}});let xe=re.events.filter(te=>te.type==="raider_destroyed").length,lt=re.events.filter(te=>te.type==="wall_damaged"&&te.destroyed).length;if(C.current={replay:re,grid:o.keep.grid,summary:{won:Te,raidType:"defend",outcome:oe.outcome,lootGained:He,lootLost:ie,raidersKilled:xe,raidersTotal:V,wallsDestroyed:lt,archersActive:o.keep.grid.structures.filter(te=>te.kind==="archerTower").length,difficulty:S}},Te)W(`Defense WIN! +${He.gold}${B.gold} +${He.wood}${B.wood} +${He.stone}${B.stone} [v] view`);else{let te=ie.gold+ie.wood+ie.stone;W(`Defense BREACH! Lost ${te} res [v] view`)}}},[o,O,W]),L=ge(()=>{let g=C.current;return g?(k(g.replay),m(g.grid),b("defend"),$(g.summary),C.current=null,!0):!1},[]),Z=ge(()=>{if(!o)return;let g=Ho(u,r,o.keep.grid);if(!g){W("!Nothing to collect here");return}K(g.updatedFragments);let S=g.yield,M={...o,keep:{...o.keep,resources:rt(Oe(o.keep.resources,S))}};O(M);let V=[];S.gold>0&&V.push(`+${S.gold}${B.gold}`),S.wood>0&&V.push(`+${S.wood}${B.wood}`),S.stone>0&&V.push(`+${S.stone}${B.stone}`);let Q=g.collected[0]?.type.replace("_"," ")??"fragment",he=g.collected.length>1?` (${g.collected.length}x)`:"";W(`${V.join(" ")} ${Q}${he}`)},[o,u,r,O,W]),G=ge(g=>{if(!o)return!1;let S=g.attackerId!==o.player.id;return k(g.replay),m(S?o.keep.grid:g.defenderGrid??o.keep.grid),b(S?"defend":"attack"),$(null),!0},[o]),X=ge(()=>{k(null),m(null),b(null),$(null)},[]),Ce=ge(()=>{o&&O({...o,tutorialCompleted:!0})},[o,O]),Tt=ge(()=>{if(!o)return;let g=Date.now(),S=g-H.current;if(S<$s){let re=Math.ceil(($s-S)/1e3);W(`Cooldown: ${re}s remaining`);return}H.current=g,y.current++;let M=Kr(),V=Ls({...M.grants},y.current),Q=Wo(o.keep,{...M,grants:V});O({...o,keep:Q});let he=y.current>Ut?" (diminished)":"";W(`+${V.gold}${B.gold} +${V.wood}${B.wood} +${V.stone}${B.stone} (${yr[M.type]??M.type})${he}`)},[o,O,W]),Nt=ge((g,S)=>{g>=0&&g<I&&S>=0&&S<I&&a({x:g,y:S})},[]),Io=ge(g=>{if(!o||o.keep.grid.structures.length===0)return;let S=o.keep.grid.structures,M=`${r.x},${r.y}`,V=S.findIndex(re=>`${re.pos.x},${re.pos.y}`===M),Q=V===-1?0:V+g;Q<0&&(Q=S.length-1),Q>=S.length&&(Q=0);let he=S[Q];a({x:he.pos.x,y:he.pos.y})},[o,r]),Pe=ge(()=>{U(null)},[]),Po=o?.keep.grid.structures.find(g=>g.pos.x===r.x&&g.pos.y===r.y)??null;return{gameSave:o,cursor:r,selectedStructure:A,structureAtCursor:Po,message:d,fragments:u,raidReplay:x,raidGrid:R,raidType:p,raidSummary:c,offlineReport:z,moveCursor:ue,cycleStructure:Se,selectStructure:nt,placeAtCursor:$t,upgradeAtCursor:jt,demolishAtCursor:v,collectAtCursor:Z,startAttackRaid:q,startDefendRaid:Y,quickDefend:Ie,watchLastRaid:L,watchRaidRecord:G,clearRaid:X,completeTutorial:Ce,grantSimResources:Tt,jumpToCoord:Nt,jumpToNextStructure:Io,clearOfflineReport:Pe}}var Mo=class{mode="online";baseUrl;auth=null;constructor(t){this.baseUrl=t.replace(/\/$/,"")}async request(t,o={}){let s={"Content-Type":"application/json",...o.headers??{}};this.auth&&(s.Authorization=`Bearer ${this.auth.token}`);let r=await fetch(`${this.baseUrl}${t}`,{...o,headers:s});if(!r.ok){let a=await r.json().catch(()=>({error:r.statusText}));throw new Error(a.error??`HTTP ${r.status}`)}return r.json()}isAuthenticated(){return this.auth!==null}async register(t){let o=await this.request("/auth/register",{method:"POST",body:JSON.stringify({displayName:t})});return this.auth={token:o.token,apiKey:o.apiKey,playerId:o.playerId},o}async login(t){let o=await this.request("/auth/login",{method:"POST",body:JSON.stringify({apiKey:t})});return this.auth={token:o.token,apiKey:t,playerId:o.playerId},o}async load(){if(!this.auth)return null;try{let t=await this.request("/me");return t.keep?{schemaVersion:1,savedAtUnixMs:Date.now(),player:{id:t.player.id,displayName:t.player.displayName,settings:{asciiMode:!1}},keep:{id:t.keep.id,name:t.keep.name,ownerPlayerId:t.player.id,grid:t.keep.grid,resources:t.keep.resources,createdAtUnixMs:t.player.createdAt,updatedAtUnixMs:Date.now()},raidHistory:[],tutorialCompleted:!0,lastPlayedAtUnixMs:Date.now(),progression:{totalBuildsToday:0,totalCommitsToday:0,lastDailyResetDay:Math.floor(Date.now()/864e5),totalRaidsWon:t.progression?.totalRaidsWon??0,totalRaidsLost:t.progression?.totalRaidsLost??0,totalStructuresPlaced:t.progression?.totalStructuresPlaced??0,currentWinStreak:t.progression?.currentWinStreak??0,bestWinStreak:t.progression?.bestWinStreak??0,achievements:t.progression?.achievements??[],totalRaidersKilledByArcher:0}}:null}catch{return null}}async save(t){this.auth&&await this.request("/keep/save",{method:"POST",body:JSON.stringify({grid:t.keep.grid,resources:t.keep.resources})})}async createNew(t){let o=await this.register(t),s=await this.load();return s||{schemaVersion:1,savedAtUnixMs:Date.now(),player:{id:o.playerId,displayName:t,settings:{asciiMode:!1}},keep:{id:`keep-${o.playerId}`,name:`${t}'s Keep`,ownerPlayerId:o.playerId,grid:{width:16,height:16,structures:[]},resources:{...St},createdAtUnixMs:Date.now(),updatedAtUnixMs:Date.now()},raidHistory:[],tutorialCompleted:!1,lastPlayedAtUnixMs:Date.now(),progression:{totalBuildsToday:0,totalCommitsToday:0,lastDailyResetDay:Math.floor(Date.now()/864e5),totalRaidsWon:0,totalRaidsLost:0,totalStructuresPlaced:0,currentWinStreak:0,bestWinStreak:0,achievements:[],totalRaidersKilledByArcher:0}}}async deleteAll(){return!1}async findMatch(){return(await this.request("/matchmaking/find",{method:"POST"})).targets}async launchPvpRaid(t,o,s){return this.request("/raids/launch",{method:"POST",body:JSON.stringify({defenderPlayerId:t,probeTypes:o,spawnSpecs:s})})}async getIncomingRaids(t){return(await this.request(`/raids/incoming?since=${t}`)).raids}async getPvpProfile(){try{let t=await this.request("/me");return{trophies:t.player.trophies,league:t.player.league,shieldExpiresAt:t.player.shieldExpiresAt,seasonId:"S1",seasonPeakTrophies:t.player.trophies}}catch{return null}}async getLeaderboard(t=50){return(await this.request(`/leaderboard?limit=${t}`)).players}async getWarCamp(){try{return await this.request("/warcamp")}catch{return null}}async trainRaider(t,o){let s=await this.request("/warcamp/train",{method:"POST",body:JSON.stringify({slotId:t,raiderType:o})});return{slots:s.slots,maxSlots:s.maxSlots}}async getBounties(){try{return(await this.request("/bounties")).bounties}catch{return[]}}async claimBounty(t){return(await this.request(`/bounties/${t}/claim`,{method:"POST"})).reward}async registerForMatchmaking(){await this.request("/matchmaking/register",{method:"POST"})}async sync(){this.auth&&await this.registerForMatchmaking()}};import{jsx as ae,jsxs as je}from"react/jsx-runtime";var Os=60,Us=18;function Na(){let{stdout:e}=$a(),[t,o]=Re({columns:e?.columns??process.stdout.columns??80,rows:e?.rows??process.stdout.rows??24});return Pa(()=>{let s=e??process.stdout,r=()=>{o({columns:s.columns,rows:s.rows})};return s.on("resize",r),()=>{s.off("resize",r)}},[e]),t}function Ba({asciiMode:e,compact:t,forceTutorial:o,autoResume:s,serverUrl:r,dryRun:a}){let{exit:T}=Da(),{columns:f,rows:d}=Na(),[l,x]=Re(r?"auth":s?"keep":"menu"),[k,R]=Re(e),[m,p]=Re(!1),[b,c]=Re(null),[$,z]=Re(null),[U,u]=Re(!1),[K,w]=Re(""),[H,y]=Re("keep"),h=Bs(1),E=Bs(r?new Mo(r):null),[C,N]=Re(!1),[A,O]=Re(null),[W,ue]=Re([]),[Se,nt]=Re(!1),[$t,jt]=Re([]),[v,q]=Re(!1),[Y,Ie]=Re({slots:[],maxSlots:3}),[L,Z]=Re(null),[G,X]=Re(null),[Ce,Tt]=Re(!1),Nt=t||f<80||d<24,Io=f<Os||d<Us,{gameSave:Pe,cursor:Po,selectedStructure:g,message:S,fragments:M,raidReplay:V,raidGrid:Q,raidType:he,raidSummary:re,offlineReport:oe,structureAtCursor:Te,moveCursor:ie,cycleStructure:et,selectStructure:He,placeAtCursor:wt,upgradeAtCursor:at,demolishAtCursor:it,collectAtCursor:Rt,startAttackRaid:xe,startDefendRaid:lt,quickDefend:te,watchLastRaid:dt,watchRaidRecord:Do,clearRaid:ir,completeTutorial:Ks,grantSimResources:Hs,jumpToCoord:Fs,jumpToNextStructure:Vs,clearOfflineReport:Ys}=Ns(o,a),lr=Yt(()=>{T()},[T]),js=Yt(()=>{Xr(),T()},[T]),dr=Yt(async(D,ne)=>{let me=E.current;if(me){Tt(!0),X(null);try{D==="login"?await me.login(ne):await me.register(ne),N(!0),x("menu"),me.getPvpProfile?.().then(Fe=>O(Fe)),me.registerForMatchmaking?.()}catch(Fe){X(Fe instanceof Error?Fe.message:"Connection failed")}finally{Tt(!1)}}},[]),qs=Yt(async()=>{let D=E.current;if(D?.findMatch){nt(!0);try{let ne=await D.findMatch();ue(ne)}catch{ue([])}finally{nt(!1)}}},[]),zs=Yt(async(D,ne,me)=>{let Fe=E.current;if(!(!Fe?.launchPvpRaid||!Pe))try{let Bt=await Fe.launchPvpRaid(D.playerId,ne,me);Do({replay:Bt.replay,attackerId:Pe.player.id,defenderKeepId:D.playerId,defenderGrid:D.grid})&&(y("pvp"),x("raid")),O(Lo=>Lo&&{...Lo,trophies:Bt.newTrophies,league:Bt.newLeague})}catch{}},[Pe,Do]),Zs=Yt(async()=>{let D=E.current;if(D?.getLeaderboard){q(!0);try{let ne=await D.getLeaderboard();jt(ne)}catch{jt([])}finally{q(!1)}}},[]);return La((D,ne)=>{if(m){p(!1);return}if(D==="?"){p(!0);return}if(U){if(ne.escape){u(!1),w("");return}if(ne.return){let me=K.split(/[, ]+/);if(me.length===2){let Fe=parseInt(me[0],16),Bt=parseInt(me[1],16);!isNaN(Fe)&&!isNaN(Bt)&&Fs(Fe,Bt)}u(!1),w("");return}if(ne.backspace||ne.delete){w(me=>me.slice(0,-1));return}/^[0-9a-fA-F, ]$/.test(D)&&w(me=>me+D);return}if(oe&&l==="keep"&&Ys(),l!=="menu"&&l!=="tutorial"){if(l==="raid"||l==="friendRaid"){(D==="q"||ne.escape)&&(ir(),c(null),z(null),x("keep"));return}if(!(l==="friendList"||l==="raidLog"||l==="settings"||l==="pvp"||l==="warcamp"||l==="leaderboard"||l==="auth"||l==="raidPlanner")){if(D==="q"){lr();return}if(ne.escape){x("menu");return}D==="h"||D==="a"||ne.leftArrow?ie(-1,0):D==="l"||D==="d"||ne.rightArrow?ie(1,0):D==="k"||D==="w"||ne.upArrow?ie(0,-1):D==="j"||D==="s"||ne.downArrow?ie(0,1):ne.return||D==="e"?wt():D==="u"?at():D==="x"?it():D==="["?et(-1):D==="]"?et(1):D==="f"?Hs():D==="c"?Rt():D==="r"?te():D==="v"?dt()&&x("raid"):D==="g"?(u(!0),w("")):ne.tab?Vs(1):D>="1"&&D<="6"&&He(parseInt(D)-1)}}}),Pe?Io?je(Lt,{flexDirection:"column",padding:1,children:[ae(Me,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep"}),ae(Me,{children:" "}),ae(Me,{color:"red",children:"Terminal too small"}),je(Me,{children:["Need ",je(Me,{bold:!0,children:[Os,"x",Us]}),", got ",je(Me,{bold:!0,children:[f,"x",d]})]}),ae(Me,{children:" "}),ae(Me,{dimColor:!0,children:"Resize your terminal or run with --compact"})]}):m?ae(rs,{}):l==="tutorial"||!Pe.tutorialCompleted?ae(ds,{gameSave:Pe,onComplete:()=>{Ks(),x("keep")}}):l==="auth"?ae(bs,{error:G,isLoading:Ce,onLogin:D=>dr("login",D),onRegister:D=>dr("register",D),onPlayOffline:()=>{N(!1),x("menu")}}):l==="menu"?ae(ns,{gameSave:Pe,onlineMode:C,onKeep:()=>x("keep"),onAttack:()=>{xe(),x("raid")},onDefend:()=>{lt(),x("raid")},onPvp:()=>x("pvp"),onFriendRaid:()=>x("friendList"),onRaidLog:()=>x("raidLog"),onSettings:()=>x("settings"),onQuit:lr}):l==="raidLog"?ae(ms,{gameSave:Pe,onBack:()=>x("menu"),onWatchReplay:D=>{Do(D)&&(y("raidLog"),x("raid"))}}):l==="settings"?ae(Ts,{onBack:()=>x("menu"),onResetGame:js,onReplayTutorial:()=>x("tutorial"),asciiMode:k,onToggleAscii:()=>R(D=>!D)}):l==="pvp"?ae(ys,{pvpProfile:A,targets:W,isSearching:Se,onSearch:qs,onAttack:D=>{Z(D),x("raidPlanner")},onWarCamp:()=>{E.current?.getWarCamp?.().then(ne=>{ne&&Ie(ne)}),x("warcamp")},onLeaderboard:()=>{Zs(),x("leaderboard")},onBack:()=>x("menu")}):l==="raidPlanner"&&L?ae(As,{targetName:L.displayName,targetTrophies:L.trophies,targetGrid:L.grid,warCamp:Y,resources:Pe.keep.resources,onLaunch:D=>{let ne=D.map(me=>me.raiderType);zs(L,ne,D),Z(null)},onBack:()=>{Z(null),x("pvp")}}):l==="warcamp"?ae(Rs,{warCamp:Y,resources:Pe.keep.resources,onTrain:(D,ne)=>{E.current?.trainRaider?.(D,ne).then(Fe=>Ie(Fe))},onBack:()=>x("pvp")}):l==="leaderboard"?ae(Ss,{entries:$t,currentPlayerId:Pe.player.id,isLoading:v,onBack:()=>x("pvp")}):l==="friendList"?ae(ps,{onSelectFriend:D=>{let ne=`friend-raid-${Date.now()}`,me=ut({probeCount:4,keepGrid:D.grid,seed:ne});c(me),z(D.grid),x("friendRaid")},onBack:()=>x("menu")}):l==="friendRaid"&&b&&$?je(Lt,{flexDirection:"column",children:[ae(Me,{bold:!0,color:"yellow",children:"[ LOCAL SIMULATION ]"}),ae(Jo,{replay:b,keepGrid:$,raidType:"attack",initialSpeed:h.current,onSpeedChange:D=>{h.current=D},onDone:()=>{c(null),z(null),x("menu")}})]}):l==="raid"&&V&&Q?ae(Jo,{replay:V,keepGrid:Q,raidType:he||"defend",summary:re||void 0,initialSpeed:h.current,onSpeedChange:D=>{h.current=D},onDone:()=>{ir(),x(H),y("keep")}}):je(Lt,{flexDirection:"column",children:[oe&&je(Lt,{flexDirection:"column",children:[(oe.resources.gold>0||oe.resources.wood>0||oe.resources.stone>0)&&je(Me,{color:"green",children:["Passive income: +",oe.resources.gold,B.gold," +",oe.resources.wood,B.wood," +",oe.resources.stone,B.stone]}),oe.raids.length>0&&je(Me,{color:"yellow",children:["Background raids: ",oe.raids.filter(D=>D.won).length,"W / ",oe.raids.filter(D=>!D.won).length,"L"]}),oe.newAchievements.length>0&&je(Me,{color:"magenta",bold:!0,children:["New achievements: ",oe.newAchievements.join(", ")]}),ae(Me,{dimColor:!0,children:"(press any key to continue)"})]}),ae(os,{resources:Pe.keep.resources,selectedStructure:g,message:U?`Jump to: ${K}_`:S,compact:Nt,structureAtCursor:Te,fragmentCount:M.length,dryRun:a}),je(Lt,{flexDirection:"row",children:[ae(ts,{grid:Pe.keep.grid,cursor:Po,asciiMode:k,compact:Nt,fragments:M}),!Nt&&je(Lt,{flexDirection:"column",marginLeft:2,width:28,children:[ae(us,{selected:g}),ae(Lt,{marginTop:1,children:ae(Me,{dimColor:!0,children:`e place u upgrade x demo
25
+ `);return`https://github.com/tooyipjee/codekeep/issues/new?title=${t}&body=${o}&labels=bug,crash`}import{Fragment as hi,jsx as Se,jsxs as Rt}from"react/jsx-runtime";function hn({onBack:e,onResetGame:t,onReplayTutorial:o,asciiMode:s,onToggleAscii:r}){let[n,c]=mo(0),[d,g]=mo(!1),[l,T]=mo(!1),[R,u]=mo(""),[i,y]=mo(null),w=[{key:"ascii",label:`ASCII Mode: ${s?"ON":"OFF"}`,desc:"Use plain ASCII borders (for basic terminals)"},{key:"tutorial",label:"Replay Tutorial",desc:"Learn how to play again"},{key:"report",label:"Report Bug",desc:"Open a GitHub issue for bugs"},{key:"reset",label:"Reset Game",desc:"Delete save and start over"},{key:"back",label:"Back",desc:"Return to menu"}];return mi((h,x)=>{if(i){(x.escape||x.return||h==="q")&&(y(null),T(!1));return}if(l){if(x.escape){T(!1),u("");return}if(x.return&&R.length>0){let _={timestamp:new Date().toISOString(),error:R,version:globalThis.__CODEKEEP_VERSION??"unknown",nodeVersion:process.version,platform:process.platform,arch:process.arch,screen:"settings"},j=zo(_);y(j),u("");let K=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";gi(`${K} "${j}"`,()=>{});return}if(x.backspace||x.delete){u(_=>_.slice(0,-1));return}h&&h.length===1&&u(_=>_+h);return}if(d){if(h==="y"||h==="Y"){t();return}g(!1);return}if(h==="q"||x.escape){e();return}if((h==="j"||h==="s"||x.downArrow)&&c(_=>Math.min(_+1,w.length-1)),(h==="k"||h==="w"||x.upArrow)&&c(_=>Math.max(_-1,0)),x.return){let _=w[n];_.key==="ascii"?r():_.key==="tutorial"?o():_.key==="report"?T(!0):_.key==="reset"?g(!0):_.key==="back"&&e()}}),Rt(go,{flexDirection:"column",padding:1,children:[Se(he,{bold:!0,color:"yellow",children:"\u25C6 Settings"}),Se(he,{children:" "}),i?Rt(go,{flexDirection:"column",children:[Se(he,{bold:!0,color:"green",children:"Bug report ready!"}),Se(he,{children:" "}),Se(he,{children:"Opening in your browser..."}),Se(he,{children:"If it didn't open, copy this URL:"}),Se(he,{children:" "}),Se(he,{color:"cyan",wrap:"wrap",children:i}),Se(he,{children:" "}),Se(he,{dimColor:!0,children:"Press Enter or Esc to go back"})]}):l?Rt(go,{flexDirection:"column",children:[Se(he,{bold:!0,color:"cyan",children:"Report a Bug"}),Se(he,{children:"Describe the issue briefly:"}),Rt(he,{color:"cyan",children:[R,Se(he,{dimColor:!0,children:"_"})]}),Se(he,{children:" "}),Se(he,{dimColor:!0,children:"Enter to generate GitHub issue URL \xB7 Esc cancel"})]}):d?Rt(go,{flexDirection:"column",children:[Se(he,{bold:!0,color:"red",children:"Are you sure you want to reset?"}),Se(he,{children:"This will permanently delete your save file."}),Se(he,{children:"All structures, resources, and achievements will be lost."}),Se(he,{children:" "}),Rt(he,{bold:!0,children:["Press ",Se(he,{color:"red",children:"Y"})," to confirm, any other key to cancel"]})]}):Rt(hi,{children:[w.map((h,x)=>Rt(go,{children:[Rt(he,{color:x===n?"yellow":void 0,bold:x===n,children:[x===n?" \u25B8 ":" ",h.label]}),Rt(he,{dimColor:!0,children:[" ",h.desc]})]},h.key)),Se(he,{children:" "}),Se(he,{dimColor:!0,children:" \u2191\u2193 navigate \xB7 Enter select \xB7 Esc back"})]})]})}import xi from"react";import{Box as Ti,Text as Le}from"ink";import{Fragment as xn,jsx as tt,jsxs as Kt}from"react/jsx-runtime";var Xo=class extends xi.Component{constructor(t){super(t),this.state={error:null,crashFilePath:null,issueUrl:null}}static getDerivedStateFromError(t){return{error:t}}componentDidCatch(t){try{let o=gn(t),s={timestamp:new Date().toISOString(),error:t.message,stack:t.stack,version:globalThis.__CODEKEEP_VERSION??"unknown",nodeVersion:process.version,platform:process.platform,arch:process.arch},r=zo(s);this.setState({crashFilePath:o,issueUrl:r})}catch{}}render(){return this.state.error?Kt(Ti,{flexDirection:"column",padding:1,children:[tt(Le,{bold:!0,color:"red",children:"\u25C6 CodeKeep \u2014 Something went wrong"}),tt(Le,{children:" "}),tt(Le,{color:"red",children:this.state.error.message}),tt(Le,{children:" "}),tt(Le,{dimColor:!0,children:"Your save file is at:"}),Kt(Le,{children:[" ","~/.config/codekeep/game.json"]}),tt(Le,{children:" "}),this.state.crashFilePath&&Kt(xn,{children:[tt(Le,{dimColor:!0,children:"Crash report saved to:"}),Kt(Le,{children:[" ",this.state.crashFilePath]}),tt(Le,{children:" "})]}),this.state.issueUrl&&Kt(xn,{children:[tt(Le,{dimColor:!0,children:"Report this bug:"}),Kt(Le,{color:"cyan",children:[" ",this.state.issueUrl]}),tt(Le,{children:" "})]}),tt(Le,{dimColor:!0,children:"If the game won't start, try:"}),Kt(Le,{bold:!0,children:[" ","codekeep --tutorial"]}),tt(Le,{children:" "}),tt(Le,{dimColor:!0,children:"Press Ctrl+C to exit"})]}):this.props.children}};import{useState as yi}from"react";import{Box as Zo,Text as xt,useInput as wi}from"ink";import{jsx as Bt,jsxs as Ft}from"react/jsx-runtime";var Ri={copper:"white",iron:"gray",silver:"whiteBright",gold:"yellow",diamond:"cyan"},Si={copper:"\u25CB",iron:"\u25CF",silver:"\u25C6",gold:"\u2605",diamond:"\u25C8"};function Tn({pvpProfile:e,targets:t,isSearching:o,onSearch:s,onAttack:r,onWarCamp:n,onLeaderboard:c,onBack:d}){let[g,l]=yi(0),T=[{key:"search",label:"Find Opponent"},{key:"warcamp",label:"War Camp"},{key:"leaderboard",label:"Leaderboard"},...t.map((y,w)=>({key:`target-${w}`,label:`Attack ${y.displayName} (${y.trophies} trophies)`})),{key:"back",label:"Back"}];wi((y,w)=>{if(w.upArrow||y==="k")l(h=>Math.max(0,h-1));else if(w.downArrow||y==="j")l(h=>Math.min(T.length-1,h+1));else if(w.return){let h=T[g];if(h.key==="search")s();else if(h.key==="warcamp")n();else if(h.key==="leaderboard")c();else if(h.key==="back")d();else if(h.key.startsWith("target-")){let x=parseInt(h.key.split("-")[1]),_=t[x];_&&r(_)}}else(w.escape||y==="q")&&d()});let R=e?.league??"copper",u=Ri[R]??"white",i=Si[R]??"\u25CB";return Ft(Zo,{flexDirection:"column",padding:1,children:[Bt(xt,{bold:!0,color:"red",children:"\u2694 PVP ARENA"}),Bt(xt,{children:" "}),e&&Ft(Zo,{flexDirection:"column",children:[Ft(Zo,{flexDirection:"row",gap:2,children:[Ft(xt,{color:u,bold:!0,children:[i," ",R.toUpperCase()," League"]}),Ft(xt,{children:["Trophies: ",Bt(xt,{bold:!0,color:"yellow",children:e.trophies})]})]}),e.shieldExpiresAt&&e.shieldExpiresAt>Date.now()&&Ft(xt,{color:"cyan",children:["Shield active (",Math.ceil((e.shieldExpiresAt-Date.now())/36e5),"h remaining)"]}),Bt(xt,{children:" "})]}),o&&Bt(xt,{color:"yellow",children:"Searching for opponents..."}),T.map((y,w)=>Bt(Zo,{children:Ft(xt,{color:w===g?"yellow":void 0,bold:w===g,children:[w===g?" \u25B8 ":" ",y.label]})},y.key)),Bt(xt,{children:" "}),Bt(xt,{dimColor:!0,children:"\u2191\u2193 select Enter choose Esc back"})]})}import{useState as Jo,useEffect as bi}from"react";import{Box as ho,Text as ot,useInput as ki}from"ink";import{jsx as Et,jsxs as At}from"react/jsx-runtime";var Vr=[{type:"raider",name:"Raider",symbol:"R"},{type:"scout",name:"Scout",symbol:"S"},{type:"brute",name:"Brute",symbol:"B"}];function yn(e){let t=Math.ceil(e/1e3),o=Math.floor(t/60),s=t%60;return`${o}:${String(s).padStart(2,"0")}`}function wn({warCamp:e,resources:t,onTrain:o,onBack:s}){let[r,n]=Jo(0),[c,d]=Jo(!1),[g,l]=Jo(0),[T,R]=Jo(Date.now());return bi(()=>{let u=setInterval(()=>R(Date.now()),1e3);return()=>clearInterval(u)},[]),ki((u,i)=>{if(c){i.upArrow||u==="k"?l(y=>Math.max(0,y-1)):i.downArrow||u==="j"?l(y=>Math.min(Vr.length-1,y+1)):i.return?(o(r,Vr[g].type),d(!1)):i.escape&&d(!1);return}i.upArrow||u==="k"?n(y=>Math.max(0,y-1)):i.downArrow||u==="j"?n(y=>Math.min(e.maxSlots-1,y+1)):i.return?e.slots[r]?.raiderType||d(!0):(i.escape||u==="q")&&s()}),At(ho,{flexDirection:"column",padding:1,children:[Et(ot,{bold:!0,color:"red",children:"\u2694 WAR CAMP"}),Et(ot,{dimColor:!0,children:"Train raiders for PvP attacks"}),Et(ot,{children:" "}),At(ho,{flexDirection:"row",gap:2,children:[At(ot,{children:["Gold: ",t.gold,W.gold]}),At(ot,{children:["Wood: ",t.wood,W.wood]}),At(ot,{children:["Stone: ",t.stone,W.stone]})]}),Et(ot,{children:" "}),At(ot,{bold:!0,children:["Slots (",e.slots.filter(u=>u.raiderType).length,"/",e.maxSlots,")"]}),Array.from({length:e.maxSlots},(u,i)=>{let y=e.slots[i],w=r===i,h=y?.readyAtMs?y.readyAtMs<=T:!1,x=y?.readyAtMs?y.readyAtMs>T:!1,_=x&&y?.readyAtMs?y.readyAtMs-T:0,j;return y?.raiderType?x?j=`${y.raiderType} training... ${yn(_)}`:h?j=`${y.raiderType} READY!`:j=`${y.raiderType}`:j="[ Empty ]",Et(ho,{children:At(ot,{color:w?"yellow":void 0,bold:w,children:[w?" \u25B8 ":" ","Slot ",i+1,": ",j]})},i)}),c&&At(ho,{flexDirection:"column",marginTop:1,children:[Et(ot,{bold:!0,color:"cyan",children:"Select raider type:"}),Vr.map((u,i)=>{let y=Bo[u.type],w=hs[u.type],h=Qe[u.type],x=t.gold>=y.gold&&t.wood>=y.wood&&t.stone>=y.stone;return Et(ho,{children:At(ot,{color:g===i?"yellow":x?void 0:"red",bold:g===i,children:[g===i?" \u25B8 ":" ",u.name," \u2014 HP:",h.hp," DMG:",h.damage," SPD:",h.speed," \u2014 ",y.gold,"g ",y.wood,"w ",y.stone,"s \u2014 ",yn(w)]})},u.type)})]}),Et(ot,{children:" "}),Et(ot,{dimColor:!0,children:"\u2191\u2193 select Enter train Esc back"})]})}import{Box as Qo,Text as Xe,useInput as vi}from"ink";import{jsx as rt,jsxs as xo}from"react/jsx-runtime";var Ci={copper:"white",iron:"gray",silver:"whiteBright",gold:"yellow",diamond:"cyan"};function Rn({entries:e,currentPlayerId:t,isLoading:o,onBack:s}){return vi((r,n)=>{(n.escape||r==="q")&&s()}),xo(Qo,{flexDirection:"column",padding:1,children:[rt(Xe,{bold:!0,color:"yellow",children:"\u{1F3C6} LEADERBOARD"}),rt(Xe,{children:" "}),o&&rt(Xe,{color:"yellow",children:"Loading..."}),!o&&e.length===0&&rt(Xe,{dimColor:!0,children:"No players on the leaderboard yet."}),!o&&e.length>0&&xo(Qo,{flexDirection:"column",children:[xo(Qo,{children:[rt(Xe,{bold:!0,children:" # "}),rt(Xe,{bold:!0,children:"Name "}),rt(Xe,{bold:!0,children:"League "}),rt(Xe,{bold:!0,children:"Trophies"})]}),e.map(r=>{let n=r.id===t,c=n?"green":void 0,d=Ci[r.league]??"white";return xo(Qo,{children:[xo(Xe,{color:c,bold:n,children:[String(r.rank).padStart(3," ")," "]}),rt(Xe,{color:c,bold:n,children:(r.displayName||"Unknown").padEnd(20," ")}),rt(Xe,{color:d,children:r.league.padEnd(10," ")}),rt(Xe,{color:"yellow",bold:!0,children:r.trophies})]},r.id)})]}),rt(Xe,{children:" "}),rt(Xe,{dimColor:!0,children:"Esc/q back"})]})}import{useState as jr}from"react";import{Box as er,Text as $e,useInput as Ei}from"ink";import{Fragment as Ai,jsx as Ye,jsxs as Ht}from"react/jsx-runtime";function Sn({onLogin:e,onRegister:t,onPlayOffline:o,error:s,isLoading:r}){let[n,c]=jr("menu"),[d,g]=jr(""),[l,T]=jr(0),R=[{key:"register",label:"Register (new player)"},{key:"login",label:"Login (with API key)"},{key:"offline",label:"Play Offline"}];return Ei((u,i)=>{if(!r){if(n==="menu"){if(i.upArrow||u==="k")T(y=>Math.max(0,y-1));else if(i.downArrow||u==="j")T(y=>Math.min(R.length-1,y+1));else if(i.return){let y=R[l];y.key==="register"?c("register"):y.key==="login"?c("login"):y.key==="offline"&&o()}return}if(i.escape){c("menu"),g("");return}if(i.return&&d.length>0){n==="login"?e(d):n==="register"&&t(d),g("");return}if(i.backspace||i.delete){g(y=>y.slice(0,-1));return}u&&u.length===1&&g(y=>y+u)}}),Ht(er,{flexDirection:"column",padding:1,children:[Ye($e,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep Online"}),Ye($e,{children:" "}),s&&Ye($e,{color:"red",children:s}),r&&Ye($e,{color:"yellow",children:"Connecting..."}),n==="menu"&&!r&&Ht(Ai,{children:[R.map((u,i)=>Ye(er,{children:Ht($e,{color:i===l?"yellow":void 0,bold:i===l,children:[i===l?" \u25B8 ":" ",u.label]})},u.key)),Ye($e,{children:" "}),Ye($e,{dimColor:!0,children:"\u2191\u2193 navigate Enter select"})]}),n==="login"&&!r&&Ht(er,{flexDirection:"column",children:[Ye($e,{children:"Enter your API key:"}),Ht($e,{color:"cyan",children:[d,Ye($e,{dimColor:!0,children:"_"})]}),Ye($e,{children:" "}),Ye($e,{dimColor:!0,children:"Enter to submit Esc back"})]}),n==="register"&&!r&&Ht(er,{flexDirection:"column",children:[Ye($e,{children:"Choose a display name:"}),Ht($e,{color:"cyan",children:[d,Ye($e,{dimColor:!0,children:"_"})]}),Ye($e,{children:" "}),Ye($e,{dimColor:!0,children:"Enter to submit Esc back"})]})]})}import{useState as Yt}from"react";import{Box as it,Text as J,useInput as Mi}from"ink";import{jsx as ee,jsxs as Pe}from"react/jsx-runtime";var bn={N:"North",S:"South",E:"East",W:"West"},oo={raider:"R",scout:"S",brute:"B"},tr={raider:"red",scout:"cyan",brute:"magenta"},kn=8;function vn(e,t){switch(e){case"N":return{x:t,y:0};case"S":return{x:t,y:I-1};case"E":return{x:I-1,y:t};case"W":return{x:0,y:t}}}function Cn({targetName:e,targetTrophies:t,targetGrid:o,warCamp:s,resources:r,onLaunch:n,onBack:c}){let[d,g]=Yt("scout"),[l,T]=Yt([]),[R,u]=Yt(0),[i,y]=Yt([]),[w,h]=Yt("N"),[x,_]=Yt(Math.floor(I/2)),[j,K]=Yt(0),N=["raider","scout","brute"];Mi((k,b)=>{if(b.escape||k==="q"){if(d==="scout"){c();return}if(d==="army"){g("scout");return}if(d==="deploy"){g("army");return}if(d==="confirm"){g("deploy");return}return}if(d==="scout"){b.return&&g("army");return}if(d==="army"){b.upArrow||k==="k"?u(L=>Math.max(0,L-1)):b.downArrow||k==="j"?u(L=>Math.min(N.length-1,L+1)):b.return?l.length<kn&&T(L=>[...L,N[R]]):b.backspace||b.delete?T(L=>L.slice(0,-1)):(k==="n"||b.tab)&&l.length>0&&(y(l.map(()=>({edge:"N",offset:Math.floor(I/2)}))),K(0),g("deploy"));return}if(d==="deploy"){b.leftArrow||k==="a"?_(w==="E"||w==="W"?L=>Math.max(0,L-1):L=>Math.max(0,L-1)):b.rightArrow||k==="d"?_(L=>Math.min(I-1,L+1)):b.upArrow||k==="w"?_(L=>Math.max(0,L-1)):b.downArrow||k==="s"?_(L=>Math.min(I-1,L+1)):k==="n"?h("N"):k==="e"?h("E"):k==="z"?h("S"):k==="x"?h("W"):b.return?(y(L=>{let m=[...L];return m[j]={edge:w,offset:x},m}),j<l.length-1?K(L=>L+1):g("confirm")):b.tab&&K(L=>(L+1)%l.length);return}if(d==="confirm"){if(b.return||k==="y"){let L=l.map((m,P)=>({raiderType:m,edge:i[P]?.edge??"N",offset:i[P]?.offset??8,waveDelay:0}));n(L)}return}});let U=(()=>{let k=Array.from({length:I},()=>Array(I).fill("\xB7"));for(let m of o.structures)m.kind==="trap"||m.kind==="ward"?k[m.pos.y][m.pos.x]="?":k[m.pos.y][m.pos.x]=ye[m.kind];if(d==="deploy"||d==="confirm"){for(let m=0;m<i.length;m++){let P=i[m];if(!P)continue;let Y=vn(P.edge,P.offset);k[Y.y][Y.x]=oo[l[m]]}if(d==="deploy"){let m=vn(w,x);k[m.y][m.x]="\u25BC"}}let b=" "+Array.from({length:I},(m,P)=>P.toString(16).toUpperCase()).join(" "),L=k.map((m,P)=>{let Y=P.toString(16).toUpperCase(),se=m.join(" ");return`${Y} ${se}`});return[b,...L]})();return Pe(it,{flexDirection:"column",padding:1,children:[ee(J,{bold:!0,color:"red",children:"\u2694 RAID PLANNER"}),Pe(it,{gap:2,children:[Pe(J,{children:["Target: ",ee(J,{bold:!0,color:"yellow",children:e})]}),Pe(J,{children:["Trophies: ",ee(J,{bold:!0,children:t})]})]}),ee(J,{children:" "}),ee(it,{flexDirection:"column",children:U.map((k,b)=>b===0?ee(J,{dimColor:!0,children:k},b):ee(J,{children:k},b))}),ee(J,{children:" "}),ee(it,{gap:2,children:ee(J,{dimColor:!0,children:"# wall $ treasury ^ tower ! archer & vault ? hidden"})}),ee(J,{children:" "}),d==="scout"&&Pe(it,{flexDirection:"column",children:[ee(J,{bold:!0,color:"cyan",children:"SCOUT PHASE"}),ee(J,{children:"Study the enemy keep. Traps and wards are hidden (?)."}),Pe(J,{children:["Structures: ",o.structures.length," placed"]}),ee(J,{children:" "}),ee(J,{dimColor:!0,children:"Enter \u2192 pick your army Esc \u2192 back"})]}),d==="army"&&Pe(it,{flexDirection:"column",children:[Pe(J,{bold:!0,color:"cyan",children:["ARMY SELECTION (",l.length,"/",kn,")"]}),ee(J,{children:" "}),N.map((k,b)=>{let L=Qe[k],m=Bo[k];return ee(it,{children:Pe(J,{color:R===b?"yellow":void 0,bold:R===b,children:[R===b?" \u25B8 ":" ",ee(J,{color:tr[k],children:oo[k]})," ",k.charAt(0).toUpperCase()+k.slice(1)," ","HP:",L.hp," DMG:",L.damage," SPD:",L.speed," ","(",m.gold,"g ",m.wood,"w ",m.stone,"s)"]})},k)}),ee(J,{children:" "}),Pe(it,{gap:1,children:[ee(J,{children:"Army: "}),l.length===0?ee(J,{dimColor:!0,children:"(empty)"}):l.map((k,b)=>ee(J,{color:tr[k],bold:!0,children:oo[k]},b))]}),ee(J,{children:" "}),ee(J,{dimColor:!0,children:"Enter add Backspace remove Tab/N \u2192 deploy Esc back"})]}),d==="deploy"&&Pe(it,{flexDirection:"column",children:[Pe(J,{bold:!0,color:"cyan",children:["DEPLOY \u2014 Placing ",oo[l[j]]," (",l[j],") [",j+1,"/",l.length,"]"]}),Pe(J,{children:["Edge: ",ee(J,{bold:!0,color:"yellow",children:bn[w]})," Position: ",ee(J,{bold:!0,children:x.toString(16).toUpperCase()})]}),ee(J,{children:" "}),Pe(it,{gap:1,children:[ee(J,{children:"Spawns: "}),l.map((k,b)=>{let L=i[b],m=b<j||b===j&&!1;return Pe(J,{color:b===j?"yellow":m?tr[k]:"gray",children:[oo[k],L?`@${L.edge}${L.offset.toString(16)}`:"",b<l.length-1?" ":""]},b)})]}),ee(J,{children:" "}),ee(J,{dimColor:!0,children:"\u2190\u2192 / \u2191\u2193 position N/E/Z/X edge Enter place Tab next Esc back"})]}),d==="confirm"&&Pe(it,{flexDirection:"column",children:[ee(J,{bold:!0,color:"green",children:"READY TO ATTACK"}),ee(J,{children:" "}),ee(it,{flexDirection:"column",children:l.map((k,b)=>{let L=i[b];return Pe(J,{children:[ee(J,{color:tr[k],bold:!0,children:oo[k]})," ",k," \u2192 ",L?`${bn[L.edge]} edge, pos ${L.offset.toString(16).toUpperCase()}`:"unplaced"]},b)})}),ee(J,{children:" "}),Pe(J,{bold:!0,children:["Press ",ee(J,{color:"green",children:"Enter"})," to launch raid or ",ee(J,{color:"red",children:"Esc"})," to adjust"]})]})]})}import{useState as To}from"react";import{Box as ro,Text as pe,useInput as Ii}from"ink";function _i(){let e=new Date;return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function En(){let e=_i(),t=It(e),o=Wo(t),s=[],r=Math.floor(I/2),n=Math.floor(I/2);s.push({id:"treasury-8-8",kind:"treasury",level:1,pos:{x:r,y:n},placedAtUnixMs:Date.now()});let c={id:`daily-${e}`,name:`Daily Challenge ${e}`,ownerPlayerId:"daily",grid:{width:I,height:I,structures:s},resources:{gold:60,wood:30,stone:20},createdAtUnixMs:Date.now(),updatedAtUnixMs:Date.now()};return{dateKey:e,seed:t,keep:c,wave:0,score:0,alive:!0,lastReplay:null,lastGrid:null}}function An(e){if(!e.alive)return e;let t=e.wave+1,o=Math.min(10,Math.floor(t/2)+1),s=3+o,r=`daily-${e.dateKey}-wave-${t}`,n=at(It(r)),c=Lt(s,o,n),d=ut({probeCount:s,keepGrid:e.keep.grid,seed:r,probeTypes:c}),g=d.events[d.events.length-1];if(g?.type!=="raid_end")return{...e,wave:t,lastReplay:d,lastGrid:e.keep.grid};let l=g.outcome==="defense_win",T=d.events.filter(h=>h.type==="raider_destroyed").length,R=l?s*o*10:T*o*3,u=d.events.filter(h=>h.type==="treasury_breach").reduce((h,x)=>({gold:h.gold+x.lootTaken.gold,wood:h.wood+x.lootTaken.wood,stone:h.stone+x.lootTaken.stone}),{gold:0,wood:0,stone:0}),i=l?{gold:10+o*3,wood:5+o*2,stone:5+o*2}:{gold:0,wood:0,stone:0},y={gold:Math.max(0,e.keep.resources.gold-u.gold),wood:Math.max(0,e.keep.resources.wood-u.wood),stone:Math.max(0,e.keep.resources.stone-u.stone)},w=nt(He(y,i));return{...e,wave:t,score:e.score+R,alive:l,keep:{...e.keep,resources:w},lastReplay:d,lastGrid:e.keep.grid}}function Mn(e){let t=`${e.dateKey}:${e.wave}:${e.score}`;return Math.abs(It(t)).toString(36).slice(0,8)}import{jsx as Be,jsxs as Ge}from"react/jsx-runtime";function _n({onBack:e,onSaveScore:t}){let[o,s]=To(()=>En()),[r,n]=To({x:8,y:8}),[c,d]=To(0),[g,l]=To("build"),[T,R]=To("Place structures, then press R to start a wave"),u=qe[c];Ii((w,h)=>{if(g==="result"){if(!o.alive){(h.return||w===" ")&&(t(o.dateKey,o.wave,o.score),e());return}(h.return||w===" ")&&(l("build"),R("Prepare for next wave \u2014 place/upgrade, then R to fight"));return}if(h.escape){t(o.dateKey,o.wave,o.score),e();return}if(h.upArrow||w==="k")n(x=>({x:x.x,y:Math.max(0,x.y-1)}));else if(h.downArrow||w==="j")n(x=>({x:x.x,y:Math.min(I-1,x.y+1)}));else if(h.leftArrow||w==="h")n(x=>({x:Math.max(0,x.x-1),y:x.y}));else if(h.rightArrow||w==="l")n(x=>({x:Math.min(I-1,x.x+1),y:x.y}));else if(w==="[")d(x=>(x-1+qe.length)%qe.length);else if(w==="]")d(x=>(x+1)%qe.length);else if(w>="1"&&w<="6")d(parseInt(w)-1);else if(w==="e"){let x=Oo(o.keep,r,u);x.ok&&x.keep?(s(_=>({..._,keep:x.keep})),R(`Placed ${Je[u]}`)):R(`!${x.reason}`)}else if(w==="u"){let x=Uo(o.keep,r);x.ok&&x.keep?(s(_=>({..._,keep:x.keep})),R("Upgraded!")):R(`!${x.reason}`)}else if(w==="x"){let x=Go(o.keep,r);x.ok&&x.keep?(s(_=>({..._,keep:x.keep})),R("Demolished")):R(`!${x.reason}`)}else if(w==="r"){let x=An(o);s(x),l("result"),x.alive?R(`Wave ${x.wave} cleared! +${x.score-o.score} pts`):R(`Breached on wave ${x.wave}! Final score: ${x.score}`)}});let i=o.keep.resources,y=o.keep.grid;return Ge(ro,{flexDirection:"column",paddingX:1,children:[Ge(ro,{flexDirection:"row",gap:1,children:[Be(pe,{bold:!0,color:"magenta",children:"\u2605 Daily Challenge"}),Be(pe,{dimColor:!0,children:"\u2502"}),Ge(pe,{children:["Wave: ",Be(pe,{bold:!0,children:o.wave})]}),Be(pe,{dimColor:!0,children:"\u2502"}),Ge(pe,{children:["Score: ",Be(pe,{bold:!0,color:"yellow",children:o.score})]}),Be(pe,{dimColor:!0,children:"\u2502"}),Ge(pe,{color:"yellow",children:[W.gold,i.gold]}),Ge(pe,{color:"green",children:[W.wood,i.wood]}),Ge(pe,{color:"white",children:[W.stone,i.stone]})]}),Be(pe,{color:T.startsWith("!")?"red":"yellow",children:T}),Ge(ro,{marginTop:1,children:[Be(ro,{flexDirection:"column",children:Array.from({length:I},(w,h)=>Be(pe,{children:Array.from({length:I},(x,_)=>{let j=r.x===_&&r.y===h,K=y.structures.find(U=>U.pos.x===_&&U.pos.y===h),N=K?ye[K.kind]:yt,$=K&&K.level>1?String(K.level):" ";if(j)return Ge(pe,{backgroundColor:"white",color:"black",bold:!0,children:[N,$]},_);if(K){let U=K.kind==="treasury"?"yellow":K.kind==="wall"?"white":K.kind==="trap"?"magenta":K.kind==="archerTower"?"redBright":K.kind==="ward"?"cyan":"green";return Ge(pe,{color:U,bold:K.level>=2,children:[N,$]},_)}return Ge(pe,{dimColor:!0,children:[N," "]},_)})},h))}),Ge(ro,{flexDirection:"column",marginLeft:2,width:24,children:[Ge(pe,{children:["Sel: ",Be(pe,{bold:!0,children:Je[u]})]}),Be(pe,{dimColor:!0,children:"e place u upgrade x demo"}),Be(pe,{dimColor:!0,children:"[ ] cycle 1-6 select"}),Be(pe,{dimColor:!0,children:"r start wave"}),Be(pe,{dimColor:!0,children:"Esc back to menu"}),g==="result"&&o.alive&&Be(pe,{color:"green",bold:!0,children:"Press Enter to continue"}),g==="result"&&!o.alive&&Ge(ro,{flexDirection:"column",marginTop:1,children:[Be(pe,{color:"red",bold:!0,children:"GAME OVER"}),Ge(pe,{children:["Waves: ",o.wave," \u2502 Score: ",o.score]}),Ge(pe,{dimColor:!0,children:["Proof: #",Mn(o)]}),Be(pe,{dimColor:!0,children:"Press Enter to exit"})]})]})]})]})}import{useState as Pi}from"react";import{Box as qr,Text as Vt,useInput as Di}from"ink";import{jsx as so,jsxs as or}from"react/jsx-runtime";function In({options:e,anomalyNames:t,onClaim:o,onDismiss:s}){let[r,n]=Pi(0);return Di((c,d)=>{d.leftArrow||c==="h"?n(g=>Math.max(0,g-1)):d.rightArrow||c==="l"?n(g=>Math.min(e.length-1,g+1)):d.return||c===" "?o(e[r].id):(d.escape||c==="q")&&s()}),or(qr,{flexDirection:"column",borderStyle:"round",borderColor:"yellow",paddingX:2,paddingY:1,children:[so(Vt,{bold:!0,color:"yellow",children:"\u2605 Victory! Choose your reward \u2605"}),t&&t.length>0&&or(Vt,{dimColor:!0,children:["Anomalies faced: ",t.join(", ")]}),so(Vt,{children:" "}),so(qr,{flexDirection:"row",gap:2,children:e.map((c,d)=>or(qr,{flexDirection:"column",borderStyle:d===r?"bold":"single",borderColor:d===r?"yellow":"gray",paddingX:2,paddingY:1,width:26,children:[or(Vt,{bold:!0,color:d===r?"yellow":"white",children:[c.icon," ",c.name]}),so(Vt,{dimColor:d!==r,children:c.description}),d===r&&so(Vt,{color:"green",children:"\u25B2 [Enter] Claim"})]},c.id))}),so(Vt,{dimColor:!0,children:"\u2190 \u2192 to browse | Enter to claim | Esc to skip"})]})}import{useState as Li}from"react";import{Box as rr,Text as de,useInput as $i}from"ink";import{Fragment as Bi,jsx as _e,jsxs as Ne}from"react/jsx-runtime";function Pn({gameSave:e,eligible:t,reason:o,onPrestige:s,onBack:r}){let[n,c]=Li(!1),d=e.prestige?.ascensionLevel??0,g=d+1,l=e.prestige,T=Xt.find(R=>R.ascensionLevel===g);return $i((R,u)=>{u.escape||R==="q"?n?c(!1):r():R==="y"&&n&&t?s():u.return&&t&&!n&&c(!0)}),Ne(rr,{flexDirection:"column",padding:2,children:[_e(de,{bold:!0,color:"magenta",children:"\u2605 PRESTIGE / ASCENSION \u2605"}),_e(de,{children:" "}),Ne(de,{bold:!0,children:["Current Ascension: ",Ne(de,{color:"yellow",children:["Level ",d]})]}),l&&Ne(Bi,{children:[Ne(de,{dimColor:!0,children:["Lifetime raids won: ",l.lifetimeRaidsWon+e.progression.totalRaidsWon]}),Ne(de,{dimColor:!0,children:["Lifetime best streak: ",Math.max(l.lifetimeBestStreak,e.progression.bestWinStreak)]})]}),_e(de,{children:" "}),_e(de,{bold:!0,children:"Permanent Unlocks:"}),Xt.map(R=>{let u=R.ascensionLevel<=d,i=R.ascensionLevel===g;return Ne(de,{color:u?"green":i?"yellow":"gray",children:[u?" \u2713 ":i?" \u2192 ":" \xB7 ",Ne(de,{bold:u||i,children:["Lv.",R.ascensionLevel," ",R.name]}),Ne(de,{dimColor:!u&&!i,children:[" \u2014 ",R.description]})]},R.id)}),_e(de,{children:" "}),!t&&Ne(de,{color:"red",children:["Cannot prestige: ",o]}),t&&!n&&Ne(rr,{flexDirection:"column",children:[Ne(de,{color:"yellow",bold:!0,children:["Ready to ascend to Level ",g,"!"]}),T&&Ne(de,{color:"green",children:["New unlock: ",T.name," \u2014 ",T.description]}),_e(de,{children:" "}),_e(de,{bold:!0,color:"red",children:"WARNING: This resets your keep, structures, and raid history."}),_e(de,{bold:!0,color:"red",children:"Achievements and prestige unlocks are permanent."}),_e(de,{children:" "}),_e(de,{dimColor:!0,children:"Press Enter to begin ascension, Esc to go back"})]}),t&&n&&Ne(rr,{flexDirection:"column",children:[_e(de,{bold:!0,color:"red",children:"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"}),_e(de,{bold:!0,color:"red",children:"\u2551 ARE YOU SURE? This cannot be undone \u2551"}),_e(de,{bold:!0,color:"red",children:"\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"}),_e(de,{children:" "}),Ne(de,{children:["Press ",_e(de,{bold:!0,color:"yellow",children:"Y"})," to confirm ascension"]}),Ne(de,{children:["Press ",_e(de,{bold:!0,children:"Esc"})," to cancel"]})]}),!t&&!n&&_e(rr,{marginTop:1,children:Ne(de,{dimColor:!0,children:["Requirement: ",Zt," raid wins"," ","(",e.progression.totalRaidsWon,"/",Zt,")"]})}),_e(de,{children:" "}),_e(de,{dimColor:!0,children:"Press Esc to return to menu"})]})}import{useState as st,useEffect as no,useCallback as ce,useRef as St}from"react";import{useEffect as Ui,useRef as Ln,useCallback as Gi}from"react";import{existsSync as $n,statSync as Bn,openSync as Wi,readSync as Ki,closeSync as Fi,watch as Hi}from"fs";import{existsSync as uu,mkdirSync as pu,readFileSync as fu,writeFileSync as mu,unlinkSync as gu}from"fs";import{join as Dn}from"path";import{homedir as Ni}from"os";var Oi=Dn(Ni(),".config","codekeep"),jt=Dn(Oi,"events.jsonl");var Yi=2e3;function Nn(e){let t=Ln(0),o=Ln(e);o.current=e;let s=Gi(()=>{if(!$n(jt))return;let r;try{r=Bn(jt).size}catch{return}if(r<t.current&&(t.current=0),r<=t.current)return;let n,c;try{let g=Buffer.alloc(r-t.current);c=Wi(jt,"r"),Ki(c,g,0,g.length,t.current),n=g.toString("utf-8")}catch{return}finally{c!==void 0&&Fi(c)}t.current=r;let d=n.split(`
26
+ `).filter(Boolean);for(let g of d)try{let l=JSON.parse(g);o.current(l)}catch{}},[]);Ui(()=>{if($n(jt))try{t.current=Bn(jt).size}catch{t.current=0}let r=null;try{r=Hi(jt,()=>s())}catch{}let n=setInterval(s,Yi);return()=>{clearInterval(n),r?.close()}},[s])}function sr(e){let{gameSave:t,replay:o,raidType:s,seed:r,difficulty:n,probeCount:c,attackerId:d,defenderKeepId:g,defenderGrid:l}=e,T=o.events[o.events.length-1];if(T?.type!=="raid_end")return null;let R=s==="defend",u=R?T.outcome==="defense_win":T.outcome!=="defense_win",i=o.events.filter(P=>P.type==="treasury_breach").reduce((P,Y)=>({gold:P.gold+Y.lootTaken.gold,wood:P.wood+Y.lootTaken.wood,stone:P.stone+Y.lootTaken.stone}),{gold:0,wood:0,stone:0}),y=o.events.filter(P=>P.type==="raider_destroyed").length,w=o.events.filter(P=>P.type==="wall_damaged"&&P.destroyed).length,h=o.events.filter(P=>P.type==="arrow_hit"&&P.hpRemaining<=0).length,x=(R?t.keep.grid:l??t.keep.grid).structures.filter(P=>P.kind==="archerTower").length,_=c>0?y/c:0,j,K,N;R?(N=i,K=u?{gold:10+n*3,wood:5+n*2,stone:5+n*2}:{gold:Math.floor(_*n*2),wood:Math.floor(_*n),stone:Math.floor(_*n)},j=K):(N={gold:0,wood:0,stone:0},K=u?i:{gold:0,wood:0,stone:0},j={gold:0,wood:0,stone:0});let $=R?{gold:Math.max(0,t.keep.resources.gold-N.gold),wood:Math.max(0,t.keep.resources.wood-N.wood),stone:Math.max(0,t.keep.resources.stone-N.stone)}:t.keep.resources,U=nt(He($,K)),k=u?t.progression.currentWinStreak+1:0,b={id:r,seed:r,rulesVersion:1,attackerId:d,defenderKeepId:g,startedAtUnixMs:Date.now(),resolvedAtUnixMs:Date.now(),outcome:T.outcome,lootLost:N,lootGained:K,replay:o,...l?{defenderGrid:l}:{}},L={...t,keep:{...t.keep,resources:U},raidHistory:[...t.raidHistory.slice(-19),b],progression:{...t.progression,totalRaidsWon:t.progression.totalRaidsWon+(u?1:0),totalRaidsLost:t.progression.totalRaidsLost+(u?0:1),currentWinStreak:k,bestWinStreak:Math.max(t.progression.bestWinStreak,k),totalRaidersKilledByArcher:t.progression.totalRaidersKilledByArcher+h}},m={won:u,raidType:s,outcome:T.outcome,lootGained:K,lootLost:N,raidersKilled:y,raidersTotal:o.events.filter(P=>P.type==="raider_spawn").length,wallsDestroyed:w,archersActive:x,difficulty:n};return{updatedSave:L,raidRecord:b,summary:m,defenseBonus:j,lootLost:N,lootGained:K,won:u,archerKills:h}}var On=5e3,zr=6e4;function Vi(e,t){if(e.keep.grid.structures.length<3)return{save:e,results:[]};let o=Math.min(Math.floor(t/io),cs);if(o===0)return{save:e,results:[]};let s=[],r=e;for(let n=0;n<o;n++){let c=r.progression.totalRaidsWon+r.progression.totalRaidsLost,d=Dt(c),g=`bg-${r.lastPlayedAtUnixMs}-${n}`,l=3+d,T=at(r.lastPlayedAtUnixMs+n),R=Lt(l,d,T),u=ut({probeCount:l,keepGrid:r.keep.grid,seed:g,probeTypes:R}),i=u.events[u.events.length-1];if(i?.type!=="raid_end")continue;let y=i.outcome==="defense_win",w=u.events.filter(k=>k.type==="treasury_breach").reduce((k,b)=>({gold:k.gold+b.lootTaken.gold,wood:k.wood+b.lootTaken.wood,stone:k.stone+b.lootTaken.stone}),{gold:0,wood:0,stone:0}),h=u.events.filter(k=>k.type==="arrow_hit"&&k.hpRemaining<=0).length,x=u.events.filter(k=>k.type==="raider_destroyed").length,_=l>0?x/l:0,j=y?{gold:10+d*3,wood:5+d*2,stone:5+d*2}:{gold:Math.floor(_*d*2),wood:Math.floor(_*d),stone:Math.floor(_*d)},K={gold:Math.max(0,r.keep.resources.gold-w.gold),wood:Math.max(0,r.keep.resources.wood-w.wood),stone:Math.max(0,r.keep.resources.stone-w.stone)},N=nt(He(K,j)),$=y?r.progression.currentWinStreak+1:0,U={id:g,seed:g,rulesVersion:1,attackerId:"npc-bg",defenderKeepId:r.keep.id,startedAtUnixMs:r.lastPlayedAtUnixMs+n*io,resolvedAtUnixMs:r.lastPlayedAtUnixMs+(n+1)*io,outcome:i.outcome,lootLost:w,lootGained:j,replay:u};r={...r,keep:{...r.keep,resources:N},raidHistory:[...r.raidHistory.slice(-19),U],progression:{...r.progression,totalRaidsWon:r.progression.totalRaidsWon+(y?1:0),totalRaidsLost:r.progression.totalRaidsLost+(y?0:1),currentWinStreak:$,bestWinStreak:Math.max(r.progression.bestWinStreak,$),totalRaidersKilledByArcher:r.progression.totalRaidersKilledByArcher+h}},s.push({won:y,lootLost:w,defenseBonus:j,difficulty:d})}return{save:r,results:s}}function Un(e,t){let[o,s]=st(null),[r,n]=st({x:8,y:8}),[c,d]=st(0),[g,l]=st(""),[T,R]=st(null),[u,i]=st(null),[y,w]=st(null),h=St({time:Date.now(),raidsWon:0,raidsLost:0,structures:0,resources:{gold:0,wood:0,stone:0},achievements:0}),[x,_]=st(null),[j,K]=st(null),[N,$]=st([]),U=St(null),k=St(0),b=St(0),L=St(null),m=St(null),P=St(null),Y=St(null),se=St(null),[v,oe]=st(1),fe=St([]),[be,me]=st([]),[Te,Ve]=st(null),C=ce(()=>{let f=Date.now();fe.current.push(f);let S=f-1800*1e3;fe.current=fe.current.filter(V=>V>S);let A=fe.current.length;A>=6?oe(2):A>=3?oe(1.5):A>=1?oe(1.2):oe(1)},[]);no(()=>{let f=setInterval(()=>{let A=Date.now()-1800*1e3;fe.current=fe.current.filter(X=>X>A);let V=fe.current.length;V>=6?oe(2):V>=3?oe(1.5):V>=1?oe(1.2):oe(1)},6e4);return()=>clearInterval(f)},[]);let B=qe[c];Nn(f=>{C(),s(S=>{if(!S)return S;let A=_r(S.keep,f),V={...S,keep:A,lastPlayedAtUnixMs:Date.now()};return t||Pt(V),V})}),no(()=>{let f=Jt();f||(f=Ks(process.env.USER||process.env.USERNAME||"Keeper")),f=Xs(f),f.lastPlayedAtUnixMs||(f={...f,lastPlayedAtUnixMs:f.savedAtUnixMs||Date.now()});let S=Date.now()-f.lastPlayedAtUnixMs,A={gold:0,wood:0,stone:0},V=[];if(S>zr&&f.keep.grid.structures.length>0&&(A=Ir(f.keep.grid,S),(A.gold>0||A.wood>0||A.stone>0)&&(f={...f,keep:{...f.keep,resources:nt(He(f.keep.resources,A))}})),S>io){let Ae=Vi(f,S);f=Ae.save,V=Ae.results}let X=Or(f);if(X.length>0){f={...f,progression:{...f.progression,achievements:[...f.progression.achievements,...X]}};for(let Ae of X){let Ze=Nr(Ae);Ze&&(f={...f,keep:{...f.keep,resources:He(f.keep.resources,Ze)}})}}(A.gold>0||A.wood>0||A.stone>0||V.length>0||X.length>0)&&K({resources:A,raids:V,newAchievements:X}),f={...f,lastPlayedAtUnixMs:Date.now()},e&&(f={...f,tutorialCompleted:!1}),h.current={time:Date.now(),raidsWon:f.progression.totalRaidsWon,raidsLost:f.progression.totalRaidsLost,structures:f.keep.grid.structures.length,resources:{...f.keep.resources},achievements:f.progression.achievements.length},s(f),t||Pt(f)},[]),no(()=>(L.current=setInterval(()=>{s(f=>{if(!f||f.keep.grid.structures.length===0)return f;let S=Ir(f.keep.grid,zr);if(Ko(f,"passive_income_boost")&&(S={gold:Math.floor(S.gold*1.5),wood:Math.floor(S.wood*1.5),stone:Math.floor(S.stone*1.5)}),S.gold===0&&S.wood===0&&S.stone===0)return f;let A={...f,keep:{...f.keep,resources:nt(He(f.keep.resources,S))},lastPlayedAtUnixMs:Date.now()};return t||Pt(A),A})},zr),()=>{L.current&&clearInterval(L.current)}),[t]),no(()=>(m.current=setInterval(()=>{$(f=>{if(!o)return f;let S=at(Date.now()),A=Os(f,Date.now());return Ns(A,o.keep.grid,Date.now(),S)})},ps),()=>{m.current&&clearInterval(m.current)}),[o]),no(()=>{let f=Y.current;if(!f||!o)return;Y.current=null;let S=Dr(N,f,o.keep.grid);if(!S)return;$(S.updatedFragments);let A=S.yield,V={...o,keep:{...o.keep,resources:nt(He(o.keep.resources,A))}};E(V);let X=[];A.gold>0&&X.push(`+${A.gold}${W.gold}`),A.wood>0&&X.push(`+${A.wood}${W.wood}`),A.stone>0&&X.push(`+${A.stone}${W.stone}`);let ke=S.collected[0]?.type.replace("_"," ")??"fragment",Ae=S.collected.length>1?` (${S.collected.length}x)`:"";F(`${X.join(" ")} ${ke}${Ae}`)},[r]),no(()=>()=>{U.current&&clearTimeout(U.current)},[]);let E=ce(f=>{let S=Or(f),A={...f,lastPlayedAtUnixMs:Date.now()};if(S.length>0){A={...A,progression:{...A.progression,achievements:[...A.progression.achievements,...S]}};for(let V of S){let X=Nr(V);X&&(A={...A,keep:{...A.keep,resources:He(A.keep.resources,X)}})}}if(s(A),t||Pt(A),S.length>0){let V=S.map(X=>lo.find(ke=>ke.id===X)?.name||X);F(`\u{1F3C6} ${V.join(", ")}!`)}},[t]),F=ce(f=>{U.current&&clearTimeout(U.current),l(f),U.current=setTimeout(()=>{l(""),U.current=null},3e3)},[]),D=ce((f,S)=>{n(A=>{let V={x:Math.max(0,Math.min(I-1,A.x+f)),y:Math.max(0,Math.min(I-1,A.y+S))};return Y.current=V,V})},[]),q=ce(f=>{d(S=>{let A=S+f;return A<0?qe.length-1:A>=qe.length?0:A})},[]),H=ce(f=>{f>=0&&f<qe.length&&d(f)},[]),Z=ce(f=>{se.current&&clearTimeout(se.current.timer);let S=setTimeout(()=>{se.current=null},1e4);se.current={save:f,timer:S}},[]),Ee=ce(()=>{if(!o)return;let f=Ko(o,"structures_lv2")?2:void 0,S=Oo(o.keep,r,B,f?{startingLevel:f}:void 0);if(S.ok&&S.keep){Z(o);let A={...o,keep:S.keep,progression:{...o.progression,totalStructuresPlaced:o.progression.totalStructuresPlaced+1}};E(A),F(`Placed ${B} [z undo]`)}else F(`!${S.reason}`)},[o,r,B,E,F,Z]),Tt=ce(()=>{if(!o)return;let f=Uo(o.keep,r);f.ok&&f.keep?(Z(o),E({...o,keep:f.keep}),F("Upgraded! [z undo]")):F(`!${f.reason}`)},[o,r,E,F,Z]),ar=ce(()=>{if(!o)return;let f=Go(o.keep,r);f.ok&&f.keep?(Z(o),E({...o,keep:f.keep}),F("Demolished (50% refund) [z undo]")):F(`!${f.reason}`)},[o,r,E,F]),ge=ce((f,S)=>{let A=Js(f,S),V=o?.activeBuffs??[],X=Qs(A,V);return me(A),{anomalies:A,modifiers:X}},[o]),_t=ce(f=>{let S=f.activeBuffs??[];return S.length===0?f:{...f,activeBuffs:en(S)}},[]),yo=ce(()=>{if(!o)return;let f=o.progression.totalRaidsWon+o.progression.totalRaidsLost,S=Dt(f),A=`attack-${Date.now()}-${Math.random()}`,V=Fo(A,S),X=3+S,ke=at(Date.now()),{anomalies:Ae,modifiers:Ze}=ge(S,ke),lt=Ze.bruteChanceMult??1,Oe=Lt(X,S,ke,lt),dt=ut({probeCount:X,keepGrid:V.grid,seed:A,probeTypes:Oe,modifiers:Ze});R(dt),i(V.grid),w("attack");let Ke=sr({gameSave:o,replay:dt,raidType:"attack",seed:A,difficulty:S,probeCount:X,attackerId:o.player.id,defenderKeepId:V.id,defenderGrid:V.grid});if(Ke){_(Ke.summary);let Nt=_t(Ke.updatedSave);if(Ke.won){let vo=at(Date.now()+1);Ve(Yo(S,vo))}E(Nt)}},[o,E,ge,_t]),ir=ce(()=>{if(!o)return;let f=o.progression.totalRaidsWon+o.progression.totalRaidsLost,S=Dt(f),A=`defend-${Date.now()}-${Math.random()}`,V=3+S,X=at(Date.now()),{anomalies:ke,modifiers:Ae}=ge(S,X),Ze=Ae.bruteChanceMult??1,lt=Lt(V,S,X,Ze),Oe=ut({probeCount:V,keepGrid:o.keep.grid,seed:A,probeTypes:lt,modifiers:Ae});R(Oe),i(o.keep.grid),w("defend");let dt=sr({gameSave:o,replay:Oe,raidType:"defend",seed:A,difficulty:S,probeCount:V,attackerId:"npc",defenderKeepId:o.keep.id});if(dt){_(dt.summary);let Ke=_t(dt.updatedSave);if(dt.won){let Nt=at(Date.now()+1);Ve(Yo(S,Nt))}E(Ke)}},[o,E,ge,_t]),wo=ce(()=>{if(!o)return;let f=o.progression.totalRaidsWon+o.progression.totalRaidsLost,S=Dt(f),A=`quick-${Date.now()}-${Math.random()}`,V=3+S,X=at(Date.now()),{modifiers:ke}=ge(S,X),Ae=ke.bruteChanceMult??1,Ze=Lt(V,S,X,Ae),lt=ut({probeCount:V,keepGrid:o.keep.grid,seed:A,probeTypes:Ze,modifiers:ke}),Oe=sr({gameSave:o,replay:lt,raidType:"defend",seed:A,difficulty:S,probeCount:V,attackerId:"npc",defenderKeepId:o.keep.id});if(Oe){let dt=_t(Oe.updatedSave);if(E(dt),P.current={replay:lt,grid:o.keep.grid,summary:Oe.summary},Oe.won){let Ke=Oe.lootGained,Nt=at(Date.now()+1);Ve(Yo(S,Nt)),F(`Defense WIN! +${Ke.gold}${W.gold} +${Ke.wood}${W.wood} +${Ke.stone}${W.stone} [v] view`)}else{let Ke=Oe.lootLost.gold+Oe.lootLost.wood+Oe.lootLost.stone;F(`Defense BREACH! Lost ${Ke} res (+${Oe.lootGained.gold}${W.gold} salvage) [v] view`)}}},[o,E,F,ge,_t]),Ro=ce(()=>{let f=P.current;return f?(R(f.replay),i(f.grid),w("defend"),_(f.summary),P.current=null,!0):!1},[]),So=ce(()=>{if(!o)return;let f=Dr(N,r,o.keep.grid);if(!f)return;$(f.updatedFragments);let S=f.yield,A={...o,keep:{...o.keep,resources:nt(He(o.keep.resources,S))}};E(A);let V=[];S.gold>0&&V.push(`+${S.gold}${W.gold}`),S.wood>0&&V.push(`+${S.wood}${W.wood}`),S.stone>0&&V.push(`+${S.stone}${W.stone}`);let X=f.collected[0]?.type.replace("_"," ")??"fragment",ke=f.collected.length>1?` (${f.collected.length}x)`:"";F(`${V.join(" ")} ${X}${ke}`)},[o,N,r,E,F]),lr=ce(f=>{if(!o)return!1;let S=f.attackerId!==o.player.id;return R(f.replay),i(S?o.keep.grid:f.defenderGrid??o.keep.grid),w(S?"defend":"attack"),_(null),!0},[o]),dr=ce(()=>{R(null),i(null),w(null),_(null)},[]),We=ce(()=>{o&&E({...o,tutorialCompleted:!0})},[o,E]),cr=ce(()=>{if(!o)return;let f=Date.now(),S=f-k.current;if(S<On){let lt=Math.ceil((On-S)/1e3);F(`Cooldown: ${lt}s remaining`);return}k.current=f,b.current++,C();let A=Ds(),V=Ko(o,"extra_faucet")?3:0,X=tn({...A.grants},Math.max(0,b.current-V)),ke=_r(o.keep,{...A,grants:X});E({...o,keep:ke});let Ae=zt+V,Ze=b.current>Ae?" (diminished)":"";F(`+${X.gold}${W.gold} +${X.wood}${W.wood} +${X.stone}${W.stone} (${ds[A.type]??A.type})${Ze}`)},[o,E,F]),qt=ce((f,S)=>{f>=0&&f<I&&S>=0&&S<I&&n({x:f,y:S})},[]),bo=ce(f=>{if(!o||o.keep.grid.structures.length===0)return;let S=o.keep.grid.structures,A=`${r.x},${r.y}`,V=S.findIndex(Ae=>`${Ae.pos.x},${Ae.pos.y}`===A),X=V===-1?0:V+f;X<0&&(X=S.length-1),X>=S.length&&(X=0);let ke=S[X];n({x:ke.pos.x,y:ke.pos.y})},[o,r]),ur=ce(()=>{if(!se.current){F("!Nothing to undo");return}let f=se.current.save;clearTimeout(se.current.timer),se.current=null,E(f),F("Undone!")},[E,F]),pr=ce((f,S,A)=>{o&&E({...o,progression:{...o.progression,dailyChallenges:{...o.progression.dailyChallenges,[f]:{wavesCleared:S,score:A}}}})},[o,E]),fr=ce(()=>{K(null)},[]),mr=ce(f=>{t||Pt(f),s(f),b.current=0},[t]),gr=ce(f=>{if(!o||!Te)return;let S=Te.find(V=>V.id===f);if(!S)return;let A={...o};if(S.type==="resources"&&S.resources)A={...A,keep:{...A.keep,resources:nt(He(A.keep.resources,S.resources))}},F(`Claimed ${S.name}!`);else if(S.type==="buff"&&S.buff){let V=A.activeBuffs??[];A={...A,activeBuffs:[...V,{...S.buff}]},F(`${S.buff.name} active for ${S.buff.raidsRemaining} raids!`)}Ve(null),E(A)},[o,Te,E,F]),hr=ce(()=>{Ve(null)},[]),xr=o?.keep.grid.structures.find(f=>f.pos.x===r.x&&f.pos.y===r.y)??null,ko=o?Pr(o.keep.grid):[],Tr=new Set(ko.flatMap(f=>f.affectedStructureIds)),yr=o?(()=>{let f=o.progression.totalRaidsWon+o.progression.totalRaidsLost,S=o.keep.grid.structures.filter(V=>V.kind==="watchtower").length,A=Zs(o.keep.id,f,S);return S>=2?A.detailed:A.vague})():void 0;return{gameSave:o,cursor:r,selectedStructure:B,structureAtCursor:xr,message:g,fragments:N,raidReplay:T,raidGrid:u,raidType:y,raidSummary:x,offlineReport:j,moveCursor:D,cycleStructure:q,selectStructure:H,placeAtCursor:Ee,upgradeAtCursor:Tt,demolishAtCursor:ar,undoLastAction:ur,collectAtCursor:So,startAttackRaid:yo,startDefendRaid:ir,quickDefend:wo,watchLastRaid:Ro,watchRaidRecord:lr,clearRaid:dr,completeTutorial:We,grantSimResources:cr,jumpToCoord:qt,jumpToNextStructure:bo,clearOfflineReport:fr,saveDailyChallengeScore:pr,showMessage:F,siegeForecast:yr,flowMultiplier:v,activeSynergies:ko,synergyStructureIds:Tr,raidAnomalies:be,pendingRewards:Te,claimReward:gr,dismissRewards:hr,applyExternalSave:mr,getSessionStats:()=>{if(!o)return null;let f=h.current;return{startedAt:f.time,raidsWon:o.progression.totalRaidsWon-f.raidsWon,raidsLost:o.progression.totalRaidsLost-f.raidsLost,structuresBuilt:o.keep.grid.structures.length-f.structures,resourcesEarned:{gold:Math.max(0,o.keep.resources.gold-f.resources.gold),wood:Math.max(0,o.keep.resources.wood-f.resources.wood),stone:Math.max(0,o.keep.resources.stone-f.resources.stone)},achievementsUnlocked:o.progression.achievements.length-f.achievements}}}}function Gn(e){let t=e.keep.grid,o=e.progression,s=e.keep.resources,r="\u250C"+"\u2500".repeat(I+2)+"\u2510",n="\u2514"+"\u2500".repeat(I+2)+"\u2518",c=[];c.push(r);for(let i=0;i<I;i++){let y="\u2502 ";for(let w=0;w<I;w++){let h=t.structures.find(x=>x.pos.x===w&&x.pos.y===i);if(h){let x=ye[h.kind]??"?";y+=h.level===3?x.toUpperCase():x}else y+=yt}y+=" \u2502",c.push(y)}c.push(n);let d=e.player.displayName||"Anonymous",g=Math.max(1,Math.floor((Date.now()-e.keep.createdAtUnixMs)/864e5)),l=o.totalRaidsWon+o.totalRaidsLost,T=l>0?Math.round(o.totalRaidsWon/l*100):0;c.push(` ${d}'s Keep \u2014 Day ${g}`),c.push(` ${s.gold}g ${s.wood}w ${s.stone}s \u2502 ${t.structures.length} structures`),c.push(` ${o.totalRaidsWon}W-${o.totalRaidsLost}L (${T}%) \u2502 Best streak: ${o.bestWinStreak}`);let R=`${e.keep.id}:${l}:${t.structures.length}:${s.gold}`,u=Math.abs(It(R)).toString(36).slice(0,6);return c.push(` #${u}`),c.join(`
27
+ `)}import{exec as Zi}from"child_process";var nr=class{mode="online";baseUrl;auth=null;constructor(t){this.baseUrl=t.replace(/\/$/,"")}async request(t,o={}){let s={"Content-Type":"application/json",...o.headers??{}};this.auth&&(s.Authorization=`Bearer ${this.auth.token}`);let r=await fetch(`${this.baseUrl}${t}`,{...o,headers:s});if(!r.ok){let n=await r.json().catch(()=>({error:r.statusText}));throw new Error(n.error??`HTTP ${r.status}`)}return r.json()}isAuthenticated(){return this.auth!==null}async register(t){let o=await this.request("/auth/register",{method:"POST",body:JSON.stringify({displayName:t})});return this.auth={token:o.token,apiKey:o.apiKey,playerId:o.playerId},o}async login(t){let o=await this.request("/auth/login",{method:"POST",body:JSON.stringify({apiKey:t})});return this.auth={token:o.token,apiKey:t,playerId:o.playerId},o}async load(){if(!this.auth)return null;try{let t=await this.request("/me");return t.keep?{schemaVersion:1,savedAtUnixMs:Date.now(),player:{id:t.player.id,displayName:t.player.displayName,settings:{asciiMode:!1}},keep:{id:t.keep.id,name:t.keep.name,ownerPlayerId:t.player.id,grid:t.keep.grid,resources:t.keep.resources,createdAtUnixMs:t.player.createdAt,updatedAtUnixMs:Date.now()},raidHistory:[],tutorialCompleted:!0,lastPlayedAtUnixMs:Date.now(),progression:{totalBuildsToday:0,totalCommitsToday:0,lastDailyResetDay:Math.floor(Date.now()/864e5),totalRaidsWon:t.progression?.totalRaidsWon??0,totalRaidsLost:t.progression?.totalRaidsLost??0,totalStructuresPlaced:t.progression?.totalStructuresPlaced??0,currentWinStreak:t.progression?.currentWinStreak??0,bestWinStreak:t.progression?.bestWinStreak??0,achievements:t.progression?.achievements??[],totalRaidersKilledByArcher:0}}:null}catch{return null}}async save(t){this.auth&&await this.request("/keep/save",{method:"POST",body:JSON.stringify({grid:t.keep.grid,resources:t.keep.resources})})}async createNew(t){let o=await this.register(t),s=await this.load();return s||{schemaVersion:1,savedAtUnixMs:Date.now(),player:{id:o.playerId,displayName:t,settings:{asciiMode:!1}},keep:{id:`keep-${o.playerId}`,name:`${t}'s Keep`,ownerPlayerId:o.playerId,grid:{width:16,height:16,structures:[]},resources:{...kt},createdAtUnixMs:Date.now(),updatedAtUnixMs:Date.now()},raidHistory:[],tutorialCompleted:!1,lastPlayedAtUnixMs:Date.now(),progression:{totalBuildsToday:0,totalCommitsToday:0,lastDailyResetDay:Math.floor(Date.now()/864e5),totalRaidsWon:0,totalRaidsLost:0,totalStructuresPlaced:0,currentWinStreak:0,bestWinStreak:0,achievements:[],totalRaidersKilledByArcher:0}}}async deleteAll(){return!1}async findMatch(){return(await this.request("/matchmaking/find",{method:"POST"})).targets}async launchPvpRaid(t,o,s){return this.request("/raids/launch",{method:"POST",body:JSON.stringify({defenderPlayerId:t,probeTypes:o,spawnSpecs:s})})}async getIncomingRaids(t){return(await this.request(`/raids/incoming?since=${t}`)).raids}async getPvpProfile(){try{let t=await this.request("/me");return{trophies:t.player.trophies,league:t.player.league,shieldExpiresAt:t.player.shieldExpiresAt,seasonId:"S1",seasonPeakTrophies:t.player.trophies}}catch{return null}}async getLeaderboard(t=50){return(await this.request(`/leaderboard?limit=${t}`)).players}async getWarCamp(){try{return await this.request("/warcamp")}catch{return null}}async trainRaider(t,o){let s=await this.request("/warcamp/train",{method:"POST",body:JSON.stringify({slotId:t,raiderType:o})});return{slots:s.slots,maxSlots:s.maxSlots}}async getBounties(){try{return(await this.request("/bounties")).bounties}catch{return[]}}async claimBounty(t){return(await this.request(`/bounties/${t}/claim`,{method:"POST"})).reward}async registerForMatchmaking(){await this.request("/matchmaking/register",{method:"POST"})}async sync(){this.auth&&await this.registerForMatchmaking()}};import{jsx as te,jsxs as xe}from"react/jsx-runtime";var Kn=60,Fn=18;function Ji(){let{stdout:e}=Xi(),[t,o]=Ce({columns:e?.columns??process.stdout.columns??80,rows:e?.rows??process.stdout.rows??24});return ji(()=>{let s=e??process.stdout,r=()=>{o({columns:s.columns,rows:s.rows})};return s.on("resize",r),()=>{s.off("resize",r)}},[e]),t}function Qi({asciiMode:e,compact:t,forceTutorial:o,autoResume:s,serverUrl:r,dryRun:n}){let{exit:c}=qi(),{columns:d,rows:g}=Ji(),[l,T]=Ce(r?"auth":s?"keep":"menu"),[R,u]=Ce(e),[i,y]=Ce(!1),[w,h]=Ce(null),[x,_]=Ce(null),[j,K]=Ce(!1),[N,$]=Ce(""),[U,k]=Ce("keep"),b=Wn(1),L=Wn(r?new nr(r):null),[m,P]=Ce(!1),[Y,se]=Ce(null),[v,oe]=Ce([]),[fe,be]=Ce(!1),[me,Te]=Ce([]),[Ve,C]=Ce(!1),[B,E]=Ce({slots:[],maxSlots:3}),[F,D]=Ce(null),[q,H]=Ce(null),[Z,Ee]=Ce(!1),Tt=t||d<80||g<24,ar=d<Kn||g<Fn,{gameSave:ge,cursor:_t,selectedStructure:yo,message:ir,fragments:wo,raidReplay:Ro,raidGrid:So,raidType:lr,raidSummary:dr,offlineReport:We,structureAtCursor:cr,moveCursor:qt,cycleStructure:bo,selectStructure:ur,placeAtCursor:pr,upgradeAtCursor:fr,demolishAtCursor:mr,undoLastAction:gr,collectAtCursor:hr,startAttackRaid:xr,startDefendRaid:ko,quickDefend:Tr,watchLastRaid:yr,watchRaidRecord:f,clearRaid:S,completeTutorial:A,grantSimResources:V,jumpToCoord:X,jumpToNextStructure:ke,clearOfflineReport:Ae,saveDailyChallengeScore:Ze,showMessage:lt,siegeForecast:Oe,flowMultiplier:dt,activeSynergies:Ke,synergyStructureIds:Nt,raidAnomalies:vo,pendingRewards:wr,claimReward:Vn,dismissRewards:jn,applyExternalSave:qn,getSessionStats:Zr}=Un(o,n),[ct,zn]=Ce(null),Jr=ao(()=>{let M=Zr();M&&(M.raidsWon+M.raidsLost>0||M.structuresBuilt>0)?(zn(M),setTimeout(()=>c(),3e3)):c()},[c,Zr]),Xn=ao(()=>{Fs(),c()},[c]),Qr=ao(async(M,re)=>{let we=L.current;if(we){Ee(!0),H(null);try{M==="login"?await we.login(re):await we.register(re),P(!0),T("menu"),we.getPvpProfile?.().then(je=>se(je)),we.registerForMatchmaking?.()}catch(je){H(je instanceof Error?je.message:"Connection failed")}finally{Ee(!1)}}},[]),Zn=ao(async()=>{let M=L.current;if(M?.findMatch){be(!0);try{let re=await M.findMatch();oe(re)}catch{oe([])}finally{be(!1)}}},[]),Jn=ao(async(M,re,we)=>{let je=L.current;if(!(!je?.launchPvpRaid||!ge))try{let bt=await je.launchPvpRaid(M.playerId,re,we);f({replay:bt.replay,attackerId:ge.player.id,defenderKeepId:M.playerId,defenderGrid:M.grid})&&(k("pvp"),T("raid")),se(Rr=>Rr&&{...Rr,trophies:bt.newTrophies,league:bt.newLeague})}catch{}},[ge,f]),Qn=ao(async()=>{let M=L.current;if(M?.getLeaderboard){C(!0);try{let re=await M.getLeaderboard();Te(re)}catch{Te([])}finally{C(!1)}}},[]);if(zi((M,re)=>{if(ct){c();return}if(!(wr&&l==="keep")){if(i){y(!1);return}if(M==="?"){y(!0);return}if(j){if(re.escape){K(!1),$("");return}if(re.return){let we=N.split(/[, ]+/);if(we.length===2){let je=parseInt(we[0],16),bt=parseInt(we[1],16);!isNaN(je)&&!isNaN(bt)&&X(je,bt)}K(!1),$("");return}if(re.backspace||re.delete){$(we=>we.slice(0,-1));return}/^[0-9a-fA-F, ]$/.test(M)&&$(we=>we+M);return}if(We&&l==="keep"){(re.return||M===" ")&&Ae();return}if(l!=="menu"&&l!=="tutorial"){if(l==="raid"||l==="friendRaid"){(M==="q"||re.escape)&&(S(),h(null),_(null),T("keep"));return}if(!(l==="friendList"||l==="raidLog"||l==="settings"||l==="pvp"||l==="warcamp"||l==="leaderboard"||l==="auth"||l==="raidPlanner"||l==="dailyChallenge")){if(M==="q"){Jr();return}if(re.escape){T("menu");return}if(M==="h"||M==="a"||re.leftArrow)qt(-1,0);else if(M==="l"||M==="d"||re.rightArrow)qt(1,0);else if(M==="k"||M==="w"||re.upArrow)qt(0,-1);else if(M==="j"||M==="s"||re.downArrow)qt(0,1);else if(re.return||M==="e")pr();else if(M==="u")fr();else if(M==="x")mr();else if(M==="[")bo(-1);else if(M==="]")bo(1);else if(M==="f")V();else if(M==="c")hr();else if(M==="r")Tr();else if(M==="v")yr()&&T("raid");else if(M==="g")K(!0),$("");else if(M==="z")gr();else if(M==="p"||M==="P"){if(ge){let we=Gn(ge),je=process.platform==="darwin"?"pbcopy":process.platform==="win32"?"clip":"xclip -selection clipboard",bt=Zi(je,()=>{});bt.stdin?.write(we),bt.stdin?.end(),lt("Keep postcard copied to clipboard!")}}else re.tab?ke(1):M>="1"&&M<="6"&&ur(parseInt(M)-1)}}}}),ct){let M=Math.floor((Date.now()-ct.startedAt)/1e3),re=Math.floor(M/60),we=M%60;return xe(Mt,{flexDirection:"column",paddingX:2,paddingY:1,children:[te(ae,{bold:!0,color:"yellow",children:"\u25C6 Session Summary"}),xe(ae,{children:["Time played: ",xe(ae,{bold:!0,children:[re,"m ",we,"s"]})]}),xe(ae,{children:["Raids: ",xe(ae,{color:"green",bold:!0,children:[ct.raidsWon," won"]})," / ",xe(ae,{color:"red",bold:!0,children:[ct.raidsLost," lost"]})]}),xe(ae,{children:["Structures built: ",te(ae,{bold:!0,children:ct.structuresBuilt})]}),xe(ae,{children:["Resources earned: ",xe(ae,{color:"yellow",children:[W.gold,ct.resourcesEarned.gold]})," ",xe(ae,{color:"green",children:[W.wood,ct.resourcesEarned.wood]})," ",xe(ae,{color:"white",children:[W.stone,ct.resourcesEarned.stone]})]}),ct.achievementsUnlocked>0&&xe(ae,{color:"magenta",bold:!0,children:["Achievements unlocked: ",ct.achievementsUnlocked]}),te(ae,{dimColor:!0,children:"(press any key to exit)"})]})}if(!ge)return te(ae,{children:"Loading..."});if(ar)return xe(Mt,{flexDirection:"column",padding:1,children:[te(ae,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep"}),te(ae,{children:" "}),te(ae,{color:"red",children:"Terminal too small"}),xe(ae,{children:["Need ",xe(ae,{bold:!0,children:[Kn,"x",Fn]}),", got ",xe(ae,{bold:!0,children:[d,"x",g]})]}),te(ae,{children:" "}),te(ae,{dimColor:!0,children:"Resize your terminal or run with --compact"})]});if(i)return te(zs,{});if(l==="tutorial"||!ge.tutorialCompleted)return te(ln,{gameSave:ge,onComplete:()=>{A(),T("keep")}});if(l==="auth")return te(Sn,{error:q,isLoading:Z,onLogin:M=>Qr("login",M),onRegister:M=>Qr("register",M),onPlayOffline:()=>{P(!1),T("menu")}});if(l==="menu")return te(rn,{gameSave:ge,onlineMode:m,onKeep:()=>T("keep"),onAttack:()=>{xr(),T("raid")},onDefend:()=>{ko(),T("raid")},onPvp:()=>T("pvp"),onDailyChallenge:()=>T("dailyChallenge"),onPrestige:()=>T("prestige"),onFriendRaid:()=>T("friendList"),onRaidLog:()=>T("raidLog"),onSettings:()=>T("settings"),onQuit:Jr});if(l==="prestige"){let M=Us(ge);return te(Pn,{gameSave:ge,eligible:M.eligible,reason:M.reason,onPrestige:()=>{let re=Gs(ge);qn(re),lt("\u2605 Ascension complete! Your keep has been reborn."),T("menu")},onBack:()=>T("menu")})}return l==="raidLog"?te(fn,{gameSave:ge,onBack:()=>T("menu"),onWatchReplay:M=>{f(M)&&(k("raidLog"),T("raid"))}}):l==="settings"?te(hn,{onBack:()=>T("menu"),onResetGame:Xn,onReplayTutorial:()=>T("tutorial"),asciiMode:R,onToggleAscii:()=>u(M=>!M)}):l==="dailyChallenge"?te(_n,{onBack:()=>T("menu"),onSaveScore:Ze}):l==="pvp"?te(Tn,{pvpProfile:Y,targets:v,isSearching:fe,onSearch:Zn,onAttack:M=>{D(M),T("raidPlanner")},onWarCamp:()=>{L.current?.getWarCamp?.().then(re=>{re&&E(re)}),T("warcamp")},onLeaderboard:()=>{Qn(),T("leaderboard")},onBack:()=>T("menu")}):l==="raidPlanner"&&F?te(Cn,{targetName:F.displayName,targetTrophies:F.trophies,targetGrid:F.grid,warCamp:B,resources:ge.keep.resources,onLaunch:M=>{let re=M.map(we=>we.raiderType);Jn(F,re,M),D(null)},onBack:()=>{D(null),T("pvp")}}):l==="warcamp"?te(wn,{warCamp:B,resources:ge.keep.resources,onTrain:(M,re)=>{L.current?.trainRaider?.(M,re).then(je=>E(je))},onBack:()=>T("pvp")}):l==="leaderboard"?te(Rn,{entries:me,currentPlayerId:ge.player.id,isLoading:Ve,onBack:()=>T("pvp")}):l==="friendList"?te(un,{onSelectFriend:M=>{let re=`friend-raid-${Date.now()}`,we=ut({probeCount:4,keepGrid:M.grid,seed:re});h(we),_(M.grid),T("friendRaid")},onBack:()=>T("menu")}):l==="friendRaid"&&w&&x?xe(Mt,{flexDirection:"column",children:[te(ae,{bold:!0,color:"yellow",children:"[ LOCAL SIMULATION ]"}),te(Kr,{replay:w,keepGrid:x,raidType:"attack",initialSpeed:b.current,onSpeedChange:M=>{b.current=M},onDone:()=>{h(null),_(null),T("menu")}})]}):l==="raid"&&Ro&&So?te(Kr,{replay:Ro,keepGrid:So,raidType:lr||"defend",summary:dr||void 0,anomalies:vo,initialSpeed:b.current,onSpeedChange:M=>{b.current=M},onDone:()=>{S(),T(U),k("keep")}}):xe(Mt,{flexDirection:"column",children:[We&&xe(Mt,{flexDirection:"column",children:[(We.resources.gold>0||We.resources.wood>0||We.resources.stone>0)&&xe(ae,{color:"green",children:["Passive income: +",We.resources.gold,W.gold," +",We.resources.wood,W.wood," +",We.resources.stone,W.stone]}),We.raids.length>0&&xe(ae,{color:"yellow",children:["Background raids: ",We.raids.filter(M=>M.won).length,"W / ",We.raids.filter(M=>!M.won).length,"L"]}),We.newAchievements.length>0&&xe(ae,{color:"magenta",bold:!0,children:["New achievements: ",We.newAchievements.join(", ")]}),te(ae,{dimColor:!0,children:"(press any key to continue)"})]}),wr&&te(In,{options:wr,anomalyNames:vo.map(M=>`${M.icon} ${M.name}`),onClaim:Vn,onDismiss:jn}),te(qs,{resources:ge.keep.resources,selectedStructure:yo,message:j?`Jump to: ${N}_`:ir,compact:Tt,structureAtCursor:cr,fragmentCount:wo.length,dryRun:n,siegeForecast:Oe,flowMultiplier:dt,activeBuffs:ge.activeBuffs}),xe(Mt,{flexDirection:"row",children:[te(Vs,{grid:ge.keep.grid,cursor:_t,asciiMode:R,compact:Tt,fragments:wo,synergyStructureIds:Nt}),!Tt&&xe(Mt,{flexDirection:"column",marginLeft:2,width:28,children:[te(cn,{selected:yo}),Ke.length>0&&xe(Mt,{marginTop:1,flexDirection:"column",children:[te(ae,{bold:!0,color:"magenta",children:"Active Synergies:"}),[...new Set(Ke.map(M=>M.name))].map(M=>xe(ae,{color:"magenta",children:[" \u2605 ",M]},M))]}),te(Mt,{marginTop:1,children:te(ae,{dimColor:!0,children:`e place u upgrade x demo
28
+ z undo p postcard
31
29
  [ ] cycle 1-6 select
32
- c collect r raid v replay
33
- g jump Tab next f +res
34
- ?help Esc menu q quit`})})]})]}),Nt&&ae(Me,{dimColor:!0,children:"e/u/x build c collect r raid v replay f +res q quit"})]}):ae(Me,{children:"Loading..."})}function Gs(e){return ae(ko,{children:ae(Ba,{...e})})}import{jsx as Ga}from"react/jsx-runtime";var ar="0.2.2";globalThis.__CODEKEEP_VERSION=ar;var Ws=new Oa;Ws.name("codekeep").description("Async tower defense terminal game powered by your coding activity").version(ar).option("--ascii","Force ASCII-only rendering (no Unicode box drawing)").option("--compact","Compact layout for narrow terminals").option("--tutorial","Replay the tutorial").option("--resume","Skip menu, jump straight to keep").option("--no-save","Dry-run mode: play without writing to disk").option("--stats","Print save file stats as JSON (headless, no TUI)").option("--online <url>","Connect to a CodeKeep server for multiplayer").option("--server <url>","Alias for --online").action(e=>{if(e.stats){let f=Gt();f||(process.stdout.write(JSON.stringify({error:"No save file found"})+`
35
- `),process.exit(1));let d=f.progression,l={version:ar,player:f.player.displayName,keepAge:Math.max(1,Math.floor((Date.now()-f.keep.createdAtUnixMs)/864e5)),structures:f.keep.grid.structures.length,resources:f.keep.resources,raids:{won:d.totalRaidsWon,lost:d.totalRaidsLost,winStreak:d.currentWinStreak,bestStreak:d.bestWinStreak},achievements:d.achievements?.length??0,tutorialCompleted:f.tutorialCompleted,lastPlayed:new Date(f.lastPlayedAtUnixMs).toISOString()};process.stdout.write(JSON.stringify(l,null,2)+`
30
+ r raid v replay f +res
31
+ g jump Tab next ~ auto
32
+ ?help Esc menu q quit`})})]})]}),Tt&&te(ae,{dimColor:!0,children:"e/u/x build r raid v replay f +res ~ auto-collect q quit"})]})}function Hn(e){return te(Xo,{children:te(Qi,{...e})})}import{jsx as ol}from"react/jsx-runtime";var Xr="0.3.0";globalThis.__CODEKEEP_VERSION=Xr;var Yn=new el;Yn.name("codekeep").description("Async tower defense terminal game powered by your coding activity").version(Xr).option("--ascii","Force ASCII-only rendering (no Unicode box drawing)").option("--compact","Compact layout for narrow terminals").option("--tutorial","Replay the tutorial").option("--resume","Skip menu, jump straight to keep").option("--no-save","Dry-run mode: play without writing to disk").option("--stats","Print save file stats as JSON (headless, no TUI)").option("--online <url>","Connect to a CodeKeep server for multiplayer").option("--server <url>","Alias for --online").action(e=>{if(e.stats){let d=Jt();d||(process.stdout.write(JSON.stringify({error:"No save file found"})+`
33
+ `),process.exit(1));let g=d.progression,l={version:Xr,player:d.player.displayName,keepAge:Math.max(1,Math.floor((Date.now()-d.keep.createdAtUnixMs)/864e5)),structures:d.keep.grid.structures.length,resources:d.keep.resources,raids:{won:g.totalRaidsWon,lost:g.totalRaidsLost,winStreak:g.currentWinStreak,bestStreak:g.bestWinStreak},achievements:g.achievements?.length??0,tutorialCompleted:d.tutorialCompleted,lastPlayed:new Date(d.lastPlayedAtUnixMs).toISOString()};process.stdout.write(JSON.stringify(l,null,2)+`
36
34
  `),process.exit(0)}(!process.stdin.isTTY||!process.stdout.isTTY)&&(process.stderr.write(`codekeep requires an interactive terminal.
37
35
  Run it directly in your terminal (not piped or in CI).
38
36
  Use --stats for headless save file info.
39
- `),process.exit(1));let t=!!Gt(),o=e.online||e.server||process.env.CODEKEEP_SERVER,{waitUntilExit:s,unmount:r}=Ua(Ga(Gs,{asciiMode:e.ascii??!1,compact:e.compact??!1,forceTutorial:e.tutorial??!1,autoResume:(e.resume??!1)&&t,serverUrl:o,dryRun:e.save===!1}),{exitOnCtrlC:!1}),a=!1;function T(){if(!a){if(a=!0,e.save!==!1){process.stderr.write(`
37
+ `),process.exit(1));let t=!!Jt(),o=e.online||e.server||process.env.CODEKEEP_SERVER,{waitUntilExit:s,unmount:r}=tl(ol(Hn,{asciiMode:e.ascii??!1,compact:e.compact??!1,forceTutorial:e.tutorial??!1,autoResume:(e.resume??!1)&&t,serverUrl:o,dryRun:e.save===!1}),{exitOnCtrlC:!1}),n=!1;function c(){if(!n){if(n=!0,e.save!==!1){process.stderr.write(`
40
38
  Saving...
41
- `);try{let f=Gt();f&&Et(f)}catch{}}r()}}process.on("SIGINT",T),process.on("SIGTERM",T),process.on("SIGHUP",T),s().then(()=>{process.exit(0)}).catch(()=>{process.exit(1)})});Ws.parse();export{ar as CLI_VERSION};
39
+ `);try{let d=Jt();d&&Pt(d)}catch{}}r()}}process.on("SIGINT",c),process.on("SIGTERM",c),process.on("SIGHUP",c),s().then(()=>{process.exit(0)}).catch(()=>{process.exit(1)})});Yn.parse();export{Xr as CLI_VERSION};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codekeep",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "description": "Async tower defense terminal game — build ASCII fortresses powered by your coding activity",
6
6
  "license": "MIT",