codekeep 0.2.0 → 0.2.2
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.
- package/dist/index.js +22 -17
- package/package.json +2 -1
package/dist/index.js
CHANGED
|
@@ -1,36 +1,41 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as $a}from"commander";import{render as Na}from"ink";import{useState as Re,useCallback as Ft,useEffect as Ma,useRef as Ls}from"react";import{Box as Lt,Text as Ie,useApp as Ia,useInput as Pa,useStdout as Da}from"ink";var N={gold:"\u25CF",wood:"\u2663",stone:"\u25A0"};var M=16,ar=8,ir=2400;var bt={gold:80,wood:40,stone:20},ro={gold:200,wood:120,stone:80},me={wall:"#",trap:"%",treasury:"$",ward:"@",watchtower:"^",archerTower:"!",vault:"&"},ot={wall:"Stone Wall",trap:"Bear Trap",treasury:"Treasury",ward:"Ward",watchtower:"Watchtower",archerTower:"Archer Tower",vault:"Vault"},$t="\xB7",rt={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}}},so={1:40,2:70,3:110},no={1:25,2:40,3:60},ao={1:20,2:35,3:50},lr={1:4,2:6,3:9},dr={1:16,2:12,3:8},cr={1:80,2:160,3:280},ur={1:.15,2:.28,3:.4},kt={1:1,2:2,3:3},pr={1:4,2:7,3:10},io={1:2,2:2,3:3},fr={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}},mr=6e4,lo={gold:2,wood:4,stone:1},co={gold:1,wood:0,stone:3},uo={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}},gr={build_success:"Miners returned",tests_pass:"Harvest complete",git_commit:"Trade caravan arrived",session_reward:"Tax collection",daily_login:"Morning tribute"},Vt=9e5,hr=5,Nt=10,Tr=.5,Yt=[{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"}],jt={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}},Do=6,xr=35e3,yr=18e4,wr=.25,Rr=2,dt=["wall","trap","treasury","ward","watchtower","archerTower","vault"],po={1:60,2:90,3:130};var Sr=1;var Ga={defense_win:7200*1e3,partial_breach:14400*1e3,full_breach:480*60*1e3},fo={raider:{gold:8,wood:4,stone:2},scout:{gold:6,wood:6,stone:0},brute:{gold:15,wood:8,stone:8}},br={raider:120*1e3,scout:120*1e3,brute:300*1e3};var Wa=1440*60*1e3,Ka=2880*60*1e3,Ha=672*60*60*1e3;var Fa=336*60*60*1e3,Va=2880*60*1e3;var Ya=720*60*1e3;import{writeFileSync as $o,readFileSync as xn,mkdirSync as yn,existsSync as Wo,renameSync as wn,unlinkSync as Rn}from"fs";import{join as jr,dirname as Sn}from"path";import{homedir as bn}from"os";function zs(t){return t.x>=0&&t.x<M&&t.y>=0&&t.y<M}function Oo(t,e){return t.structures.find(o=>o.pos.x===e.x&&o.pos.y===e.y)}function Zs(t,e,o){return zs(e)?Oo(t,e)?{ok:!1,reason:"Cell is occupied"}:{ok:!0}:{ok:!1,reason:"Out of bounds"}}function Pr(t,e){return t.gold>=e.gold&&t.wood>=e.wood&&t.stone>=e.stone}function Dr(t,e,o){let s=Zs(t.grid,e,o);if(!s.ok)return{ok:!1,reason:s.reason};let r=rt[o][1];if(!Pr(t.resources,r))return{ok:!1,reason:$r(t.resources,r)};let a={id:`${o}-${e.x}-${e.y}-${Date.now()}`,kind:o,level:1,pos:{...e},placedAtUnixMs:Date.now()};return{ok:!0,keep:{...t,resources:Nr(t.resources,r),grid:{...t.grid,structures:[...t.grid.structures,a]},updatedAtUnixMs:Date.now()}}}function Lr(t,e){let o=Oo(t.grid,e);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=rt[o.kind][s];if(!Pr(t.resources,r))return{ok:!1,reason:$r(t.resources,r)};let a={...o,level:s};return{ok:!0,keep:{...t,resources:Nr(t.resources,r),grid:{...t.grid,structures:t.grid.structures.map(T=>T.id===o.id?a:T)},updatedAtUnixMs:Date.now()}}}function Br(t,e){let o=Oo(t.grid,e);if(!o)return{ok:!1,reason:"No structure at this position"};let s=Xs(o);return{ok:!0,keep:{...t,resources:Ve(t.resources,s),grid:{...t.grid,structures:t.grid.structures.filter(r=>r.id!==o.id)},updatedAtUnixMs:Date.now()}}}function Xs(t){let e=0,o=0,s=0;for(let r=1;r<=t.level;r++){let a=rt[t.kind][r];e+=a.gold,o+=a.wood,s+=a.stone}return{gold:Math.floor(e*.5),wood:Math.floor(o*.5),stone:Math.floor(s*.5)}}function $r(t,e){let o=[];return e.gold>t.gold&&o.push(`${e.gold-t.gold} more gold`),e.wood>t.wood&&o.push(`${e.wood-t.wood} more wood`),e.stone>t.stone&&o.push(`${e.stone-t.stone} more stone`),o.length>0?`Need ${o.join(", ")}`:"Not enough resources"}function Nr(t,e){return{gold:t.gold-e.gold,wood:t.wood-e.wood,stone:t.stone-e.stone}}function Ve(t,e){return{gold:t.gold+e.gold,wood:t.wood+e.wood,stone:t.stone+e.stone}}function Uo(t,e){let o=e.grants??uo[e.type]??{gold:0,wood:0,stone:0},s=Ve(t.resources,o);return{...t,resources:ct(s),updatedAtUnixMs:Date.now()}}function ct(t){return{gold:Math.min(t.gold,ro.gold*10),wood:Math.min(t.wood,ro.wood*10),stone:Math.min(t.stone,ro.stone*10)}}function Go(t,e){let o=Math.min(Math.floor(e/mr),60),s=t.structures.filter(a=>a.kind==="treasury").length,r=t.structures.filter(a=>a.kind==="watchtower").length;return{gold:o*(s*lo.gold+r*co.gold),wood:o*(s*lo.wood+r*co.wood),stone:o*(s*lo.stone+r*co.stone)}}function Or(){let t=["build_success","tests_pass","git_commit","session_reward"],e=t[Math.floor(Math.random()*t.length)];return{type:e,timestamp:Date.now(),grants:uo[e]}}function Js(t){return so[t]}function Qs(t){return no[t]}function en(t){return ao[t]}function tn(t){return po[t]}function kr(t){return lr[t]}function vr(t){return dr[t]}function Lo(t){return cr[t]}function on(t){return ur[t]}function rn(t){return kt[t]}function sn(t){return pr[t]}function nn(t){return io[t]}function an(t){return fr[t]}function Er(t,e){return Math.max(Math.abs(t.x-e.x),Math.abs(t.y-e.y))}function _e(t,e){return Math.abs(t.x-e.x)+Math.abs(t.y-e.y)}function ln(t,e){let o=t.structures.filter(a=>a.kind==="ward"),s=t.structures.filter(a=>a.kind==="watchtower"),r=0;for(let a of o){let T=1;for(let m of s)Er(a.pos,m.pos)<=1&&(T=Math.max(T,1+rn(m.level)));Er(a.pos,e)<=T&&(r=Math.max(r,on(a.level)))}return r}function Ur(t){let e=t|0;return()=>{e=e+1831565813|0;let o=Math.imul(e^e>>>15,1|e);return o=o+Math.imul(o^o>>>7,61|o)^o,((o^o>>>14)>>>0)/4294967296}}function Gr(t){let e=0;for(let o=0;o<t.length;o++){let s=t.charCodeAt(o);e=(e<<5)-e+s|0}return e}function dn(t,e){switch(t){case"N":return{x:e,y:0};case"S":return{x:e,y:M-1};case"E":return{x:M-1,y:e};case"W":return{x:0,y:e}}}function Wr(t,e){return e.x<0||e.x>=M||e.y<0||e.y>=M?!1:t.grid[e.y][e.x]}function Kr(t){for(let e=0;e<M;e++)for(let o=0;o<M;o++)t.grid[e][o]=!0;for(let e of t.solids)e.destroyed||(t.grid[e.pos.y][e.pos.x]=!1)}function Hr(t,e,o){if(t.x===e.x&&t.y===e.y)return null;let s=d=>`${d.x},${d.y}`,r=new Map,a=new Set,T=d=>Math.abs(d.x-e.x)+Math.abs(d.y-e.y),m=s(t);r.set(m,{pos:t,g:0,f:T(t),parent:null});let i=new Map;for(;r.size>0;){let d="",S=1/0;for(let[f,p]of r)p.f<S&&(S=p.f,d=f);let E=r.get(d);if(r.delete(d),E.pos.x===e.x&&E.pos.y===e.y){let f=s(e),p=i.get(f);for(;p&&p!==m;)f=p,p=i.get(f);let[b,c]=f.split(",").map(Number);return{x:b,y:c}}a.add(d);let y=[{x:E.pos.x-1,y:E.pos.y},{x:E.pos.x+1,y:E.pos.y},{x:E.pos.x,y:E.pos.y-1},{x:E.pos.x,y:E.pos.y+1}];for(let f of y){let p=s(f);if(a.has(p)||!Wr(o,f)&&!(f.x===e.x&&f.y===e.y))continue;let b=E.g+1,c=r.get(p);c&&b>=c.g||(i.set(p,d),r.set(p,{pos:f,g:b,f:b+T(f),parent:d}))}}return null}function cn(t,e){switch(t){case"wall":return Js(e);case"archerTower":return Qs(e);case"watchtower":return en(e);case"vault":return tn(e);default:return 0}}var un=["archerTower","watchtower"];function Ar(t,e){return t.solids.find(o=>!o.destroyed&&_e(o.pos,e)===1)}function mo(t,e,o){o.hp-=Le[e.raiderType].damage;let s=o.hp<=0;if(s){o.destroyed=!0,Kr(t);let r=t.archers.find(a=>a.structureId===o.structureId);r&&(r.destroyed=!0)}o.kind==="wall"?t.events.push({t:t.tick,type:"wall_damaged",structureId:o.structureId,hpRemaining:Math.max(0,o.hp),destroyed:s}):t.events.push({t:t.tick,type:"structure_damaged",structureId:o.structureId,structureKind:o.kind,hpRemaining:Math.max(0,o.hp),destroyed:s})}function Cr(t,e,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(m=>Wr(t,m)).sort((m,i)=>{let d=_e(m,e.pos),S=_e(i,e.pos);return d-S})[0];if(!r||_e(e.pos,r)===0)return!1;let a=Hr(e.pos,r,t);if(!a)return!1;let T={...e.pos};return e.pos={...a},t.events.push({t:t.tick,type:"raider_move",probeId:e.id,from:T,to:{...e.pos}}),!0}function pn(t,e){return t.solids.filter(s=>!s.destroyed&&un.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,e.pos)-_e(r.pos,e.pos)})[0]??null}function fn(t,e){let o=t.solids.filter(s=>!s.destroyed&&_e(s.pos,e.pos)===1);return o.length===0?null:o.sort((s,r)=>s.hp-r.hp)[0]}function ut(t){let e=Ur(Gr(t.seed)),{keepGrid:o}=t,s=["wall","archerTower","watchtower","vault"],r=o.structures.filter(c=>s.includes(c.kind)).sort((c,B)=>c.id.localeCompare(B.id)).map(c=>({structureId:c.id,kind:c.kind,pos:{...c.pos},hp:cn(c.kind,c.level),destroyed:!1})),a=o.structures.filter(c=>c.kind==="trap").sort((c,B)=>c.id.localeCompare(B.id)).map(c=>({structureId:c.id,pos:{...c.pos},level:c.level,cooldownRemaining:0})),T=o.structures.filter(c=>c.kind==="archerTower").sort((c,B)=>c.id.localeCompare(B.id)).map(c=>({structureId:c.id,pos:{...c.pos},level:c.level,cooldownRemaining:0,destroyed:!1})),m=o.structures.filter(c=>c.kind==="treasury").sort((c,B)=>c.id.localeCompare(B.id)).map(c=>({structureId:c.id,pos:{...c.pos},level:c.level,storedResources:Lo(c.level)}));m.length===0&&(m=[{structureId:"__virtual_center_treasury",pos:{x:8,y:8},level:1,storedResources:Lo(1)}]);let i={tick:0,raiders:[],solids:r,traps:a,archers:T,treasuries:m,events:[],grid:Array.from({length:M},()=>Array(M).fill(!0)),totalLoot:{gold:0,wood:0,stone:0}};Kr(i);let d=[],S=["N","S","E","W"];for(let c=0;c<t.probeCount;c++){let B=t.spawnSpecs?.[c],Y=B?.edge??S[Math.floor(e()*S.length)],O=B?.offset??Math.floor(e()*M),u=B?.raiderType??t.probeTypes?.[c]??"raider",G=B?.waveDelay??0;d.push({id:c,edge:Y,offset:O,raiderType:u,spawnAtTick:G})}function E(c,B){let Y=dn(c.edge,c.offset),O=null,u=1/0;for(let G of m){let A=_e(G.pos,Y);A<u&&(u=A,O=G)}i.raiders.push({id:c.id,pos:{...Y},hp:Le[c.raiderType].hp,raiderType:c.raiderType,stunRemaining:0,targetId:O?.structureId??null,alive:!0,looted:{gold:0,wood:0,stone:0}}),i.events.push({t:B,type:"raider_spawn",probeId:c.id,edge:c.edge,pos:{...Y},raiderType:c.raiderType,maxHp:Le[c.raiderType].hp})}for(let c of d)c.spawnAtTick===0&&E(c,0);for(;i.tick<ir;){i.tick++;for(let u of d)u.spawnAtTick===i.tick&&E(u,i.tick);for(let u of i.traps)u.cooldownRemaining>0&&u.cooldownRemaining--;for(let u of i.archers)u.cooldownRemaining>0&&u.cooldownRemaining--;let c=i.raiders.filter(u=>u.alive).sort((u,G)=>u.id-G.id),B=d.some(u=>u.spawnAtTick>i.tick);if(c.length===0&&!B)break;for(let u of i.archers){if(u.destroyed||u.cooldownRemaining>0)continue;let G=nn(u.level),A=sn(u.level),W=c.filter(g=>g.alive&&_e(u.pos,g.pos)<=G),x=W.length===0?void 0:W.sort((g,P)=>{let C=g.stunRemaining>0?0:1,k=P.stunRemaining>0?0:1;if(C!==k)return C-k;let w=i.treasuries.find(Te=>Te.structureId===g.targetId),X=i.treasuries.find(Te=>Te.structureId===P.targetId),oe=w?_e(g.pos,w.pos):1/0,ce=X?_e(P.pos,X.pos):1/0;return oe-ce})[0];x&&(x.hp-=A,u.cooldownRemaining=an(u.level),x.hp<=0?(x.alive=!1,i.events.push({t:i.tick,type:"arrow_hit",probeId:x.id,archerId:u.structureId,damage:A,hpRemaining:0}),i.events.push({t:i.tick,type:"raider_destroyed",probeId:x.id,pos:{...x.pos}})):i.events.push({t:i.tick,type:"arrow_hit",probeId:x.id,archerId:u.structureId,damage:A,hpRemaining:x.hp}))}for(let u of c){if(!u.alive)continue;if(u.stunRemaining>0){u.stunRemaining--;continue}let G=Le[u.raiderType].speed;for(let A=0;A<G&&u.alive;A++){if(u.raiderType==="brute"){let k=pn(i,u);if(k){if(_e(u.pos,k.pos)===1){mo(i,u,k);break}if(Cr(i,u,k)){let X=i.traps.find(oe=>oe.pos.x===u.pos.x&&oe.pos.y===u.pos.y&&oe.cooldownRemaining===0);if(X){u.stunRemaining=kr(X.level),X.cooldownRemaining=vr(X.level),i.events.push({t:i.tick,type:"raider_stunned",probeId:u.id,pos:{...u.pos},trapId:X.structureId,stunTicks:u.stunRemaining});break}continue}let w=Ar(i,u.pos);if(w){mo(i,u,w);break}}}let W=i.treasuries.find(k=>k.structureId===u.targetId);if(!W||W.storedResources<=0){let k=i.treasuries.filter(w=>w.storedResources>0).sort((w,X)=>{let oe=_e(w.pos,u.pos),ce=_e(X.pos,u.pos);return oe-ce||w.structureId.localeCompare(X.structureId)})[0];if(!k){u.alive=!1,i.events.push({t:i.tick,type:"raider_destroyed",probeId:u.id,pos:{...u.pos}});break}u.targetId=k.structureId}let x=i.treasuries.find(k=>k.structureId===u.targetId);if(u.pos.x===x.pos.x&&u.pos.y===x.pos.y){let k=ln(o,x.pos),w=Math.max(1,Math.floor(Le[u.raiderType].loot*x.level*(1-k))),X=Math.min(w,x.storedResources);x.storedResources-=X;let oe=Math.ceil(X*.4),ce=Math.ceil(X*.35),Te=Math.max(0,X-oe-ce),Tt={gold:oe,wood:ce,stone:Te};u.looted.gold+=oe,u.looted.wood+=ce,u.looted.stone+=Te,i.totalLoot.gold+=oe,i.totalLoot.wood+=ce,i.totalLoot.stone+=Te,i.events.push({t:i.tick,type:"treasury_breach",structureId:x.structureId,lootTaken:Tt});break}let g=Hr(u.pos,x.pos,i);if(!g){if(u.raiderType==="scout"){let w=fn(i,u);if(w){mo(i,u,w);break}}let k=Ar(i,u.pos);if(k)mo(i,u,k);else{let w=i.solids.filter(X=>!X.destroyed).sort((X,oe)=>_e(X.pos,u.pos)-_e(oe.pos,u.pos))[0];w&&Cr(i,u,w)}break}let P={...u.pos};u.pos={...g},i.events.push({t:i.tick,type:"raider_move",probeId:u.id,from:P,to:{...u.pos}});let C=i.traps.find(k=>k.pos.x===u.pos.x&&k.pos.y===u.pos.y&&k.cooldownRemaining===0);if(C){let k=kr(C.level);u.stunRemaining=k,C.cooldownRemaining=vr(C.level),i.events.push({t:i.tick,type:"raider_stunned",probeId:u.id,pos:{...u.pos},trapId:C.structureId,stunTicks:k});break}}}let Y=i.raiders.every(u=>!u.alive||u.stunRemaining>100),O=d.some(u=>u.spawnAtTick>i.tick);if(Y&&!O)break}let y=i.treasuries.reduce((c,B)=>c+B.storedResources,0),f=i.treasuries.reduce((c,B)=>c+Lo(B.level),0),p,b=i.totalLoot.gold+i.totalLoot.wood+i.totalLoot.stone;return b===0?p="defense_win":y>0&&b<f*.5?p="partial_breach":p="full_breach",i.events.push({t:i.tick,type:"raid_end",outcome:p}),{tickRateHz:ar,maxTicks:i.tick,events:i.events}}function Bo(t,e){return Math.abs(t.x-e.x)+Math.abs(t.y-e.y)}function mn(t){let e=Object.entries(jt),o=e.reduce((r,[,a])=>r+a.weight,0),s=t()*o;for(let[r,a]of e)if(s-=a.weight,s<=0)return r;return"gold_nugget"}function gn(t,e,o){return!!(e.structures.some(s=>s.pos.x===t.x&&s.pos.y===t.y)||o.some(s=>s.pos.x===t.x&&s.pos.y===t.y))}function Fr(t,e,o,s){if(t.length>=Do)return t;let r=e.structures.filter(d=>d.kind==="archerTower").length,a=Math.min(r,2),T=1+(s()<.4?1:0),m=Math.min(T+a,Do-t.length),i=[];for(let d=0;d<m;d++){let S=null;for(let E=0;E<30;E++){let y=Math.floor(s()*M),f=Math.floor(s()*M),p={x:y,y:f};if(!gn(p,e,[...t,...i])){S=p;break}}if(!S)break;i.push({id:`frag-${o}-${d}`,type:mn(s),pos:S,spawnedAtMs:o})}return[...t,...i]}function Vr(t,e,o){let s=t.findIndex(d=>d.pos.x===e.x&&d.pos.y===e.y);if(s===-1)return null;let r=[t[s]],a=o.structures.filter(d=>d.kind==="watchtower"),T=0;for(let d of a)Bo(d.pos,e)<=kt[d.level]&&(T=Math.max(T,d.level));if(T>0)for(let d of t)r.includes(d)||Bo(e,d.pos)<=T&&r.push(d);let m=new Set(r.map(d=>d.id)),i={gold:0,wood:0,stone:0};for(let d of r){let S=jt[d.type].yield,E=1;o.structures.some(f=>f.kind==="treasury"&&Bo(f.pos,d.pos)<=Rr)&&(E+=wr),i={gold:i.gold+Math.ceil(S.gold*E),wood:i.wood+Math.ceil(S.wood*E),stone:i.stone+Math.ceil(S.stone*E)}}return{yield:i,updatedFragments:t.filter(d=>!m.has(d.id)),collected:r}}function Yr(t,e){return t.filter(o=>e-o.spawnedAtMs<yr)}var _r=[{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 go(t,e){let o=_r[Math.max(0,Math.min(e-1,_r.length-1))],s=Ur(Gr(t)),r=[],a=new Set,T=Math.max(1,Math.floor(o.structureCount/5));for(let y=0;y<T;y++){let f=Mr(s,a);if(!f)break;r.push(vt("treasury",f,Et(s,o.maxUpgradeLevel))),a.add(`${f.x},${f.y}`)}let m=Math.floor(o.structureCount*.35);for(let y=0;y<m;y++){let f=Ir(s,a,r);if(!f)break;r.push(vt("wall",f,Et(s,o.maxUpgradeLevel))),a.add(`${f.x},${f.y}`)}let i=Math.floor(o.structureCount*.2);for(let y=0;y<i;y++){let f=hn(s,a);if(!f)break;r.push(vt("trap",f,Et(s,o.maxUpgradeLevel))),a.add(`${f.x},${f.y}`)}let d=Math.max(1,Math.floor(o.structureCount*.15));for(let y=0;y<d;y++){let f=r.filter(c=>c.kind==="treasury"),p=f.length>0?f[Math.floor(s()*f.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<M&&c.y>=0&&c.y<M&&!a.has(`${c.x},${c.y}`));if(b.length>0){let c=b[Math.floor(s()*b.length)];r.push(vt("ward",c,Et(s,o.maxUpgradeLevel))),a.add(`${c.x},${c.y}`)}}let S=Math.max(0,Math.floor(o.structureCount*.1));for(let y=0;y<S;y++){let f=Ir(s,a,r);if(!f)break;r.push(vt("archerTower",f,Et(s,o.maxUpgradeLevel))),a.add(`${f.x},${f.y}`)}for(let y=0;y<Sr;y++){let f=Mr(s,a);if(!f)break;r.push(vt("vault",f,Et(s,o.maxUpgradeLevel))),a.add(`${f.x},${f.y}`)}let E=o.structureCount-r.length;for(let y=0;y<E;y++){let f=Tn(s,a);if(!f)break;r.push(vt("watchtower",f,Et(s,o.maxUpgradeLevel))),a.add(`${f.x},${f.y}`)}return{id:`npc-${t}-${e}`,name:`NPC Keep (Lv.${o.level})`,ownerPlayerId:"npc",grid:{width:16,height:16,structures:r},resources:{...bt},createdAtUnixMs:Date.now(),updatedAtUnixMs:Date.now()}}function vt(t,e,o){return{id:`${t}-${e.x}-${e.y}`,kind:t,level:o,pos:{...e},placedAtUnixMs:Date.now()}}function Et(t,e){let o=Math.floor(t()*e)+1;return Math.min(e,o)}function Mr(t,e){for(let o=0;o<50;o++){let s=4+Math.floor(t()*(M-8)),r=4+Math.floor(t()*(M-8));if(!e.has(`${s},${r}`))return{x:s,y:r}}return null}function Ir(t,e,o){for(let s=0;s<50;s++){let r=o[Math.floor(t()*o.length)],a=Math.floor(t()*3)-1,T=Math.floor(t()*3)-1,m=r.pos.x+a,i=r.pos.y+T;if(m>=0&&m<M&&i>=0&&i<M&&!e.has(`${m},${i}`))return{x:m,y:i}}return null}function hn(t,e){for(let o=0;o<50;o++){let s=Math.floor(t()*4),r,a;if(s===0?(r=Math.floor(t()*M),a=Math.floor(t()*3)):s===1?(r=Math.floor(t()*M),a=M-1-Math.floor(t()*3)):s===2?(r=Math.floor(t()*3),a=Math.floor(t()*M)):(r=M-1-Math.floor(t()*3),a=Math.floor(t()*M)),!e.has(`${r},${a}`))return{x:r,y:a}}return null}function Tn(t,e){for(let o=0;o<50;o++){let s=Math.floor(t()*M),r=Math.floor(t()*M);if(!e.has(`${s},${r}`))return{x:s,y:r}}return null}var No=1;function kn(){return jr(bn(),".config","codekeep")}function Ko(){return jr(kn(),"game.json")}function qr(t){let e=`player-${Date.now()}`;return{schemaVersion:No,savedAtUnixMs:Date.now(),player:{id:e,displayName:t,settings:{asciiMode:!1}},keep:{id:`keep-${e}-${Date.now()}`,name:`${t}'s Keep`,ownerPlayerId:e,grid:{width:16,height:16,structures:[]},resources:{...bt},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 At(t){let e=Ko(),o=Sn(e);Wo(o)||yn(o,{recursive:!0});let s=e+".tmp",r=JSON.stringify({...t,savedAtUnixMs:Date.now()},null,2);$o(s,r,"utf-8"),wn(s,e)}function qt(){let t=Ko();if(!Wo(t))return null;let e;try{e=xn(t,"utf-8")}catch{return null}let o;try{o=JSON.parse(e)}catch{let s=t+".bak";try{$o(s,e,"utf-8")}catch{}return process.stderr.write(`[codekeep] Corrupted save backed up to ${s}
|
|
3
|
-
`),null}if(o.schemaVersion!==
|
|
4
|
-
`),null}return o}function zr(){let t=Ko();if(!Wo(t))return!1;try{return Rn(t),!0}catch{return!1}}import{Box as Zr,Text as ze}from"ink";import{jsx as Ze,jsxs as Xr}from"react/jsx-runtime";var vn={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"},En={wall:"whiteBright",trap:"magentaBright",treasury:"yellowBright",ward:"cyanBright",watchtower:"greenBright",archerTower:"redBright"},An=Object.fromEntries(Object.entries(jt).map(([t,e])=>[t,e.color]));function Cn(t,e){return Math.abs(t.x-e.x)+Math.abs(t.y-e.y)}function Ho(t,e){return Math.max(Math.abs(t.x-e.x),Math.abs(t.y-e.y))}function _n(t,e){let o=new Set;if(t.kind==="archerTower"){let s=io[t.level];for(let r=0;r<M;r++)for(let a=0;a<M;a++)Cn(t.pos,{x:a,y:r})<=s&&!(a===t.pos.x&&r===t.pos.y)&&o.add(`${a},${r}`);return{tiles:o,color:"red"}}if(t.kind==="watchtower"){let s=kt[t.level];for(let r=0;r<M;r++)for(let a=0;a<M;a++)Ho(t.pos,{x:a,y:r})<=s&&!(a===t.pos.x&&r===t.pos.y)&&o.add(`${a},${r}`);return{tiles:o,color:"green"}}if(t.kind==="ward"){let s=1,r=e.filter(a=>a.kind==="watchtower");for(let a of r)Ho(t.pos,a.pos)<=1&&(s=Math.max(s,1+kt[a.level]));s=Math.min(s,5);for(let a=0;a<M;a++)for(let T=0;T<M;T++)Ho(t.pos,{x:T,y:a})<=s&&!(T===t.pos.x&&a===t.pos.y)&&o.add(`${T},${a}`);return{tiles:o,color:"cyan"}}return null}function Jr({grid:t,cursor:e,asciiMode:o,compact:s,fragments:r=[]}){let a=o?"-":"\u2500",T=o?"|":"\u2502",m=o?"+":"\u250C",i=o?"+":"\u2510",d=o?"+":"\u2514",S=o?"+":"\u2518",E=s?1:2,y=(s?" ":" ")+Array.from({length:M},(u,G)=>s?G.toString(16).toUpperCase():G.toString(16).toUpperCase()+" ").join(""),f=(s?" ":" ")+m+a.repeat(M*E)+i,p=(s?" ":" ")+d+a.repeat(M*E)+S,b=new Map;for(let u of t.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=b.get(`${e.x},${e.y}`),Y=B?_n(B,t.structures):null,O=[];for(let u=0;u<M;u++){let G=s?u.toString(16).toUpperCase():" "+u.toString(16).toUpperCase(),A=[];for(let W=0;W<M;W++){let x=e.x===W&&e.y===u,g=b.get(`${W},${u}`),P=`${W},${u}`,C=Y?.tiles.has(P)??!1,k,w,X=!1,oe=c.get(P);g?(k=me[g.kind],w=vn[g.kind],g.level>=2&&(X=!0),g.level===3&&(w=En[g.kind])):oe?(k="~",w=An[oe.type]??"cyan",X=!0):(k=$t,w=void 0);let ce=s?"":g&&g.level>1?String(g.level):" ";x?A.push(Ze(ze,{backgroundColor:"white",color:"black",bold:!0,children:k+ce},W)):C&&!g&&!oe?A.push(Ze(ze,{color:Y.color,children:"\u2591"+(s?"":" ")},W)):C&&g?A.push(Ze(ze,{color:w,bold:X,backgroundColor:Y.color==="red"?"red":void 0,children:k+ce},W)):w?A.push(Ze(ze,{color:w,bold:X,children:k+ce},W)):A.push(Ze(ze,{dimColor:!0,children:k+(s?"":" ")},W))}O.push(Xr(Zr,{children:[Ze(ze,{dimColor:!0,children:G}),Ze(ze,{dimColor:!0,children:T}),A,Ze(ze,{dimColor:!0,children:T})]},u))}return Xr(Zr,{flexDirection:"column",children:[Ze(ze,{dimColor:!0,children:y}),Ze(ze,{dimColor:!0,children:f}),O,Ze(ze,{dimColor:!0,children:p})]})}import{Box as Fo,Text as de}from"ink";import{Fragment as Pn,jsx as Me,jsxs as Ye}from"react/jsx-runtime";var Mn={wall:"WL",trap:"TR",treasury:"TY",ward:"WD",watchtower:"WT",archerTower:"AT"};function In(t){let e=[];return t.gold>0&&e.push(`${N.gold}${t.gold}`),t.wood>0&&e.push(`${N.wood}${t.wood}`),t.stone>0&&e.push(`${N.stone}${t.stone}`),e.join(" ")}function Qr({resources:t,selectedStructure:e,message:o,compact:s,structureAtCursor:r,fragmentCount:a=0}){if(s){let m=Mn[e];return Me(Fo,{flexDirection:"column",marginBottom:0,children:Ye(de,{children:[Me(de,{bold:!0,color:"yellow",children:"\u25C6"}),Me(de,{dimColor:!0,children:" \u2502 "}),Ye(de,{color:"yellow",children:[N.gold,t.gold]}),Me(de,{children:" "}),Ye(de,{color:"green",children:[N.wood,t.wood]}),Me(de,{children:" "}),Ye(de,{color:"white",children:[N.stone,t.stone]}),Me(de,{dimColor:!0,children:" \u2502 "}),Me(de,{bold:!0,children:m}),o?Me(de,{dimColor:!0,children:" \u2502 "}):null,o?Me(de,{color:o.startsWith("!")?"red":"yellow",children:o}):null]})})}let T=r?`${ot[r.kind]} Lv.${r.level}`+(r.level<3?` \u2192 Lv.${r.level+1}: ${In(rt[r.kind][r.level+1])}`:" (MAX)"):"";return Ye(Fo,{flexDirection:"column",marginBottom:1,children:[Ye(Fo,{flexDirection:"row",gap:1,children:[Me(de,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep"}),Me(de,{dimColor:!0,children:"\u2502"}),Ye(de,{color:"yellow",children:[N.gold," ",t.gold]}),Ye(de,{color:"green",children:[N.wood," ",t.wood]}),Ye(de,{color:"white",children:[N.stone," ",t.stone]}),Me(de,{dimColor:!0,children:"\u2502"}),Ye(de,{children:["Sel: ",Me(de,{bold:!0,children:ot[e]})]}),a>0&&Ye(Pn,{children:[Me(de,{dimColor:!0,children:"\u2502"}),Ye(de,{color:"cyan",bold:!0,children:["~ ",a," on ground"]})]})]}),Me(de,{color:o.startsWith("!")?"red":"yellow",children:o||" "}),Me(de,{dimColor:!0,children:T||" "})]})}import{Box as Dn,Text as _}from"ink";import{jsx as K,jsxs as pe}from"react/jsx-runtime";function Ot(t){let e=[];return t.gold>0&&e.push(`${N.gold}${t.gold}`),t.wood>0&&e.push(`${N.wood}${t.wood}`),t.stone>0&&e.push(`${N.stone}${t.stone}`),e.join(" ")}function es(){let t=Le,e=rt;return pe(Dn,{flexDirection:"column",padding:1,children:[K(_,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep \u2014 Help"}),K(_,{children:" "}),K(_,{bold:!0,children:"Navigation"}),K(_,{children:" h/j/k/l or WASD or Arrows Move cursor"}),K(_,{children:" g + hex coords + Enter Jump to coordinate (e.g. g 5,3)"}),K(_,{children:" Tab Jump to next structure"}),K(_,{children:" Esc Back to menu"}),K(_,{children:" "}),K(_,{bold:!0,children:"Building"}),pe(_,{children:[" ","[ / ] Cycle structure type"]}),K(_,{children:" 1-6 Select structure by number"}),K(_,{children:" Enter or e Place structure at cursor"}),K(_,{children:" u Upgrade structure (Lv.1\u21922\u21923)"}),K(_,{children:" x Demolish structure (50% refund)"}),K(_,{children:" "}),K(_,{bold:!0,children:"Foraging"}),K(_,{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"]}),K(_,{children:" "}),K(_,{bold:!0,children:"Combat"}),K(_,{children:" r Quick defend (instant result)"}),K(_,{children:" v View last quick-defend replay"}),K(_,{children:" Defend Keep (menu) Watch raiders assault your grid"}),K(_,{children:" Attack NPC (menu) Raid an NPC keep for loot"}),K(_,{children:" "}),K(_,{bold:!0,children:"Other"}),K(_,{children:" f Kingdom boon (+resources)"}),K(_,{children:" ? Toggle this help (works on any screen)"}),K(_,{children:" q Save and quit"}),K(_,{children:" "}),K(_,{bold:!0,children:"Structures (cost Lv.1 \u2192 Lv.2 \u2192 Lv.3)"}),pe(_,{children:[" ",pe(_,{color:"white",children:["1 ",me.wall]})," Stone Wall Blocks raiders, has HP ",Ot(e.wall[1])]}),pe(_,{children:[" ",pe(_,{color:"magenta",children:["2 ",me.trap]})," Bear Trap Stuns raiders on contact ",Ot(e.trap[1])]}),pe(_,{children:[" ",pe(_,{color:"yellow",children:["3 ",me.treasury]})," Treasury Stores loot, generates income ",Ot(e.treasury[1])]}),pe(_,{children:[" ",pe(_,{color:"cyan",children:["4 ",me.ward]})," Ward Reduces loot stolen nearby ",Ot(e.ward[1])]}),pe(_,{children:[" ",pe(_,{color:"green",children:["5 ",me.watchtower]})," Watchtower Extends ward range, auto-gathers ",Ot(e.watchtower[1])]}),pe(_,{children:[" ",pe(_,{color:"redBright",children:["6 ",me.archerTower]})," Archer Tower Fires arrows at raiders in range ",Ot(e.archerTower[1])]}),K(_,{children:" "}),K(_,{bold:!0,children:"Resources"}),pe(_,{children:[" ",K(_,{color:"yellow",children:N.gold})," Gold Earned from events, foraging, and raids"]}),pe(_,{children:[" ",K(_,{color:"green",children:N.wood})," Wood Earned from treasuries and events"]}),pe(_,{children:[" ",K(_,{color:"white",children:N.stone})," Stone Earned from watchtowers and events"]}),K(_,{children:" Treasuries and watchtowers generate passive income over time."}),K(_,{children:" "}),K(_,{bold:!0,children:"Raider Types"}),pe(_,{children:[" Raider HP ",t.raider.hp,", dmg ",t.raider.damage,", speed ",t.raider.speed," \u2014 standard foot soldier"]}),pe(_,{children:[" Scout HP ",t.scout.hp,", dmg ",t.scout.damage,", speed ",t.scout.speed," \u2014 fast, moves twice per tick"]}),pe(_,{children:[" Brute HP ",t.brute.hp,", dmg ",t.brute.damage,", speed ",t.brute.speed," \u2014 heavy hitter, hard to kill"]}),K(_,{children:" "}),K(_,{bold:!0,children:"Raid Difficulty"}),K(_,{children:" Difficulty scales with total raids completed (Lv.1\u20135)."}),K(_,{children:" Higher levels bring more raiders, scouts, and brutes."}),pe(_,{children:[" Outcomes: ",K(_,{color:"green",children:"Defense Win"})," \xB7 ",K(_,{color:"yellow",children:"Partial Breach"})," \xB7 ",K(_,{color:"red",children:"Full Breach"})]}),K(_,{children:" "}),K(_,{dimColor:!0,children:"Press any key to close"})]})}import{useState as Ln}from"react";import{Box as ts,Text as Xe,useInput as Bn}from"ink";import{jsx as zt,jsxs as xt}from"react/jsx-runtime";function $n(t){let e=[{key:"keep",label:"Build Keep",desc:"Place and upgrade structures"},{key:"defend",label:"Defend Keep",desc:"Watch NPCs attack YOUR defenses"},{key:"attack",label:"Attack NPC",desc:"Raid an NPC keep for resources"}];return t&&e.push({key:"pvp",label:"\u2694 PvP Arena",desc:"Fight real players for trophies"}),e.push({key:"friendRaid",label:"Raid Rival Keep",desc:"Plunder a rival lord's fortress"},{key:"raidLog",label:"Raid Log",desc:"View recent raid history"},{key:"settings",label:"Settings",desc:"Game options and reset"},{key:"quit",label:"Rest for the Night",desc:"Save and exit"}),e}function os({gameSave:t,onlineMode:e,onKeep:o,onAttack:s,onDefend:r,onFriendRaid:a,onPvp:T,onRaidLog:m,onSettings:i,onQuit:d}){let S=$n(!!e),[E,y]=Ln(0);Bn((O,u)=>{if(O==="k"||O==="w"||u.upArrow)y(G=>Math.max(0,G-1));else if(O==="j"||O==="s"||u.downArrow)y(G=>Math.min(S.length-1,G+1));else if(u.return){let G=S[E];G.key==="keep"?o():G.key==="defend"?r():G.key==="attack"?s():G.key==="pvp"?T?.():G.key==="friendRaid"?a():G.key==="raidLog"?m():G.key==="settings"?i():G.key==="quit"&&d()}else O==="q"&&d()});let f=t.keep.grid.structures.length,p=t.progression,b=p.totalRaidsWon+p.totalRaidsLost,c=Math.max(1,Math.floor((Date.now()-t.keep.createdAtUnixMs)/864e5)),B=t.keep.grid.structures.filter(O=>O.kind==="treasury").length,Y=t.keep.grid.structures.filter(O=>O.kind==="archerTower").length;return xt(ts,{flexDirection:"column",padding:1,children:[zt(Xe,{bold:!0,color:"yellow",children:`
|
|
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:`
|
|
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`}),zt(Xe,{children:" "}),xt(Xe,{dimColor:!0,children:[" ",t.player.displayName,"'s Keep \u2014 ",c,"d old"]}),xt(Xe,{dimColor:!0,children:[" ",f," structures (",B,"$ ",Y,"!) \xB7 Raids ",p.totalRaidsWon,"W / ",p.totalRaidsLost,"L \xB7 Streak ",p.currentWinStreak," (best ",p.bestWinStreak,")"]}),xt(Xe,{dimColor:!0,children:[" Difficulty: Lv.",b<=2?1:b<=5?2:b<=9?3:b<=14?4:5]}),xt(Xe,{dimColor:!0,children:[" Achievements: ",t.progression.achievements?.length||0,"/",10]}),zt(Xe,{children:" "}),S.map((O,u)=>xt(ts,{children:[xt(Xe,{color:u===E?"yellow":void 0,bold:u===E,children:[u===E?" \u25B8 ":" ",O.label]}),xt(Xe,{dimColor:!0,children:[" ",O.desc]})]},O.key)),zt(Xe,{children:" "}),zt(Xe,{dimColor:!0,children:" \u2191\u2193 navigate Enter select q quit"})]})}import{useState as pt,useEffect as rs,useCallback as Nn,useRef as On}from"react";import{Box as Je,Text as q,useInput as Un}from"ink";import{jsx as te,jsxs as ye}from"react/jsx-runtime";var Vo={raider:"R",scout:"S",brute:"B"};function Yo(t,e){let o=t/e;return o>.6?"green":o>.3?"yellow":"red"}function Gn(t,e){let o=t/e;return o>.6?"white":o>.3?"yellow":"red"}function jo(t,e){let o=[];return t.gold>0&&o.push(`${e}${t.gold}${N.gold}`),t.wood>0&&o.push(`${e}${t.wood}${N.wood}`),t.stone>0&&o.push(`${e}${t.stone}${N.stone}`),o.join(" ")}function Wn(t,e,o=6){let s=Math.round(t/e*o);return"\u2588".repeat(s)+"\u2591".repeat(o-s)}var Kn={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"};function qo({replay:t,keepGrid:e,raidType:o,summary:s,initialSpeed:r,onSpeedChange:a,onDone:T}){let[m,i]=pt(0),[d,S]=pt(r??1),E=Nn(R=>{S(R),a?.(R)},[a]),[y,f]=pt(!1),[p,b]=pt(new Map),[c,B]=pt(()=>{let R=new Map,V={wall:so,archerTower:no,watchtower:ao,vault:po};for(let H of e.structures){let Se=V[H.kind];if(Se){let L=Se[H.level];R.set(H.id,{structureId:H.id,kind:H.kind,pos:{...H.pos},hp:L,maxHp:L,destroyed:!1})}}return R}),[Y,O]=pt([]),[u,G]=pt(new Set),[A,W]=pt([]),[x,g]=pt(null),P=On(-1);Un((R,V)=>{if(R==="q"||V.escape){T();return}if(R==="p"||R===" "){f(H=>!H);return}R==="1"&&E(1),R==="2"&&E(2),R==="4"&&E(4),R==="8"&&E(8),(R==="n"||V.return)&&i(t.maxTicks)}),rs(()=>{if(y||x)return;let R=setInterval(()=>{i(V=>{let H=V+1;return H>t.maxTicks?(clearInterval(R),V):H})},1e3/t.tickRateHz/d);return()=>clearInterval(R)},[y,d,x,t]),rs(()=>{if(m<=P.current)return;let R=t.events.filter(L=>L.t>P.current&&L.t<=m),V=[],H=[],Se=new Map;b(L=>{let z=new Map(L);for(let U of R)switch(U.type){case"raider_spawn":{let J=U.raiderType??"raider",Ee=U.maxHp??Le[J].hp;z.set(U.probeId,{id:U.probeId,pos:{...U.pos},alive:!0,stunned:!1,hp:Ee,maxHp:Ee,raiderType:J});break}case"raider_move":{let J=z.get(U.probeId);J&&(J.pos={...U.to},J.stunned=!1);break}case"raider_stunned":{let J=z.get(U.probeId);J&&(J.stunned=!0);break}case"arrow_hit":{let J=z.get(U.probeId);J&&(J.hp=Math.max(0,U.hpRemaining));break}case"raider_destroyed":{let J=z.get(U.probeId);J&&(J.alive=!1);break}default:break}return Se=z,z}),B(L=>{let z=new Map(L);for(let U of R)if(U.type==="wall_damaged"||U.type==="structure_damaged"){let J=z.get(U.structureId);J&&(J.hp=Math.max(0,U.hpRemaining),J.destroyed=U.destroyed)}return z});for(let L of R)switch(L.type){case"raider_spawn":{let z=L.raiderType??"raider",U=Vo[z]??"R",J=L.edge==="N"?"\u2193":L.edge==="S"?"\u2191":L.edge==="W"?"\u2192":"\u2190";V.push(`${U} Raider ${L.probeId+1} enters from ${L.edge} ${J}`),H.push({pos:{...L.pos},char:J,color:"yellowBright",bold:!0,expiresAtTick:m+3,priority:0});break}case"raider_stunned":{V.push(`\u26A1 Raider ${L.probeId+1} STUNNED ${L.stunTicks}t`),H.push({pos:{...L.pos},char:"\u2727",color:"cyanBright",bold:!0,expiresAtTick:m+3,priority:2});break}case"wall_damaged":{if(L.destroyed){V.push("\u{1F4A5} Wall DESTROYED!");let z=e.structures.find(U=>U.id===L.structureId);z&&H.push({pos:{...z.pos},char:"\u2717",color:"redBright",bold:!0,expiresAtTick:m+4,priority:2})}else V.push(`\u2694 Wall hit (${L.hpRemaining} HP)`);break}case"structure_damaged":{let z=ot[L.structureKind]??L.structureKind;if(L.destroyed){V.push(`\u{1F4A5} ${z} DESTROYED!`);let U=e.structures.find(J=>J.id===L.structureId);U&&H.push({pos:{...U.pos},char:"\u2717",color:"redBright",bold:!0,expiresAtTick:m+5,priority:3})}else V.push(`\u2694 ${z} hit (${L.hpRemaining} HP)`);break}case"arrow_hit":{let z=Se.get(L.probeId),U=z?{...z.pos}:null;U&&H.push({pos:U,char:"\u2020",color:"redBright",bold:!0,expiresAtTick:m+2,priority:1}),L.hpRemaining<=0?(V.push(`\u{1F3F9} Archer slew raider ${L.probeId+1}!`),U&&H.push({pos:U,char:"\u2716",color:"redBright",bold:!0,expiresAtTick:m+4,priority:3})):V.push(`\u{1F3F9} Arrow hit raider ${L.probeId+1} (-${L.damage} \u2192 ${L.hpRemaining} HP)`);break}case"treasury_breach":{let z=jo(L.lootTaken,""),U=o==="attack"?"Looted":"Lost";V.push(`\u{1F4B0} TREASURY BREACHED! ${U} ${z}`),G(Ee=>new Set([...Ee,L.structureId]));let J=e.structures.find(Ee=>Ee.id===L.structureId);J&&H.push({pos:{...J.pos},char:"\u26A1",color:"yellowBright",bold:!0,expiresAtTick:m+5,priority:3});break}case"raider_destroyed":{R.some(U=>U.type==="arrow_hit"&&U.probeId===L.probeId&&U.hpRemaining<=0&&U.t===L.t)||V.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!";g(z),V.push(z);break}default:break}O(L=>[...L.filter(z=>z.expiresAtTick>m),...H]),P.current=m,V.length>0&&W(L=>[...L.slice(-10),...V])},[m,o,t,e]);let C=new Map;for(let R of e.structures)C.set(`${R.pos.x},${R.pos.y}`,R);if(!e.structures.some(R=>R.kind==="treasury")){let R={id:"__virtual_center_treasury",kind:"treasury",pos:{x:8,y:8},level:1};C.set("8,8",R)}let w=new Map;for(let[,R]of p)R.alive&&w.set(`${R.pos.x},${R.pos.y}`,R);let X=new Map;for(let[,R]of c)X.set(`${R.pos.x},${R.pos.y}`,R);let oe=new Map;for(let R of Y){let V=`${R.pos.x},${R.pos.y}`,H=oe.get(V);(!H||R.priority>H.priority||R.priority===H.priority&&R.expiresAtTick>H.expiresAtTick)&&oe.set(V,R)}let ce=" "+Array.from({length:M},(R,V)=>V.toString(16).toUpperCase()+" ").join(""),Te=[te(q,{dimColor:!0,children:ce},"hdr")];for(let R=0;R<M;R++){let V=[te(q,{dimColor:!0,children:R.toString(16).toUpperCase()+" "},"lbl")];for(let H=0;H<M;H++){let Se=`${H},${R}`,L=w.get(Se),z=C.get(Se),U=X.get(Se),J=oe.get(Se);if(J&&!L)V.push(te(q,{color:J.color,bold:J.bold,children:J.char+" "},H));else if(L){let Ee=L.stunned?"\u25CA":Vo[L.raiderType]??"\u25CF",tt=L.stunned?"cyan":Yo(L.hp,L.maxHp);V.push(te(q,{color:tt,bold:!0,children:Ee+" "},H))}else if(z)if(U&&!U.destroyed){let Ee=Gn(U.hp,U.maxHp),tt=me[U.kind]??"#";V.push(te(q,{color:Ee,bold:U.hp>U.maxHp*.6,children:tt+" "},H))}else if(U&&U.destroyed)V.push(te(q,{color:"red",dimColor:!0,children:"x "},H));else if(u.has(z.id))V.push(te(q,{color:"red",bold:!0,children:"$ "},H));else{let Ee=me[z.kind];V.push(te(q,{color:Kn[z.kind]||"white",children:Ee+" "},H))}else V.push(te(q,{dimColor:!0,children:$t+" "},H))}Te.push(te(Je,{children:V},R))}let Tt=Array.from(p.values()).filter(R=>R.alive),wt=Array.from(p.values()).filter(R=>!R.alive);return ye(Je,{flexDirection:"column",padding:1,children:[ye(Je,{flexDirection:"row",gap:2,children:[te(q,{bold:!0,color:o==="defend"?"red":"green",children:o==="defend"?"\u2694 DEFENDING YOUR KEEP":"\u2694 ATTACKING NPC KEEP"}),ye(q,{children:["Tick: ",m,"/",t.maxTicks]}),ye(q,{children:["Speed: ",d,"x"]}),te(q,{dimColor:!0,children:y?"[PAUSED]":""})]}),te(q,{children:" "}),ye(Je,{flexDirection:"row",children:[te(Je,{flexDirection:"column",children:Te}),ye(Je,{flexDirection:"column",marginLeft:2,width:38,children:[Tt.length>0&&ye(Je,{flexDirection:"column",marginBottom:1,children:[te(q,{bold:!0,children:"Raiders"}),Tt.map(R=>ye(Je,{children:[ye(q,{color:Yo(R.hp,R.maxHp),bold:!0,children:[Vo[R.raiderType],R.id+1]}),te(q,{children:" "}),te(q,{color:Yo(R.hp,R.maxHp),children:Wn(R.hp,R.maxHp)}),ye(q,{dimColor:!0,children:[" ",R.hp,"/",R.maxHp]}),R.stunned&&te(q,{color:"cyan",children:" STUN"})]},R.id)),wt.length>0&&ye(q,{dimColor:!0,children:[" ",wt.length," slain"]})]}),te(q,{bold:!0,children:"Battle Log"}),(()=>{let R=A.slice(-10);return R.map((V,H)=>te(q,{dimColor:H<Math.max(0,R.length-3),wrap:"truncate",children:V},H))})()]})]}),te(q,{children:" "}),x?ye(Je,{flexDirection:"column",children:[te(q,{bold:!0,color:x.includes("VICTORY")||x.includes("SUCCESS")?"green":"red",children:x}),s&&ye(Je,{flexDirection:"column",marginTop:1,children:[te(q,{bold:!0,children:"\u2550\u2550\u2550 Raid Summary \u2550\u2550\u2550"}),ye(q,{children:["Difficulty: Lv.",s.difficulty," Raiders: ",s.raidersKilled,"/",s.raidersTotal," slain"]}),ye(q,{children:["Walls destroyed: ",s.wallsDestroyed," Archer towers: ",s.archersActive]}),s.lootGained.gold+s.lootGained.wood+s.lootGained.stone>0&&ye(q,{color:"green",children:["Resources gained: ",jo(s.lootGained,"+")]}),s.lootLost.gold+s.lootLost.wood+s.lootLost.stone>0&&ye(q,{color:"red",children:["Resources lost: ",jo(s.lootLost,"-")]})]}),te(q,{dimColor:!0,children:"Press q to return"})]}):ye(Je,{flexDirection:"column",children:[te(q,{dimColor:!0,children:"p pause 1/2/4/8 speed n/\u21B5 skip q back"}),ye(q,{dimColor:!0,children:[te(q,{color:"green",bold:!0,children:"R"}),"=Raider ",te(q,{color:"yellow",bold:!0,children:"S"}),"=Scout ",te(q,{color:"red",bold:!0,children:"B"}),"=Brute ",te(q,{color:"cyan",children:"\u25CA"}),"=Stunned ",te(q,{color:"red",children:"\u2716"}),"=Kill ",te(q,{color:"redBright",children:"\u2020"}),"=Arrow ",te(q,{color:"yellowBright",children:"\u2193\u2191\u2192\u2190"}),"=Spawn"]})]})]})}import{useState as Ut,useCallback as ss}from"react";import{Box as ho,Text as n,useInput as Hn}from"ink";import{Fragment as Ue,jsx as l,jsxs as I}from"react/jsx-runtime";var Zt=["welcome","resources","move","place_wall","place_treasury","place_archer","place_trap","upgrade_explain","first_raid","raid_result","foraging","tips","done"],ns={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"};function as({gameSave:t,onComplete:e}){let[o,s]=Ut("welcome"),[r,a]=Ut({x:7,y:7}),[T,m]=Ut([]),[i,d]=Ut([]),[S,E]=Ut(""),[y,f]=Ut(0),p=y>=4,b=Zt.indexOf(o),c=Zt.length-1,B=ss(()=>{let A=Zt.indexOf(o);A<Zt.length-1&&s(Zt[A+1])},[o]),Y=o==="place_wall"?"wall":o==="place_treasury"?"treasury":o==="place_archer"?"archerTower":o==="place_trap"?"trap":null,O=ss(()=>{let A={width:16,height:16,structures:[...T]},W=ut({probeCount:2,keepGrid:A,seed:"tutorial-raid",probeTypes:["raider","scout"]}),x=[],g=0,P=0,C=!1;for(let w of W.events)w.type==="raider_spawn"?x.push(` Raider ${w.probeId+1} appears from the ${w.edge} edge`):w.type==="wall_damaged"&&w.destroyed?(P++,x.push(" A stone wall was destroyed!")):w.type==="raider_stunned"?x.push(` Raider ${w.probeId+1} stepped on a bear trap \u2014 stunned!`):w.type==="arrow_hit"&&w.hpRemaining<=0?(g++,x.push(` Archer tower eliminated raider ${w.probeId+1}!`)):w.type==="raider_destroyed"&&!x[x.length-1]?.includes(`raider ${w.probeId+1}`)?(g++,x.push(` Raider ${w.probeId+1} was destroyed`)):w.type==="treasury_breach"?(C=!0,x.push(" Raiders breached your treasury!")):w.type==="raid_end"&&(w.outcome==="defense_win"?x.push(" \u2713 DEFENSE WIN \u2014 all raiders defeated!"):x.push(" \u2717 Raiders got through \u2014 time to strengthen defenses"));if(x.length>10){let w=[...x.slice(0,3),` ... ${x.length-6} more events ...`,...x.slice(-3)];d(w)}else d(x);let k=W.events.find(w=>w.type==="raid_end");E(k?.type==="raid_end"&&k.outcome==="defense_win"?"win":"loss"),B()},[T,B]);Hn((A,W)=>{if(A==="s"&&o!=="move"){e();return}if(["welcome","resources","move","upgrade_explain","first_raid","raid_result","foraging","tips","done"].includes(o)){if(o==="move"){if(A==="h"||A==="a"||W.leftArrow){a(g=>({...g,x:Math.max(0,g.x-1)})),f(g=>g+1);return}if(A==="l"||A==="d"||W.rightArrow){a(g=>({...g,x:Math.min(M-1,g.x+1)})),f(g=>g+1);return}if(A==="k"||A==="w"||W.upArrow){a(g=>({...g,y:Math.max(0,g.y-1)})),f(g=>g+1);return}if(A==="j"||W.downArrow){a(g=>({...g,y:Math.min(M-1,g.y+1)})),f(g=>g+1);return}if((W.return||A===" ")&&p){B();return}return}if(o==="first_raid"){O();return}if(o==="done"){e();return}(W.return||A===" ")&&B();return}if(Y){if(A==="h"||A==="a"||W.leftArrow)a(g=>({...g,x:Math.max(0,g.x-1)}));else if(A==="l"||A==="d"||W.rightArrow)a(g=>({...g,x:Math.min(M-1,g.x+1)}));else if(A==="k"||A==="w"||W.upArrow)a(g=>({...g,y:Math.max(0,g.y-1)}));else if(A==="j"||W.downArrow)a(g=>({...g,y:Math.min(M-1,g.y+1)}));else if(W.return||A==="e"){if(T.some(C=>C.pos.x===r.x&&C.pos.y===r.y))return;let P={id:`tut-${Y}-${r.x}-${r.y}`,kind:Y,level:1,pos:{...r},placedAtUnixMs:Date.now()};m(C=>[...C,P]),B()}}});let u=()=>{let g=new Map;for(let C of T)g.set(`${C.pos.x},${C.pos.y}`,C);let P=[];for(let C=3;C<13;C++){let k=[];for(let w=3;w<13;w++){let X=r.x===w&&r.y===C,oe=g.get(`${w},${C}`),ce=$t,Te;oe&&(ce=me[oe.kind],Te=ns[oe.kind]),X?k.push(l(n,{backgroundColor:"white",color:"black",bold:!0,children:ce+" "},w)):Te?k.push(l(n,{color:Te,bold:!0,children:ce+" "},w)):k.push(l(n,{dimColor:!0,children:ce+" "},w))}P.push(l(ho,{children:k},C))}return l(ho,{flexDirection:"column",children:P})},G=`[${b}/${c}]`;return I(ho,{flexDirection:"column",padding:1,children:[I(ho,{children:[l(n,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep \u2014 Tutorial "}),l(n,{dimColor:!0,children:G})]}),l(n,{children:" "}),o==="welcome"&&I(Ue,{children:[I(n,{bold:!0,color:"cyan",children:["Welcome to CodeKeep, ",t.player.displayName,"!"]}),l(n,{children:" "}),I(n,{children:["CodeKeep is a ",l(n,{bold:!0,children:"tower defense"})," game played in your terminal."]}),l(n,{children:" "}),I(n,{children:[" ","Build a ",l(n,{bold:!0,children:"fortress"})," on a 16\xD716 grid"]}),I(n,{children:[" ","Place ",l(n,{bold:!0,children:"walls"}),", ",l(n,{bold:!0,children:"traps"}),", and ",l(n,{bold:!0,children:"archer towers"})," to defend"]}),I(n,{children:[" ","Protect your ",l(n,{bold:!0,color:"yellow",children:"treasuries"})," from raiding parties"]}),I(n,{children:[" ","Earn resources over time and from coding activity"]}),l(n,{children:" "}),l(n,{children:"Let's learn how to play!"}),l(n,{children:" "}),l(n,{dimColor:!0,children:"Enter to continue \xB7 s to skip tutorial"})]}),o==="resources"&&I(Ue,{children:[l(n,{bold:!0,color:"cyan",children:"Resources"}),l(n,{children:" "}),l(n,{children:"You have three resources to build and upgrade structures:"}),l(n,{children:" "}),I(n,{children:[" ",I(n,{color:"yellow",bold:!0,children:[N.gold," Gold"]})," \u2014 Your main currency. Earned from events and raids."]}),I(n,{children:[" ",I(n,{color:"green",bold:!0,children:[N.wood," Wood"]})," \u2014 Building material. Earned from treasuries and events."]}),I(n,{children:[" ",I(n,{color:"white",bold:!0,children:[N.stone," Stone"]})," \u2014 Heavy material. Used for walls and towers."]}),l(n,{children:" "}),l(n,{children:"Resources grow passively and from coding activity (git commits!)."}),I(n,{children:["You can also press ",l(n,{bold:!0,children:"f"})," for a kingdom boon anytime."]}),l(n,{children:" "}),l(n,{dimColor:!0,children:"Enter to continue"})]}),o==="move"&&I(Ue,{children:[l(n,{bold:!0,color:"cyan",children:"Movement"}),l(n,{children:" "}),l(n,{children:"Move the cursor with:"}),I(n,{children:[" ",l(n,{bold:!0,children:"h j k l"})," (vim) \xB7 ",l(n,{bold:!0,children:"W A S D"})," \xB7 ",l(n,{bold:!0,children:"Arrow keys"})]}),l(n,{children:" "}),I(n,{children:["Try moving around \u2014 ",p?l(n,{color:"green",bold:!0,children:"Great! Press Enter to continue."}):l(n,{dimColor:!0,children:"move at least 4 times to proceed"})]}),l(n,{children:" "}),u()]}),o==="place_wall"&&I(Ue,{children:[I(n,{bold:!0,color:"cyan",children:["Build: Stone Wall ",l(n,{color:"white",children:"#"})]}),l(n,{children:" "}),I(n,{children:["Walls ",l(n,{bold:!0,children:"block raiders"})," and force them to find another path."]}),l(n,{children:"They have HP and will eventually break if attacked."}),l(n,{children:" "}),I(n,{children:["Move to an empty cell and press ",l(n,{bold:!0,children:"Enter"})," to place one."]}),l(n,{children:" "}),u(),l(n,{children:" "}),l(n,{dimColor:!0,children:"Move with h/j/k/l \xB7 place with Enter"})]}),o==="place_treasury"&&I(Ue,{children:[I(n,{bold:!0,color:"cyan",children:["Build: Treasury ",l(n,{color:"yellow",children:"$"})]}),l(n,{children:" "}),I(n,{children:["Treasuries are what ",l(n,{bold:!0,color:"red",children:"raiders target"}),"."]}),I(n,{children:["They also generate ",l(n,{bold:!0,children:"passive income"})," over time."]}),l(n,{children:"Place them in protected spots behind your walls!"}),l(n,{children:" "}),l(n,{children:"Place a treasury somewhere on the grid."}),l(n,{children:" "}),u(),l(n,{children:" "}),l(n,{dimColor:!0,children:"Move and press Enter to place"})]}),o==="place_archer"&&I(Ue,{children:[I(n,{bold:!0,color:"cyan",children:["Build: Archer Tower ",l(n,{color:"redBright",children:"!"})]}),l(n,{children:" "}),I(n,{children:["Archer towers ",l(n,{bold:!0,children:"shoot arrows"})," at raiders within range."]}),l(n,{children:"They fire automatically and can kill raiders before they reach your treasury."}),l(n,{children:"Place them where raiders will pass by!"}),l(n,{children:" "}),l(n,{children:"Place an archer tower on the grid."}),l(n,{children:" "}),u(),l(n,{children:" "}),l(n,{dimColor:!0,children:"Move and press Enter to place"})]}),o==="place_trap"&&I(Ue,{children:[I(n,{bold:!0,color:"cyan",children:["Build: Bear Trap ",l(n,{color:"magenta",children:"%"})]}),l(n,{children:" "}),I(n,{children:["Traps ",l(n,{bold:!0,children:"stun raiders"})," that walk over them."]}),l(n,{children:"A stunned raider can't move for several ticks \u2014 perfect for"}),l(n,{children:"your archer towers to finish them off!"}),l(n,{children:" "}),l(n,{children:"Place a bear trap on a path raiders might take."}),l(n,{children:" "}),u(),l(n,{children:" "}),l(n,{dimColor:!0,children:"Move and press Enter to place"})]}),o==="upgrade_explain"&&I(Ue,{children:[l(n,{bold:!0,color:"cyan",children:"Upgrading & More Structures"}),l(n,{children:" "}),l(n,{children:"In the full game you can:"}),l(n,{children:" "}),I(n,{children:[" ",l(n,{bold:!0,children:"u"})," Upgrade a structure (Lv.1 \u2192 2 \u2192 3) for better stats"]}),I(n,{children:[" ",l(n,{bold:!0,children:"x"})," Demolish a structure (get 50% refund)"]}),I(n,{children:[" ",l(n,{bold:!0,children:"1-6"})," Quick-select any structure type"]}),l(n,{children:" "}),l(n,{children:"Two structures you haven't placed yet:"}),l(n,{children:" "}),I(n,{children:[" ",l(n,{color:"cyan",bold:!0,children:me.ward})," ",ot.ward," \u2014 Place next to a treasury to ",l(n,{bold:!0,children:"reduce loot"})]}),l(n,{children:" raiders can steal. Wards protect a 1-tile radius around them."}),l(n,{children:" "}),I(n,{children:[" ",l(n,{color:"green",bold:!0,children:me.watchtower})," ",ot.watchtower," \u2014 ",l(n,{bold:!0,children:"Extends ward range"})," when adjacent."]}),l(n,{children:" Also auto-gathers forage nearby and earns passive stone."}),l(n,{children:" "}),l(n,{dimColor:!0,children:"Combo: Ward next to Treasury + Watchtower next to Ward = max protection!"}),l(n,{children:" "}),l(n,{dimColor:!0,children:"Enter to continue"})]}),o==="first_raid"&&I(Ue,{children:[l(n,{bold:!0,color:"cyan",children:"Your First Raid!"}),l(n,{children:" "}),l(n,{children:"Let's test your defenses. Two raiders will attack your layout:"}),l(n,{children:" "}),u(),l(n,{children:" "}),I(n,{children:[" You placed: ",T.map(A=>I(n,{children:[l(n,{color:ns[A.kind],bold:!0,children:me[A.kind]})," "]},A.id))]}),l(n,{children:" "}),l(n,{bold:!0,color:"yellow",children:"Press any key to simulate the raid!"})]}),o==="raid_result"&&I(Ue,{children:[l(n,{bold:!0,color:S==="win"?"green":"yellow",children:S==="win"?"Victory! Your defenses held!":"The raiders got through \u2014 but that's okay!"}),l(n,{children:" "}),l(n,{bold:!0,children:"Raid replay:"}),i.map((A,W)=>l(n,{color:A.includes("WIN")?"green":A.includes("eliminated")||A.includes("destroyed")?"cyan":A.includes("breached")||A.includes("through")?"red":A.includes("stunned")?"magenta":void 0,children:A},W)),l(n,{children:" "}),S!=="win"&&l(n,{dimColor:!0,children:"Don't worry \u2014 you'll have plenty of resources to build better defenses!"}),l(n,{children:" "}),l(n,{dimColor:!0,children:"Enter to continue"})]}),o==="foraging"&&I(Ue,{children:[l(n,{bold:!0,color:"cyan",children:"Foraging"}),l(n,{children:" "}),I(n,{children:["Glowing ",l(n,{color:"cyan",bold:!0,children:"~"})," fragments appear on your grid over time."]}),I(n,{children:["Move your cursor over one and press ",l(n,{bold:!0,children:"c"})," to collect resources!"]}),l(n,{children:" "}),I(n,{children:[" ",l(n,{color:"cyan",children:"~"})," Gold Nugget ",l(n,{color:"yellow",children:"~"})," Timber ",l(n,{color:"green",children:"~"})," Ore ",l(n,{color:"white",children:"~"})," Gem"]}),l(n,{children:" "}),l(n,{children:"Structure synergies:"}),I(n,{children:[" ",l(n,{color:"redBright",children:"!"})," Archer Towers increase spawn rate"]}),I(n,{children:[" ",l(n,{color:"yellow",children:"$"})," Treasuries boost yield when nearby"]}),I(n,{children:[" ",l(n,{color:"green",children:"^"})," Watchtowers auto-collect nearby fragments"]}),l(n,{children:" "}),l(n,{dimColor:!0,children:"Enter to continue"})]}),o==="tips"&&I(Ue,{children:[l(n,{bold:!0,color:"cyan",children:"Pro Tips"}),l(n,{children:" "}),I(n,{children:[" ",l(n,{bold:!0,children:"?"})," Full help screen (anytime)"]}),I(n,{children:[" ",l(n,{bold:!0,children:"1-6"})," Quick-select structures"]}),I(n,{children:[" ",l(n,{bold:!0,children:"Tab"})," Jump between your structures"]}),I(n,{children:[" ",l(n,{bold:!0,children:"r"})," Quick defend (instant raid result)"]}),I(n,{children:[" ",l(n,{bold:!0,children:"v"})," Watch replay of last defense"]}),I(n,{children:[" ",l(n,{bold:!0,children:"f"})," Kingdom boon (free resources)"]}),I(n,{children:[" ",l(n,{bold:!0,children:"Esc"})," Back to main menu"]}),l(n,{children:" "}),l(n,{bold:!0,children:"Strategy:"}),I(n,{children:[" \u2022 Place walls to create ",l(n,{bold:!0,children:"chokepoints"})]}),I(n,{children:[" \u2022 Put traps in the chokepoint so raiders get ",l(n,{bold:!0,children:"stunned"})]}),I(n,{children:[" \u2022 Put archer towers nearby to ",l(n,{bold:!0,children:"finish stunned raiders"})]}),I(n,{children:[" \u2022 Hide treasuries ",l(n,{bold:!0,children:"deep inside"})," your walls"]}),I(n,{children:[" \u2022 Place wards next to treasuries to ",l(n,{bold:!0,children:"reduce loot stolen"})]}),I(n,{children:[" \u2022 ",l(n,{bold:!0,children:"Hover over"})," towers/wards to see their ",l(n,{bold:!0,color:"red",children:"range overlay"})]}),l(n,{children:" "}),l(n,{dimColor:!0,children:"Enter to continue"})]}),o==="done"&&I(Ue,{children:[l(n,{bold:!0,color:"yellow",children:"You're ready to defend your keep!"}),l(n,{children:" "}),l(n,{children:"Your structures from the tutorial won't carry over \u2014 you start"}),l(n,{children:"with a clean grid and starting resources."}),l(n,{children:" "}),l(n,{children:"Go forth, build wisely, and may your walls hold strong!"}),l(n,{children:" "}),l(n,{dimColor:!0,children:"Press Enter to start playing"})]})]})}import{Box as is,Text as zo}from"ink";import{jsx as Yn,jsxs as To}from"react/jsx-runtime";var Fn={wall:"white",trap:"magenta",treasury:"yellow",ward:"cyan",watchtower:"green",archerTower:"redBright"};function Vn(t){let e=[];return t.gold>0&&e.push(`${N.gold}${t.gold}`),t.wood>0&&e.push(`${N.wood}${t.wood}`),t.stone>0&&e.push(`${N.stone}${t.stone}`),e.join(" ")}function ls({selected:t}){return To(is,{flexDirection:"column",children:[Yn(zo,{bold:!0,children:"Structures [ ]"}),dt.map((e,o)=>{let s=e===t,r=rt[e][1];return To(is,{children:[To(zo,{color:s?Fn[e]:void 0,bold:s,dimColor:!s,children:[s?"\u25B8":" "," ",o+1," ",me[e]," ",ot[e]]}),s&&To(zo,{dimColor:!0,children:[" ",Vn(r)]})]},e)})]})}import{useState as jn}from"react";import{Box as xo,Text as ft,useInput as qn}from"ink";import{jsx as Ct,jsxs as Gt}from"react/jsx-runtime";var Zo=[{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 ds({onSelectFriend:t,onBack:e}){let[o,s]=jn(0);return qn((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(Zo.length-1,T+1));else if(a.return){let T=Zo[o],m=go(T.seed,T.difficulty);m.name=`${T.name}'s Keep`,m.ownerPlayerId=T.name.toLowerCase(),t(m)}else(r==="q"||a.escape)&&e()}),Gt(xo,{flexDirection:"column",padding:1,children:[Ct(xo,{children:Ct(ft,{bold:!0,color:"cyan",children:"\u2694 Rival Keeps"})}),Ct(ft,{children:" "}),Ct(ft,{dimColor:!0,children:" Choose a rival lord's keep to raid for plunder."}),Ct(ft,{children:" "}),Zo.map((r,a)=>Gt(xo,{flexDirection:"column",children:[Gt(xo,{children:[Gt(ft,{color:a===o?"yellow":void 0,bold:a===o,children:[a===o?" \u25B8 ":" ",r.name]}),Gt(ft,{dimColor:!0,children:[" Lv.",r.difficulty]})]}),a===o&&Gt(ft,{dimColor:!0,children:[' "',r.tagline,'"']})]},r.name)),Ct(ft,{children:" "}),Ct(ft,{dimColor:!0,children:" \u2191\u2193 navigate Enter raid Esc back"})]})}import{useState as cs}from"react";import{Box as Xt,Text as we,useInput as zn}from"ink";import{Fragment as Qn,jsx as Be,jsxs as Qe}from"react/jsx-runtime";function Zn(t){let e=[];return t.gold>0&&e.push(`+${t.gold}${N.gold}`),t.wood>0&&e.push(`+${t.wood}${N.wood}`),t.stone>0&&e.push(`+${t.stone}${N.stone}`),e.join(" ")}function Xn(t){let e=[];return t.gold>0&&e.push(`-${t.gold}${N.gold}`),t.wood>0&&e.push(`-${t.wood}${N.wood}`),t.stone>0&&e.push(`-${t.stone}${N.stone}`),e.join(" ")}function us({gameSave:t,onBack:e,onWatchReplay:o}){let[s,r]=cs("raids"),[a,T]=cs(0),m=[...t.raidHistory].reverse().slice(0,15);zn((d,S)=>{if(d==="q"||S.escape){e();return}(S.tab||d==="t")&&r(E=>E==="raids"?"achievements":"raids"),s==="raids"&&m.length>0&&((d==="j"||S.downArrow)&&T(E=>Math.min(E+1,m.length-1)),(d==="k"||S.upArrow)&&T(E=>Math.max(E-1,0)),(S.return||d==="v")&&m[a]&&o&&o(m[a]))});let i=t.progression;return Qe(Xt,{flexDirection:"column",padding:1,children:[Qe(Xt,{gap:2,children:[Be(we,{bold:!0,color:s==="raids"?"yellow":void 0,underline:s==="raids",children:"Raid Log"}),Be(we,{bold:!0,color:s==="achievements"?"yellow":void 0,underline:s==="achievements",children:"Achievements"}),Be(we,{dimColor:!0,children:"(Tab to switch)"})]}),Be(we,{children:" "}),s==="raids"&&Qe(Xt,{flexDirection:"column",children:[Qe(we,{dimColor:!0,children:[" Total: ",i.totalRaidsWon,"W / ",i.totalRaidsLost,"L \xB7 Streak: ",i.currentWinStreak," (best ",i.bestWinStreak,")"]}),Be(we,{children:" "}),m.length===0?Be(we,{dimColor:!0,children:" No raids yet. Try Defend Keep or Attack NPC!"}):m.map((d,S)=>{let E=Jn(d.resolvedAtUnixMs),y=d.attackerId!==t.player.id,f=d.outcome==="defense_win"?y?"\u2713":"\u2717":y?"\u2717":"\u2713",p=(y?d.outcome==="defense_win":d.outcome!=="defense_win")?"green":"red",b=y?"DEF":"ATK",c=d.lootLost.gold+d.lootLost.wood+d.lootLost.stone>0?` ${Xn(d.lootLost)}`:"",B=d.lootGained.gold+d.lootGained.wood+d.lootGained.stone>0?` ${Zn(d.lootGained)}`:"",Y=S===a?">":" ";return Qe(we,{dimColor:S>4&&S!==a,bold:S===a,children:[Y," ",Be(we,{color:p,children:f})," ",b," ",d.outcome.replace("_"," "),c,B," ",Qe(we,{dimColor:!0,children:["(",E,")"]})]},d.id)}),m.length>0&&Qe(Qn,{children:[Be(we,{children:" "}),Be(we,{dimColor:!0,children:" j/k navigate \xB7 Enter/v watch replay"})]})]}),s==="achievements"&&Qe(Xt,{flexDirection:"column",children:[Qe(we,{dimColor:!0,children:[" ",i.achievements?.length||0," / ",Yt.length," earned"]}),Be(we,{children:" "}),Yt.map(d=>{let S=i.achievements?.includes(d.id);return Be(Xt,{children:Qe(we,{color:S?"green":void 0,dimColor:!S,children:[" ",S?"\u2605":"\u2606"," ",Be(we,{bold:S,children:d.name})," \u2014 ",d.desc,d.bonus&&S?Qe(we,{color:"yellow",children:[" (",d.bonus,")"]}):null]})},d.id)})]}),Be(we,{children:" "}),Be(we,{dimColor:!0,children:" Tab switch \xB7 Esc/q back"})]})}function Jn(t){let e=Date.now()-t;return e<6e4?"just now":e<36e5?`${Math.floor(e/6e4)}m ago`:e<864e5?`${Math.floor(e/36e5)}h ago`:`${Math.floor(e/864e5)}d ago`}import{useState as wo}from"react";import{Box as Ro,Text as ke,useInput as sa}from"ink";import{writeFileSync as ea,mkdirSync as ta,existsSync as oa}from"fs";import{join as ps}from"path";import{homedir as ra}from"os";var Xo=ps(ra(),".config","codekeep","crashes");function fs(t,e){oa(Xo)||ta(Xo,{recursive:!0});let o={timestamp:new Date().toISOString(),error:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,version:"0.1.0",nodeVersion:process.version,platform:process.platform,arch:process.arch,screen:e?.screen,gameState:e?.gameState},s=`crash-${Date.now()}.json`,r=ps(Xo,s);return ea(r,JSON.stringify(o,null,2),"utf-8"),r}function yo(t){let e=encodeURIComponent(`[Crash]: ${t.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`}),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
|
|
11
11
|
|
|
12
|
-
**Error:** ${
|
|
12
|
+
**Error:** ${e.error}
|
|
13
13
|
|
|
14
14
|
**Stack:**
|
|
15
15
|
\`\`\`
|
|
16
|
-
${
|
|
16
|
+
${e.stack??"N/A"}
|
|
17
17
|
\`\`\`
|
|
18
18
|
|
|
19
19
|
## Environment
|
|
20
|
-
- Version: ${
|
|
21
|
-
- Node: ${
|
|
22
|
-
- OS: ${
|
|
23
|
-
- Screen: ${
|
|
24
|
-
- Time: ${
|
|
25
|
-
`);return`https://github.com/tooyipjee/codekeep/issues/new?title=${
|
|
20
|
+
- Version: ${e.version}
|
|
21
|
+
- Node: ${e.nodeVersion}
|
|
22
|
+
- OS: ${e.platform} ${e.arch}
|
|
23
|
+
- Screen: ${e.screen??"unknown"}
|
|
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
26
|
Open this URL to report the bug:
|
|
27
|
-
${
|
|
27
|
+
${$}
|
|
28
28
|
|
|
29
|
-
`),S(!1),y("");return}if(b.backspace||b.delete){y(c=>c.slice(0,-1));return}p&&p.length===1&&y(c=>c+p);return}if(m){if(p==="y"||p==="Y"){e();return}i(!1);return}if(p==="q"||b.escape){t();return}if((p==="j"||p==="s"||b.downArrow)&&T(c=>Math.min(c+1,f.length-1)),(p==="k"||p==="w"||b.upArrow)&&T(c=>Math.max(c-1,0)),b.return){let c=f[a];c.key==="ascii"?r():c.key==="tutorial"?o():c.key==="report"?S(!0):c.key==="reset"?i(!0):c.key==="back"&&t()}}),mt(Ro,{flexDirection:"column",padding:1,children:[$e(ke,{bold:!0,color:"yellow",children:"\u25C6 Settings"}),$e(ke,{children:" "}),d?mt(Ro,{flexDirection:"column",children:[$e(ke,{bold:!0,color:"cyan",children:"Report a Bug"}),$e(ke,{children:"Describe the issue briefly:"}),mt(ke,{color:"cyan",children:[E,$e(ke,{dimColor:!0,children:"_"})]}),$e(ke,{children:" "}),$e(ke,{dimColor:!0,children:"Enter to generate GitHub issue URL \xB7 Esc cancel"})]}):m?mt(Ro,{flexDirection:"column",children:[$e(ke,{bold:!0,color:"red",children:"Are you sure you want to reset?"}),$e(ke,{children:"This will permanently delete your save file."}),$e(ke,{children:"All structures, resources, and achievements will be lost."}),$e(ke,{children:" "}),mt(ke,{bold:!0,children:["Press ",$e(ke,{color:"red",children:"Y"})," to confirm, any other key to cancel"]})]}):mt(na,{children:[f.map((p,b)=>mt(Ro,{children:[mt(ke,{color:b===a?"yellow":void 0,bold:b===a,children:[b===a?" \u25B8 ":" ",p.label]}),mt(ke,{dimColor:!0,children:[" ",p.desc]})]},p.key)),$e(ke,{children:" "}),$e(ke,{dimColor:!0,children:" \u2191\u2193 navigate \xB7 Enter select \xB7 Esc back"})]})]})}import aa from"react";import{Box as ia,Text as Ae}from"ink";import{Fragment as gs,jsx as Ge,jsxs as _t}from"react/jsx-runtime";var So=class extends aa.Component{constructor(e){super(e),this.state={error:null,crashFilePath:null,issueUrl:null}}static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e){try{let o=fs(e),s={timestamp:new Date().toISOString(),error:e.message,stack:e.stack,version:"0.1.0",nodeVersion:process.version,platform:process.platform,arch:process.arch},r=yo(s);this.setState({crashFilePath:o,issueUrl:r})}catch{}}render(){return this.state.error?_t(ia,{flexDirection:"column",padding:1,children:[Ge(Ae,{bold:!0,color:"red",children:"\u25C6 CodeKeep \u2014 Something went wrong"}),Ge(Ae,{children:" "}),Ge(Ae,{color:"red",children:this.state.error.message}),Ge(Ae,{children:" "}),Ge(Ae,{dimColor:!0,children:"Your save file is at:"}),_t(Ae,{children:[" ","~/.config/codekeep/game.json"]}),Ge(Ae,{children:" "}),this.state.crashFilePath&&_t(gs,{children:[Ge(Ae,{dimColor:!0,children:"Crash report saved to:"}),_t(Ae,{children:[" ",this.state.crashFilePath]}),Ge(Ae,{children:" "})]}),this.state.issueUrl&&_t(gs,{children:[Ge(Ae,{dimColor:!0,children:"Report this bug:"}),_t(Ae,{color:"cyan",children:[" ",this.state.issueUrl]}),Ge(Ae,{children:" "})]}),Ge(Ae,{dimColor:!0,children:"If the game won't start, try:"}),_t(Ae,{bold:!0,children:[" ","codekeep --tutorial"]}),Ge(Ae,{children:" "}),Ge(Ae,{dimColor:!0,children:"Press Ctrl+C to exit"})]}):this.props.children}};import{useState as la}from"react";import{Box as bo,Text as et,useInput as da}from"ink";import{jsx as yt,jsxs as Mt}from"react/jsx-runtime";var ca={copper:"white",iron:"gray",silver:"whiteBright",gold:"yellow",diamond:"cyan"},ua={copper:"\u25CB",iron:"\u25CF",silver:"\u25C6",gold:"\u2605",diamond:"\u25C8"};function hs({pvpProfile:t,targets:e,isSearching:o,onSearch:s,onAttack:r,onWarCamp:a,onLeaderboard:T,onBack:m}){let[i,d]=la(0),S=[{key:"search",label:"Find Opponent"},{key:"warcamp",label:"War Camp"},{key:"leaderboard",label:"Leaderboard"},...e.map((p,b)=>({key:`target-${b}`,label:`Attack ${p.displayName} (${p.trophies} trophies)`})),{key:"back",label:"Back"}];da((p,b)=>{if(b.upArrow||p==="k")d(c=>Math.max(0,c-1));else if(b.downArrow||p==="j")d(c=>Math.min(S.length-1,c+1));else if(b.return){let c=S[i];if(c.key==="search")s();else if(c.key==="warcamp")a();else if(c.key==="leaderboard")T();else if(c.key==="back")m();else if(c.key.startsWith("target-")){let B=parseInt(c.key.split("-")[1]),Y=e[B];Y&&r(Y)}}else(b.escape||p==="q")&&m()});let E=t?.league??"copper",y=ca[E]??"white",f=ua[E]??"\u25CB";return Mt(bo,{flexDirection:"column",padding:1,children:[yt(et,{bold:!0,color:"red",children:"\u2694 PVP ARENA"}),yt(et,{children:" "}),t&&Mt(bo,{flexDirection:"column",children:[Mt(bo,{flexDirection:"row",gap:2,children:[Mt(et,{color:y,bold:!0,children:[f," ",E.toUpperCase()," League"]}),Mt(et,{children:["Trophies: ",yt(et,{bold:!0,color:"yellow",children:t.trophies})]})]}),t.shieldExpiresAt&&t.shieldExpiresAt>Date.now()&&Mt(et,{color:"cyan",children:["Shield active (",Math.ceil((t.shieldExpiresAt-Date.now())/36e5),"h remaining)"]}),yt(et,{children:" "})]}),o&&yt(et,{color:"yellow",children:"Searching for opponents..."}),S.map((p,b)=>yt(bo,{children:Mt(et,{color:b===i?"yellow":void 0,bold:b===i,children:[b===i?" \u25B8 ":" ",p.label]})},p.key)),yt(et,{children:" "}),yt(et,{dimColor:!0,children:"\u2191\u2193 select Enter choose Esc back"})]})}import{useState as ko,useEffect as pa}from"react";import{Box as Jt,Text as We,useInput as fa}from"ink";import{jsx as gt,jsxs as ht}from"react/jsx-runtime";var Jo=[{type:"raider",name:"Raider",symbol:"R"},{type:"scout",name:"Scout",symbol:"S"},{type:"brute",name:"Brute",symbol:"B"}];function Ts(t){let e=Math.ceil(t/1e3),o=Math.floor(e/60),s=e%60;return`${o}:${String(s).padStart(2,"0")}`}function xs({warCamp:t,resources:e,onTrain:o,onBack:s}){let[r,a]=ko(0),[T,m]=ko(!1),[i,d]=ko(0),[S,E]=ko(Date.now());return pa(()=>{let y=setInterval(()=>E(Date.now()),1e3);return()=>clearInterval(y)},[]),fa((y,f)=>{if(T){f.upArrow||y==="k"?d(p=>Math.max(0,p-1)):f.downArrow||y==="j"?d(p=>Math.min(Jo.length-1,p+1)):f.return?(o(r,Jo[i].type),m(!1)):f.escape&&m(!1);return}f.upArrow||y==="k"?a(p=>Math.max(0,p-1)):f.downArrow||y==="j"?a(p=>Math.min(t.maxSlots-1,p+1)):f.return?t.slots[r]?.raiderType||m(!0):(f.escape||y==="q")&&s()}),ht(Jt,{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(Jt,{flexDirection:"row",gap:2,children:[ht(We,{children:["Gold: ",e.gold,N.gold]}),ht(We,{children:["Wood: ",e.wood,N.wood]}),ht(We,{children:["Stone: ",e.stone,N.stone]})]}),gt(We,{children:" "}),ht(We,{bold:!0,children:["Slots (",t.slots.filter(y=>y.raiderType).length,"/",t.maxSlots,")"]}),Array.from({length:t.maxSlots},(y,f)=>{let p=t.slots[f],b=r===f,c=p?.readyAtMs?p.readyAtMs<=S:!1,B=p?.readyAtMs?p.readyAtMs>S:!1,Y=B&&p?.readyAtMs?p.readyAtMs-S:0,O;return p?.raiderType?B?O=`${p.raiderType} training... ${Ts(Y)}`:c?O=`${p.raiderType} READY!`:O=`${p.raiderType}`:O="[ Empty ]",gt(Jt,{children:ht(We,{color:b?"yellow":void 0,bold:b,children:[b?" \u25B8 ":" ","Slot ",f+1,": ",O]})},f)}),T&&ht(Jt,{flexDirection:"column",marginTop:1,children:[gt(We,{bold:!0,color:"cyan",children:"Select raider type:"}),Jo.map((y,f)=>{let p=fo[y.type],b=br[y.type],c=Le[y.type],B=e.gold>=p.gold&&e.wood>=p.wood&&e.stone>=p.stone;return gt(Jt,{children:ht(We,{color:i===f?"yellow":B?void 0:"red",bold:i===f,children:[i===f?" \u25B8 ":" ",y.name," \u2014 HP:",c.hp," DMG:",c.damage," SPD:",c.speed," \u2014 ",p.gold,"g ",p.wood,"w ",p.stone,"s \u2014 ",Ts(b)]})},y.type)})]}),gt(We,{children:" "}),gt(We,{dimColor:!0,children:"\u2191\u2193 select Enter train Esc back"})]})}import{Box as vo,Text as Ne,useInput as ma}from"ink";import{jsx as Ke,jsxs as Qt}from"react/jsx-runtime";var ga={copper:"white",iron:"gray",silver:"whiteBright",gold:"yellow",diamond:"cyan"};function ys({entries:t,currentPlayerId:e,isLoading:o,onBack:s}){return ma((r,a)=>{(a.escape||r==="q")&&s()}),Qt(vo,{flexDirection:"column",padding:1,children:[Ke(Ne,{bold:!0,color:"yellow",children:"\u{1F3C6} LEADERBOARD"}),Ke(Ne,{children:" "}),o&&Ke(Ne,{color:"yellow",children:"Loading..."}),!o&&t.length===0&&Ke(Ne,{dimColor:!0,children:"No players on the leaderboard yet."}),!o&&t.length>0&&Qt(vo,{flexDirection:"column",children:[Qt(vo,{children:[Ke(Ne,{bold:!0,children:" # "}),Ke(Ne,{bold:!0,children:"Name "}),Ke(Ne,{bold:!0,children:"League "}),Ke(Ne,{bold:!0,children:"Trophies"})]}),t.map(r=>{let a=r.id===e,T=a?"green":void 0,m=ga[r.league]??"white";return Qt(vo,{children:[Qt(Ne,{color:T,bold:a,children:[String(r.rank).padStart(3," ")," "]}),Ke(Ne,{color:T,bold:a,children:(r.displayName||"Unknown").padEnd(20," ")}),Ke(Ne,{color:m,children:r.league.padEnd(10," ")}),Ke(Ne,{color:"yellow",bold:!0,children:r.trophies})]},r.id)})]}),Ke(Ne,{children:" "}),Ke(Ne,{dimColor:!0,children:"Esc/q back"})]})}import{useState as Qo}from"react";import{Box as Eo,Text as Ce,useInput as ha}from"ink";import{Fragment as Ta,jsx as De,jsxs as It}from"react/jsx-runtime";function ws({onLogin:t,onRegister:e,onPlayOffline:o,error:s,isLoading:r}){let[a,T]=Qo("menu"),[m,i]=Qo(""),[d,S]=Qo(0),E=[{key:"register",label:"Register (new player)"},{key:"login",label:"Login (with API key)"},{key:"offline",label:"Play Offline"}];return ha((y,f)=>{if(!r){if(a==="menu"){if(f.upArrow||y==="k")S(p=>Math.max(0,p-1));else if(f.downArrow||y==="j")S(p=>Math.min(E.length-1,p+1));else if(f.return){let p=E[d];p.key==="register"?T("register"):p.key==="login"?T("login"):p.key==="offline"&&o()}return}if(f.escape){T("menu"),i("");return}if(f.return&&m.length>0){a==="login"?t(m):a==="register"&&e(m),i("");return}if(f.backspace||f.delete){i(p=>p.slice(0,-1));return}y&&y.length===1&&i(p=>p+y)}}),It(Eo,{flexDirection:"column",padding:1,children:[De(Ce,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep Online"}),De(Ce,{children:" "}),s&&De(Ce,{color:"red",children:s}),r&&De(Ce,{color:"yellow",children:"Connecting..."}),a==="menu"&&!r&&It(Ta,{children:[E.map((y,f)=>De(Eo,{children:It(Ce,{color:f===d?"yellow":void 0,bold:f===d,children:[f===d?" \u25B8 ":" ",y.label]})},y.key)),De(Ce,{children:" "}),De(Ce,{dimColor:!0,children:"\u2191\u2193 navigate Enter select"})]}),a==="login"&&!r&&It(Eo,{flexDirection:"column",children:[De(Ce,{children:"Enter your API key:"}),It(Ce,{color:"cyan",children:[m,De(Ce,{dimColor:!0,children:"_"})]}),De(Ce,{children:" "}),De(Ce,{dimColor:!0,children:"Enter to submit Esc back"})]}),a==="register"&&!r&&It(Eo,{flexDirection:"column",children:[De(Ce,{children:"Choose a display name:"}),It(Ce,{color:"cyan",children:[m,De(Ce,{dimColor:!0,children:"_"})]}),De(Ce,{children:" "}),De(Ce,{dimColor:!0,children:"Enter to submit Esc back"})]})]})}import{useState as Pt}from"react";import{Box as je,Text as F,useInput as xa}from"ink";import{jsx as Z,jsxs as ve}from"react/jsx-runtime";var Rs={N:"North",S:"South",E:"East",W:"West"},Wt={raider:"R",scout:"S",brute:"B"},Ao={raider:"red",scout:"cyan",brute:"magenta"},Ss=8;function bs(t,e){switch(t){case"N":return{x:e,y:0};case"S":return{x:e,y:M-1};case"E":return{x:M-1,y:e};case"W":return{x:0,y:e}}}function ks({targetName:t,targetTrophies:e,targetGrid:o,warCamp:s,resources:r,onLaunch:a,onBack:T}){let[m,i]=Pt("scout"),[d,S]=Pt([]),[E,y]=Pt(0),[f,p]=Pt([]),[b,c]=Pt("N"),[B,Y]=Pt(Math.floor(M/2)),[O,u]=Pt(0),G=["raider","scout","brute"];xa((x,g)=>{if(g.escape||x==="q"){if(m==="scout"){T();return}if(m==="army"){i("scout");return}if(m==="deploy"){i("army");return}if(m==="confirm"){i("deploy");return}return}if(m==="scout"){g.return&&i("army");return}if(m==="army"){g.upArrow||x==="k"?y(P=>Math.max(0,P-1)):g.downArrow||x==="j"?y(P=>Math.min(G.length-1,P+1)):g.return?d.length<Ss&&S(P=>[...P,G[E]]):g.backspace||g.delete?S(P=>P.slice(0,-1)):(x==="n"||g.tab)&&d.length>0&&(p(d.map(()=>({edge:"N",offset:Math.floor(M/2)}))),u(0),i("deploy"));return}if(m==="deploy"){g.leftArrow||x==="a"?Y(b==="E"||b==="W"?P=>Math.max(0,P-1):P=>Math.max(0,P-1)):g.rightArrow||x==="d"?Y(P=>Math.min(M-1,P+1)):g.upArrow||x==="w"?Y(P=>Math.max(0,P-1)):g.downArrow||x==="s"?Y(P=>Math.min(M-1,P+1)):x==="n"?c("N"):x==="e"?c("E"):x==="z"?c("S"):x==="x"?c("W"):g.return?(p(P=>{let C=[...P];return C[O]={edge:b,offset:B},C}),O<d.length-1?u(P=>P+1):i("confirm")):g.tab&&u(P=>(P+1)%d.length);return}if(m==="confirm"){if(g.return||x==="y"){let P=d.map((C,k)=>({raiderType:C,edge:f[k]?.edge??"N",offset:f[k]?.offset??8,waveDelay:0}));a(P)}return}});let W=(()=>{let x=Array.from({length:M},()=>Array(M).fill("\xB7"));for(let C of o.structures)C.kind==="trap"||C.kind==="ward"?x[C.pos.y][C.pos.x]="?":x[C.pos.y][C.pos.x]=me[C.kind];if(m==="deploy"||m==="confirm"){for(let C=0;C<f.length;C++){let k=f[C];if(!k)continue;let w=bs(k.edge,k.offset);x[w.y][w.x]=Wt[d[C]]}if(m==="deploy"){let C=bs(b,B);x[C.y][C.x]="\u25BC"}}let g=" "+Array.from({length:M},(C,k)=>k.toString(16).toUpperCase()).join(" "),P=x.map((C,k)=>{let w=k.toString(16).toUpperCase(),X=C.join(" ");return`${w} ${X}`});return[g,...P]})();return ve(je,{flexDirection:"column",padding:1,children:[Z(F,{bold:!0,color:"red",children:"\u2694 RAID PLANNER"}),ve(je,{gap:2,children:[ve(F,{children:["Target: ",Z(F,{bold:!0,color:"yellow",children:t})]}),ve(F,{children:["Trophies: ",Z(F,{bold:!0,children:e})]})]}),Z(F,{children:" "}),Z(je,{flexDirection:"column",children:W.map((x,g)=>g===0?Z(F,{dimColor:!0,children:x},g):Z(F,{children:x},g))}),Z(F,{children:" "}),Z(je,{gap:2,children:Z(F,{dimColor:!0,children:"# wall $ treasury ^ tower ! archer & vault ? hidden"})}),Z(F,{children:" "}),m==="scout"&&ve(je,{flexDirection:"column",children:[Z(F,{bold:!0,color:"cyan",children:"SCOUT PHASE"}),Z(F,{children:"Study the enemy keep. Traps and wards are hidden (?)."}),ve(F,{children:["Structures: ",o.structures.length," placed"]}),Z(F,{children:" "}),Z(F,{dimColor:!0,children:"Enter \u2192 pick your army Esc \u2192 back"})]}),m==="army"&&ve(je,{flexDirection:"column",children:[ve(F,{bold:!0,color:"cyan",children:["ARMY SELECTION (",d.length,"/",Ss,")"]}),Z(F,{children:" "}),G.map((x,g)=>{let P=Le[x],C=fo[x];return Z(je,{children:ve(F,{color:E===g?"yellow":void 0,bold:E===g,children:[E===g?" \u25B8 ":" ",Z(F,{color:Ao[x],children:Wt[x]})," ",x.charAt(0).toUpperCase()+x.slice(1)," ","HP:",P.hp," DMG:",P.damage," SPD:",P.speed," ","(",C.gold,"g ",C.wood,"w ",C.stone,"s)"]})},x)}),Z(F,{children:" "}),ve(je,{gap:1,children:[Z(F,{children:"Army: "}),d.length===0?Z(F,{dimColor:!0,children:"(empty)"}):d.map((x,g)=>Z(F,{color:Ao[x],bold:!0,children:Wt[x]},g))]}),Z(F,{children:" "}),Z(F,{dimColor:!0,children:"Enter add Backspace remove Tab/N \u2192 deploy Esc back"})]}),m==="deploy"&&ve(je,{flexDirection:"column",children:[ve(F,{bold:!0,color:"cyan",children:["DEPLOY \u2014 Placing ",Wt[d[O]]," (",d[O],") [",O+1,"/",d.length,"]"]}),ve(F,{children:["Edge: ",Z(F,{bold:!0,color:"yellow",children:Rs[b]})," Position: ",Z(F,{bold:!0,children:B.toString(16).toUpperCase()})]}),Z(F,{children:" "}),ve(je,{gap:1,children:[Z(F,{children:"Spawns: "}),d.map((x,g)=>{let P=f[g],C=g<O||g===O&&!1;return ve(F,{color:g===O?"yellow":C?Ao[x]:"gray",children:[Wt[x],P?`@${P.edge}${P.offset.toString(16)}`:"",g<d.length-1?" ":""]},g)})]}),Z(F,{children:" "}),Z(F,{dimColor:!0,children:"\u2190\u2192 / \u2191\u2193 position N/E/Z/X edge Enter place Tab next Esc back"})]}),m==="confirm"&&ve(je,{flexDirection:"column",children:[Z(F,{bold:!0,color:"green",children:"READY TO ATTACK"}),Z(F,{children:" "}),Z(je,{flexDirection:"column",children:d.map((x,g)=>{let P=f[g];return ve(F,{children:[Z(F,{color:Ao[x],bold:!0,children:Wt[x]})," ",x," \u2192 ",P?`${Rs[P.edge]} edge, pos ${P.offset.toString(16).toUpperCase()}`:"unplaced"]},g)})}),Z(F,{children:" "}),ve(F,{bold:!0,children:["Press ",Z(F,{color:"green",children:"Enter"})," to launch raid or ",Z(F,{color:"red",children:"Esc"})," to adjust"]})]})]})}import{useState as st,useEffect as Co,useCallback as he,useRef as Ht}from"react";import{useEffect as Ra,useRef as Es,useCallback as Sa}from"react";import{existsSync as As,statSync as Cs,openSync as ba,readSync as ka,closeSync as va,watch as Ea}from"fs";import{existsSync as dd,mkdirSync as cd,readFileSync as ud,writeFileSync as pd,unlinkSync as fd}from"fs";import{join as vs}from"path";import{homedir as ya}from"os";var wa=vs(ya(),".config","codekeep"),Dt=vs(wa,"events.jsonl");var Aa=2e3;function _s(t){let e=Es(0),o=Es(t);o.current=t;let s=Sa(()=>{if(!As(Dt))return;let r;try{r=Cs(Dt).size}catch{return}if(r<e.current&&(e.current=0),r<=e.current)return;let a,T;try{let i=Buffer.alloc(r-e.current);T=ba(Dt,"r"),ka(T,i,0,i.length,e.current),a=i.toString("utf-8")}catch{return}finally{T!==void 0&&va(T)}e.current=r;let m=a.split(`
|
|
30
|
-
`).filter(Boolean);for(let i of m)try{let d=JSON.parse(i);o.current(d)}catch{}},[]);Ra(()=>{if(As(Dt))try{e.current=Cs(Dt).size}catch{e.current=0}let r=null;try{r=Ea(Dt,()=>s())}catch{}let a=setInterval(s,Aa);return()=>{clearInterval(a),r?.close()}},[s])}function eo(t){return t<=2?1:t<=5?2:t<=9?3:t<=14?4:5}function to(t,e,o){let s=[];for(let r=0;r<t;r++)e>=3&&o()<.2?s.push("brute"):e>=2&&o()<.3?s.push("scout"):s.push("raider");return s}function Kt(t){let e=t|0;return()=>{e=e+1831565813|0;let o=Math.imul(e^e>>>15,1|e);return o=o+Math.imul(o^o>>>7,61|o)^o,((o^o>>>14)>>>0)/4294967296}}function Ms(t){let e=t.progression;return{...t,progression:{...e,totalRaidsWon:e.totalRaidsWon??0,totalRaidsLost:e.totalRaidsLost??0,totalStructuresPlaced:e.totalStructuresPlaced??0,currentWinStreak:e.currentWinStreak??0,bestWinStreak:e.bestWinStreak??0,achievements:e.achievements??[],totalRaidersKilledByArcher:e.totalRaidersKilledByArcher??e.totalProbesKilledByScanner??0}}}var Ca={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 er(t){return Ca[t]??null}function tr(t){let e=t.progression,o=new Set(e.achievements),s=[],r=(T,m)=>{!o.has(T)&&m&&s.push(T)};r("first_structure",e.totalStructuresPlaced>=1),r("defense_win_5",e.totalRaidsWon>=5),r("win_streak_3",e.bestWinStreak>=3),r("win_streak_5",e.bestWinStreak>=5),r("structures_20",e.totalStructuresPlaced>=20),r("raids_10",e.totalRaidsWon+e.totalRaidsLost>=10),r("archer_kills_10",e.totalRaidersKilledByArcher>=10),r("hoarder",t.keep.resources.gold+t.keep.resources.wood+t.keep.resources.stone>=500);let a=new Set(t.keep.grid.structures.map(T=>T.kind));return r("all_types",a.size>=dt.length),r("max_level",t.keep.grid.structures.some(T=>T.level===3)),s}function Is(t,e){if(e<=Nt)return t;let o=Math.pow(Tr,Math.floor((e-Nt)/Nt)+1);return{gold:Math.max(1,Math.floor(t.gold*o)),wood:Math.max(1,Math.floor(t.wood*o)),stone:Math.max(1,Math.floor(t.stone*o))}}var Ps=5e3,or=6e4;function _a(t,e){if(t.keep.grid.structures.length<3)return{save:t,results:[]};let o=Math.min(Math.floor(e/Vt),hr);if(o===0)return{save:t,results:[]};let s=[],r=t;for(let a=0;a<o;a++){let T=r.progression.totalRaidsWon+r.progression.totalRaidsLost,m=eo(T),i=`bg-${r.lastPlayedAtUnixMs}-${a}`,d=3+m,S=Kt(r.lastPlayedAtUnixMs+a),E=to(d,m,S),y=ut({probeCount:d,keepGrid:r.keep.grid,seed:i,probeTypes:E}),f=y.events[y.events.length-1];if(f?.type!=="raid_end")continue;let p=f.outcome==="defense_win",b=y.events.filter(A=>A.type==="treasury_breach").reduce((A,W)=>({gold:A.gold+W.lootTaken.gold,wood:A.wood+W.lootTaken.wood,stone:A.stone+W.lootTaken.stone}),{gold:0,wood:0,stone:0}),c=y.events.filter(A=>A.type==="arrow_hit"&&A.hpRemaining<=0).length,B=p?{gold:10+m*3,wood:5+m*2,stone:5+m*2}:{gold:0,wood:0,stone:0},Y={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)},O=ct(Ve(Y,B)),u=p?r.progression.currentWinStreak+1:0,G={id:i,seed:i,rulesVersion:1,attackerId:"npc-bg",defenderKeepId:r.keep.id,startedAtUnixMs:r.lastPlayedAtUnixMs+a*Vt,resolvedAtUnixMs:r.lastPlayedAtUnixMs+(a+1)*Vt,outcome:f.outcome,lootLost:b,lootGained:B,replay:y};r={...r,keep:{...r.keep,resources:O},raidHistory:[...r.raidHistory.slice(-19),G],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:B,difficulty:m})}return{save:r,results:s}}function Ds(t){let[e,o]=st(null),[s,r]=st({x:8,y:8}),[a,T]=st(0),[m,i]=st(""),[d,S]=st(null),[E,y]=st(null),[f,p]=st(null),[b,c]=st(null),[B,Y]=st(null),[O,u]=st([]),G=Ht(null),A=Ht(0),W=Ht(0),x=Ht(null),g=Ht(null),P=Ht(null),C=dt[a];_s(h=>{o(v=>{if(!v)return v;let $=Uo(v.keep,h),j={...v,keep:$,lastPlayedAtUnixMs:Date.now()};return At(j),j})}),Co(()=>{let h=qt();h||(h=qr(process.env.USER||process.env.USERNAME||"Keeper")),h=Ms(h),h.lastPlayedAtUnixMs||(h={...h,lastPlayedAtUnixMs:h.savedAtUnixMs||Date.now()});let v=Date.now()-h.lastPlayedAtUnixMs,$={gold:0,wood:0,stone:0},j=[];if(v>or&&h.keep.grid.structures.length>0&&($=Go(h.keep.grid,v),($.gold>0||$.wood>0||$.stone>0)&&(h={...h,keep:{...h.keep,resources:ct(Ve(h.keep.resources,$))}})),v>Vt){let re=_a(h,v);h=re.save,j=re.results}let ee=tr(h);if(ee.length>0){h={...h,progression:{...h.progression,achievements:[...h.progression.achievements,...ee]}};for(let re of ee){let fe=er(re);fe&&(h={...h,keep:{...h.keep,resources:Ve(h.keep.resources,fe)}})}}($.gold>0||$.wood>0||$.stone>0||j.length>0||ee.length>0)&&Y({resources:$,raids:j,newAchievements:ee}),h={...h,lastPlayedAtUnixMs:Date.now()},t&&(h={...h,tutorialCompleted:!1}),o(h),At(h)},[]),Co(()=>(x.current=setInterval(()=>{o(h=>{if(!h||h.keep.grid.structures.length===0)return h;let v=Go(h.keep.grid,or);if(v.gold===0&&v.wood===0&&v.stone===0)return h;let $={...h,keep:{...h.keep,resources:ct(Ve(h.keep.resources,v))},lastPlayedAtUnixMs:Date.now()};return At($),$})},or),()=>{x.current&&clearInterval(x.current)}),[]),Co(()=>(g.current=setInterval(()=>{u(h=>{if(!e)return h;let v=Kt(Date.now()),$=Yr(h,Date.now());return Fr($,e.keep.grid,Date.now(),v)})},xr),()=>{g.current&&clearInterval(g.current)}),[e]),Co(()=>()=>{G.current&&clearTimeout(G.current)},[]);let k=he(h=>{let v=tr(h),$={...h,lastPlayedAtUnixMs:Date.now()};if(v.length>0){$={...$,progression:{...$.progression,achievements:[...$.progression.achievements,...v]}};for(let j of v){let ee=er(j);ee&&($={...$,keep:{...$.keep,resources:Ve($.keep.resources,ee)}})}}if(o($),At($),v.length>0){let j=v.map(ee=>Yt.find(be=>be.id===ee)?.name||ee);w(`\u{1F3C6} ${j.join(", ")}!`)}},[]),w=he(h=>{G.current&&clearTimeout(G.current),i(h),G.current=setTimeout(()=>{i(""),G.current=null},3e3)},[]),X=he((h,v)=>{r($=>({x:Math.max(0,Math.min(M-1,$.x+h)),y:Math.max(0,Math.min(M-1,$.y+v))}))},[]),oe=he(h=>{T(v=>{let $=v+h;return $<0?dt.length-1:$>=dt.length?0:$})},[]),ce=he(h=>{h>=0&&h<dt.length&&T(h)},[]),Te=he(()=>{if(!e)return;let h=Dr(e.keep,s,C);if(h.ok&&h.keep){let v={...e,keep:h.keep,progression:{...e.progression,totalStructuresPlaced:e.progression.totalStructuresPlaced+1}};k(v),w(`Placed ${C}`)}else w(`!${h.reason}`)},[e,s,C,k,w]),Tt=he(()=>{if(!e)return;let h=Lr(e.keep,s);h.ok&&h.keep?(k({...e,keep:h.keep}),w("Upgraded!")):w(`!${h.reason}`)},[e,s,k,w]),wt=he(()=>{if(!e)return;let h=Br(e.keep,s);h.ok&&h.keep?(k({...e,keep:h.keep}),w("Demolished (50% refund)")):w(`!${h.reason}`)},[e,s,k,w]),oo=he(()=>{if(!e)return;let h=e.progression.totalRaidsWon+e.progression.totalRaidsLost,v=eo(h),$=`attack-${Date.now()}-${Math.random()}`,j=go($,v),ee=3+v,be=Kt(Date.now()),re=to(ee,v,be),fe=ut({probeCount:ee,keepGrid:j.grid,seed:$,probeTypes:re});S(fe),y(j.grid),p("attack");let se=fe.events[fe.events.length-1];if(se?.type==="raid_end"){let ue=se.outcome!=="defense_win",He=fe.events.filter(xe=>xe.type==="treasury_breach").reduce((xe,it)=>({gold:xe.gold+it.lootTaken.gold,wood:xe.wood+it.lootTaken.wood,stone:xe.stone+it.lootTaken.stone}),{gold:0,wood:0,stone:0}),Oe=fe.events.filter(xe=>xe.type==="raider_destroyed").length,Rt=fe.events.filter(xe=>xe.type==="wall_damaged"&&xe.destroyed).length;c({won:ue,raidType:"attack",outcome:se.outcome,lootGained:He,lootLost:{gold:0,wood:0,stone:0},raidersKilled:Oe,raidersTotal:ee,wallsDestroyed:Rt,archersActive:j.grid.structures.filter(xe=>xe.kind==="archerTower").length,difficulty:v});let nt=ue?ct(Ve(e.keep.resources,He)):e.keep.resources,at=ue?e.progression.currentWinStreak+1:0,St={id:$,seed:$,rulesVersion:1,attackerId:e.player.id,defenderKeepId:j.id,startedAtUnixMs:Date.now(),resolvedAtUnixMs:Date.now(),outcome:se.outcome,lootLost:{gold:0,wood:0,stone:0},lootGained:ue?He:{gold:0,wood:0,stone:0},replay:fe,defenderGrid:j.grid};k({...e,keep:{...e.keep,resources:nt},raidHistory:[...e.raidHistory.slice(-19),St],progression:{...e.progression,totalRaidsWon:e.progression.totalRaidsWon+(ue?1:0),totalRaidsLost:e.progression.totalRaidsLost+(ue?0:1),currentWinStreak:at,bestWinStreak:Math.max(e.progression.bestWinStreak,at)}})}},[e,k]),R=he(()=>{if(!e)return;let h=e.progression.totalRaidsWon+e.progression.totalRaidsLost,v=eo(h),$=`defend-${Date.now()}-${Math.random()}`,j=3+v,ee=Kt(Date.now()),be=to(j,v,ee),re=ut({probeCount:j,keepGrid:e.keep.grid,seed:$,probeTypes:be});S(re),y(e.keep.grid),p("defend");let fe=re.events[re.events.length-1];if(fe?.type==="raid_end"){let se=fe.outcome==="defense_win",ue=re.events.filter(Q=>Q.type==="treasury_breach").reduce((Q,lt)=>({gold:Q.gold+lt.lootTaken.gold,wood:Q.wood+lt.lootTaken.wood,stone:Q.stone+lt.lootTaken.stone}),{gold:0,wood:0,stone:0}),He=re.events.filter(Q=>Q.type==="raider_destroyed").length,Oe=re.events.filter(Q=>Q.type==="wall_damaged"&&Q.destroyed).length,Rt=re.events.filter(Q=>Q.type==="arrow_hit"&&Q.hpRemaining<=0).length,nt=se?{gold:10+v*3,wood:5+v*2,stone:5+v*2}:{gold:0,wood:0,stone:0};c({won:se,raidType:"defend",outcome:fe.outcome,lootGained:nt,lootLost:ue,raidersKilled:He,raidersTotal:j,wallsDestroyed:Oe,archersActive:e.keep.grid.structures.filter(Q=>Q.kind==="archerTower").length,difficulty:v});let at={gold:Math.max(0,e.keep.resources.gold-ue.gold),wood:Math.max(0,e.keep.resources.wood-ue.wood),stone:Math.max(0,e.keep.resources.stone-ue.stone)},St=ct(Ve(at,nt)),xe=se?e.progression.currentWinStreak+1:0,it={id:$,seed:$,rulesVersion:1,attackerId:"npc",defenderKeepId:e.keep.id,startedAtUnixMs:Date.now(),resolvedAtUnixMs:Date.now(),outcome:fe.outcome,lootLost:ue,lootGained:nt,replay:re};k({...e,keep:{...e.keep,resources:St},raidHistory:[...e.raidHistory.slice(-19),it],progression:{...e.progression,totalRaidsWon:e.progression.totalRaidsWon+(se?1:0),totalRaidsLost:e.progression.totalRaidsLost+(se?0:1),currentWinStreak:xe,bestWinStreak:Math.max(e.progression.bestWinStreak,xe),totalRaidersKilledByArcher:e.progression.totalRaidersKilledByArcher+Rt}})}},[e,k]),V=he(()=>{if(!e)return;let h=e.progression.totalRaidsWon+e.progression.totalRaidsLost,v=eo(h),$=`quick-${Date.now()}-${Math.random()}`,j=3+v,ee=Kt(Date.now()),be=to(j,v,ee),re=ut({probeCount:j,keepGrid:e.keep.grid,seed:$,probeTypes:be}),fe=re.events[re.events.length-1];if(fe?.type==="raid_end"){let se=fe.outcome==="defense_win",ue=re.events.filter(Q=>Q.type==="treasury_breach").reduce((Q,lt)=>({gold:Q.gold+lt.lootTaken.gold,wood:Q.wood+lt.lootTaken.wood,stone:Q.stone+lt.lootTaken.stone}),{gold:0,wood:0,stone:0}),He=re.events.filter(Q=>Q.type==="arrow_hit"&&Q.hpRemaining<=0).length,Oe=se?{gold:10+v*3,wood:5+v*2,stone:5+v*2}:{gold:0,wood:0,stone:0},Rt={gold:Math.max(0,e.keep.resources.gold-ue.gold),wood:Math.max(0,e.keep.resources.wood-ue.wood),stone:Math.max(0,e.keep.resources.stone-ue.stone)},nt=ct(Ve(Rt,Oe)),at=se?e.progression.currentWinStreak+1:0,St={id:$,seed:$,rulesVersion:1,attackerId:"npc",defenderKeepId:e.keep.id,startedAtUnixMs:Date.now(),resolvedAtUnixMs:Date.now(),outcome:fe.outcome,lootLost:ue,lootGained:Oe,replay:re};k({...e,keep:{...e.keep,resources:nt},raidHistory:[...e.raidHistory.slice(-19),St],progression:{...e.progression,totalRaidsWon:e.progression.totalRaidsWon+(se?1:0),totalRaidsLost:e.progression.totalRaidsLost+(se?0:1),currentWinStreak:at,bestWinStreak:Math.max(e.progression.bestWinStreak,at),totalRaidersKilledByArcher:e.progression.totalRaidersKilledByArcher+He}});let xe=re.events.filter(Q=>Q.type==="raider_destroyed").length,it=re.events.filter(Q=>Q.type==="wall_damaged"&&Q.destroyed).length;if(P.current={replay:re,grid:e.keep.grid,summary:{won:se,raidType:"defend",outcome:fe.outcome,lootGained:Oe,lootLost:ue,raidersKilled:xe,raidersTotal:j,wallsDestroyed:it,archersActive:e.keep.grid.structures.filter(Q=>Q.kind==="archerTower").length,difficulty:v}},se)w(`Defense WIN! +${Oe.gold}${N.gold} +${Oe.wood}${N.wood} +${Oe.stone}${N.stone} [v] view`);else{let Q=ue.gold+ue.wood+ue.stone;w(`Defense BREACH! Lost ${Q} res [v] view`)}}},[e,k,w]),H=he(()=>{let h=P.current;return h?(S(h.replay),y(h.grid),p("defend"),c(h.summary),P.current=null,!0):!1},[]),Se=he(()=>{if(!e)return;let h=Vr(O,s,e.keep.grid);if(!h){w("!Nothing to collect here");return}u(h.updatedFragments);let v=h.yield,$={...e,keep:{...e.keep,resources:ct(Ve(e.keep.resources,v))}};k($);let j=[];v.gold>0&&j.push(`+${v.gold}${N.gold}`),v.wood>0&&j.push(`+${v.wood}${N.wood}`),v.stone>0&&j.push(`+${v.stone}${N.stone}`);let ee=h.collected[0]?.type.replace("_"," ")??"fragment",be=h.collected.length>1?` (${h.collected.length}x)`:"";w(`${j.join(" ")} ${ee}${be}`)},[e,O,s,k,w]),L=he(h=>{if(!e)return!1;let v=h.attackerId!==e.player.id;return S(h.replay),y(v?e.keep.grid:h.defenderGrid??e.keep.grid),p(v?"defend":"attack"),c(null),!0},[e]),z=he(()=>{S(null),y(null),p(null),c(null)},[]),U=he(()=>{e&&k({...e,tutorialCompleted:!0})},[e,k]),J=he(()=>{if(!e)return;let h=Date.now(),v=h-A.current;if(v<Ps){let re=Math.ceil((Ps-v)/1e3);w(`Cooldown: ${re}s remaining`);return}A.current=h,W.current++;let $=Or(),j=Is({...$.grants},W.current),ee=Uo(e.keep,{...$,grants:j});k({...e,keep:ee});let be=W.current>Nt?" (diminished)":"";w(`+${j.gold}${N.gold} +${j.wood}${N.wood} +${j.stone}${N.stone} (${gr[$.type]??$.type})${be}`)},[e,k,w]),Ee=he((h,v)=>{h>=0&&h<M&&v>=0&&v<M&&r({x:h,y:v})},[]),tt=he(h=>{if(!e||e.keep.grid.structures.length===0)return;let v=e.keep.grid.structures,$=`${s.x},${s.y}`,j=v.findIndex(re=>`${re.pos.x},${re.pos.y}`===$),ee=j===-1?0:j+h;ee<0&&(ee=v.length-1),ee>=v.length&&(ee=0);let be=v[ee];r({x:be.pos.x,y:be.pos.y})},[e,s]),Mo=he(()=>{Y(null)},[]),Pe=e?.keep.grid.structures.find(h=>h.pos.x===s.x&&h.pos.y===s.y)??null;return{gameSave:e,cursor:s,selectedStructure:C,structureAtCursor:Pe,message:m,fragments:O,raidReplay:d,raidGrid:E,raidType:f,raidSummary:b,offlineReport:B,moveCursor:X,cycleStructure:oe,selectStructure:ce,placeAtCursor:Te,upgradeAtCursor:Tt,demolishAtCursor:wt,collectAtCursor:Se,startAttackRaid:oo,startDefendRaid:R,quickDefend:V,watchLastRaid:H,watchRaidRecord:L,clearRaid:z,completeTutorial:U,grantSimResources:J,jumpToCoord:Ee,jumpToNextStructure:tt,clearOfflineReport:Mo}}var _o=class{mode="online";baseUrl;auth=null;constructor(e){this.baseUrl=e.replace(/\/$/,"")}async request(e,o={}){let s={"Content-Type":"application/json",...o.headers??{}};this.auth&&(s.Authorization=`Bearer ${this.auth.token}`);let r=await fetch(`${this.baseUrl}${e}`,{...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(e){let o=await this.request("/auth/register",{method:"POST",body:JSON.stringify({displayName:e})});return this.auth={token:o.token,apiKey:o.apiKey,playerId:o.playerId},o}async login(e){let o=await this.request("/auth/login",{method:"POST",body:JSON.stringify({apiKey:e})});return this.auth={token:o.token,apiKey:e,playerId:o.playerId},o}async load(){if(!this.auth)return null;try{let e=await this.request("/me");return e.keep?{schemaVersion:1,savedAtUnixMs:Date.now(),player:{id:e.player.id,displayName:e.player.displayName,settings:{asciiMode:!1}},keep:{id:e.keep.id,name:e.keep.name,ownerPlayerId:e.player.id,grid:e.keep.grid,resources:e.keep.resources,createdAtUnixMs:e.player.createdAt,updatedAtUnixMs:Date.now()},raidHistory:[],tutorialCompleted:!0,lastPlayedAtUnixMs:Date.now(),progression:{totalBuildsToday:0,totalCommitsToday:0,lastDailyResetDay:Math.floor(Date.now()/864e5),totalRaidsWon:e.progression?.totalRaidsWon??0,totalRaidsLost:e.progression?.totalRaidsLost??0,totalStructuresPlaced:e.progression?.totalStructuresPlaced??0,currentWinStreak:e.progression?.currentWinStreak??0,bestWinStreak:e.progression?.bestWinStreak??0,achievements:e.progression?.achievements??[],totalRaidersKilledByArcher:0}}:null}catch{return null}}async save(e){this.auth&&await this.request("/keep/save",{method:"POST",body:JSON.stringify({grid:e.keep.grid,resources:e.keep.resources})})}async createNew(e){let o=await this.register(e),s=await this.load();return s||{schemaVersion:1,savedAtUnixMs:Date.now(),player:{id:o.playerId,displayName:e,settings:{asciiMode:!1}},keep:{id:`keep-${o.playerId}`,name:`${e}'s Keep`,ownerPlayerId:o.playerId,grid:{width:16,height:16,structures:[]},resources:{...bt},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(e,o,s){return this.request("/raids/launch",{method:"POST",body:JSON.stringify({defenderPlayerId:e,probeTypes:o,spawnSpecs:s})})}async getIncomingRaids(e){return(await this.request(`/raids/incoming?since=${e}`)).raids}async getPvpProfile(){try{let e=await this.request("/me");return{trophies:e.player.trophies,league:e.player.league,shieldExpiresAt:e.player.shieldExpiresAt,seasonId:"S1",seasonPeakTrophies:e.player.trophies}}catch{return null}}async getLeaderboard(e=50){return(await this.request(`/leaderboard?limit=${e}`)).players}async getWarCamp(){try{return await this.request("/warcamp")}catch{return null}}async trainRaider(e,o){let s=await this.request("/warcamp/train",{method:"POST",body:JSON.stringify({slotId:e,raiderType:o})});return{slots:s.slots,maxSlots:s.maxSlots}}async getBounties(){try{return(await this.request("/bounties")).bounties}catch{return[]}}async claimBounty(e){return(await this.request(`/bounties/${e}/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 qe}from"react/jsx-runtime";var Bs=60,$s=18;function La(){let{stdout:t}=Da(),[e,o]=Re({columns:t?.columns??process.stdout.columns??80,rows:t?.rows??process.stdout.rows??24});return Ma(()=>{let s=t??process.stdout,r=()=>{o({columns:s.columns,rows:s.rows})};return s.on("resize",r),()=>{s.off("resize",r)}},[t]),e}function Ba({asciiMode:t,compact:e,forceTutorial:o,autoResume:s,serverUrl:r}){let{exit:a}=Ia(),{columns:T,rows:m}=La(),[i,d]=Re(r?"auth":s?"keep":"menu"),[S,E]=Re(t),[y,f]=Re(!1),[p,b]=Re(null),[c,B]=Re(null),[Y,O]=Re(!1),[u,G]=Re(""),[A,W]=Re("keep"),x=Ls(1),g=Ls(r?new _o(r):null),[P,C]=Re(!1),[k,w]=Re(null),[X,oe]=Re([]),[ce,Te]=Re(!1),[Tt,wt]=Re([]),[oo,R]=Re(!1),[V,H]=Re({slots:[],maxSlots:3}),[Se,L]=Re(null),[z,U]=Re(null),[J,Ee]=Re(!1),tt=e||T<80||m<24,Mo=T<Bs||m<$s,{gameSave:Pe,cursor:h,selectedStructure:v,message:$,fragments:j,raidReplay:ee,raidGrid:be,raidType:re,raidSummary:fe,offlineReport:se,structureAtCursor:ue,moveCursor:He,cycleStructure:Oe,selectStructure:Rt,placeAtCursor:nt,upgradeAtCursor:at,demolishAtCursor:St,collectAtCursor:xe,startAttackRaid:it,startDefendRaid:Q,quickDefend:lt,watchLastRaid:Us,watchRaidRecord:Io,clearRaid:rr,completeTutorial:Gs,grantSimResources:Ws,jumpToCoord:Ks,jumpToNextStructure:Hs,clearOfflineReport:Fs}=Ds(o),sr=Ft(()=>{a()},[a]),Vs=Ft(()=>{zr(),a()},[a]),nr=Ft(async(D,ne)=>{let ge=g.current;if(ge){Ee(!0),U(null);try{D==="login"?await ge.login(ne):await ge.register(ne),C(!0),d("menu"),ge.getPvpProfile?.().then(Fe=>w(Fe)),ge.registerForMatchmaking?.()}catch(Fe){U(Fe instanceof Error?Fe.message:"Connection failed")}finally{Ee(!1)}}},[]),Ys=Ft(async()=>{let D=g.current;if(D?.findMatch){Te(!0);try{let ne=await D.findMatch();oe(ne)}catch{oe([])}finally{Te(!1)}}},[]),js=Ft(async(D,ne,ge)=>{let Fe=g.current;if(!(!Fe?.launchPvpRaid||!Pe))try{let Bt=await Fe.launchPvpRaid(D.playerId,ne,ge);Io({replay:Bt.replay,attackerId:Pe.player.id,defenderKeepId:D.playerId,defenderGrid:D.grid})&&(W("pvp"),d("raid")),w(Po=>Po&&{...Po,trophies:Bt.newTrophies,league:Bt.newLeague})}catch{}},[Pe,Io]),qs=Ft(async()=>{let D=g.current;if(D?.getLeaderboard){R(!0);try{let ne=await D.getLeaderboard();wt(ne)}catch{wt([])}finally{R(!1)}}},[]);return Pa((D,ne)=>{if(y){f(!1);return}if(D==="?"){f(!0);return}if(Y){if(ne.escape){O(!1),G("");return}if(ne.return){let ge=u.split(/[, ]+/);if(ge.length===2){let Fe=parseInt(ge[0],16),Bt=parseInt(ge[1],16);!isNaN(Fe)&&!isNaN(Bt)&&Ks(Fe,Bt)}O(!1),G("");return}if(ne.backspace||ne.delete){G(ge=>ge.slice(0,-1));return}/^[0-9a-fA-F, ]$/.test(D)&&G(ge=>ge+D);return}if(se&&i==="keep"&&Fs(),i!=="menu"&&i!=="tutorial"){if(i==="raid"||i==="friendRaid"){(D==="q"||ne.escape)&&(rr(),b(null),B(null),d("keep"));return}if(!(i==="friendList"||i==="raidLog"||i==="settings"||i==="pvp"||i==="warcamp"||i==="leaderboard"||i==="auth"||i==="raidPlanner")){if(D==="q"){sr();return}if(ne.escape){d("menu");return}D==="h"||D==="a"||ne.leftArrow?He(-1,0):D==="l"||D==="d"||ne.rightArrow?He(1,0):D==="k"||D==="w"||ne.upArrow?He(0,-1):D==="j"||D==="s"||ne.downArrow?He(0,1):ne.return||D==="e"?nt():D==="u"?at():D==="x"?St():D==="["?Oe(-1):D==="]"?Oe(1):D==="f"?Ws():D==="c"?xe():D==="r"?lt():D==="v"?Us()&&d("raid"):D==="g"?(O(!0),G("")):ne.tab?Hs(1):D>="1"&&D<="6"&&Rt(parseInt(D)-1)}}}),Pe?Mo?qe(Lt,{flexDirection:"column",padding:1,children:[ae(Ie,{bold:!0,color:"yellow",children:"\u25C6 CodeKeep"}),ae(Ie,{children:" "}),ae(Ie,{color:"red",children:"Terminal too small"}),qe(Ie,{children:["Need ",qe(Ie,{bold:!0,children:[Bs,"x",$s]}),", got ",qe(Ie,{bold:!0,children:[T,"x",m]})]}),ae(Ie,{children:" "}),ae(Ie,{dimColor:!0,children:"Resize your terminal or run with --compact"})]}):y?ae(es,{}):i==="tutorial"||!Pe.tutorialCompleted?ae(as,{gameSave:Pe,onComplete:()=>{Gs(),d("keep")}}):i==="auth"?ae(ws,{error:z,isLoading:J,onLogin:D=>nr("login",D),onRegister:D=>nr("register",D),onPlayOffline:()=>{C(!1),d("menu")}}):i==="menu"?ae(os,{gameSave:Pe,onlineMode:P,onKeep:()=>d("keep"),onAttack:()=>{it(),d("raid")},onDefend:()=>{Q(),d("raid")},onPvp:()=>d("pvp"),onFriendRaid:()=>d("friendList"),onRaidLog:()=>d("raidLog"),onSettings:()=>d("settings"),onQuit:sr}):i==="raidLog"?ae(us,{gameSave:Pe,onBack:()=>d("menu"),onWatchReplay:D=>{Io(D)&&(W("raidLog"),d("raid"))}}):i==="settings"?ae(ms,{onBack:()=>d("menu"),onResetGame:Vs,onReplayTutorial:()=>d("tutorial"),asciiMode:S,onToggleAscii:()=>E(D=>!D)}):i==="pvp"?ae(hs,{pvpProfile:k,targets:X,isSearching:ce,onSearch:Ys,onAttack:D=>{L(D),d("raidPlanner")},onWarCamp:()=>{g.current?.getWarCamp?.().then(ne=>{ne&&H(ne)}),d("warcamp")},onLeaderboard:()=>{qs(),d("leaderboard")},onBack:()=>d("menu")}):i==="raidPlanner"&&Se?ae(ks,{targetName:Se.displayName,targetTrophies:Se.trophies,targetGrid:Se.grid,warCamp:V,resources:Pe.keep.resources,onLaunch:D=>{let ne=D.map(ge=>ge.raiderType);js(Se,ne,D),L(null)},onBack:()=>{L(null),d("pvp")}}):i==="warcamp"?ae(xs,{warCamp:V,resources:Pe.keep.resources,onTrain:(D,ne)=>{g.current?.trainRaider?.(D,ne).then(Fe=>H(Fe))},onBack:()=>d("pvp")}):i==="leaderboard"?ae(ys,{entries:Tt,currentPlayerId:Pe.player.id,isLoading:oo,onBack:()=>d("pvp")}):i==="friendList"?ae(ds,{onSelectFriend:D=>{let ne=`friend-raid-${Date.now()}`,ge=ut({probeCount:4,keepGrid:D.grid,seed:ne});b(ge),B(D.grid),d("friendRaid")},onBack:()=>d("menu")}):i==="friendRaid"&&p&&c?qe(Lt,{flexDirection:"column",children:[ae(Ie,{bold:!0,color:"yellow",children:"[ LOCAL SIMULATION ]"}),ae(qo,{replay:p,keepGrid:c,raidType:"attack",initialSpeed:x.current,onSpeedChange:D=>{x.current=D},onDone:()=>{b(null),B(null),d("menu")}})]}):i==="raid"&&ee&&be?ae(qo,{replay:ee,keepGrid:be,raidType:re||"defend",summary:fe||void 0,initialSpeed:x.current,onSpeedChange:D=>{x.current=D},onDone:()=>{rr(),d(A),W("keep")}}):qe(Lt,{flexDirection:"column",children:[se&&qe(Lt,{flexDirection:"column",children:[(se.resources.gold>0||se.resources.wood>0||se.resources.stone>0)&&qe(Ie,{color:"green",children:["Passive income: +",se.resources.gold,N.gold," +",se.resources.wood,N.wood," +",se.resources.stone,N.stone]}),se.raids.length>0&&qe(Ie,{color:"yellow",children:["Background raids: ",se.raids.filter(D=>D.won).length,"W / ",se.raids.filter(D=>!D.won).length,"L"]}),se.newAchievements.length>0&&qe(Ie,{color:"magenta",bold:!0,children:["New achievements: ",se.newAchievements.join(", ")]}),ae(Ie,{dimColor:!0,children:"(press any key to continue)"})]}),ae(Qr,{resources:Pe.keep.resources,selectedStructure:v,message:Y?`Jump to: ${u}_`:$,compact:tt,structureAtCursor:ue,fragmentCount:j.length}),qe(Lt,{flexDirection:"row",children:[ae(Jr,{grid:Pe.keep.grid,cursor:h,asciiMode:S,compact:tt,fragments:j}),!tt&&qe(Lt,{flexDirection:"column",marginLeft:2,width:28,children:[ae(ls,{selected:v}),ae(Lt,{marginTop:1,children:ae(Ie,{dimColor:!0,children:`e place u upgrade x demo
|
|
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
|
|
31
31
|
[ ] cycle 1-6 select
|
|
32
32
|
c collect r raid v replay
|
|
33
33
|
g jump Tab next f +res
|
|
34
|
-
?help Esc menu q quit`})})]})]}),
|
|
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)+`
|
|
36
|
+
`),process.exit(0)}(!process.stdin.isTTY||!process.stdout.isTTY)&&(process.stderr.write(`codekeep requires an interactive terminal.
|
|
37
|
+
Run it directly in your terminal (not piped or in CI).
|
|
38
|
+
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(`
|
|
35
40
|
Saving...
|
|
36
|
-
`);try{let
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "codekeep",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Async tower defense terminal game — build ASCII fortresses powered by your coding activity",
|
|
6
6
|
"license": "MIT",
|
|
@@ -9,6 +9,7 @@
|
|
|
9
9
|
"url": "https://github.com/tooyipjee/codekeep.git",
|
|
10
10
|
"directory": "packages/cli"
|
|
11
11
|
},
|
|
12
|
+
"engines": { "node": ">=20" },
|
|
12
13
|
"keywords": ["terminal", "game", "tower-defense", "ascii", "cli", "tui", "pvp"],
|
|
13
14
|
"bin": {
|
|
14
15
|
"codekeep": "./dist/index.js"
|