Add terrain biomes jumping and extensible gathering professions

This commit is contained in:
dingo
2026-09-08 21:54:23 -04:00
parent 141cb9e6b2
commit df7b245ca7
34 changed files with 1895 additions and 184 deletions
+2 -2
View File
@@ -17,13 +17,13 @@
</header>
<section id="season" class="season"><div><span id="phase-label">THE GATHERING</span><strong id="season-clock">7d 00h</strong></div><span id="season-detail">Until the Harbinger</span><div class="thin-track"><i id="season-progress"></i></div></section>
<section id="boss-bar" class="boss-bar" hidden><button id="target-boss" title="Target Harbinger" aria-label="Target Harbinger"><i data-lucide="crosshair"></i> THE HARBINGER</button><div class="bar"><i id="boss-health"></i></div><small id="boss-count"></small></section>
<aside id="settings" class="panel settings" hidden><div class="panel-title"><h2>Display</h2><button data-close="settings" class="icon" title="Close" aria-label="Close display settings"><i data-lucide="x"></i></button></div><label>Detail <select id="quality"><option value="high">High</option><option value="low">Low</option></select></label><label>Camera distance <input id="zoom" type="range" min="30" max="100" value="62" /></label><button id="dev-boss" hidden><i data-lucide="flame"></i> Awaken Harbinger</button><button id="logout"><i data-lucide="log-out"></i> Sign out</button></aside>
<aside id="settings" class="panel settings" hidden><div class="panel-title"><h2>Display</h2><button data-close="settings" class="icon" title="Close" aria-label="Close display settings"><i data-lucide="x"></i></button></div><label>Detail <select id="quality"><option value="high">High</option><option value="low">Low</option></select></label><label>Camera distance <input id="zoom" type="range" min="18" max="100" value="30" /></label><button id="dev-boss" hidden><i data-lucide="flame"></i> Awaken Harbinger</button><button id="logout"><i data-lucide="log-out"></i> Sign out</button></aside>
<aside id="inventory" class="panel inventory" hidden><div class="panel-title"><h2>Inventory</h2><button data-close="inventory" class="icon" title="Close" aria-label="Close inventory"><i data-lucide="x"></i></button></div><div id="inventory-items"></div><h3>Permanent titles</h3><div id="earned-titles"></div><h3>Crafting</h3><div id="recipes"></div><h3>Skills</h3><div id="skills" class="skills"></div></aside>
<div id="target" class="target" hidden><span id="target-name"></span><span id="target-health"></span></div>
<div id="notice" role="status" class="notice" hidden></div>
<footer class="bottom" id="game-controls" hidden>
<section class="vitals"><div><strong id="character-name">Traveler</strong><span id="health-number">100 / 100</span></div><div class="bar"><i id="health-fill"></i></div><div class="vital-detail"><span><i data-lucide="hourglass"></i><span id="play-time">2h left today</span></span><span id="kills">0 kills</span></div><div class="progression-line"><strong id="character-level">Level 1</strong><span id="character-experience">0 XP</span></div><progress id="experience-meter" class="experience-meter" aria-label="Level experience" max="1" value="0"></progress><div class="progression-bank"><span id="stat-point-bank">0 stat points saved</span><span id="title-count">0 titles</span></div></section>
<nav class="actions" aria-label="Actions"><button id="attack" title="Attack" aria-label="Attack"><i data-lucide="swords"></i></button><button id="gather" title="Gather" aria-label="Gather"><i data-lucide="pickaxe"></i></button><button id="heal" title="Use bandage" aria-label="Use bandage"><i data-lucide="heart-pulse"></i><small id="bandage-count">0</small></button><button id="keystone" title="Return with keystone" aria-label="Return with keystone"><i data-lucide="gem"></i></button><span></span><button id="inventory-toggle" title="Inventory and crafting" aria-label="Inventory and crafting"><i data-lucide="backpack"></i></button></nav>
<nav class="actions" aria-label="Actions"><button id="jump" title="Jump (Space)" aria-label="Jump">↑</button><button id="attack" title="Attack (F)" aria-label="Attack"><i data-lucide="swords"></i></button><button id="gather" title="Gather" aria-label="Gather"><i data-lucide="pickaxe"></i></button><button id="heal" title="Use bandage" aria-label="Use bandage"><i data-lucide="heart-pulse"></i><small id="bandage-count">0</small></button><button id="keystone" title="Return with keystone" aria-label="Return with keystone"><i data-lucide="gem"></i></button><span></span><button id="inventory-toggle" title="Inventory and crafting" aria-label="Inventory and crafting"><i data-lucide="backpack"></i></button></nav>
<section class="location"><canvas id="minimap" width="140" height="140" aria-label="World map"></canvas><span id="coordinates">0, 0</span><small id="chunk-count">9 chunks</small></section>
</footer>
<nav id="movement" class="movement" aria-label="Movement" hidden><button data-move="up" aria-label="Move north"><i data-lucide="chevron-up"></i></button><button data-move="left" aria-label="Move west"><i data-lucide="chevron-left"></i></button><button data-move="down" aria-label="Move south"><i data-lucide="chevron-down"></i></button><button data-move="right" aria-label="Move east"><i data-lucide="chevron-right"></i></button></nav>
+2 -2
View File
@@ -11,7 +11,7 @@ function button(label:string,key:string,fn:()=>void,disabled=false){const b=node
function request(op:string,target:string,slot=''){sendIntent(op,target,0,0,slot);}
function render(){
for(const b of nav.querySelectorAll('button'))b.setAttribute('aria-pressed',String(b.dataset.section===selected));
const next=JSON.stringify([selected,latest.entity.state,latest.remainingSeconds>0,latest.statPoints,latest.pendingVitalChoices,latest.allocatedStats,latest.stats,latest.items,latest.equipment,latest.inventory,latest.carryWeight]);
const next=JSON.stringify([selected,latest.entity.state,latest.remainingSeconds>0,latest.statPoints,latest.pendingVitalChoices,latest.allocatedStats,latest.stats,latest.items,latest.equipment,latest.inventory,latest.carryWeight,latest.gathering,latest.gatheringEffects,latest.consumables]);
if(next===signature)return;signature=next;
const focus=root.contains(document.activeElement)?(document.activeElement as HTMLElement).dataset.focusKey:undefined;
const opened=new Set(Array.from(body.querySelectorAll<HTMLDetailsElement>('details[open]')).map(d=>d.dataset.key));body.replaceChildren();
@@ -32,7 +32,7 @@ function render(){
if(slot==='ring'){const label=node('label','Ring slot'),select=node('select');select.dataset.focusKey=`ring-${item.id}`;select.setAttribute('aria-label',`Ring slot for ${item.name}`);for(let n=1;n<=8;n++)select.append(new Option(`Ring ${n}${c.equipment?.[`ring${n}`]?' · Occupied':' · Empty'}`,`ring${n}`));select.value=rings.get(item.id)??equipmentSlots.find(s=>s.startsWith('ring')&&!c.equipment?.[s])??'ring1';slot=select.value;select.onchange=()=>{slot=select.value;rings.set(item.id,slot)};label.append(select);actions.append(label);}
actions.append(button('Equip',`equip-${item.id}`,()=>request('equip',item.id,slot),!active()||!item.equippable),button('Drop',`drop-${item.id}`,()=>request('drop',item.id),!active()));card.append(actions);grid.append(card);
}
for(const [key,count] of Object.entries(c.inventory??{}))if(count>0){const card=node('article','','stack-card');card.append(node('span',`${statLabel(key)} × ${count}`),button('Drop one',`drop-stack-${key}`,()=>request('drop',key),!active()));grid.append(card);}
for(const [key,count] of Object.entries(c.inventory??{}))if(count>0){const card=node('article','','stack-card');card.append(node('span',`${c.stackNames?.[key]??statLabel(key)} × ${count}`),button('Drop one',`drop-stack-${key}`,()=>request('drop',key),!active()));const consumable=c.consumables?.find(v=>v.id===key);if(consumable)card.append(node('p',`${consumable.description} · ${consumable.seconds}s`),modifiersView(consumable.modifiers),button('Use',`consume-${key}`,()=>request('consume',key),!active()));grid.append(card);}
if(!grid.children.length)grid.append(node('p','Your bag is empty.'));body.append(grid);
}
for(const d of body.querySelectorAll<HTMLDetailsElement>('details'))d.open=opened.has(d.dataset.key);
+6 -2
View File
@@ -12,7 +12,7 @@ export const signed = (value:number) => `${value>0?'+':''}${numberText(value)}`;
export function node<K extends keyof HTMLElementTagNameMap>(tag:K,text='',className='') { const e=document.createElement(tag);e.textContent=text;e.className=className;return e; }
export function modifiersView(modifiers:StatModifier[] = []) {
const list=node('div','','title-effects');
for(const m of modifiers??[]) for(const [value,suffix] of [[m.flat,''],[m.percent,'%']] as const) if(value) list.append(node('span',`${signed(value)}${suffix} ${statLabel(m.stat)}`,value>0?'effect-positive':'effect-negative'));
for(const m of modifiers??[]) for(const [value,suffix] of [[m.flat,''],[m.percent,'%']] as const) if(value) list.append(node('span',`${signed(value)}${suffix} ${statLabel(m.stat)}${m.skill?` (${statLabel(m.skill)})`:m.stat.startsWith("gathering")?" (all gathering skills)":""}`,value>0?'effect-positive':'effect-negative'));
return list;
}
export function statsBreakdown(c:Character) {
@@ -21,7 +21,11 @@ export function statsBreakdown(c:Character) {
for(const label of ['Stat','Base','Flat','%','Final']) { const th=node('th',label);th.scope='col';head.append(th); }
const body=table.createTBody();
for(const key of [...primaryStats,...derivedStats]) { const v=c.stats?.[key];if(!v)continue;const row=body.insertRow(),heading=node('th',statLabel(key));heading.scope='row';row.append(heading);for(const text of [numberText(v.base),signed(v.flat),`${signed(v.percent)}%`,numberText(v.final)])row.insertCell().textContent=text; }
wrapper.append(table);return wrapper;
for(const g of Object.values(c.gathering??{})){
const row=body.insertRow();const th=node('th',`${g.name}: level ${g.level}, effective ${g.effectiveLevel} · ${g.xp} XP · ${g.xpToNextLevel} to next`);th.colSpan=5;row.append(th);
for(const [name,v] of [['Level',g.levelValue],['Yield %',g.yield],['Speed %',g.speed],['XP %',g.experience]] as const){const row=body.insertRow();row.append(node('th',name));for(const text of [numberText(v.base),signed(v.flat),`${signed(v.percent)}%`,numberText(v.final)])row.insertCell().textContent=text;}
}
wrapper.append(table);for(const effect of c.gatheringEffects??[]){wrapper.append(node('p',`${effect.name} · expires ${new Date(effect.expiresAt*1000).toLocaleTimeString()}`),modifiersView(effect.modifiers));}return wrapper;
}
export function itemDetails(item:ItemInstance,c:Character) {
const card=node('article','','gear-card');
+42 -6
View File
@@ -8,7 +8,7 @@ const statKeys=[...primaryStats,...derivedStats],metrics=['level','kills','world
const root=node('section','','catalog-editor'),header=node('div','','catalog-heading'),version=node('p'),tabs=node('div','','catalog-tabs'),list=node('div','','catalog-list'),forms=node('div'),message=node('p','','message');
const refresh=button('Refresh catalog',()=>void load());header.append(node('h2','Game content'),version,refresh);message.hidden=true;message.setAttribute('role','status');root.append(header,message,tabs,list,forms);
let catalog:Catalog,changes:Audit[]=[],section='titles',editing=false,loading=false,saving=false;
for(const [key,label] of [['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);}
for(const [key,label] of [['titles','Titles'],['items','Equipment'],['requirements','Requirement sets'],['effects','Effect sets'],['gathering','Gathering'],['resources','Resources'],['biomes','Biomes'],['consumables','Consumables'],['stats','Stat formulas'],['audit','Content audit']]){const b=button(label,()=>{if(editing||saving){show('Finish or cancel the open draft first.');return;}section=key;render()});b.dataset.section=key;tabs.append(b);}
function button(text:string,fn:()=>void){const b=node('button',text,'button secondary');b.type='button';b.onclick=fn;return b;}
function show(text:string){message.textContent=text;message.hidden=false;}
function field(label:string,input:HTMLElement){const wrap=node('label',label);wrap.append(input);return wrap;}
@@ -22,7 +22,7 @@ function repeat<T>(title:string,addLabel:string,make:(value?:T)=>{node:HTMLEleme
function append(value?:T){if(entries.length>=max)return;const entry=make(value),row=node('div','','catalog-row');entries.push(entry);row.append(entry.node,button('Remove',()=>{entries.splice(entries.indexOf(entry),1);row.remove();add.disabled=false}));rows.append(row);add.disabled=entries.length>=max;}
for(const value of initial)append(value);return {node:group,read:()=>entries.map(e=>e.read())};
}
function modifiers(){return repeat<StatModifier>('Modifiers','Add modifier',value=>{const group=node('div','','catalog-fields'),stat=select(statKeys,value?.stat),flat=number(value?.flat??0,-1000000),percent=number(value?.percent??0,-100,10000);group.append(field('Stat',stat),field('Flat change',flat),field('Percent change (%)',percent));return {node:group,read:()=>({stat:stat.value,flat:Number(flat.value),percent:Number(percent.value)})}});}
function modifiers(){return repeat<StatModifier>('Modifiers','Add modifier',value=>{const group=node('div','','catalog-fields'),stat=select([...statKeys,'gatheringLevel','gatheringYield','gatheringSpeed','gatheringXP'],value?.stat),flat=number(value?.flat??0,-1000000),percent=number(value?.percent??0,-100,10000);const skill=node('select');skill.append(new Option('All gathering skills',''));for(const s of catalog.gathering?.skills??[])skill.append(new Option(s.name,s.id));skill.value=value?.skill??'';const scope=field('Gathering skill scope',skill);const update=()=>{scope.hidden=!stat.value.startsWith('gathering');if(scope.hidden)skill.value=''};stat.onchange=update;update();group.append(field('Stat',stat),field('Flat change',flat),field('Percent change (%)',percent),scope);return {node:group,read:()=>({stat:stat.value,flat:Number(flat.value),percent:Number(percent.value),...(skill.value?{skill:skill.value}:{})})}});}
function requirementRows(initial:Requirement[]=[]){return repeat<Requirement>('Requirements','Add requirement',value=>{const group=node('div','','catalog-fields'),metric=select(metrics,value?.metric),minimum=number(value?.atLeast??1,1,1000000000,'1');group.append(field('Metric',metric),field('At least',minimum));return {node:group,read:()=>({metric:metric.value,atLeast:Number(minimum.value)})}},initial,8);}
function setChoices(equipment=false){
const group=node('div'),req=node('fieldset','','catalog-title-choices'),effects=node('fieldset','','catalog-title-choices');req.append(node('legend','Reusable requirement sets'));effects.append(node('legend','Reusable effect sets'));
@@ -36,7 +36,7 @@ function setForm(kind:'requirements'|'effects'){
if(editing||saving){show('Finish the open draft or pending request first.');return;}
const values=identity(),rows=kind==='requirements'?requirementRows([{metric:'level',atLeast:2}]):modifiers();
const fields=form(kind==='requirements'?'Create requirement set':'Create effect set',kind==='requirements'?'create-requirement-set':'create-effect-set',()=>kind==='requirements'?{requirementSet:{...values.read(),requirements:rows.read()}}:{effectSet:{...values.read(),modifiers:rows.read()}});
fields.append(values.node,rows.node,node('p','Reusable sets are immutable. Publish a new ID for a variation. Effects currently support flat and percentage stat modifiers.','muted'));
fields.append(values.node,rows.node,node('p','Reusable sets are immutable. Publish a new definition for a variation. Effects currently support flat and percentage stat modifiers.','muted'));
}
function form(title:string,op:string,payload:()=>object){
editing=true;refresh.disabled=true;const expectedVersion=catalog.version,form=node('form','','catalog-form'),error=node('p','','error'),fields=node('div'),reason=node('textarea'),preview=node('section','','catalog-preview');
@@ -63,12 +63,13 @@ function form(title:string,op:string,payload:()=>object){
}
function previewView(result:ContentPreview){
const root=node('div'),r=result.resolved;root.append(node('h4','Validated publication preview'),node('p',`Version ${result.basedOnVersion} → ${result.proposedVersion}. Nothing has been published.`));
const definition=r.title??r.item??r.requirementSet??r.effectSet;
const definition=r.title??r.item??r.requirementSet??r.effectSet??r.gatheringSkill??r.resource??r.biome??r.consumable;
if(definition)root.append(node('strong',definition.name),node('p',definition.description),node('p','Permanent ID assigned on publication.','muted'));
const requirements=r.title?.requirements??r.requirementSet?.requirements;
if(requirements)root.append(node('p',requirements.map(v=>`${statLabel(v.metric)} ≥ ${v.atLeast}`).join(' / ')));
if(r.item)root.append(node('p',`Requires level ${r.item.requirements.level}; ${Object.entries(r.item.requirements.stats??{}).map(([key,n])=>`${statLabel(key)} ≥ ${n}`).join(' / ')}`),node('p',`Required titles: ${(r.item.requirements.titles??[]).join(', ')||'None'}`));
const modifiers=r.title?.effects.modifiers??r.item?.modifiers??r.effectSet?.modifiers;if(modifiers)root.append(modifiersView(modifiers));
if(r.gatheringSkill||r.resource||r.biome||r.consumable)root.append(node('pre',JSON.stringify(r.gatheringSkill??r.resource??r.biome??r.consumable,null,2)));
if(r.stats){root.append(node('p','Validated base values and primary-to-derived coefficients.'));const details=node('details');details.append(node('summary','Review stat formulas'),node('pre',JSON.stringify(r.stats,null,2)));root.append(details);}
return root;
}
@@ -83,7 +84,7 @@ function titleForm(){
function itemForm(){
if(editing||saving){show('Finish or cancel the open draft first.');return;}
const values=identity(),slot=select(itemSlots,'weapon'),weight=number(1,0,10000),drop=number(0,0,100),level=number(1,1,10000,'1'),effects=modifiers();
const requirements=repeat<{stat:string;value:number}>('Required stats','Add required stat',value=>{const group=node('div','','catalog-fields'),stat=select(statKeys,value?.stat),minimum=number(value?.value??1);group.append(field('Stat',stat),field('Minimum value',minimum));return {node:group,read:()=>({stat:stat.value,value:Number(minimum.value)})}},[],statKeys.length);
const requirements=repeat<{stat:string;value:number}>('Required stats','Add required stat',value=>{const group=node('div','','catalog-fields'),stat=select([...statKeys,'gatheringLevel','gatheringYield','gatheringSpeed','gatheringXP'],value?.stat),minimum=number(value?.value??1);group.append(field('Stat',stat),field('Minimum value',minimum));return {node:group,read:()=>({stat:stat.value,value:Number(minimum.value)})}},[],statKeys.length);
const titles=node('fieldset','','catalog-title-choices');titles.append(node('legend','Required titles'));const checks=(catalog.titles??[]).map(t=>{const input=node('input');input.type='checkbox';titles.append(field(t.name,input));return {id:t.id,input}});
const sets=setChoices(true);
const fields=form('Create equipment','create-item',()=>{const req=requirements.read();if(new Set(req.map(r=>r.stat)).size!==req.length)throw new Error('Each required stat can appear once.');return {...sets.read(),item:{...values.read(),slot:slot.value,weight:Number(weight.value),dropChance:Number(drop.value),requirements:{level:Number(level.value),stats:Object.fromEntries(req.map(r=>[r.stat,r.value])),titles:checks.filter(c=>c.input.checked).map(c=>c.id)},modifiers:effects.read()}}});
@@ -98,7 +99,8 @@ function statsForm(){
}
function render(){
version.textContent=`Catalog version ${catalog.version}`;for(const b of tabs.querySelectorAll('button'))b.setAttribute('aria-pressed',String(b.dataset.section===section));list.replaceChildren();
if(section==='titles'){
if(['gathering','resources','biomes','consumables'].includes(section)){gatheringList();
}else if(section==='titles'){
list.append(button('Create title',titleForm));for(const t of catalog.titles??[]){const d=node('details','','catalog-definition');d.append(node('summary',t.name),node('p',`${t.id} · ${t.scope} · ${t.description}`),node('p',(t.requirements??[]).map(r=>`${statLabel(r.metric)} ≥ ${r.atLeast}`).join(' / ')),modifiersView(t.effects.modifiers));if(t.effects.damage||t.effects.moveSpeed)d.append(node('p',`Damage ${t.effects.damage}; movement ${t.effects.moveSpeed}`));list.append(d);}
}else if(section==='items'){
list.append(button('Create equipment',itemForm));for(const i of catalog.items??[]){const d=node('details','','catalog-definition');d.append(node('summary',i.name),node('p',`${i.id} · ${statLabel(i.slot)} · Weight ${i.weight} · Drop chance ${i.dropChance??0}%`),node('p',i.description),node('p',`Requires level ${i.requirements.level}; ${Object.entries(i.requirements.stats??{}).map(([k,v])=>`${statLabel(k)} ${v}`).join(', ')} ${(i.requirements.titles??[]).map(id=>`Title: ${catalog.titles.find(t=>t.id===id)?.name??id}`).join(', ')}`),modifiersView(i.modifiers));list.append(d);}
@@ -116,3 +118,37 @@ function render(){
async function load(){if(loading||editing)return;loading=true;refresh.disabled=true;try{const data=await api<{catalog:Catalog;changes:Audit[]}>('/api/control/catalog');catalog=data.catalog;changes=data.changes;render();}catch(e){show((e as Error).message)}finally{loading=false;refresh.disabled=editing;}}
export function showCatalog(parent:HTMLElement){if(root.parentElement!==parent)parent.replaceChildren(root);if(!catalog&&!loading)void load();}
export function hasCatalogDraft(){return editing;}
function contentChoice(values:{id:string;name:string}[]) {
const input=node('select');input.required=true;for(const v of values)input.append(new Option(v.name,v.id));return input;
}
function gatheringForm(kind:string){
if(editing||saving){show('Finish or cancel the open draft first.');return;}
const values=identity(),g=catalog.gathering;
if(kind==='gathering'){
const base=number(20,1,1000000,'1'),step=number(10,0,1000000,'1'),max=number(1000,2,10000,'1');
const fields=form('Create gathering skill','create-gathering-skill',()=>({gatheringSkill:{...values.read(),baseXp:Number(base.value),xpPerLevel:Number(step.value),maxLevel:Number(max.value)}}));
fields.append(values.node,field('XP from level 1 to 2',base),field('Extra XP cost per level',step),field('Maximum earned level',max),node('p','Earned XP belongs to the character. Temporary level bonuses affect gathering difficulty without granting XP or permanent levels.','muted'));
}else if(kind==='resources'){
const skill=contentChoice(g?.skills??[]),model=select(['tree','ore','herb']),output=select(['wood','ore','herb','self']),level=number(1,1,10000,'1'),amount=number(1,1,1000,'1'),xp=number(2,0,1000000,'1'),seconds=number(1,0.1,3600),respawn=number(120,1,604800),density=number(4,0,32,'1');
output.options[3].text='New material named after this resource';
const biomeFields=node('fieldset','','catalog-title-choices');biomeFields.append(node('legend','Spawn biomes'));
const checks=(g?.biomes??[]).map(b=>{const i=node('input');i.type='checkbox';biomeFields.append(field(b.name,i));return{id:b.id,input:i}});
const fields=form('Create resource','create-resource',()=>{const biomes=checks.filter(v=>v.input.checked).map(v=>v.id);if(!biomes.length)throw new Error('Choose at least one biome.');return{resource:{...values.read(),skillId:skill.value,model:model.value,output:output.value,requiredLevel:Number(level.value),amount:Number(amount.value),xp:Number(xp.value),seconds:Number(seconds.value),respawnSeconds:Number(respawn.value),density:Number(density.value),biomes}}});
fields.append(values.node,field('Gathering skill',skill),field('Model preset',model),field('Gathered material',output),field('Required effective skill level',level),field('Base amount per success',amount),field('Base profession XP per success',xp),field('Gathering interval (seconds)',seconds),field('Respawn interval (seconds)',respawn),field('Nodes per matching chunk (before forest density bonus)',density),biomeFields,node('p','Players may risk attempts up to 20 levels below this requirement. Failures can destroy the node until respawn and inflict damage/fatigue. New definitions appear in unexplored chunks of new-generation worlds; explored layouts stay fixed. Models use existing placeholders until milestone 4.5.','muted'));
}else if(kind==='biomes'){
const color=text('#426044',7);color.type='color';const weight=number(3,1,100,'1');
const fields=form('Create biome','create-biome',()=>({biome:{...values.read(),color:color.value,weight:Number(weight.value)}}));
fields.append(values.node,field('Terrain color',color),field('Relative occurrence weight',weight),node('p','Applies to unexplored chunks. Publish resource definitions referencing this biome to populate it. Mob populations arrive in milestone 4.','muted'));
}else{
const seconds=number(120,1,86400),effects=modifiers();
const fields=form('Create gathering consumable','create-consumable',()=>{const mods=effects.read();if(!mods.length||mods.some(m=>!m.stat.startsWith('gathering')))throw new Error('Choose gathering level, yield, speed, or XP modifiers.');return{consumable:{...values.read(),seconds:Number(seconds.value),modifiers:mods}}});
fields.append(values.node,field('Duration (seconds)',seconds),effects.node,node('p','Grant this item from Characters → Manage items and titles. Players use it from their bag. Reuse refreshes this consumable’s duration; distinct sources combine. Expiry uses real time, including time offline.','muted'));
}
}
function gatheringList(){
const labels:Record<string,string>={gathering:'gathering skill',resources:'resource',biomes:'biome',consumables:'gathering consumable'};
list.append(button(`Create ${labels[section]}`,()=>gatheringForm(section)));
const g=catalog.gathering;const entries=section==='gathering'?g?.skills:section==='resources'?g?.resources:section==='biomes'?g?.biomes:g?.consumables;
for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),node('pre',JSON.stringify(v,null,2)));list.append(d);}
}
+147 -14
View File
@@ -10,6 +10,7 @@ export interface Protocol {
export interface ContentCatalog {
effectSets?: EffectSet[];
gathering?: GatheringContent;
items: ItemDefinition[];
requirementSets?: RequirementSet[];
stats: ContentStatsRules;
@@ -27,9 +28,58 @@ export interface EffectSet {
export interface StatModifier {
flat: number;
percent: number;
skill?: string;
stat: string;
}
export interface GatheringContent {
biomes: BiomeDefinition[];
consumables: GatheringConsumable[];
resources: ResourceDefinition[];
skills: GatheringSkill[];
}
export interface BiomeDefinition {
color: string;
description: string;
id: string;
name: string;
weight: number;
}
export interface GatheringConsumable {
description: string;
id: string;
modifiers: StatModifier[];
name: string;
seconds: number;
}
export interface ResourceDefinition {
amount: number;
biomes: string[];
density: number;
description: string;
id: string;
model: string;
name: string;
output: string;
requiredLevel: number;
respawnSeconds: number;
seconds: number;
skillId: string;
xp: number;
}
export interface GatheringSkill {
baseXp: number;
description: string;
id: string;
maxLevel: number;
name: string;
xpPerLevel: number;
}
export interface ItemDefinition {
description: string;
dropChance: number;
@@ -81,19 +131,39 @@ export interface TitleEffects {
}
export interface ContentChange {
biome?: BiomeDefinitionDraft;
consumable?: GatheringConsumableDraft;
effectSet?: EffectSetDraft;
effectSetIds?: string[];
expectedVersion: number;
gatheringSkill?: GatheringSkillDraft;
id: string;
item?: ItemDraft;
op: string;
reason: string;
requirementSet?: RequirementSetDraft;
requirementSetIds?: string[];
resource?: ResourceDefinitionDraft;
stats?: ContentStatsRules;
title?: TitleDraft;
}
export interface BiomeDefinitionDraft {
color: string;
description: string;
id?: string;
name: string;
weight: number;
}
export interface GatheringConsumableDraft {
description: string;
id?: string;
modifiers: StatModifier[];
name: string;
seconds: number;
}
export interface EffectSetDraft {
description: string;
id?: string;
@@ -101,6 +171,15 @@ export interface EffectSetDraft {
name: string;
}
export interface GatheringSkillDraft {
baseXp: number;
description: string;
id?: string;
maxLevel: number;
name: string;
xpPerLevel: number;
}
export interface ItemDraft {
description: string;
dropChance: number;
@@ -119,6 +198,22 @@ export interface RequirementSetDraft {
requirements: ContentRequirement[];
}
export interface ResourceDefinitionDraft {
amount: number;
biomes: string[];
density: number;
description: string;
id?: string;
model: string;
name: string;
output: string;
requiredLevel: number;
respawnSeconds: number;
seconds: number;
skillId: string;
xp: number;
}
export interface TitleDraft {
description: string;
effects: TitleEffects;
@@ -152,6 +247,7 @@ export interface Snapshot {
chunkKeys: string[];
chunks: Chunk[];
entities: Entity[];
gatherRisks?: { [key: string]: GatheringRisk };
message: string;
self: Character;
tick: number;
@@ -163,6 +259,7 @@ export interface Snapshot {
export interface Chunk {
biome: string;
color?: string;
heights: number[];
key: string;
resolution: number;
@@ -173,13 +270,16 @@ export interface Chunk {
}
export interface Entity {
hp: number;
id: string;
kind: string;
maxHp: number;
name: string;
position: Vec3;
state: string;
hp: number;
id: string;
kind: string;
maxHp: number;
name: string;
position: Vec3;
requiredLevel?: number;
resourceId?: string;
skillId?: string;
state: string;
}
export interface Vec3 {
@@ -188,14 +288,27 @@ export interface Vec3 {
z: number;
}
export interface GatheringRisk {
allowed: boolean;
damage: number;
destruction: number;
failure: number;
negative: number;
seconds: number;
}
export interface Character {
ack: number;
allocatedStats: { [key: string]: number };
carryWeight: number;
consumables?: GatheringConsumable[];
entity: Entity;
equipment: { [key: string]: string };
experience: number;
experienceToNextLevel: number;
gatherAttempt: number;
gathering?: { [key: string]: SkillProgress };
gatheringEffects?: TimedGatheringEffect[];
hasKeystone: boolean;
healthChoices: number;
inventory: { [key: string]: number };
@@ -208,12 +321,39 @@ export interface Character {
playedSeconds: number;
remainingSeconds: number;
skills: { [key: string]: number };
stackNames?: { [key: string]: string };
stamina: number;
statPoints: number;
stats: { [key: string]: StatValue };
titles: TitleAward[];
}
export interface SkillProgress {
effectiveLevel: number;
experience: StatValue;
level: number;
levelValue: StatValue;
name: string;
speed: StatValue;
xp: number;
xpToNextLevel: number;
yield: StatValue;
}
export interface StatValue {
base: number;
final: number;
flat: number;
percent: number;
}
export interface TimedGatheringEffect {
expiresAt: number;
modifiers: StatModifier[];
name: string;
source: string;
}
export interface ItemInstance {
definitionId: string;
description: string;
@@ -227,13 +367,6 @@ export interface ItemInstance {
weight: number;
}
export interface StatValue {
base: number;
final: number;
flat: number;
percent: number;
}
export interface TitleAward {
description: string;
earnedAt: string;
+2 -2
View File
@@ -1,7 +1,7 @@
export type InputAction = 'north' | 'south' | 'west' | 'east' | 'attack' | 'gather' | 'inventory' | 'heal' | 'return';
export type InputAction = 'north' | 'south' | 'west' | 'east' | 'attack' | 'gather' | 'inventory' | 'heal' | 'return' | 'jump';
const bindings: Readonly<Record<string, InputAction>> = {
KeyW:'north', ArrowUp:'north', KeyS:'south', ArrowDown:'south', KeyA:'west', ArrowLeft:'west',
KeyD:'east', ArrowRight:'east', Space:'attack', KeyE:'gather', KeyI:'inventory'
KeyD:'east', ArrowRight:'east', Space:'jump', KeyF:'attack', KeyE:'gather', KeyI:'inventory'
};
export function isEditing(target: EventTarget | null) {
return target instanceof HTMLElement && !!target.closest('input,select,textarea,[contenteditable]:not([contenteditable="false"])');
+18 -7
View File
@@ -23,6 +23,7 @@ let inputElapsed = 0;
let walkTo: { x: number; z: number } | undefined;
let pendingAction: { op: string; target: string } | undefined;
let actionElapsed = 0;
let riskyArmed = "", gatherSent = 0;
// A gather target can stay legitimately, persistently unreachable for a long time (a
// depleted resource waits out a real respawn timer measured in minutes, not a stray
// frame) -- retrying it forever would starve everything else. But a *working* attack is
@@ -64,7 +65,7 @@ function send(op: string, target = '', x = 0, z = 0, slot = '') {
}
function selection(entity?: Entity) {
view.selected = entity; visible('target', !!entity);
if (entity) { $('target-name').textContent = entity.name; $('target-health').textContent = ['boss', 'sentinel', 'player'].includes(entity.kind) ? `${Math.ceil(entity.hp)} / ${Math.ceil(entity.maxHp)}` : pretty(entity.kind); }
if (entity) { $('target-name').textContent = entity.name; $('target-health').textContent = ['boss', 'sentinel', 'player'].includes(entity.kind) ? `${Math.ceil(entity.hp)} / ${Math.ceil(entity.maxHp)}` : pretty(entity.kind); const risk=snapshot?.gatherRisks?.[entity.resourceId??entity.kind];if(risk){const skill=snapshot?.self.gathering?.[entity.skillId??''];$('target-health').textContent=`${skill?.name??'Gathering'} ${entity.requiredLevel??1} · Yours ${skill?.level??1} (effective ${skill?.effectiveLevel??1}) · ${risk.seconds.toFixed(1)}s interval · ${risk.allowed?`${risk.failure.toFixed(0)}% failure; on failure ${risk.destruction.toFixed(0)}% destruction, ${risk.negative.toFixed(0)}% chance of ${risk.damage.toFixed(0)} damage + fatigue`:'Too difficult: over +20 levels'}`;} }
}
function action(op: string) {
if (!snapshot) return;
@@ -77,6 +78,13 @@ function action(op: string) {
}
if (!target) { notice('No target nearby.'); return; }
selection(target);
const risk=snapshot.gatherRisks?.[target.resourceId??target.kind];
if(op==='gather'&&risk){
walkTo=undefined;pendingAction=undefined;
if(!risk.allowed){notice('This resource is more than 20 levels above your effective gathering level.');return;}
if(risk.failure>0&&riskyArmed!==target.id){riskyArmed=target.id;notice(`Dangerous attempt: ${risk.failure.toFixed(0)}% failure. Inspect the target risks, then press Gather again to attempt.`);return;}
}
riskyArmed='';gatherSent=0;
pendingAction = { op: target.kind === 'corpse' ? 'loot' : op, target: target.id };
walkTo = target.position;
lastProgress = undefined; lastProgressAt = Date.now();
@@ -89,6 +97,8 @@ function connect() {
ws.onmessage = event => {
const value = JSON.parse(event.data) as Snapshot;
if (value.type !== 'snapshot' || value.version !== 1) { ws?.close(); notice('Client and server versions do not match.'); return; }
if(pendingAction?.op==='gather' && snapshot && value.self.gatherAttempt!==snapshot.self.gatherAttempt){pendingAction=undefined;walkTo=undefined;gatherSent=0;}
if(gatherSent && value.self.ack>=gatherSent)gatherSent=0;
snapshot = value; view.update(value); updateHUD(value);
const state = value.self.entity.state;
if (state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. Their belongings remain in this world.', false);
@@ -130,7 +140,8 @@ function inventory(c: Character) {
row.append(label, button); recipes.append(row);
}
const skills = $('skills'); skills.replaceChildren();
for (const skill of ['gathering', 'crafting', 'combat']) { const label = document.createElement('span'); label.textContent = pretty(skill); const amount = document.createElement('b'); amount.textContent = `${c.skills[skill] ?? 0} XP`; label.append(amount); skills.append(label); }
for(const g of Object.values(c.gathering??{})){const label=document.createElement('span');label.textContent=`${g.name} · Level ${g.level} (effective ${g.effectiveLevel})`;const amount=document.createElement('b');amount.textContent=`${g.xp} XP · ${g.xpToNextLevel} to next`;label.append(amount);skills.append(label);}
for (const skill of ['crafting', 'combat']) { const label = document.createElement('span'); label.textContent = pretty(skill); const amount = document.createElement('b'); amount.textContent = `${c.skills[skill] ?? 0} XP`; label.append(amount); skills.append(label); }
}
function minimap(s: Snapshot) {
const canvas = $<HTMLCanvasElement>('minimap'), ctx = canvas.getContext('2d')!;
@@ -180,7 +191,7 @@ async function boot() {
input = new InputActions(() => hasOpenMenu() || isEditing(document.activeElement) || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open, key => {
if(key==='attack'||key==='gather')action(key);
else if(key==='inventory')$('inventory-toggle').click();
else if(key==='heal'||key==='return')send(key);
else if(key==='heal'||key==='return'||key==='jump')send(key);
});
view.start(dt => {
inputElapsed += dt;
@@ -211,12 +222,12 @@ async function boot() {
actionElapsed = 0;
const sig = progressSignature();
if (sig !== undefined && sig !== lastProgress) { lastProgress = sig; lastProgressAt = Date.now(); }
if (Date.now() - lastProgressAt > 5000) {
if (Date.now() - lastProgressAt > Math.max(5000,((snapshot.gatherRisks?.[target?.resourceId??target?.kind??'']?.seconds??0)+2)*1000)) {
avoidUntil.set(pendingAction.target, Date.now() + 8000);
const retryOp = pendingAction.op === 'loot' ? 'gather' : pendingAction.op;
walkTo = undefined; pendingAction = undefined;
action(retryOp);
} else { send(pendingAction.op, pendingAction.target); }
if(retryOp!=='gather')action(retryOp);else notice('Gathering stopped. Select a resource to try again.');
} else if(pendingAction.op!=='gather'||!gatherSent) { send(pendingAction.op, pendingAction.target);if(pendingAction.op==='gather')gatherSent=sequence; }
}
}
} else { x = dx / distance; z = dz / distance; actionElapsed = 0.3; }
@@ -265,7 +276,7 @@ async function boot() {
};
document.querySelectorAll<HTMLButtonElement>(`[data-close="${id}"]`).forEach(button=>button.onclick=()=>menu.close());
}
$('attack').onclick = () => input.trigger('attack'); $('gather').onclick = () => input.trigger('gather'); $('heal').onclick = () => input.trigger('heal'); $('keystone').onclick = () => input.trigger('return');
$('jump').onclick = () => input.trigger('jump'); $('attack').onclick = () => input.trigger('attack'); $('gather').onclick = () => input.trigger('gather'); $('heal').onclick = () => input.trigger('heal'); $('keystone').onclick = () => input.trigger('return');
$('target-boss').onclick = () => { selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); };
$('dev-boss').onclick = () => void api('/api/dev/boss', {}).catch(e => notice(e.message));
$('reconnect').onclick = () => location.reload();
+4 -2
View File
@@ -1,7 +1,7 @@
import { api, el, type RecordCharacter } from './portal-shared';
import { statLabel } from './character-stats';
type Catalog={items:{id:string;name:string}[];titles:{id:string;name:string}[]};
type Catalog={gathering?:{resources:{id:string;name:string;output:string}[];consumables:{id:string;name:string}[]};items:{id:string;name:string}[];titles:{id:string;name:string}[]};
export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()=>void){
const root=el('section','','player-content');root.append(el('h3','Manage items and titles'));
if(!enabled){root.append(el('p','A living character or survivor with an available world owner is required.','muted'));return root;}
@@ -19,11 +19,13 @@ export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()
switch(operation.value){
case 'grant-item':
for(const i of catalog.items)choice.append(new Option(`${i.name} (${i.id})`,i.id));
for(const r of catalog.gathering?.resources??[])if(r.output==='self')choice.append(new Option(r.name,r.id));
for(const i of catalog.gathering?.consumables??[])choice.append(new Option(i.name,i.id));
for(const id of ['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage'])choice.append(new Option(statLabel(id),id));
notice.textContent='Items go into the bag. Equipment requirements still apply when equipping.';break;
case 'remove-item':
for(const i of v.items??[]){const slot=Object.entries(v.equipment??{}).find(([,id])=>id===i.id)?.[0];choice.append(new Option(`${i.name}${slot?` [${statLabel(slot)}]`:''} · ${i.id}`,i.id));}
for(const [id,n] of Object.entries(v.inventory??{}))if(n>0)choice.append(new Option(`${statLabel(id)} · ${n} held`,id));
for(const [id,n] of Object.entries(v.inventory??{}))if(n>0)choice.append(new Option(`${v.stackNames?.[id]??statLabel(id)} · ${n} held`,id));
notice.textContent='Removes the selected instance or stack quantity. Equipped items are unequipped automatically.';break;
case 'grant-title':
for(const t of catalog.titles)choice.append(new Option(`${t.name} (${t.id})`,t.id));
+2
View File
@@ -9,3 +9,5 @@
@media(min-height:521px){.inventory{bottom:195px}}
@media(max-width:800px) and (min-height:521px){.movement:not([hidden]){bottom:255px}.inventory{bottom:258px;max-height:calc(100dvh - 350px)}.notice{bottom:375px}}
@media(max-height:520px){.movement:not([hidden]){bottom:178px}}
#target-health{white-space:normal;line-height:1.5;max-width:min(550px,80vw)}
+3 -2
View File
@@ -20,7 +20,7 @@ export class WorldView {
player?: T.Group;
snapshot?: Snapshot;
selected?: Entity;
distance = 46;
distance = 30;
frames = 0;
moving = false;
private highQuality = true;
@@ -124,7 +124,7 @@ export class WorldView {
if (this.chunks.has(chunk.key)) continue;
const n = chunk.resolution, step = chunk.size / n;
const positions: number[] = [], colors: number[] = [], indices: number[] = [];
const green = new T.Color('#425e3e'), light = new T.Color('#748058'), stone = new T.Color('#829092');
const green = new T.Color(chunk.color || '#425e3e'), light = new T.Color('#748058'), stone = new T.Color('#829092');
for (let z = 0; z <= n; z++) for (let x = 0; x <= n; x++) {
const wx = chunk.x * chunk.size + x * step, wz = chunk.z * chunk.size + z * step;
const h = chunk.heights[z * (n + 1) + x];
@@ -177,6 +177,7 @@ export class WorldView {
}
update(snapshot: Snapshot) {
this.snapshot = snapshot;
if (!this.initialized) this.addChunks([], []);
this.addChunks(snapshot.chunks, snapshot.chunkKeys);
const unavailable = new Set(snapshot.unavailableResources);
const resources = [...this.chunks.values()].flatMap(c => c.data.resources).filter(r => !unavailable.has(r.id));