Add physical hub portals and shared housing entrances
This commit is contained in:
+58
-21
@@ -56,6 +56,7 @@ let powers:ReturnType<typeof createPowerPanel>;
|
||||
let housing:ReturnType<typeof createHousingPanel>;
|
||||
let drawer:ReturnType<typeof createPlayerDrawer>;
|
||||
let items:ReturnType<typeof createItemActions>;
|
||||
let pendingInteraction:{id:string;key?:string;progressAt:number;position:Entity['position']}|undefined;
|
||||
let placement:{id:string;rotation:string;range:number}|undefined;
|
||||
let view: WorldView;
|
||||
const selectedWorld = new URLSearchParams(location.search).get('world');
|
||||
@@ -79,6 +80,7 @@ function selection(entity?: Entity) {
|
||||
}
|
||||
function action(op: string) {
|
||||
if (!snapshot) return;
|
||||
pendingInteraction=undefined;
|
||||
const now = Date.now();
|
||||
const kinds = op === 'attack' ? (snapshot.self.attack?.effect==='heal'?['player']:['boss', 'sentinel','mob']) : ['tree', 'ore', 'herb', 'corpse'];
|
||||
let target = view.selected;
|
||||
@@ -90,7 +92,7 @@ function action(op: string) {
|
||||
selection(target);
|
||||
const risk=snapshot.gatherRisks?.[target.resourceId??target.kind];
|
||||
if(op==='gather'&&risk){
|
||||
walkTo=undefined;pendingAction=undefined;
|
||||
walkTo=undefined;pendingAction=undefined;pendingInteraction=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;}
|
||||
}
|
||||
@@ -99,7 +101,28 @@ function action(op: string) {
|
||||
walkTo = target.position;
|
||||
lastProgress = undefined; lastProgressAt = Date.now();
|
||||
}
|
||||
function entranceDistance(e:Entity){const p=snapshot!.self.entity.position;return Math.hypot(e.position.x-p.x,e.position.y-p.y,e.position.z-p.z)}
|
||||
function useEscapeStone(){
|
||||
if(!snapshot||config.kind==='hub'||!['gathering','cataclysm'].includes(snapshot.world.phase)||!(snapshot.self.inventory.escape_stone>0)){notice('Use a world portal here.');return}
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;items.cancel();send('move');
|
||||
void showTravel({worldId:config.worldId,route:'escape',beforeTravel:()=>{requestedClose=true},afterTravel:departed=>{requestedClose=departed}});
|
||||
}
|
||||
function openEntrance(e:Entity,key?:string){
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;send('move');
|
||||
if(e.kind==='portal')void showTravel({worldId:config.worldId,route:config.kind==='hub'?'hub':'portal',beforeTravel:()=>{requestedClose=true},afterTravel:departed=>{requestedClose=departed}});
|
||||
else if(e.kind==='house-door'){
|
||||
if(key){const item=snapshot?.self.items.find(i=>i.id===key);if(item?.houseId)housing.enter(item.houseId,key);else notice('That key is no longer in your inventory.')}
|
||||
else housing.openEntrance();
|
||||
}
|
||||
}
|
||||
function approachEntrance(e:Entity,key?:string){
|
||||
if(!snapshot||snapshot.self.houseId)return;
|
||||
items.cancel();input.clear();pendingAction=undefined;send('move');visible('inventory',false);visible('settings',false);selection(e);
|
||||
if(entranceDistance(e)<=config.gatherRange-.4){openEntrance(e,key);return}
|
||||
pendingInteraction={id:e.id,key,progressAt:Date.now(),position:{...snapshot.self.entity.position}};walkTo=e.position;notice('Approaching '+e.name+'. Movement or Esc cancels.');
|
||||
}
|
||||
function connect() {
|
||||
pendingInteraction=undefined;
|
||||
requestedClose = false; sequence = 0; snapshot = undefined;
|
||||
powers.hotbar.hidden = true;
|
||||
visible('game-controls',false); visible('movement',false); visible('inventory',false);
|
||||
@@ -109,7 +132,7 @@ 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(pendingAction?.op==='gather' && snapshot && value.self.gatherAttempt!==snapshot.self.gatherAttempt){pendingAction=undefined;pendingInteraction=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);
|
||||
@@ -122,6 +145,7 @@ function connect() {
|
||||
} 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 () => {
|
||||
pendingInteraction=undefined;
|
||||
powers.hotbar.hidden = true;
|
||||
visible('game-controls',false); visible('movement',false); visible('inventory',false);
|
||||
$('connection-status').textContent = 'Disconnected'; $('connection-dot').parentElement!.classList.add('offline'); input.clear(); walkTo = undefined;
|
||||
@@ -132,7 +156,7 @@ function connect() {
|
||||
};
|
||||
}
|
||||
function showEnding(title: string, detail: string, survivor: boolean) {
|
||||
input.clear(); walkTo = undefined; pendingAction = undefined;
|
||||
input.clear(); walkTo = undefined; pendingAction = undefined;pendingInteraction=undefined;
|
||||
if(powers)powers.hotbar.hidden=true;
|
||||
visible('game-controls',false);visible('movement',false);visible('inventory',false);
|
||||
$('ending-title').textContent = title; $('ending-detail').textContent = detail;
|
||||
@@ -170,6 +194,7 @@ function updateHUD(s: Snapshot) {
|
||||
items?.update();
|
||||
const playable=['alive','eligible'].includes(c.entity.state)&&c.remainingSeconds>0;
|
||||
powers.hotbar.hidden=!playable;
|
||||
visible('travel',playable&&!c.houseId&&config.kind!=='hub'&&['gathering','cataclysm'].includes(w.phase)&&c.inventory.escape_stone>0);
|
||||
visible('game-controls', playable); visible('movement', playable && !hasOpenMenu());
|
||||
$('character-name').textContent = c.entity.name;
|
||||
$('character-level').textContent = `Level ${c.level || 1}`;
|
||||
@@ -210,11 +235,12 @@ async function boot() {
|
||||
input = new InputActions(() => hasOpenMenu() || isEditing(document.activeElement) || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open, key => {
|
||||
if(snapshot?.self.houseId){if(key==='inventory'||key==='gather'){housing.open();return}if(key==='jump'){send('jump');return}return}
|
||||
if((key==='attack'||key==='gather')&&items?.targeting){const target=view.selected?.id;if(target)items.choose(target);else notice('Select a target first.');return}
|
||||
if((key==='attack'||key==='gather')&&view.selected&&['portal','house-door'].includes(view.selected.kind)){approachEntrance(view.selected);return}
|
||||
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','structure'].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==='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','structure','portal','house-door'].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();
|
||||
@@ -228,15 +254,26 @@ async function boot() {
|
||||
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;
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;view.moving=false;
|
||||
if(inputElapsed>=0.05){send('move');inputElapsed=0;}return;
|
||||
}
|
||||
if(snapshot.self.houseId){let {x,z}=input.movement;if(x||z)walkTo=undefined;const p=snapshot.self.housePosition;if(walkTo&&p){const dx=walkTo.x-p.x,dz=walkTo.z-p.z,n=Math.hypot(dx,dz);if(n>.25){x=dx/n;z=dz/n}else walkTo=undefined}if(inputElapsed>=.05){send('move','',x,z);inputElapsed=0}return}
|
||||
let {x,z} = input.movement;
|
||||
if (x || z) { walkTo = undefined; pendingAction = undefined; }
|
||||
if (x || z) { walkTo = undefined; pendingAction = undefined;pendingInteraction=undefined; }
|
||||
if(pendingInteraction){
|
||||
const p=snapshot.self.entity.position,previous=pendingInteraction.position;
|
||||
if(Math.hypot(p.x-previous.x,p.z-previous.z)>.1){pendingInteraction.progressAt=Date.now();pendingInteraction.position={...p}}
|
||||
if(Date.now()-pendingInteraction.progressAt>5000){pendingInteraction=undefined;walkTo=undefined;notice('Approach stopped. Check your carry weight or choose a clear path.');}
|
||||
}
|
||||
if(pendingInteraction){
|
||||
const e=snapshot.entities.find(e=>e.id===pendingInteraction!.id);
|
||||
if(!e){pendingInteraction=undefined;walkTo=undefined;notice('Entrance is no longer available.');}
|
||||
else if(entranceDistance(e)<=config.gatherRange-.4){const key=pendingInteraction.key;openEntrance(e,key);return}
|
||||
else walkTo=e.position;
|
||||
}
|
||||
const actionTarget = pendingAction?.target === snapshot.self.entity.id ? snapshot.self.entity : snapshot.entities.find(e => e.id === pendingAction?.target);
|
||||
if (pendingAction?.op === 'attack') {
|
||||
if (!actionTarget || actionTarget.hp <= 0) { walkTo = undefined; pendingAction = undefined; }
|
||||
if (!actionTarget || actionTarget.hp <= 0) { walkTo = undefined; pendingAction = undefined;pendingInteraction=undefined; }
|
||||
else walkTo = actionTarget.position;
|
||||
}
|
||||
if (walkTo) {
|
||||
@@ -264,7 +301,7 @@ async function boot() {
|
||||
if (Date.now() - lastProgressAt > Math.max(5000,attackWait*1000,((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;
|
||||
walkTo = undefined; pendingAction = undefined;pendingInteraction=undefined;
|
||||
if(retryOp!=='gather' && snapshot.self.attack?.effect!=='heal')action(retryOp);else notice('Action stopped. Select a target to try again.');
|
||||
} else if(pendingAction.op!=='gather'||!gatherSent) { send(pendingAction.op, pendingAction.target);if(pendingAction.op==='gather')gatherSent=sequence; }
|
||||
}
|
||||
@@ -276,14 +313,14 @@ async function boot() {
|
||||
}, 50);
|
||||
const [loadedConfig, chunks] = await Promise.all([api<Config>('/api/config'), api<Chunk[]>('/api/preview'), view.load()]);
|
||||
config = loadedConfig;
|
||||
housing=createHousingPanel(()=>snapshot?.self,worldPrefix,()=>config.kind==='hub',()=>{input.clear();walkTo=undefined;pendingAction=undefined;placement=undefined;visible('inventory',false);selection()});$('hud').append(housing.toolbar);
|
||||
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,(id,slot)=>items.activate(id,slot));$('hud').append(powers.hotbar);$('settings').append(input.settings());
|
||||
const aim=(bag:boolean)=>{input.clear();walkTo=undefined;pendingAction=undefined;placement=undefined;send('move');visible('inventory',bag);visible('movement',!bag);if(bag)$('inventory').querySelector<HTMLButtonElement>('[data-view="bag"]')?.click();};
|
||||
housing=createHousingPanel(()=>snapshot?.self,worldPrefix,()=>config.kind==='hub',()=>{input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;placement=undefined;visible('inventory',false);selection()});$('hud').append(housing.toolbar);
|
||||
powers=createPowerPanel((op,target,x,z,slot)=>{if(op==='cast'){input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;send('move')}send(op,target,x,z,slot)},()=>view.selected,notice,worldPrefix,(id,slot)=>items.activate(id,slot));$('hud').append(powers.hotbar);$('settings').append(input.settings());
|
||||
const aim=(bag:boolean)=>{input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;placement=undefined;send('move');visible('inventory',bag);visible('movement',!bag);if(bag)$('inventory').querySelector<HTMLButtonElement>('[data-view="bag"]')?.click();};
|
||||
const startPlacement=(id:string,rotation:string,range:number)=>{items?.cancel();aim(false);placement={id,rotation,range};notice('Click clear ground to build. Esc cancels.');};
|
||||
items=createItemActions({panel:$('inventory'),hud:$('hud'),character:()=>snapshot?.self,prefix:worldPrefix,send,notice,aim,selected:()=>view.selected?.id??'',assign:(id,slot)=>powers.assignItem(id,slot),travel:()=>$('travel').click(),key:(id,destroy)=>destroy?housing.destroyKey(id):housing.open(),place:id=>{void api<BuildingContent>('/api/building').then(b=>{const d=b.definitions.find(d=>'kit_'+d.id===id);if(!d)throw new Error('This kit has no structure definition.');startPlacement(d.id,'0',b.range)}).catch(e=>notice(e.message))}});$('hud').append(items.bar);
|
||||
items=createItemActions({panel:$('inventory'),hud:$('hud'),character:()=>snapshot?.self,prefix:worldPrefix,send,notice,aim,selected:()=>view.selected?.id??'',assign:(id,slot)=>powers.assignItem(id,slot),travel:()=>useEscapeStone(),key:(id,destroy,target)=>{if(destroy)housing.destroyKey(id);else{const door=snapshot?.entities.find(e=>e.id===target&&e.kind==='house-door');if(door)approachEntrance(door,id);else notice('Select the housing entrance in a hub.')}},place:id=>{void api<BuildingContent>('/api/building').then(b=>{const d=b.definitions.find(d=>'kit_'+d.id===id);if(!d)throw new Error('This kit has no structure definition.');startPlacement(d.id,'0',b.range)}).catch(e=>notice(e.message))}});$('hud').append(items.bar);
|
||||
drawer=createPlayerDrawer($('inventory'),powers,send,worldPrefix,housing.root,buildingPanel(()=>snapshot?.self,startPlacement,worldPrefix));
|
||||
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;}});};
|
||||
const travelButton=document.createElement('button');travelButton.id='travel';travelButton.textContent='Use escape stone';travelButton.title='Consume an escape stone to reach a hub';travelButton.hidden=true;$('inventory-toggle').before(travelButton);
|
||||
travelButton.onclick=()=>useEscapeStone();
|
||||
$<HTMLInputElement>('zoom').value = String(view.distance);
|
||||
view.addChunks(chunks); view.updateEntities(chunks.flatMap(c => c.resources));
|
||||
visible('dev-boss', config.development);
|
||||
@@ -314,21 +351,21 @@ async function boot() {
|
||||
$(`${id}-toggle`).onclick=()=>{
|
||||
if(!$(id).hidden){menu.close();return;}
|
||||
if(id==='inventory'&&snapshot)inventory(snapshot.self);
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;send('move');visible(id,true);visible('movement',false);menu.opened($(`${id}-toggle`));
|
||||
input.clear();walkTo=undefined;pendingAction=undefined;pendingInteraction=undefined;send('move');visible(id,true);visible('movement',false);menu.opened($(`${id}-toggle`));
|
||||
};
|
||||
document.querySelectorAll<HTMLButtonElement>(`[data-close="${id}"]`).forEach(button=>button.onclick=()=>menu.close());
|
||||
}
|
||||
$('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 = () => { if(snapshot?.world.phase==='won'){walkTo={x:0,z:0};pendingAction=undefined;return;} selection(snapshot?.entities.find(e => e.id === 'boss')); walkTo = { x: 0, z: 0 }; pendingAction = { op: 'attack', target: 'boss' }; lastProgress = undefined; lastProgressAt = Date.now(); };
|
||||
$('target-boss').onclick = () => { if(snapshot?.world.phase==='won'){walkTo={x:0,z:0};pendingAction=undefined;pendingInteraction=undefined;return;} 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();
|
||||
$('new-character').onclick = () => { requestedClose = true; ws?.close(); location.reload(); };
|
||||
$('logout').onclick = async () => { requestedClose = true; await api('/auth/logout', {}); ws?.close(); location.reload(); };
|
||||
$<HTMLSelectElement>('quality').onchange = event => view.quality((event.target as HTMLSelectElement).value === 'high');
|
||||
$<HTMLInputElement>('zoom').oninput = event => { view.distance = Number((event.target as HTMLInputElement).value); view.resize(); };
|
||||
window.addEventListener('keydown',e=>{if(e.code==='Escape'&&placement){placement=undefined;notice('Placement canceled.');}});
|
||||
window.addEventListener('blur', () => { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); });
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) { input.clear(); walkTo = undefined; pendingAction=undefined; send('move'); } });
|
||||
window.addEventListener('keydown',e=>{if(e.code==='Escape'&&pendingInteraction){pendingInteraction=undefined;walkTo=undefined;input.clear();send('move');notice('Approach canceled.')}if(e.code==='Escape'&&placement){placement=undefined;notice('Placement canceled.');}});
|
||||
window.addEventListener('blur', () => { input.clear(); walkTo = undefined; pendingAction=undefined;pendingInteraction=undefined; send('move'); });
|
||||
document.addEventListener('visibilitychange', () => { if (document.hidden) { input.clear(); walkTo = undefined; pendingAction=undefined;pendingInteraction=undefined; send('move'); } });
|
||||
const movements: Record<string, InputAction> = { up:'north',down:'south',left:'west',right:'east' };
|
||||
document.querySelectorAll<HTMLButtonElement>('[data-move]').forEach(button => {
|
||||
const key = movements[button.dataset.move!],source=`pointer-${button.dataset.move}`;
|
||||
@@ -343,8 +380,8 @@ async function boot() {
|
||||
if(snapshot.self.houseId){if(hit.entity?.kind==='house-exit')void housing.leave();else if(hit.entity)housing.open(hit.entity.id);else if(hit.point)walkTo=hit.point;return}
|
||||
if(placement){if(!hit.point||hit.entity){notice('Choose unoccupied ground. Esc cancels.');return}const p=snapshot.self.entity.position,x=(hit.point.x-p.x)/placement.range,z=(hit.point.z-p.z)/placement.range;if(Math.hypot(x,z)>1){notice('Choose ground within '+placement.range+'m.');return}send('build',placement.id,x,z,placement.rotation);placement=undefined;return;}
|
||||
|
||||
if (hit.entity) { if(hit.entity.kind==='portal'){$('travel').click();return;} selection(hit.entity); action(['boss', 'sentinel','mob','player','structure'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
|
||||
else if (hit.point) { selection(); walkTo = hit.point; pendingAction = undefined; }
|
||||
if (hit.entity) { if(['portal','house-door'].includes(hit.entity.kind)){approachEntrance(hit.entity);return;} selection(hit.entity); action(['boss', 'sentinel','mob','player','structure'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
|
||||
else if (hit.point) { selection(); walkTo = hit.point; pendingAction = undefined;pendingInteraction=undefined; }
|
||||
});
|
||||
Object.defineProperty(window, '__aeternalis', { value: { diagnostics: () => view.diagnostics(), get snapshot() { return snapshot; }, get walkTo() { return walkTo; }, get pendingAction() { return pendingAction; }, get keys() { return input.keys; } }, configurable: true });
|
||||
// Authentication and all input handlers must be ready before character creation.
|
||||
|
||||
Reference in New Issue
Block a user