codekeep 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +36 -0
- package/package.json +41 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
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!==No){let s=t+`.v${o.schemaVersion}.bak`;try{$o(s,e,"utf-8")}catch{}return process.stderr.write(`[codekeep] Save version mismatch (got ${o.schemaVersion}, need ${No}), backed up to ${s}
|
|
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:`
|
|
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
|
+
\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
|
+
\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
|
+
\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
|
+
\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
|
|
11
|
+
|
|
12
|
+
**Error:** ${t.error}
|
|
13
|
+
|
|
14
|
+
**Stack:**
|
|
15
|
+
\`\`\`
|
|
16
|
+
${t.stack??"N/A"}
|
|
17
|
+
\`\`\`
|
|
18
|
+
|
|
19
|
+
## Environment
|
|
20
|
+
- Version: ${t.version}
|
|
21
|
+
- Node: ${t.nodeVersion}
|
|
22
|
+
- OS: ${t.platform} ${t.arch}
|
|
23
|
+
- Screen: ${t.screen??"unknown"}
|
|
24
|
+
- Time: ${t.timestamp}
|
|
25
|
+
`);return`https://github.com/tooyipjee/codekeep/issues/new?title=${e}&body=${o}&labels=bug,crash`}import{Fragment as na,jsx as $e,jsxs as mt}from"react/jsx-runtime";function ms({onBack:t,onResetGame:e,onReplayTutorial:o,asciiMode:s,onToggleAscii:r}){let[a,T]=wo(0),[m,i]=wo(!1),[d,S]=wo(!1),[E,y]=wo(""),f=[{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 sa((p,b)=>{if(d){if(b.escape){S(!1),y("");return}if(b.return&&E.length>0){let c={timestamp:new Date().toISOString(),error:E,version:"0.1.0",nodeVersion:process.version,platform:process.platform,arch:process.arch,screen:"settings"},B=yo(c);process.stderr.write(`
|
|
26
|
+
Open this URL to report the bug:
|
|
27
|
+
${B}
|
|
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
|
|
31
|
+
[ ] cycle 1-6 select
|
|
32
|
+
c collect r raid v replay
|
|
33
|
+
g jump Tab next f +res
|
|
34
|
+
?help Esc menu q quit`})})]})]}),tt&&ae(Ie,{dimColor:!0,children:"e/u/x build c collect r raid v replay f +res q quit"})]}):ae(Ie,{children:"Loading..."})}function Ns(t){return ae(So,{children:ae(Ba,{...t})})}import{jsx as Oa}from"react/jsx-runtime";var Os=new $a;Os.name("codekeep").description("Async tower defense terminal game powered by your coding activity").version("0.1.0").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("--online <url>","Connect to a CodeKeep server for multiplayer").option("--server <url>","Alias for --online").action(t=>{let e=!!qt(),o=t.online||t.server||process.env.CODEKEEP_SERVER,{waitUntilExit:s,unmount:r}=Na(Oa(Ns,{asciiMode:t.ascii??!1,compact:t.compact??!1,forceTutorial:t.tutorial??!1,autoResume:(t.resume??!1)&&e,serverUrl:o}),{exitOnCtrlC:!1}),a=!1;function T(){if(!a){a=!0,process.stderr.write(`
|
|
35
|
+
Saving...
|
|
36
|
+
`);try{let m=qt();m&&At(m)}catch{}r()}}process.on("SIGINT",T),process.on("SIGTERM",T),process.on("SIGHUP",T),s().then(()=>{process.exit(0)}).catch(()=>{process.exit(1)})});Os.parse();
|
package/package.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "codekeep",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "Async tower defense terminal game — build ASCII fortresses powered by your coding activity",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "https://github.com/tooyipjee/codekeep.git",
|
|
10
|
+
"directory": "packages/cli"
|
|
11
|
+
},
|
|
12
|
+
"keywords": ["terminal", "game", "tower-defense", "ascii", "cli", "tui", "pvp"],
|
|
13
|
+
"bin": {
|
|
14
|
+
"codekeep": "./dist/index.js"
|
|
15
|
+
},
|
|
16
|
+
"files": ["dist"],
|
|
17
|
+
"scripts": {
|
|
18
|
+
"build": "tsup",
|
|
19
|
+
"dev": "tsx src/index.tsx",
|
|
20
|
+
"test": "vitest run",
|
|
21
|
+
"typecheck": "tsc --noEmit",
|
|
22
|
+
"prepublishOnly": "tsup"
|
|
23
|
+
},
|
|
24
|
+
"dependencies": {
|
|
25
|
+
"chalk": "^5",
|
|
26
|
+
"commander": "^13",
|
|
27
|
+
"ink": "^6",
|
|
28
|
+
"react": "^19"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@codekeep/server": "workspace:*",
|
|
32
|
+
"@codekeep/shared": "workspace:*",
|
|
33
|
+
"@types/react": "^19",
|
|
34
|
+
"@vitest/coverage-v8": "3",
|
|
35
|
+
"ink-testing-library": "^4",
|
|
36
|
+
"tsup": "^8",
|
|
37
|
+
"tsx": "^4",
|
|
38
|
+
"typescript": "^5.7",
|
|
39
|
+
"vitest": "^3"
|
|
40
|
+
}
|
|
41
|
+
}
|