Add playable hub travel with durable character transfers

This commit is contained in:
dingo
2026-09-09 12:17:10 -04:00
parent eee6f4c46f
commit f3d6f927e2
42 changed files with 1338 additions and 63 deletions
+16 -15
View File
@@ -1,4 +1,5 @@
import './style.css';
import { showTravel } from './travel';
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';
@@ -8,7 +9,7 @@ import { InputActions, isEditing, type InputAction } from './input-actions';
import { hasOpenMenu, registerMenu } from './menu-focus';
type Recipe = { Inputs: Record<string, number>; Outputs: Record<string, number> };
type Config = { worldId: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record<string, Recipe>; playerSpeed: number; gatherRange: number; attackRange: number };
type Config = { worldId: string; kind: string; development: boolean; worlds: { id: string; url: string }[]; recipes: Record<string, Recipe>; playerSpeed: number; gatherRange: number; attackRange: number };
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
const visible = (id: string, show: boolean) => { $(id).hidden = !show; };
const pretty = (s: string) => s.replaceAll('_', ' ').replace(/^./, c => c.toUpperCase());
@@ -60,7 +61,7 @@ async function api<T>(path: string, body?: unknown): Promise<T> {
}
function notice(message: string) { $('notice').textContent = message; visible('notice', true); clearTimeout(noticeTimer); noticeTimer = setTimeout(() => visible('notice', false), 3500); }
function send(op: string, target = '', x = 0, z = 0, slot = '') {
if (ws?.readyState !== WebSocket.OPEN || !snapshot || snapshot.self.entity.state !== 'alive') return;
if (ws?.readyState !== WebSocket.OPEN || !snapshot || !['alive','eligible'].includes(snapshot.self.entity.state)) return;
const intent: Intent = { op, target, x, z, slot, seq: ++sequence };
ws.send(JSON.stringify(intent));
}
@@ -104,7 +105,6 @@ function connect() {
$('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 (state === 'eligible') showEnding('A passage forward.', 'The Harbinger has fallen. Your character and belongings can continue to a new world.', true);
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);
};
ws.onclose = async () => {
@@ -159,7 +159,7 @@ function minimap(s: Snapshot) {
}
function updateHUD(s: Snapshot) {
const c = s.self, w = s.world;
visible('game-controls', true); visible('movement', c.entity.state === 'alive' && $('inventory').hidden && $('settings').hidden);
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}`;
$('character-experience').textContent = experienceText(c);
@@ -179,10 +179,15 @@ function updateHUD(s: Snapshot) {
$('season-clock').textContent = time(w.phase === 'gathering' ? w.bossInSeconds : w.collapseInSeconds);
$('season-detail').textContent = w.phase === 'gathering' ? 'Until the Harbinger' : `${Math.round(w.safeRadius)}m of world remaining`;
$('season-progress').style.width = `${w.safeRadius / w.radius * 100}%`;
visible('boss-bar', w.phase === 'cataclysm'); $('boss-health').style.width = `${w.bossHp / w.bossMaxHp * 100}%`; $('boss-count').textContent = `${Math.ceil(w.bossHp)} / ${Math.ceil(w.bossMaxHp)}`;
visible('boss-bar', w.phase === 'cataclysm' || w.phase === 'won'); $('boss-health').style.width = `${w.bossHp / w.bossMaxHp * 100}%`; $('boss-count').textContent = w.phase==='won'?'Portal at 0, 0':`${Math.ceil(w.bossHp)} / ${Math.ceil(w.bossMaxHp)}`;
$('coordinates').textContent = `${Math.round(c.entity.position.x)}, ${Math.round(c.entity.position.z)}`;
$('chunk-count').textContent = `${view.chunks.size} chunks`;
if (!$('inventory').hidden) inventory(c);
if(w.kind==='hub'){ $('phase-label').textContent='THE HUB';$('season-clock').textContent='Permanent haven';$('season-detail').textContent='Crafting allowed · No experience gained'; }
if(w.phase==='won'){ $('season-clock').textContent='Portal open';$('season-detail').textContent='Find the victory portal at 0, 0'; }
visible('target-boss',w.kind!=='hub');$('target-boss').textContent=w.phase==='won'?'Find victory portal':'Target Harbinger';$('target-boss').setAttribute('aria-label',w.phase==='won'?'Find victory portal':'Target Harbinger');
visible('dev-boss',config.development&&w.kind!=='hub');
$<HTMLButtonElement>('attack').disabled=w.kind==='hub'||w.phase==='won';$<HTMLButtonElement>('gather').disabled=w.kind==='hub'||w.phase==='won';
selection(view.selected); minimap(s);
if (s.message && s.message !== lastNotice) { notice(s.message); lastNotice = s.message; }
}
@@ -252,6 +257,8 @@ async function boot() {
}, 50);
const [loadedConfig, chunks] = await Promise.all([api<Config>('/api/config'), api<Chunk[]>('/api/preview'), view.load()]);
config = loadedConfig;
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);
view.addChunks(chunks); view.updateEntities(chunks.flatMap(c => c.resources));
$('connection-status').textContent = 'World online';
@@ -262,19 +269,13 @@ async function boot() {
else if (me?.character) {
$<HTMLDialogElement>('arrival').close();
if (me.character.entity.state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. A fresh world is a new beginning.', false);
else if (me.character.entity.state === 'eligible') showEnding('A passage forward.', 'Your survivor passage is saved.', true);
else connect();
} else {
if (me?.active) {
visible('join-form', false);
const link = document.createElement('a'); link.href = `/game?world=${encodeURIComponent(me.active.worldId)}`; link.className = 'command'; link.textContent = `Continue ${me.active.name} in ${me.active.worldId}`; $('passages').append(link);
}
const passages = await api<{ characterId: string; sourceWorld: string; name: string }[]>('/api/passages').catch(() => []);
for (const passage of passages.filter(p => p.sourceWorld !== config.worldId)) {
const button = document.createElement('button'); button.textContent = `Continue as ${passage.name}`;
button.onclick = async () => { try { await api('/api/join', { name: '', passage: passage.characterId }); $<HTMLDialogElement>('arrival').close(); connect(); } catch (e) { $('arrival-error').textContent = String((e as Error).message); } };
$('passages').append(button);
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);
}
if(config.kind==='hub'){visible('join-form',false);$('arrival-error').textContent='Enter a hub through travel from your current character. Open your account to continue.';}
}
$<HTMLFormElement>('join-form').onsubmit = async event => {
event.preventDefault(); const button = $<HTMLButtonElement>('join'); button.disabled = true;
@@ -292,7 +293,7 @@ async function boot() {
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 = () => { 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;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(); };
@@ -310,7 +311,7 @@ async function boot() {
view.canvas.addEventListener('pointerdown', event => {
if (!snapshot || hasOpenMenu() || $<HTMLDialogElement>('arrival').open || $<HTMLDialogElement>('ending').open || event.button !== 0) return;
const hit = view.pick(event.clientX, event.clientY);
if (hit.entity) { selection(hit.entity); action(['boss', 'sentinel','mob','player'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
if (hit.entity) { if(hit.entity.kind==='portal'){$('travel').click();return;} selection(hit.entity); action(['boss', 'sentinel','mob','player'].includes(hit.entity.kind) ? 'attack' : 'gather'); }
else if (hit.point) { selection(); walkTo = hit.point; pendingAction = 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 });