Add spells, weapon abilities, and durable corpse resurrection
This commit is contained in:
@@ -26,7 +26,9 @@ export function statsBreakdown(c:Character) {
|
||||
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;}
|
||||
}
|
||||
for(const p of Object.values(c.crafting??{})){const row=body.insertRow();const th=node('th',`${p.name}: level ${p.level} · ${p.xp} XP · ${p.xpToNextLevel} to next`);th.colSpan=5;row.append(th);}
|
||||
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;
|
||||
for(const v of Object.values(c.weapons??{})){const row=body.insertRow();const th=node('th',`${v.name}: level ${v.level} · ${v.xp} XP`);th.colSpan=5;row.append(th)}
|
||||
for(const v of Object.values(c.powers??{})){const row=body.insertRow();const th=node('th',`${v.definition.name}: rank ${v.level} · ${v.xp} XP`);th.colSpan=5;row.append(th)}
|
||||
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');
|
||||
|
||||
@@ -9,7 +9,7 @@ function craftPool(){return repeat<CraftStat>('Available crafted stats','Add pos
|
||||
const group=node('div','','catalog-fields'),stat=select(statKeys,value?.stat),min=number(value?.min??1,-1000000),max=number(value?.max??5,-1000000),weight=number(value?.weight??1,.01,1000),percent=node('input');percent.type='checkbox';percent.checked=value?.percent??false;
|
||||
group.append(field('Stat',stat),field('Minimum roll',min),field('Maximum roll',max),field('Selection weight',weight),field('Percentage modifier',percent));
|
||||
return {node:group,read:()=>({stat:stat.value,min:Number(min.value),max:Number(max.value),weight:Number(weight.value),percent:percent.checked})};},[],32);}
|
||||
function craftMaterials(){return [...['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'].map(id=>({id,name:statLabel(id)})),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...(catalog.gathering?.consumables??[]),...(catalog.crafting?.materials??[])];}
|
||||
function craftMaterials(){return [...['axe','flint_and_steel','fishing_pole','wood','ore','herb','bandage','escape_stone'].map(id=>({id,name:statLabel(id)})),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...(catalog.gathering?.consumables??[]),...(catalog.crafting?.materials??[]),{id:'revival_stone',name:'Revival stone'},...(catalog.powers?.powers??[]).filter(p=>p.book).map(p=>({id:'book_'+p.id,name:p.name+' spell book'}))];}
|
||||
function recipeForm(initial?:CraftRecipe){
|
||||
if(editing||saving){show('Finish or cancel the open draft first.');return;}
|
||||
const values=identity(initial),profession=contentChoice(catalog.crafting?.professions??[],initial?.profession),level=number(initial?.level??1,1,1000,'1'),xp=number(initial?.xp??20,1,1000000,'1');
|
||||
@@ -41,7 +41,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'],['gathering','Gathering'],['resources','Resources'],['biomes','Biomes'],['consumables','Consumables'],['attacks','Attacks'],['mobs','Mobs'],['loot','Loot tables'],['spawns','Mob spawns'],['craft-recipes','Recipes'],['craft-professions','Crafting professions'],['craft-materials','Crafting materials'],['craft-rules','Crafting tuning'],['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'],['attacks','Attacks'],['mobs','Mobs'],['loot','Loot tables'],['spawns','Mob spawns'],['powers','Spells and abilities'],['weapons','Weapon types'],['craft-recipes','Recipes'],['craft-professions','Crafting professions'],['craft-materials','Crafting materials'],['craft-rules','Crafting tuning'],['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;}
|
||||
@@ -96,7 +96,7 @@ 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.craftRecipe??r.craftProfession??r.craftMaterial??r.title??r.item??r.requirementSet??r.effectSet??r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn;
|
||||
const definition=r.power??r.weapon??r.craftRecipe??r.craftProfession??r.craftMaterial??r.title??r.item??r.requirementSet??r.effectSet??r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn;
|
||||
if(definition)root.append(node('strong',definition.name),node('p',definition.description),node('p',r.targetId?`Revision ${r.biome?.revision??r.craftRecipe?.revision} of the existing definition`:'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(' / ')));
|
||||
@@ -104,7 +104,8 @@ function previewView(result:ContentPreview){
|
||||
const modifiers=r.title?.effects.modifiers??r.item?.modifiers??r.effectSet?.modifiers;if(modifiers)root.append(modifiersView(modifiers));
|
||||
if(r.item?.craftPool?.length)root.append(node('p',`${r.item.craftRolls??0} random stat rolls per crafted item`),readableDefinition(r.item.craftPool));
|
||||
if(r.gatheringSkill||r.resource||r.biome||r.consumable||r.attack||r.mob||r.loot||r.spawn)root.append(readableDefinition(r.gatheringSkill??r.resource??r.biome??r.consumable??r.attack??r.mob??r.loot??r.spawn));
|
||||
if(r.craftRecipe||r.craftProfession||r.craftMaterial||r.craftRules)root.append(readableDefinition(r.craftRecipe??r.craftProfession??r.craftMaterial??r.craftRules));
|
||||
if(r.power||r.weapon)root.append(readableDefinition(r.power??r.weapon));
|
||||
if(r.craftRecipe||r.craftProfession||r.craftMaterial||r.craftRules)root.append(readableDefinition(r.craftRecipe??r.craftProfession??r.craftMaterial??r.craftRules));
|
||||
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'),readableDefinition(r.stats));root.append(details);}
|
||||
return root;
|
||||
}
|
||||
@@ -119,13 +120,14 @@ function titleForm(){
|
||||
function itemForm(){
|
||||
if(editing||saving){show('Finish or cancel the open draft first.');return;}
|
||||
const pool=craftPool(),rolls=number(0,0,8,'1');
|
||||
const weaponType=contentChoice([{id:'',name:'No proficiency'},...(catalog.powers?.weapons??[])]);weaponType.required=false;
|
||||
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,'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 attack=contentChoice([{id:'',name:'Basic melee / none'},...(catalog.combat?.attacks??[])]);attack.required=false;
|
||||
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(),craftPool:pool.read(),craftRolls:Number(rolls.value),slot:slot.value,...(slot.value==='weapon'&&attack.value?{attackId:attack.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()}}});
|
||||
fields.append(values.node,field('Equipment slot',slot),field('Weapon attack profile',attack),field('Weight',weight),field('Sentinel drop chance (%)',drop),node('p','Zero disables sentinel drops. Drop-rate bonuses apply. Requirements are checked without equipment bonuses.','muted'),sets.node,field('Required level',level),requirements.node,titles,effects.node,field('Stats rolled when crafted',rolls),pool.node);
|
||||
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(),weaponType:weaponType.value,craftPool:pool.read(),craftRolls:Number(rolls.value),slot:slot.value,...(slot.value==='weapon'&&attack.value?{attackId:attack.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()}}});
|
||||
fields.append(values.node,field('Equipment slot',slot),field('Weapon attack profile',attack),field('Weapon proficiency',weaponType),field('Weight',weight),field('Sentinel drop chance (%)',drop),node('p','Zero disables sentinel drops. Drop-rate bonuses apply. Requirements are checked without equipment bonuses.','muted'),sets.node,field('Required level',level),requirements.node,titles,effects.node,field('Stats rolled when crafted',rolls),pool.node);
|
||||
}
|
||||
function statsForm(){
|
||||
if(editing||saving){show('Finish or cancel the open draft first.');return;}
|
||||
@@ -136,7 +138,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.startsWith('craft-')){craftingList();
|
||||
if(section==='powers'||section==='weapons'){powerList();
|
||||
}else if(section.startsWith('craft-')){craftingList();
|
||||
}else if(['attacks','mobs','loot','spawns'].includes(section)){combatList();
|
||||
}else if(['gathering','resources','biomes','consumables'].includes(section)){gatheringList();
|
||||
}else if(section==='titles'){
|
||||
@@ -163,7 +166,7 @@ function contentChoice(values:{id:string;name:string}[],initial?:string) {
|
||||
}
|
||||
|
||||
function readableDefinition(value:unknown, context=''):HTMLElement {
|
||||
const names = [...catalog.items,...catalog.titles,...(catalog.gathering?.skills??[]),...(catalog.gathering?.resources??[]),...(catalog.gathering?.biomes??[]),...(catalog.gathering?.consumables??[]),...(catalog.combat?.attacks??[]),...(catalog.combat?.mobs??[]),...(catalog.combat?.loot??[]),...(catalog.crafting?.professions??[]),...(catalog.crafting?.materials??[])];
|
||||
const names = [...catalog.items,...catalog.titles,...(catalog.gathering?.skills??[]),...(catalog.gathering?.resources??[]),...(catalog.gathering?.biomes??[]),...(catalog.gathering?.consumables??[]),...(catalog.combat?.attacks??[]),...(catalog.combat?.mobs??[]),...(catalog.combat?.loot??[]),...(catalog.crafting?.professions??[]),...(catalog.crafting?.materials??[]),...(catalog.powers?.weapons??[]),...(catalog.powers?.powers??[])];
|
||||
const reference=(v:string)=>names.find(n=>n.id===v)?.name??statLabel(v);
|
||||
if(Array.isArray(value)) {
|
||||
const list=node('ul','','catalog-values');
|
||||
@@ -238,7 +241,7 @@ function combatForm(kind:string){
|
||||
const fields=form('Create mob','create-mob',()=>({mob:{...values.read(),model:model.value,behavior:behavior.value,attackId:attack.value,lootId:loot.value,...Object.fromEntries(inputs.map(v=>[v.key,Number(v.input.value)]))}}));
|
||||
fields.append(values.node,field('Model preset',model),field('Behavior',behavior),field('Attack profile',attack),field('Loot table',loot),...inputs.map(v=>field(v.label,v.input)),node('p','Health/power = base × level × (1 + world age in days × scaling). Defence is flat. Aggressive creatures pursue within the leash; guards defend their detection radius; passive creatures retaliate only when attacked. Models remain placeholders until milestone 4.5.','muted'));
|
||||
}else if(kind==='loot'){
|
||||
const items=[...catalog.items,...(catalog.crafting?.materials??[]),...(catalog.gathering?.consumables??[]),...(catalog.gathering?.resources??[]).filter(r=>r.output==='self'),...['wood','ore','herb','bandage','escape_stone','axe','flint_and_steel','fishing_pole'].map(id=>({id,name:statLabel(id)}))];
|
||||
const items=[...catalog.items,...craftMaterials()];
|
||||
const entries=repeat('Loot entries','Add loot entry',()=>{const group=node('div','','catalog-fields'),item=contentChoice(items),amount=number(1,1,100,'1'),chance=number(100,0,100),pool=text('',40),weight=number(1,1,10000,'1');pool.required=false;group.append(field('Item',item),field('Quantity',amount),field('Drop chance (%)',chance),field('Weighted group (blank = independent)',pool),field('Group weight',weight));return{node:group,read:()=>({item:item.value,amount:Number(amount.value),chance:Number(chance.value),group:pool.value.trim(),weight:Number(weight.value)})}},[],32);
|
||||
const fields=form('Create loot table','create-loot',()=>({loot:{...values.read(),entries:entries.read()}}));fields.append(values.node,entries.node,node('p','Blank groups roll independently; 100% is guaranteed. Each named group selects one entry by weight, then rolls that entry’s chance. Finisher luck affects non-guaranteed chances. New mobs leave a lootable corpse; the corpse is shared and may be looted by nearby players.','muted'));
|
||||
}else{
|
||||
@@ -253,3 +256,24 @@ function combatList(){
|
||||
list.append(button(`Create ${labels[section]}`,()=>combatForm(section)));
|
||||
for(const v of entries??[]){const d=node('details','','catalog-definition');d.append(node('summary',v.name),node('p',v.description),readableDefinition(v));list.append(d)}
|
||||
}
|
||||
|
||||
function powerList(){
|
||||
const p=catalog.powers;if(!p)return;
|
||||
if(section==='weapons'){
|
||||
list.append(button('Create weapon type',()=>{if(editing||saving)return;const values=identity(),base=number(100,1,1000000,'1'),per=number(50,1,1000000,'1'),max=number(1000,1,1000,'1');form('Create weapon type','create-weapon',()=>({weapon:{...values.read(),baseXp:Number(base.value),xpPerLevel:Number(per.value),maxLevel:Number(max.value)}})).append(values.node,field('XP to level 2',base),field('Additional XP per level',per),field('Maximum level',max));}));
|
||||
for(const w of p.weapons){const d=node('details','','catalog-definition');d.append(node('summary',w.name),readableDefinition(w));list.append(d)}return;
|
||||
}
|
||||
list.append(button('Create spell or ability',powerForm));
|
||||
for(const v of p.powers){const d=node('details','','catalog-definition');d.append(node('summary',v.name+' · '+v.kind),node('p',v.description),readableDefinition(v));if(v.book)d.append(node('p','Teach using '+v.name+' spell book, available in player item controls and loot tables.'));list.append(d)}
|
||||
}
|
||||
function powerForm(){
|
||||
if(editing||saving)return;
|
||||
const values=identity(),kind=select(['spell','ability']),attack=contentChoice(catalog.combat?.attacks??[]),targeting=select(['target','self','aura']),weapon=contentChoice([{id:'',name:'None'},...(catalog.powers?.weapons??[])]);weapon.required=false;
|
||||
const resurrection=node('input'),book=node('input');resurrection.type=book.type='checkbox';book.checked=true;
|
||||
const basePower=number(10,0,100000),weaponLevel=number(1,1,1000,'1'),level=number(1,1,1000,'1'),mana=number(5,0,10000),cast=number(0,0,30),cooldown=number(2,.1,120),scaling=number(.03,0,1),base=number(100,1,1000000,'1'),per=number(50,1,1000000,'1'),max=number(1000,1,1000,'1');
|
||||
const stats=repeat<{stat:string;minimum:number}>('Required stats without equipment','Add requirement',v=>{const group=node('div','','catalog-fields'),stat=select(statKeys,v?.stat),minimum=number(v?.minimum??1,0,1000000);group.append(field('Stat',stat),field('Minimum',minimum));return {node:group,read:()=>({stat:stat.value,minimum:Number(minimum.value)})}},[],32);
|
||||
const parents=repeat<{id:string;rank:number}>('Predecessor spells (all required)','Add predecessor',v=>{const group=node('div','','catalog-fields'),id=contentChoice((catalog.powers?.powers??[]).filter(p=>p.kind==='spell'),v?.id),rank=number(v?.rank??2,1,1000,'1');group.append(field('Spell',id),field('Required rank',rank));return {node:group,read:()=>({id:id.value,rank:Number(rank.value)})}},[],16);
|
||||
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 fields=form('Create spell or ability','create-power',()=>{const r=stats.read(),pre=parents.read();if(new Set(r.map(v=>v.stat)).size!==r.length||new Set(pre.map(v=>v.id)).size!==pre.length)throw new Error('Requirements must not repeat.');return {power:{...values.read(),kind:kind.value,attackId:resurrection.checked?'':attack.value,targeting:resurrection.checked?'target':targeting.value,resurrection:resurrection.checked,weapon:kind.value==='ability'?weapon.value:'',weaponLevel:Number(weaponLevel.value),requirements:{level:Number(level.value),stats:Object.fromEntries(r.map(v=>[v.stat,v.minimum])),titles:checks.filter(v=>v.input.checked).map(v=>v.id)},parents:kind.value==='ability'?{}:Object.fromEntries(pre.map(v=>[v.id,v.rank])),book:kind.value==='spell'&&book.checked,mana:Number(mana.value),castSeconds:resurrection.checked?0:Number(cast.value),cooldown:Number(cooldown.value),basePower:Number(basePower.value),rankScaling:Number(scaling.value),baseXp:Number(base.value),xpPerLevel:Number(per.value),maxLevel:kind.value==='ability'?1:Number(max.value)}}});
|
||||
fields.append(values.node,field('Kind',kind),field('Combat effect profile',attack),field('Targeting',targeting),field('Corpse resurrection (instant, adjacent, consent required)',resurrection),field('Learn from a consumable spell book',book),field('Weapon type for ability',weapon),field('Weapon level required',weaponLevel),field('Character level required',level),stats.node,titles,parents.node,field('Base effect power',basePower),field('Mana cost',mana),field('Cast time (seconds)',cast),field('Cooldown (seconds)',cooldown),field('Power increase per rank (0.03 = 3%)',scaling),field('XP to rank 2',base),field('Additional XP per rank',per),field('Maximum spell rank',max),node('p','A spell without a book automatically unlocks from its predecessor requirements. Abilities require the matching equipped weapon. Existing learned powers retain their definition. Aura profiles require a melee delivery, radius, and duration.','muted'));
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface ContentCatalog {
|
||||
effectSets?: EffectSet[];
|
||||
gathering?: GatheringContent;
|
||||
items: ItemDefinition[];
|
||||
powers?: PowerContent;
|
||||
requirementSets?: RequirementSet[];
|
||||
stats: ContentStatsRules;
|
||||
titles: TitleDefinition[];
|
||||
@@ -213,6 +214,7 @@ export interface ItemDefinition {
|
||||
name: string;
|
||||
requirements: ItemRequirements;
|
||||
slot: string;
|
||||
weaponType?: string;
|
||||
weight: number;
|
||||
}
|
||||
|
||||
@@ -230,6 +232,38 @@ export interface ItemRequirements {
|
||||
titles: string[];
|
||||
}
|
||||
|
||||
export interface PowerContent {
|
||||
powers: PowerDefinition[];
|
||||
revivalHealth: number;
|
||||
revivalRange: number;
|
||||
spellXp: number;
|
||||
weaponXp: number;
|
||||
weapons: GatheringSkill[];
|
||||
}
|
||||
|
||||
export interface PowerDefinition {
|
||||
attackId: string;
|
||||
basePower: number;
|
||||
baseXp: number;
|
||||
book: boolean;
|
||||
castSeconds: number;
|
||||
cooldown: number;
|
||||
description: string;
|
||||
id: string;
|
||||
kind: string;
|
||||
mana: number;
|
||||
maxLevel: number;
|
||||
name: string;
|
||||
parents: { [key: string]: number };
|
||||
rankScaling: number;
|
||||
requirements: ItemRequirements;
|
||||
resurrection: boolean;
|
||||
targeting: string;
|
||||
weapon: string;
|
||||
weaponLevel: number;
|
||||
xpPerLevel: number;
|
||||
}
|
||||
|
||||
export interface RequirementSet {
|
||||
description: string;
|
||||
id: string;
|
||||
@@ -280,6 +314,7 @@ export interface ContentChange {
|
||||
loot?: LootTableDraft;
|
||||
mob?: MobDefinitionDraft;
|
||||
op: string;
|
||||
power?: PowerDraft;
|
||||
reason: string;
|
||||
requirementSet?: RequirementSetDraft;
|
||||
requirementSetIds?: string[];
|
||||
@@ -288,6 +323,7 @@ export interface ContentChange {
|
||||
stats?: ContentStatsRules;
|
||||
targetId?: string;
|
||||
title?: TitleDraft;
|
||||
weapon?: GatheringSkillDraft;
|
||||
}
|
||||
|
||||
export interface CombatAttackDraft {
|
||||
@@ -374,6 +410,7 @@ export interface ItemDraft {
|
||||
name: string;
|
||||
requirements: ItemRequirements;
|
||||
slot: string;
|
||||
weaponType?: string;
|
||||
weight: number;
|
||||
}
|
||||
|
||||
@@ -403,6 +440,29 @@ export interface MobDefinitionDraft {
|
||||
xp: number;
|
||||
}
|
||||
|
||||
export interface PowerDraft {
|
||||
attackId: string;
|
||||
basePower: number;
|
||||
baseXp: number;
|
||||
book: boolean;
|
||||
castSeconds: number;
|
||||
cooldown: number;
|
||||
description: string;
|
||||
id?: string;
|
||||
kind: string;
|
||||
mana: number;
|
||||
maxLevel: number;
|
||||
name: string;
|
||||
parents: { [key: string]: number };
|
||||
rankScaling: number;
|
||||
requirements: ItemRequirements;
|
||||
resurrection: boolean;
|
||||
targeting: string;
|
||||
weapon: string;
|
||||
weaponLevel: number;
|
||||
xpPerLevel: number;
|
||||
}
|
||||
|
||||
export interface RequirementSetDraft {
|
||||
description: string;
|
||||
id?: string;
|
||||
@@ -564,6 +624,7 @@ export interface Character {
|
||||
allocatedStats: { [key: string]: number };
|
||||
attack?: CombatAttack;
|
||||
carryWeight: number;
|
||||
casting?: string;
|
||||
consumables?: GatheringConsumable[];
|
||||
craftedStacks?: CraftedStack[];
|
||||
crafting?: { [key: string]: CraftProgress };
|
||||
@@ -585,6 +646,7 @@ export interface Character {
|
||||
manaChoices: number;
|
||||
pendingVitalChoices: number;
|
||||
playedSeconds: number;
|
||||
powers?: { [key: string]: LearnedPower };
|
||||
remainingSeconds: number;
|
||||
skills: { [key: string]: number };
|
||||
stackNames?: { [key: string]: string };
|
||||
@@ -592,6 +654,7 @@ export interface Character {
|
||||
statPoints: number;
|
||||
stats: { [key: string]: StatValue };
|
||||
titles: TitleAward[];
|
||||
weapons?: { [key: string]: WeaponProgress };
|
||||
}
|
||||
|
||||
export interface CraftedStack {
|
||||
@@ -659,9 +722,19 @@ export interface ItemInstance {
|
||||
requirementMessage: string;
|
||||
requirements: ItemRequirements;
|
||||
slot: string;
|
||||
weaponType?: string;
|
||||
weight: number;
|
||||
}
|
||||
|
||||
export interface LearnedPower {
|
||||
attack: CombatAttack;
|
||||
definition: PowerDefinition;
|
||||
level: number;
|
||||
readyAt: number;
|
||||
xp: number;
|
||||
xpToNextLevel: number;
|
||||
}
|
||||
|
||||
export interface TitleAward {
|
||||
description: string;
|
||||
earnedAt: string;
|
||||
@@ -672,6 +745,14 @@ export interface TitleAward {
|
||||
worldId: string;
|
||||
}
|
||||
|
||||
export interface WeaponProgress {
|
||||
id: string;
|
||||
level: number;
|
||||
name: string;
|
||||
xp: number;
|
||||
xpToNextLevel: number;
|
||||
}
|
||||
|
||||
export interface WorldInfo {
|
||||
ageSeconds: number;
|
||||
bossHp: number;
|
||||
|
||||
@@ -1,37 +1,2 @@
|
||||
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:'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"])');
|
||||
}
|
||||
|
||||
// Physical input is separate from gameplay intents. Rebinding/controller mapping
|
||||
// can feed these same actions later without changing authoritative game commands.
|
||||
export class InputActions {
|
||||
private held = new Map<string, InputAction>();
|
||||
constructor(private blocked: () => boolean, private onAction: (action: InputAction) => void) {
|
||||
window.addEventListener('keydown', event => {
|
||||
const action = bindings[event.code];
|
||||
if (!action || event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || isEditing(event.target) || blocked()) return;
|
||||
event.preventDefault();
|
||||
if (['north','south','west','east'].includes(action)) this.held.set(event.code, action);
|
||||
else if (!event.repeat) this.trigger(action);
|
||||
});
|
||||
window.addEventListener('keyup', event => this.held.delete(event.code));
|
||||
window.addEventListener('blur', () => this.clear());
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) this.clear(); });
|
||||
document.addEventListener('focusin', event => { if (isEditing(event.target) || blocked()) this.clear(); });
|
||||
}
|
||||
trigger(action: InputAction) { if (!this.blocked()) this.onAction(action); }
|
||||
press(source: string, action: InputAction) { if (!this.blocked()) this.held.set(source, action); }
|
||||
release(source: string) { this.held.delete(source); }
|
||||
clear() { this.held.clear(); }
|
||||
get keys() { return [...this.held.keys()]; }
|
||||
get movement() {
|
||||
if (this.blocked()) { this.clear(); return {x:0,z:0}; }
|
||||
const actions = new Set(this.held.values());
|
||||
return {x:Number(actions.has('east'))-Number(actions.has('west')), z:Number(actions.has('south'))-Number(actions.has('north'))};
|
||||
}
|
||||
}
|
||||
export { InputActions, isEditing, actionNames } from './input-controls';
|
||||
export type { InputAction } from './input-controls';
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
export type InputAction = 'north'|'south'|'west'|'east'|'attack'|'gather'|'inventory'|'heal'|'return'|'jump'|'next-target'|'previous-target'|'cancel-cast'|'slot1'|'slot2'|'slot3'|'slot4'|'slot5'|'slot6'|'slot7'|'slot8';
|
||||
export const actionNames:InputAction[]=['north','south','west','east','attack','gather','inventory','heal','return','jump','next-target','previous-target','cancel-cast','slot1','slot2','slot3','slot4','slot5','slot6','slot7','slot8'];
|
||||
const defaults:Record<string,InputAction>={KeyW:'north',ArrowUp:'north',KeyS:'south',ArrowDown:'south',KeyA:'west',ArrowLeft:'west',KeyD:'east',ArrowRight:'east',Space:'jump',KeyF:'attack',KeyE:'gather',KeyI:'inventory',KeyQ:'previous-target',KeyR:'next-target',KeyX:'cancel-cast',Digit1:'slot1',Digit2:'slot2',Digit3:'slot3',Digit4:'slot4',Digit5:'slot5',Digit6:'slot6',Digit7:'slot7',Digit8:'slot8'};
|
||||
const padDefaults:Record<string,InputAction>={'0':'jump','1':'gather','2':'attack','3':'heal','4':'previous-target','5':'next-target','6':'slot1','7':'slot2','9':'inventory','12':'slot3','13':'slot4','14':'slot5','15':'slot6'};
|
||||
export function isEditing(target:EventTarget|null){return target instanceof HTMLElement&&!!target.closest('input,select,textarea,[contenteditable]:not([contenteditable="false"])');}
|
||||
const valid=(a:unknown):a is InputAction=>typeof a==='string'&&actionNames.includes(a as InputAction);
|
||||
import { closeFocusedMenu } from './menu-focus';
|
||||
export class InputActions {
|
||||
private held=new Map<string,InputAction>();
|
||||
private bindings={...defaults};private padBindings={...padDefaults};private padPressed=new Set<string>();
|
||||
private padX=0;private padZ=0;
|
||||
constructor(private blocked:()=>boolean,private onAction:(action:InputAction)=>void){
|
||||
try{const data=JSON.parse(localStorage.getItem('aeternalis.controls.v1')??'null');if(data){this.bindings={};this.padBindings={};for(const [code,a] of Object.entries(data.keyboard??{}))if(valid(a)&&code!=='Escape')this.bindings[code]=a;for(const [code,a] of Object.entries(data.gamepad??{}))if(valid(a)&&/^\d+$/.test(code)&&Number(code)<32)this.padBindings[code]=a;}}catch{/* Defaults remain usable when storage is unavailable. */}
|
||||
window.addEventListener('keydown',e=>{const a=this.bindings[e.code];if(!a||e.defaultPrevented||e.ctrlKey||e.metaKey||e.altKey||isEditing(e.target)||blocked())return;e.preventDefault();if(['north','south','west','east'].includes(a))this.held.set(e.code,a);else if(!e.repeat)this.trigger(a);});
|
||||
window.addEventListener('keyup',e=>this.held.delete(e.code));window.addEventListener('blur',()=>this.clear());
|
||||
document.addEventListener('visibilitychange',()=>{if(document.hidden)this.clear()});document.addEventListener('focusin',e=>{if(isEditing(e.target)||blocked())this.clear()});
|
||||
}
|
||||
trigger(action:InputAction){if(!this.blocked()&&!document.hidden)this.onAction(action)}
|
||||
press(source:string,action:InputAction){if(!this.blocked())this.held.set(source,action)}
|
||||
release(source:string){this.held.delete(source)}
|
||||
clear(){this.held.clear();this.padX=this.padZ=0}
|
||||
get keys(){return [...this.held.keys()]}
|
||||
pollController(){
|
||||
this.padX=this.padZ=0;const pressed=new Set<string>();const pad=navigator.getGamepads?.().find(p=>p?.connected);if(!pad){this.padPressed=pressed;return}
|
||||
const blocked=this.blocked()||document.hidden||!document.hasFocus();
|
||||
if(!blocked){this.padX=Math.abs(pad.axes[0]??0)>.2?pad.axes[0]:0;this.padZ=Math.abs(pad.axes[1]??0)>.2?pad.axes[1]:0}
|
||||
pad.buttons.forEach((b,i)=>{if(!b.pressed)return;const key=String(i);pressed.add(key);const action=this.padBindings[key];if(blocked&&!document.hidden&&document.hasFocus()&&!this.padPressed.has(key))this.menuButton(i);if(action&&!blocked){if(action==='east')this.padX=1;else if(action==='west')this.padX=-1;else if(action==='north')this.padZ=-1;else if(action==='south')this.padZ=1;else if(!this.padPressed.has(key))this.trigger(action)}});this.padPressed=pressed;
|
||||
}
|
||||
get movement(){if(this.blocked()){this.clear();return{x:0,z:0}};const a=new Set(this.held.values());return{x:Math.max(-1,Math.min(1,Number(a.has('east'))-Number(a.has('west'))+this.padX)),z:Math.max(-1,Math.min(1,Number(a.has('south'))-Number(a.has('north'))+this.padZ))}}
|
||||
private menuButton(i:number){
|
||||
if(i===1||i===9){closeFocusedMenu();return}
|
||||
const focused=document.activeElement as HTMLElement|null,menu=focused?.closest('.panel,dialog,form');if(!menu)return;
|
||||
const options=[...menu.querySelectorAll<HTMLElement>('button:not([disabled]),input:not([disabled]),select:not([disabled]),summary,a[href]')].filter(e=>e.getClientRects().length>0);
|
||||
if(i===12||i===13){const at=options.indexOf(focused!);options[(at+(i===13?1:options.length-1)+options.length)%options.length]?.focus();return}
|
||||
if((i===14||i===15)&&focused instanceof HTMLSelectElement){focused.selectedIndex=Math.max(0,Math.min(focused.options.length-1,focused.selectedIndex+(i===15?1:-1)));focused.dispatchEvent(new Event('change',{bubbles:true}));return}
|
||||
if(i===0&&focused&&!['INPUT','SELECT'].includes(focused.tagName))focused.click();
|
||||
}
|
||||
settings(){
|
||||
const root=document.createElement('details');const title=document.createElement('summary');title.textContent='Keyboard and controller bindings';root.append(title);
|
||||
const note=document.createElement('p');note.textContent='Left stick moves. Button numbers use the browser gamepad mapping. Esc always closes the focused menu. Bindings are saved on this browser.';root.append(note);
|
||||
const render=()=>{root.querySelectorAll('label').forEach(e=>e.remove());for(const a of actionNames){const label=document.createElement('label');label.textContent=a.replaceAll('-',' ');const keyboard=document.createElement('select'),pad=document.createElement('select');keyboard.setAttribute('aria-label',a+' keyboard');pad.setAttribute('aria-label',a+' gamepad');for(const code of ['',...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map(k=>'Key'+k),...Array.from({length:10},(_,i)=>'Digit'+i),'Space','ArrowUp','ArrowDown','ArrowLeft','ArrowRight'])keyboard.append(new Option(code||'Unbound',code));for(let i=-1;i<32;i++)pad.append(new Option(i<0?'Unbound':'Button '+i,i<0?'':String(i)));keyboard.value=Object.keys(this.bindings).find(k=>this.bindings[k]===a)??'';pad.value=Object.keys(this.padBindings).find(k=>this.padBindings[k]===a)??'';
|
||||
const change=(map:Record<string,InputAction>,code:string)=>{for(const k of Object.keys(map))if(map[k]===a)delete map[k];if(code)map[code]=a;this.clear();this.save();render();root.querySelector<HTMLSelectElement>(`select[aria-label="${a} ${map===this.bindings?'keyboard':'gamepad'}"]`)?.focus()};keyboard.onchange=()=>change(this.bindings,keyboard.value);pad.onchange=()=>change(this.padBindings,pad.value);label.append(keyboard,pad);root.append(label);
|
||||
}};render();const reset=document.createElement('button');reset.type='button';reset.textContent='Reset bindings';reset.onclick=()=>{this.bindings={...defaults};this.padBindings={...padDefaults};this.clear();this.save();render()};root.append(reset);return root;
|
||||
}
|
||||
private save(){try{localStorage.setItem('aeternalis.controls.v1',JSON.stringify({keyboard:this.bindings,gamepad:this.padBindings}))}catch{/* Session bindings still work. */}}
|
||||
}
|
||||
+18
-4
@@ -1,6 +1,7 @@
|
||||
import './style.css';
|
||||
import { showTravel } from './travel';
|
||||
import { craftingPanel } from './crafting-panel';
|
||||
import { createPowerPanel, revivalPanel } from './power-panel';
|
||||
import { createIcons, Crosshair, Settings2, X, Flame, LogOut, Hourglass, Swords, Pickaxe, HeartPulse, Gem, Backpack, ChevronUp, ChevronDown, ChevronLeft, ChevronRight, ArrowRight, RefreshCw } from 'lucide';
|
||||
import { WorldView } from './world-view';
|
||||
import type { Character, Chunk, Entity, Intent, Snapshot } from './generated';
|
||||
@@ -49,6 +50,7 @@ function progressSignature(): number | undefined {
|
||||
const avoidUntil = new Map<string, number>();
|
||||
let requestedClose = false;
|
||||
let input: InputActions;
|
||||
let powers:ReturnType<typeof createPowerPanel>;
|
||||
let view: WorldView;
|
||||
const selectedWorld = new URLSearchParams(location.search).get('world');
|
||||
const worldPrefix = selectedWorld && /^[a-z][a-z0-9-]{0,30}$/.test(selectedWorld) ? `/worlds/${selectedWorld}` : '';
|
||||
@@ -101,11 +103,15 @@ function connect() {
|
||||
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;
|
||||
const previousState = snapshot?.self.entity.state;
|
||||
snapshot = value; view.update(value); updateHUD(value);
|
||||
$('connection-status').textContent = 'Connected'; $('connection-dot').parentElement!.classList.remove('offline');
|
||||
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);
|
||||
else if (value.self.remainingSeconds <= 0) showEnding('Rest until tomorrow.', 'Your daily play time is complete. Your keystone will return you to your previous location after 00:00 UTC.', false);
|
||||
const ending = $<HTMLDialogElement>('ending');
|
||||
if (previousState === 'dead' && state !== 'dead') ending.close();
|
||||
if (state === 'dead') {
|
||||
if (!ending.open) showEnding('A life, remembered.', 'Your belongings remain on your corpse. Revival requires another player and your consent; replacement makes this death final.', false);
|
||||
} else if (value.self.remainingSeconds <= 0 && !ending.open) showEnding('Rest until tomorrow.', 'Your daily play time is complete. Your keystone will return you to your previous location after 00:00 UTC.', false);
|
||||
};
|
||||
ws.onclose = async () => {
|
||||
$('connection-status').textContent = 'Disconnected'; $('connection-dot').parentElement!.classList.add('offline'); input.clear(); walkTo = undefined;
|
||||
@@ -127,7 +133,8 @@ function showEnding(title: string, detail: string, survivor: boolean) {
|
||||
if (survivor && destinations.children.length === 0) { const p = document.createElement('p'); p.textContent = 'Your passage is saved. No destination world is open yet.'; destinations.append(p); }
|
||||
visible('reconnect', false);
|
||||
visible('new-character', snapshot?.self.entity.state === 'dead' && ['gathering','cataclysm'].includes(snapshot.world.phase));
|
||||
$<HTMLDialogElement>('ending').show();
|
||||
$('ending').querySelector('.revival-panel')?.remove();if(snapshot?.self.entity.state==='dead')$('ending').append(revivalPanel(worldPrefix));
|
||||
$<HTMLDialogElement>('ending').show();
|
||||
}
|
||||
function inventory(c: Character) {
|
||||
$('earned-titles').replaceChildren(permanentTitles(c.titles));
|
||||
@@ -152,6 +159,7 @@ function minimap(s: Snapshot) {
|
||||
}
|
||||
function updateHUD(s: Snapshot) {
|
||||
const c = s.self, w = s.world;
|
||||
powers?.update(c);
|
||||
visible('game-controls', true); visible('movement', ['alive','eligible'].includes(c.entity.state) && $('inventory').hidden && $('settings').hidden);
|
||||
$('character-name').textContent = c.entity.name;
|
||||
$('character-level').textContent = `Level ${c.level || 1}`;
|
||||
@@ -191,6 +199,9 @@ 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.startsWith('slot'))powers.useSlot(Number(key.slice(4))-1);
|
||||
else if(key==='cancel-cast')send('cancel-cast');
|
||||
else if(key==='next-target'||key==='previous-target'){if(!snapshot)return;const p=snapshot.self.entity.position,targets=[snapshot.self.entity,...snapshot.entities].filter(e=>['mob','sentinel','boss','player','corpse'].includes(e.kind)).sort((a,b)=>Math.hypot(a.position.x-p.x,a.position.z-p.z)-Math.hypot(b.position.x-p.x,b.position.z-p.z)||a.id.localeCompare(b.id));if(targets.length){const i=targets.findIndex(e=>e.id===view.selected?.id);selection(targets[(i+(key==='next-target'?1:targets.length-1)+targets.length)%targets.length])}}
|
||||
else if(key==='heal'||key==='return'||key==='jump')send(key);
|
||||
});
|
||||
view.start();
|
||||
@@ -201,6 +212,7 @@ async function boot() {
|
||||
const now = performance.now(), dt = (now - lastInputAt) / 1000;
|
||||
lastInputAt = now;
|
||||
inputElapsed += dt;
|
||||
input.pollController();
|
||||
if (!snapshot || ws?.readyState !== WebSocket.OPEN || $<HTMLDialogElement>('ending').open) return;
|
||||
if(document.hidden||hasOpenMenu()||isEditing(document.activeElement)){
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;view.moving=false;
|
||||
@@ -250,6 +262,7 @@ async function boot() {
|
||||
}, 50);
|
||||
const [loadedConfig, chunks] = await Promise.all([api<Config>('/api/config'), api<Chunk[]>('/api/preview'), view.load()]);
|
||||
config = loadedConfig;
|
||||
powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix);$('recipes').after(powers.root);$('hud').append(powers.hotbar);$('settings').append(input.settings());
|
||||
const travelButton=document.createElement('button');travelButton.id='travel';travelButton.textContent='Travel';travelButton.title='World travel';$('inventory-toggle').before(travelButton);
|
||||
travelButton.onclick=()=>{if(!snapshot)return;input.clear();walkTo=undefined;pendingAction=undefined;send('move');void showTravel({worldId:config.worldId,route:config.kind==='hub'?'hub':snapshot.world.phase==='won'?'portal':'escape',beforeTravel:()=>{requestedClose=true;},afterTravel:departed=>{requestedClose=departed;}});};
|
||||
$<HTMLInputElement>('zoom').value = String(view.distance);
|
||||
@@ -264,7 +277,8 @@ async function boot() {
|
||||
if (me.character.entity.state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. A fresh world is a new beginning.', false);
|
||||
else connect();
|
||||
} else {
|
||||
if (me?.active) {
|
||||
if(me&&!me.active)$('passages').append(revivalPanel(worldPrefix));
|
||||
if (me?.active) {
|
||||
visible('join-form', false);
|
||||
const link = document.createElement('a'); link.href = me.active.state==='transit'?'/':`/game?world=${encodeURIComponent(me.active.worldId)}`; link.className = 'command'; link.textContent = me.active.state==='transit'?'Resume travel from your account':`Continue ${me.active.name} in ${me.active.worldId}`; $('passages').append(link);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,12 @@ function visible(menu: Menu) {
|
||||
!menu.element.matches('dialog:not([open])') && menu.element.getClientRects().length > 0;
|
||||
}
|
||||
export function hasOpenMenu() { return [...menus].some(visible); }
|
||||
export function closeFocusedMenu() {
|
||||
const open=[...menus].filter(visible).sort((a,b)=>b.order-a.order);
|
||||
const focused=open.filter(m=>m.element.contains(document.activeElement));
|
||||
const menu=focused.find(m=>!focused.some(other=>other!==m&&m.element.contains(other.element)))??open[0];
|
||||
if(!menu)return false;menu.close();return true;
|
||||
}
|
||||
|
||||
// Menus use their own close operation, including inline editors and native dialogs.
|
||||
// Capture Escape before input fields or gameplay; close one focused layer only.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { api, el, type RecordCharacter } from './portal-shared';
|
||||
import { statLabel } from './character-stats';
|
||||
|
||||
type Catalog={crafting?:{materials:{id:string;name:string}[]};gathering?:{resources:{id:string;name:string;output:string}[];consumables:{id:string;name:string}[]};items:{id:string;name:string}[];titles:{id:string;name:string}[]};
|
||||
type Catalog={powers?:{powers:{id:string;name:string;book:boolean}[]};crafting?:{materials:{id:string;name:string}[]};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;}
|
||||
@@ -18,6 +18,7 @@ export function playerContent(record:RecordCharacter,enabled:boolean,onQueued:()
|
||||
const v=record.character.view;choice.replaceChildren();
|
||||
switch(operation.value){
|
||||
case 'grant-item':
|
||||
choice.append(new Option('Revival stone','revival_stone'));for(const p of catalog.powers?.powers??[])if(p.book)choice.append(new Option(p.name+' spell book','book_'+p.id));
|
||||
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));
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import type {Character,Entity} from './generated';
|
||||
import {node,statLabel} from './character-stats';
|
||||
import {api} from './portal-shared';
|
||||
|
||||
export function createPowerPanel(send:(op:string,target?:string,x?:number,z?:number,slot?:string)=>void,target:()=>Entity|undefined,notice:(s:string)=>void,prefix:string){
|
||||
const root=node('section','','power-panel'),hotbar=node('div','','power-hotbar'),bookList=node('div'),known=node('div'),casting=node('p');root.append(node('h3','Spells and abilities'),casting,bookList,known);
|
||||
let latest:Character,signature='',slots:string[]=[],character='',busy=false;
|
||||
const use=async(id:string)=>{if(!latest||busy)return;const power=latest.powers?.[id];if(!power&&id!=='item')return;const selected=target();if(id==='item'||power?.definition.resurrection){if(selected?.kind!=='corpse'){notice('Select a player corpse and stand next to it.');return}busy=true;try{await api(prefix+'/api/revive',{corpse:selected.id,power:id});notice('Player revived.')}catch(e){notice((e as Error).message)}finally{busy=false}}else {const aim=power!.definition.targeting;if(aim==='target'&&!selected){notice('Select a target first.');return}send('cast',aim==='target'?selected!.id:latest.entity.id,0,0,id)}};
|
||||
const buttons=Array.from({length:8},(_,i)=>{const b=node('button',String(i+1));b.type='button';b.onclick=()=>void use(slots[i]);hotbar.append(b);return b});
|
||||
function refreshSlots(){buttons.forEach((b,i)=>{const p=latest.powers?.[slots[i]];b.textContent=p?`${i+1} · ${p.definition.name}`:`${i+1} · Empty`;b.disabled=!p||!['alive','eligible'].includes(latest.entity.state);b.title=p?`${p.definition.mana} mana · ${p.definition.cooldown}s cooldown`:'Assign a learned power in Inventory';})}
|
||||
const save=()=>{try{localStorage.setItem('aeternalis.slots.'+character,JSON.stringify(slots))}catch{};refreshSlots()};
|
||||
function update(c:Character){latest=c;if(character!==c.entity.id){character=c.entity.id;signature='';slots=[];try{slots=JSON.parse(localStorage.getItem('aeternalis.slots.'+character)??'[]');if(!Array.isArray(slots))slots=[]}catch{slots=[]}}
|
||||
casting.textContent=`Mana ${Math.floor(c.mana??0)} / ${Math.floor(c.stats?.manaPoints?.final??0)} · Stamina ${Math.floor(c.stamina??0)}${c.casting?' · '+c.casting:''}`;refreshSlots();const sig=JSON.stringify([c.powers,c.weapons,c.inventory]);if(sig===signature)return;signature=sig;known.replaceChildren();bookList.replaceChildren();
|
||||
for(const [id,n] of Object.entries(c.inventory)){if(n<1)continue;if(id.startsWith('book_')){const b=node('button',`Learn from ${c.stackNames?.[id]??statLabel(id)} (${n})`);b.type='button';b.onclick=()=>send('learn',id);bookList.append(b)}if(id==='revival_stone'){const b=node('button',`Use revival stone (${n})`);b.type='button';b.onclick=()=>void use('item');bookList.append(b)}}
|
||||
for(const v of Object.values(c.weapons??{}))known.append(node('p',`${v.name} · Level ${v.level} · ${v.xp} XP · ${v.xpToNextLevel} to next`));
|
||||
for(const v of Object.values(c.powers??{})){const d=v.definition,detail=node('details'),assign=node('select'),activate=node('button','Use '+d.name);assign.setAttribute('aria-label','Action slot for '+d.name);assign.append(new Option('Not assigned',''));for(let i=0;i<8;i++)assign.append(new Option('Slot '+(i+1),String(i)));const at=slots.indexOf(d.id);assign.value=at<0?'':String(at);assign.onchange=()=>{slots=slots.map(id=>id===d.id?'':id);if(assign.value!=='')slots[Number(assign.value)]=d.id;save()};activate.type='button';activate.onclick=()=>void use(d.id);detail.append(node('summary',`${d.name} · ${d.kind==='spell'?'Rank '+v.level:'Ability'}`),node('p',`${v.xp} XP · ${v.xpToNextLevel} to next · ${d.mana} mana · ${d.castSeconds}s cast · ${d.cooldown}s cooldown`),node('p',`${d.targeting}${d.resurrection?' · corpse revival':` · ${v.attack.effect} · ${v.attack.range}m range`}`),assign,activate);known.append(detail)}
|
||||
if(!Object.keys(c.powers??{}).length)known.append(node('p','Use a spell book or train a weapon to unlock powers.'));
|
||||
}
|
||||
return {root,hotbar,update,useSlot:(i:number)=>void use(slots[i])};
|
||||
}
|
||||
|
||||
export function revivalPanel(prefix:string){
|
||||
const root=node('section','','revival-panel'),status=node('p'),button=node('button','Check revival status');button.type='button';root.append(status,button);
|
||||
let current:{available:boolean;characterId?:string;allowed?:boolean;active?:string},busy=false;
|
||||
async function refresh(){if(busy)return;busy=true;try{current=await api(prefix+'/api/revival');if(current.active){status.textContent='Your character is active. Continue to reconnect.';button.textContent='Continue character'}else if(current.available){status.textContent='Another player can revive you at your corpse. Creating a replacement permanently ends this option.';button.textContent=current.allowed?'Disable revival consent':'Allow revival'}else{status.textContent='No recoverable corpse is available in this world.';button.textContent='Check revival status'}}catch(e){status.textContent=(e as Error).message}finally{busy=false}}
|
||||
button.onclick=async()=>{if(busy)return;if(current?.active){location.href='/game?world='+encodeURIComponent(current.active);return}if(current?.available){busy=true;try{await api(prefix+'/api/revival/consent',{characterId:current.characterId,allowed:!current.allowed})}catch(e){status.textContent=(e as Error).message}finally{busy=false}}await refresh()};
|
||||
const check=node('button','Refresh revival status');check.type='button';check.onclick=()=>void refresh();root.append(check);void refresh();return root;
|
||||
}
|
||||
@@ -12,3 +12,5 @@
|
||||
|
||||
#target-health{white-space:normal;line-height:1.5;max-width:min(550px,80vw)}
|
||||
.crafting-workbench{display:grid;gap:12px;font-size:12px;line-height:1.5}.crafting-workbench h3{margin:8px 0 0}.crafting-workbench form{display:grid;gap:8px}.crafting-workbench .recipe{display:grid;grid-template-columns:minmax(0,1fr) 68px;gap:6px}.crafting-workbench .recipe button{grid-column:1/-1;justify-self:end}.crafting-workbench details{border-top:1px solid var(--progression-border);padding:10px 0;overflow-wrap:anywhere}.crafting-workbench summary{cursor:pointer}.crafting-workbench details p{margin:8px 0}.crafting-workbench [role=status]{color:#d6e4b6}
|
||||
|
||||
.power-panel{display:grid;gap:10px;font-size:12px;line-height:1.5}.power-panel details{padding:8px 0;border-top:1px solid var(--progression-border)}.power-panel select,.power-panel button{margin-top:8px}.power-hotbar{pointer-events:auto;position:absolute;bottom:110px;left:50%;transform:translateX(-50%);display:flex;gap:4px;max-width:85vw;flex-wrap:wrap;justify-content:center}.power-hotbar button{font-size:11px;padding:6px;min-height:32px}.revival-panel{display:grid;gap:8px;margin-top:15px}.revival-panel p{margin:0}.settings details p{margin:10px 0;font-size:12px}@media(max-width:800px){.power-hotbar{bottom:205px;max-width:72vw}.power-hotbar button{font-size:10px;min-height:28px}}
|
||||
|
||||
Reference in New Issue
Block a user