Add skills, coins, combat visuals, equipment tiers, and crafting scaffolding.
Introduce skill progression with a client panel, physical coin stacks, food healing and Health XP, tiered equipment with effective combat stats, combat movement visuals, crafting station definitions with a shared craft UI shell and item/recipe stubs, plus expanded test coverage.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
The contents of this binary file are not shown.
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#4a7a40"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">AR</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#4a7a40"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">AR</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#9a5030"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">AX</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#9a5030"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">AX</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#8b6914"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">CL</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#8b6914"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">CL</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#a06030"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">CK</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#a06030"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">CK</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#806080"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">CR</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#806080"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">CR</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#506080"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">DF</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#506080"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">DF</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#4080a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">DX</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#4080a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">DX</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#3070a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">FS</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#3070a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">FS</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#a03030"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">HP</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#a03030"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">HP</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#8a6040"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">LW</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#8a6040"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">LW</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#6050a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">MG</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#6050a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">MG</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#8060a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">MN</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#8060a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">MN</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#606060"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">MI</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#606060"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">MI</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#806040"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SI</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#806040"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SI</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#408060"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SM</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#408060"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SM</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#a04040"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">ST</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#a04040"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">ST</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#7a8a9a"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SW</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#7a8a9a"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">SW</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#7070a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">TL</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#7070a0"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">TL</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#6a6050"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">UN</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#6a6050"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">UN</text></svg>@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#5a7040"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">WC</text></svg>
@@ -0,0 +1 @@<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#5a7040"/><text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">WC</text></svg>@@ -11,19 +11,19 @@
<span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
<span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
<button id="friends-toggle" type="button">Friends</button>
<button id="skills-toggle" type="button">Skills</button>
<button id="bag-toggle" type="button">Bag</button>
<button id="leave" type="button">Leave world</button>
</div>
<aside id="bag-panel" hidden>
<h2>Bag</h2>
<p id="bag-coins">0 coins</p>
<p id="bag-coins" hidden>0 coins</p>
<div id="equip-grid" class="item-grid equip"></div>
<div id="bag-grid" class="item-grid"></div>
<p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p>
<div class="bag-actions">
<button id="bag-drop" type="button">Drop</button>
<button id="bag-equip" type="button">Equip</button>
<button id="bag-bank" type="button">Deposit selected</button>
</div>
</aside>
<aside id="bank-panel" hidden>
@@ -31,13 +31,25 @@
<h2>Bank</h2>
<button id="bank-close" type="button">Close</button>
</header>
<p id="vault-coins"></p>
<div id="vault-grid" class="item-grid"></div>
<h3>Inheritance</h3>
<p id="inherit-coins"></p>
<div id="inherit-grid" class="item-grid"></div>
<button id="bank-claim" type="button">Claim inheritance into vault</button>
<p class="hint">Stand next to a bank block. Click a vault slot to withdraw. Deposit uses the selected bag slot.</p>
<p id="vault-coins" hidden></p>
<div class="bank-tabs">
<button id="bank-tab-available" type="button" class="bank-tab active">Available</button>
<button id="bank-tab-reserved" type="button" class="bank-tab">Reserved</button>
<button id="bank-tab-inherit" type="button" class="bank-tab">Inheritance</button>
</div>
<div id="bank-available-pane">
<div id="vault-grid" class="item-grid"></div>
<p class="hint">Click an item to move it to your bag. Right-click for partial transfers.</p>
</div>
<div id="bank-reserved-pane" hidden>
<div id="vault-reserved-grid" class="item-grid"></div>
<p class="hint">Goods reserved by outstanding cheques. Redeem a cheque at the bank to claim them.</p>
</div>
<div id="bank-inherit-pane" hidden>
<p id="inherit-coins" hidden></p>
<div id="inherit-grid" class="item-grid"></div>
<button id="bank-claim" type="button">Claim inheritance into vault</button>
</div>
</aside>
<aside id="friends-panel" hidden>
<h2>Friends</h2>
@@ -48,6 +60,11 @@
<div id="outgoing-list"></div>
<p class="hint">Right-click a bag item and choose Send to deliver by pigeon to the bank or a player.</p>
</aside>
<aside id="skills-panel" hidden>
<h2>Skills</h2>
<div id="skills-list" class="skills-grid"></div>
<p class="hint">Successful melee hits split XP between the weapon skill and Strength.</p>
</aside>
<div id="send-backdrop" class="modal-backdrop" hidden></div>
<aside id="send-panel" hidden>
@@ -82,6 +99,35 @@
<div id="send-search-result"></div>
</aside>
<div id="transfer-backdrop" class="modal-backdrop" hidden></div>
<aside id="transfer-panel" hidden>
<header>
<h2>Transfer</h2>
<button id="transfer-close" type="button">Close</button>
</header>
<p id="transfer-item-name"></p>
<label class="send-row">Quantity
<input id="transfer-qty" type="number" min="1" step="1" value="1">
</label>
<button id="transfer-confirm" type="button">Transfer</button>
</aside>
<div id="write-cheque-backdrop" class="modal-backdrop" hidden></div>
<aside id="write-cheque-panel" hidden>
<header>
<h2>Write cheque</h2>
<button id="write-cheque-close" type="button">Close</button>
</header>
<p id="write-cheque-hint" class="hint">Choose goods from your vault to reserve on this cheque.</p>
<div id="write-cheque-vault" class="item-grid"></div>
<p id="write-cheque-item"></p>
<label class="send-row">Quantity
<input id="write-cheque-qty" type="number" min="1" step="1" value="1">
</label>
<button id="write-cheque-confirm" type="button" disabled>Write</button>
<p id="write-cheque-status" class="hint"></p>
</aside>
<div id="letter-backdrop" class="modal-backdrop" hidden></div>
<aside id="letter-panel" hidden>
<header>
@@ -98,6 +144,34 @@
<p id="letter-status" class="hint"></p>
</aside>
<div id="craft-backdrop" class="modal-backdrop" hidden></div>
<aside id="craft-panel" hidden>
<header>
<h2 id="craft-station-name">Crafting</h2>
<button id="craft-close" type="button">Close</button>
</header>
<div class="craft-layout">
<div class="craft-recipes">
<div id="craft-recipe-grid" class="craft-recipe-grid"></div>
</div>
<div class="craft-detail">
<p id="craft-detail-empty" class="hint">Select a recipe.</p>
<div id="craft-detail-body" hidden>
<div class="craft-output">
<img id="craft-output-img" alt="">
<h3 id="craft-output-name"></h3>
</div>
<ul id="craft-inputs" class="craft-inputs"></ul>
<p id="craft-status" class="hint"></p>
<div id="craft-progress" class="craft-progress" hidden>
<div id="craft-progress-fill" class="craft-progress-fill"></div>
</div>
<button id="craft-button" type="button" disabled>Craft</button>
</div>
</div>
</div>
</aside>
<div id="nametag" hidden></div>
<div id="chat-bubbles"></div>
<div id="chat-bar" hidden>
@@ -11,19 +11,19 @@ <span>Walk/run: <strong id="gait">walk</strong> (press R)</span> <span>Walk/run: <strong id="gait">walk</strong> (press R)</span> <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span> <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span> <button id="friends-toggle" type="button">Friends</button> <button id="friends-toggle" type="button">Friends</button> <button id="skills-toggle" type="button">Skills</button> <button id="bag-toggle" type="button">Bag</button> <button id="bag-toggle" type="button">Bag</button> <button id="leave" type="button">Leave world</button> <button id="leave" type="button">Leave world</button> </div> </div> <aside id="bag-panel" hidden> <aside id="bag-panel" hidden> <h2>Bag</h2> <h2>Bag</h2> <p id="bag-coins">0 coins</p> <p id="bag-coins" hidden>0 coins</p> <div id="equip-grid" class="item-grid equip"></div> <div id="equip-grid" class="item-grid equip"></div> <div id="bag-grid" class="item-grid"></div> <div id="bag-grid" class="item-grid"></div> <p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p> <p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p> <div class="bag-actions"> <div class="bag-actions"> <button id="bag-drop" type="button">Drop</button> <button id="bag-drop" type="button">Drop</button> <button id="bag-equip" type="button">Equip</button> <button id="bag-equip" type="button">Equip</button> <button id="bag-bank" type="button">Deposit selected</button> </div> </div> </aside> </aside> <aside id="bank-panel" hidden> <aside id="bank-panel" hidden>@@ -31,13 +31,25 @@ <h2>Bank</h2> <h2>Bank</h2> <button id="bank-close" type="button">Close</button> <button id="bank-close" type="button">Close</button> </header> </header> <p id="vault-coins"></p> <p id="vault-coins" hidden></p> <div id="vault-grid" class="item-grid"></div> <div class="bank-tabs"> <h3>Inheritance</h3> <button id="bank-tab-available" type="button" class="bank-tab active">Available</button> <p id="inherit-coins"></p> <button id="bank-tab-reserved" type="button" class="bank-tab">Reserved</button> <div id="inherit-grid" class="item-grid"></div> <button id="bank-tab-inherit" type="button" class="bank-tab">Inheritance</button> <button id="bank-claim" type="button">Claim inheritance into vault</button> </div> <p class="hint">Stand next to a bank block. Click a vault slot to withdraw. Deposit uses the selected bag slot.</p> <div id="bank-available-pane"> <div id="vault-grid" class="item-grid"></div> <p class="hint">Click an item to move it to your bag. Right-click for partial transfers.</p> </div> <div id="bank-reserved-pane" hidden> <div id="vault-reserved-grid" class="item-grid"></div> <p class="hint">Goods reserved by outstanding cheques. Redeem a cheque at the bank to claim them.</p> </div> <div id="bank-inherit-pane" hidden> <p id="inherit-coins" hidden></p> <div id="inherit-grid" class="item-grid"></div> <button id="bank-claim" type="button">Claim inheritance into vault</button> </div> </aside> </aside> <aside id="friends-panel" hidden> <aside id="friends-panel" hidden> <h2>Friends</h2> <h2>Friends</h2>@@ -48,6 +60,11 @@ <div id="outgoing-list"></div> <div id="outgoing-list"></div> <p class="hint">Right-click a bag item and choose Send to deliver by pigeon to the bank or a player.</p> <p class="hint">Right-click a bag item and choose Send to deliver by pigeon to the bank or a player.</p> </aside> </aside> <aside id="skills-panel" hidden> <h2>Skills</h2> <div id="skills-list" class="skills-grid"></div> <p class="hint">Successful melee hits split XP between the weapon skill and Strength.</p> </aside> <div id="send-backdrop" class="modal-backdrop" hidden></div> <div id="send-backdrop" class="modal-backdrop" hidden></div> <aside id="send-panel" hidden> <aside id="send-panel" hidden>@@ -82,6 +99,35 @@ <div id="send-search-result"></div> <div id="send-search-result"></div> </aside> </aside> <div id="transfer-backdrop" class="modal-backdrop" hidden></div> <aside id="transfer-panel" hidden> <header> <h2>Transfer</h2> <button id="transfer-close" type="button">Close</button> </header> <p id="transfer-item-name"></p> <label class="send-row">Quantity <input id="transfer-qty" type="number" min="1" step="1" value="1"> </label> <button id="transfer-confirm" type="button">Transfer</button> </aside> <div id="write-cheque-backdrop" class="modal-backdrop" hidden></div> <aside id="write-cheque-panel" hidden> <header> <h2>Write cheque</h2> <button id="write-cheque-close" type="button">Close</button> </header> <p id="write-cheque-hint" class="hint">Choose goods from your vault to reserve on this cheque.</p> <div id="write-cheque-vault" class="item-grid"></div> <p id="write-cheque-item"></p> <label class="send-row">Quantity <input id="write-cheque-qty" type="number" min="1" step="1" value="1"> </label> <button id="write-cheque-confirm" type="button" disabled>Write</button> <p id="write-cheque-status" class="hint"></p> </aside> <div id="letter-backdrop" class="modal-backdrop" hidden></div> <div id="letter-backdrop" class="modal-backdrop" hidden></div> <aside id="letter-panel" hidden> <aside id="letter-panel" hidden> <header> <header>@@ -98,6 +144,34 @@ <p id="letter-status" class="hint"></p> <p id="letter-status" class="hint"></p> </aside> </aside> <div id="craft-backdrop" class="modal-backdrop" hidden></div> <aside id="craft-panel" hidden> <header> <h2 id="craft-station-name">Crafting</h2> <button id="craft-close" type="button">Close</button> </header> <div class="craft-layout"> <div class="craft-recipes"> <div id="craft-recipe-grid" class="craft-recipe-grid"></div> </div> <div class="craft-detail"> <p id="craft-detail-empty" class="hint">Select a recipe.</p> <div id="craft-detail-body" hidden> <div class="craft-output"> <img id="craft-output-img" alt=""> <h3 id="craft-output-name"></h3> </div> <ul id="craft-inputs" class="craft-inputs"></ul> <p id="craft-status" class="hint"></p> <div id="craft-progress" class="craft-progress" hidden> <div id="craft-progress-fill" class="craft-progress-fill"></div> </div> <button id="craft-button" type="button" disabled>Craft</button> </div> </div> </div> </aside> <div id="nametag" hidden></div> <div id="nametag" hidden></div> <div id="chat-bubbles"></div> <div id="chat-bubbles"></div> <div id="chat-bar" hidden> <div id="chat-bar" hidden>@@ -0,0 +1,62 @@
import { mkdirSync, writeFileSync } from "node:fs";
import { ALL_SKILL_IDS } from "../../shared/definitions/skills.js";
const labels = {
clubfighting: "CL",
swordfighting: "SW",
axefighting: "AX",
archery: "AR",
unarmed: "UN",
magic: "MG",
strength: "ST",
dexterity: "DX",
mind: "MN",
defence: "DF",
health: "HP",
stamina: "SM",
woodcutting: "WC",
mining: "MI",
fishing: "FS",
smithing: "SI",
crafting: "CR",
leatherworking: "LW",
tailoring: "TL",
cooking: "CK"
};
const colors = {
clubfighting: "#8b6914",
swordfighting: "#7a8a9a",
axefighting: "#9a5030",
archery: "#4a7a40",
unarmed: "#6a6050",
magic: "#6050a0",
strength: "#a04040",
dexterity: "#4080a0",
mind: "#8060a0",
defence: "#506080",
health: "#a03030",
stamina: "#408060",
woodcutting: "#5a7040",
mining: "#606060",
fishing: "#3070a0",
smithing: "#806040",
crafting: "#806080",
leatherworking: "#8a6040",
tailoring: "#7070a0",
cooking: "#a06030"
};
mkdirSync(new URL("../assets/skills/", import.meta.url), { recursive: true });
const dir = new URL("../assets/skills/", import.meta.url);
for (const id of ALL_SKILL_IDS)
{
const svg = [
"<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\">",
`<rect width="32" height="32" rx="6" fill="${colors[id] ?? "#2a3344"}"/>`,
`<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">${labels[id] ?? "?"}</text>`,
"</svg>"
].join("");
writeFileSync(new URL(`${id}.svg`, dir), svg);
}
@@ -0,0 +1,62 @@import { mkdirSync, writeFileSync } from "node:fs";import { ALL_SKILL_IDS } from "../../shared/definitions/skills.js";const labels = { clubfighting: "CL", swordfighting: "SW", axefighting: "AX", archery: "AR", unarmed: "UN", magic: "MG", strength: "ST", dexterity: "DX", mind: "MN", defence: "DF", health: "HP", stamina: "SM", woodcutting: "WC", mining: "MI", fishing: "FS", smithing: "SI", crafting: "CR", leatherworking: "LW", tailoring: "TL", cooking: "CK"};const colors = { clubfighting: "#8b6914", swordfighting: "#7a8a9a", axefighting: "#9a5030", archery: "#4a7a40", unarmed: "#6a6050", magic: "#6050a0", strength: "#a04040", dexterity: "#4080a0", mind: "#8060a0", defence: "#506080", health: "#a03030", stamina: "#408060", woodcutting: "#5a7040", mining: "#606060", fishing: "#3070a0", smithing: "#806040", crafting: "#806080", leatherworking: "#8a6040", tailoring: "#7070a0", cooking: "#a06030"};mkdirSync(new URL("../assets/skills/", import.meta.url), { recursive: true });const dir = new URL("../assets/skills/", import.meta.url);for (const id of ALL_SKILL_IDS){ const svg = [ "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\">", `<rect width="32" height="32" rx="6" fill="${colors[id] ?? "#2a3344"}"/>`, `<text x="16" y="21" text-anchor="middle" fill="#f0ece0" font-size="11" font-family="Segoe UI,sans-serif" font-weight="600">${labels[id] ?? "?"}</text>`, "</svg>" ].join(""); writeFileSync(new URL(`${id}.svg`, dir), svg);}@@ -1,9 +1,10 @@
export class GameSocket
{
constructor (url, onMessage)
constructor (url, onMessage, { onClose } = {})
{
this.url = url;
this.onMessage = onMessage;
this.onClose = onClose;
this.socket = null;
}
@@ -14,6 +15,10 @@ export class GameSocket
{
this.onMessage(JSON.parse(event.data));
});
this.socket.addEventListener("close", (event) =>
{
this.onClose?.(event);
});
return new Promise((resolve, reject) =>
{
this.socket.addEventListener("open", resolve, { once: true });
@@ -1,9 +1,10 @@export class GameSocketexport class GameSocket{{ constructor (url, onMessage) constructor (url, onMessage, { onClose } = {}) { { this.url = url; this.url = url; this.onMessage = onMessage; this.onMessage = onMessage; this.onClose = onClose; this.socket = null; this.socket = null; } }@@ -14,6 +15,10 @@ export class GameSocket { { this.onMessage(JSON.parse(event.data)); this.onMessage(JSON.parse(event.data)); }); }); this.socket.addEventListener("close", (event) => { this.onClose?.(event); }); return new Promise((resolve, reject) => return new Promise((resolve, reject) => { { this.socket.addEventListener("open", resolve, { once: true }); this.socket.addEventListener("open", resolve, { once: true });@@ -0,0 +1,340 @@
import {
itemDefinition,
itemDisplayName,
itemAssetPathForStack,
formatQuantity
} from "/shared/definitions/items.js";
import { craftingStationDefinition } from "/shared/definitions/craftingStations.js";
import {
CRAFT_DURATION_MS,
canStartCraft,
countItemInSlots,
hasRecipeInputs,
recipesForStation
} from "/shared/crafting/recipes.js";
export function initCrafting ({
socket,
MessageType,
getInventorySlots,
getSkillLevel
})
{
const backdrop = document.getElementById("craft-backdrop");
const panel = document.getElementById("craft-panel");
const stationName = document.getElementById("craft-station-name");
const recipeGrid = document.getElementById("craft-recipe-grid");
const detailEmpty = document.getElementById("craft-detail-empty");
const detailBody = document.getElementById("craft-detail-body");
const outputImg = document.getElementById("craft-output-img");
const outputName = document.getElementById("craft-output-name");
const inputsList = document.getElementById("craft-inputs");
const statusEl = document.getElementById("craft-status");
const progressWrap = document.getElementById("craft-progress");
const progressFill = document.getElementById("craft-progress-fill");
const craftButton = document.getElementById("craft-button");
let open = false;
let stationId = null;
let recipes = [];
let selectedRecipeId = null;
let crafting = false;
let craftTimer = null;
let craftAnimFrame = null;
let craftStartedAt = 0;
document.getElementById("craft-close").addEventListener("click", () => close());
backdrop.addEventListener("click", () => close());
craftButton.addEventListener("click", () => startCraft());
function selectedRecipe ()
{
return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
}
function stationSkillLevel ()
{
const def = craftingStationDefinition(stationId);
return getSkillLevel?.(def?.skillId) ?? 1;
}
function refresh ()
{
if (!open)
{ return; }
renderRecipeGrid();
renderDetail();
}
function renderRecipeGrid ()
{
recipeGrid.replaceChildren();
for (const recipe of recipes)
{
recipeGrid.append(renderRecipeCell(recipe));
}
}
function renderRecipeCell (recipe)
{
const def = itemDefinition(recipe.output.itemId);
const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };
const cell = document.createElement("button");
cell.type = "button";
cell.className = "craft-recipe-cell";
if (recipe.recipeId === selectedRecipeId)
{ cell.classList.add("selected"); }
const img = document.createElement("img");
img.src = itemAssetPathForStack(stack);
img.alt = def?.displayName ?? "Item";
const label = document.createElement("span");
label.className = "craft-recipe-name";
label.textContent = def?.displayName ?? "Item";
cell.append(img, label);
cell.addEventListener("click", () =>
{
if (crafting)
{ return; }
selectedRecipeId = recipe.recipeId;
renderRecipeGrid();
renderDetail();
});
return cell;
}
function renderDetail ()
{
const recipe = selectedRecipe();
if (!recipe)
{
detailEmpty.hidden = false;
detailBody.hidden = true;
return;
}
detailEmpty.hidden = true;
detailBody.hidden = false;
const outputStack = {
itemId: recipe.output.itemId,
quantity: Math.max(1, recipe.output.quantity | 0 || 1)
};
outputImg.src = itemAssetPathForStack(outputStack);
outputImg.alt = itemDisplayName(outputStack);
const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
inputsList.replaceChildren();
const slots = getInventorySlots?.() ?? [];
for (const input of recipe.inputs ?? [])
{
inputsList.append(renderInputRow(input, slots));
}
updateCraftState(slots, recipe);
}
function renderInputRow (input, slots)
{
const need = input.quantity | 0;
const have = countItemInSlots(slots, input.itemId);
const stack = { itemId: input.itemId, quantity: need };
const row = document.createElement("li");
row.className = "craft-input-row";
if (have < need)
{ row.classList.add("short"); }
const img = document.createElement("img");
img.src = itemAssetPathForStack(stack);
img.alt = itemDisplayName(stack);
const text = document.createElement("span");
text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
row.append(img, text);
return row;
}
function updateCraftState (slots, recipe)
{
if (crafting)
{
craftButton.disabled = true;
return;
}
const skill = stationSkillLevel();
const minLevel = recipe.minSkillLevel | 0 || 1;
if (skill < minLevel)
{
statusEl.textContent = `Requires skill level ${minLevel} (you have ${skill}).`;
craftButton.disabled = true;
return;
}
const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
if (canStartCraft(slotsSnapshot, recipe, skill))
{
statusEl.textContent = `Crafting takes ${CRAFT_DURATION_MS / 1000} seconds.`;
craftButton.disabled = false;
return;
}
if (!hasRecipeInputs(slotsSnapshot, recipe))
{
statusEl.textContent = "Missing materials.";
}
else
{
statusEl.textContent = "Not enough bag space for the result.";
}
craftButton.disabled = true;
}
function startCraft ()
{
const recipe = selectedRecipe();
if (!recipe || crafting)
{ return; }
const slots = getInventorySlots?.() ?? [];
if (!canStartCraft(slots, recipe, stationSkillLevel()))
{
renderDetail();
return;
}
crafting = true;
craftButton.disabled = true;
progressWrap.hidden = false;
progressFill.style.width = "0%";
statusEl.textContent = "Crafting…";
craftStartedAt = performance.now();
socket.send({
type: MessageType.startCraft,
stationId,
recipeId: recipe.recipeId
});
animateProgress();
craftTimer = window.setTimeout(() => finishCraft(true), CRAFT_DURATION_MS);
}
function animateProgress ()
{
const tick = (now) =>
{
if (!crafting)
{ return; }
const elapsed = now - craftStartedAt;
const pct = Math.min(100, (elapsed / CRAFT_DURATION_MS) * 100);
progressFill.style.width = `${pct}%`;
if (pct < 100)
{ craftAnimFrame = requestAnimationFrame(tick); }
};
craftAnimFrame = requestAnimationFrame(tick);
}
function stopCraftAnimation ()
{
if (craftTimer != null)
{
clearTimeout(craftTimer);
craftTimer = null;
}
if (craftAnimFrame != null)
{
cancelAnimationFrame(craftAnimFrame);
craftAnimFrame = null;
}
crafting = false;
progressWrap.hidden = true;
progressFill.style.width = "0%";
}
function finishCraft (timedOut)
{
stopCraftAnimation();
if (timedOut)
{
statusEl.textContent = "Waiting for server…";
}
renderDetail();
}
function openStation (nextStationId)
{
const def = craftingStationDefinition(nextStationId);
if (!def)
{ return; }
stationId = nextStationId;
recipes = recipesForStation(nextStationId);
selectedRecipeId = recipes[0]?.recipeId ?? null;
stationName.textContent = def.displayName;
open = true;
panel.hidden = false;
backdrop.hidden = false;
statusEl.textContent = recipes.length
? "Select a recipe."
: "No recipes defined for this station yet.";
renderRecipeGrid();
renderDetail();
}
function close ()
{
if (crafting)
{
socket.send({ type: MessageType.cancelCraft });
stopCraftAnimation();
}
open = false;
stationId = null;
recipes = [];
selectedRecipeId = null;
panel.hidden = true;
backdrop.hidden = true;
detailEmpty.hidden = false;
detailBody.hidden = true;
statusEl.textContent = "";
}
function handleCraftResult (message)
{
if (!open || message.recipeId !== selectedRecipeId)
{ return; }
stopCraftAnimation();
if (message.ok)
{
statusEl.textContent = message.burned
? "The food burned."
: "Craft complete.";
}
else
{
statusEl.textContent = message.error ?? "Could not craft.";
}
renderDetail();
}
return {
openStation,
close,
refresh,
handleCraftResult,
isOpen ()
{
return open;
},
isBlocking ()
{
if (!open)
{ return false; }
if (backdrop && !backdrop.hidden)
{ return true; }
const x = GameInput.mousePosition.x;
const y = GameInput.mousePosition.y;
const box = panel.getBoundingClientRect();
return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
},
reset ()
{
close();
}
};
}
@@ -0,0 +1,340 @@import { itemDefinition, itemDisplayName, itemAssetPathForStack, formatQuantity} from "/shared/definitions/items.js";import { craftingStationDefinition } from "/shared/definitions/craftingStations.js";import { CRAFT_DURATION_MS, canStartCraft, countItemInSlots, hasRecipeInputs, recipesForStation} from "/shared/crafting/recipes.js";export function initCrafting ({ socket, MessageType, getInventorySlots, getSkillLevel}){ const backdrop = document.getElementById("craft-backdrop"); const panel = document.getElementById("craft-panel"); const stationName = document.getElementById("craft-station-name"); const recipeGrid = document.getElementById("craft-recipe-grid"); const detailEmpty = document.getElementById("craft-detail-empty"); const detailBody = document.getElementById("craft-detail-body"); const outputImg = document.getElementById("craft-output-img"); const outputName = document.getElementById("craft-output-name"); const inputsList = document.getElementById("craft-inputs"); const statusEl = document.getElementById("craft-status"); const progressWrap = document.getElementById("craft-progress"); const progressFill = document.getElementById("craft-progress-fill"); const craftButton = document.getElementById("craft-button"); let open = false; let stationId = null; let recipes = []; let selectedRecipeId = null; let crafting = false; let craftTimer = null; let craftAnimFrame = null; let craftStartedAt = 0; document.getElementById("craft-close").addEventListener("click", () => close()); backdrop.addEventListener("click", () => close()); craftButton.addEventListener("click", () => startCraft()); function selectedRecipe () { return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null; } function stationSkillLevel () { const def = craftingStationDefinition(stationId); return getSkillLevel?.(def?.skillId) ?? 1; } function refresh () { if (!open) { return; } renderRecipeGrid(); renderDetail(); } function renderRecipeGrid () { recipeGrid.replaceChildren(); for (const recipe of recipes) { recipeGrid.append(renderRecipeCell(recipe)); } } function renderRecipeCell (recipe) { const def = itemDefinition(recipe.output.itemId); const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 }; const cell = document.createElement("button"); cell.type = "button"; cell.className = "craft-recipe-cell"; if (recipe.recipeId === selectedRecipeId) { cell.classList.add("selected"); } const img = document.createElement("img"); img.src = itemAssetPathForStack(stack); img.alt = def?.displayName ?? "Item"; const label = document.createElement("span"); label.className = "craft-recipe-name"; label.textContent = def?.displayName ?? "Item"; cell.append(img, label); cell.addEventListener("click", () => { if (crafting) { return; } selectedRecipeId = recipe.recipeId; renderRecipeGrid(); renderDetail(); }); return cell; } function renderDetail () { const recipe = selectedRecipe(); if (!recipe) { detailEmpty.hidden = false; detailBody.hidden = true; return; } detailEmpty.hidden = true; detailBody.hidden = false; const outputStack = { itemId: recipe.output.itemId, quantity: Math.max(1, recipe.output.quantity | 0 || 1) }; outputImg.src = itemAssetPathForStack(outputStack); outputImg.alt = itemDisplayName(outputStack); const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : ""; outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`; inputsList.replaceChildren(); const slots = getInventorySlots?.() ?? []; for (const input of recipe.inputs ?? []) { inputsList.append(renderInputRow(input, slots)); } updateCraftState(slots, recipe); } function renderInputRow (input, slots) { const need = input.quantity | 0; const have = countItemInSlots(slots, input.itemId); const stack = { itemId: input.itemId, quantity: need }; const row = document.createElement("li"); row.className = "craft-input-row"; if (have < need) { row.classList.add("short"); } const img = document.createElement("img"); img.src = itemAssetPathForStack(stack); img.alt = itemDisplayName(stack); const text = document.createElement("span"); text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`; row.append(img, text); return row; } function updateCraftState (slots, recipe) { if (crafting) { craftButton.disabled = true; return; } const skill = stationSkillLevel(); const minLevel = recipe.minSkillLevel | 0 || 1; if (skill < minLevel) { statusEl.textContent = `Requires skill level ${minLevel} (you have ${skill}).`; craftButton.disabled = true; return; } const slotsSnapshot = slots ?? getInventorySlots?.() ?? []; if (canStartCraft(slotsSnapshot, recipe, skill)) { statusEl.textContent = `Crafting takes ${CRAFT_DURATION_MS / 1000} seconds.`; craftButton.disabled = false; return; } if (!hasRecipeInputs(slotsSnapshot, recipe)) { statusEl.textContent = "Missing materials."; } else { statusEl.textContent = "Not enough bag space for the result."; } craftButton.disabled = true; } function startCraft () { const recipe = selectedRecipe(); if (!recipe || crafting) { return; } const slots = getInventorySlots?.() ?? []; if (!canStartCraft(slots, recipe, stationSkillLevel())) { renderDetail(); return; } crafting = true; craftButton.disabled = true; progressWrap.hidden = false; progressFill.style.width = "0%"; statusEl.textContent = "Crafting…"; craftStartedAt = performance.now(); socket.send({ type: MessageType.startCraft, stationId, recipeId: recipe.recipeId }); animateProgress(); craftTimer = window.setTimeout(() => finishCraft(true), CRAFT_DURATION_MS); } function animateProgress () { const tick = (now) => { if (!crafting) { return; } const elapsed = now - craftStartedAt; const pct = Math.min(100, (elapsed / CRAFT_DURATION_MS) * 100); progressFill.style.width = `${pct}%`; if (pct < 100) { craftAnimFrame = requestAnimationFrame(tick); } }; craftAnimFrame = requestAnimationFrame(tick); } function stopCraftAnimation () { if (craftTimer != null) { clearTimeout(craftTimer); craftTimer = null; } if (craftAnimFrame != null) { cancelAnimationFrame(craftAnimFrame); craftAnimFrame = null; } crafting = false; progressWrap.hidden = true; progressFill.style.width = "0%"; } function finishCraft (timedOut) { stopCraftAnimation(); if (timedOut) { statusEl.textContent = "Waiting for server…"; } renderDetail(); } function openStation (nextStationId) { const def = craftingStationDefinition(nextStationId); if (!def) { return; } stationId = nextStationId; recipes = recipesForStation(nextStationId); selectedRecipeId = recipes[0]?.recipeId ?? null; stationName.textContent = def.displayName; open = true; panel.hidden = false; backdrop.hidden = false; statusEl.textContent = recipes.length ? "Select a recipe." : "No recipes defined for this station yet."; renderRecipeGrid(); renderDetail(); } function close () { if (crafting) { socket.send({ type: MessageType.cancelCraft }); stopCraftAnimation(); } open = false; stationId = null; recipes = []; selectedRecipeId = null; panel.hidden = true; backdrop.hidden = true; detailEmpty.hidden = false; detailBody.hidden = true; statusEl.textContent = ""; } function handleCraftResult (message) { if (!open || message.recipeId !== selectedRecipeId) { return; } stopCraftAnimation(); if (message.ok) { statusEl.textContent = message.burned ? "The food burned." : "Craft complete."; } else { statusEl.textContent = message.error ?? "Could not craft."; } renderDetail(); } return { openStation, close, refresh, handleCraftResult, isOpen () { return open; }, isBlocking () { if (!open) { return false; } if (backdrop && !backdrop.hidden) { return true; } const x = GameInput.mousePosition.x; const y = GameInput.mousePosition.y; const box = panel.getBoundingClientRect(); return x >= box.left && x < box.right && y >= box.top && y < box.bottom; }, reset () { close(); } };}@@ -1,7 +1,10 @@
import {
itemDefinition,
itemDescription,
itemOriginSummary,
itemAssetPathForStack,
itemDisplayName,
formatQuantity,
ItemId,
EQUIPMENT_SLOT,
LETTER_MAX_BODY_CHARS
@@ -28,13 +31,14 @@ export function initInventory ({
const bagPanel = document.getElementById("bag-panel");
const bagGrid = document.getElementById("bag-grid");
const equipGrid = document.getElementById("equip-grid");
const coins = document.getElementById("bag-coins");
const hint = document.getElementById("bag-hint");
const bankPanel = document.getElementById("bank-panel");
const vaultGrid = document.getElementById("vault-grid");
const vaultCoins = document.getElementById("vault-coins");
const vaultReservedGrid = document.getElementById("vault-reserved-grid");
const inheritGrid = document.getElementById("inherit-grid");
const inheritCoins = document.getElementById("inherit-coins");
const bankAvailablePane = document.getElementById("bank-available-pane");
const bankReservedPane = document.getElementById("bank-reserved-pane");
const bankInheritPane = document.getElementById("bank-inherit-pane");
const sendPanel = document.getElementById("send-panel");
const sendBackdrop = document.getElementById("send-backdrop");
@@ -48,12 +52,20 @@ export function initInventory ({
const letterSave = document.getElementById("letter-save");
const letterTitle = document.getElementById("letter-title");
const letterStatus = document.getElementById("letter-status");
const transferPanel = document.getElementById("transfer-panel");
const transferBackdrop = document.getElementById("transfer-backdrop");
const writeChequePanel = document.getElementById("write-cheque-panel");
const writeChequeBackdrop = document.getElementById("write-cheque-backdrop");
const writeChequeVault = document.getElementById("write-cheque-vault");
let bag = { inventory: [], equipment: { slots: {} }, currency: 0, vault: [], vaultCurrency: 0 };
let bag = { inventory: [], equipment: { slots: {} }, vault: [], vaultReserved: [] };
let selected = null;
let bankOpen = false;
let bankTab = "available";
let sendState = null;
let letterState = null;
let transferState = null;
let writeChequeState = null;
let pendingSearch = false;
let localCharacterId = null;
@@ -73,15 +85,20 @@ export function initInventory ({
{ return; }
socket.send({ type: MessageType.equipItem, slotIndex: selected });
});
document.getElementById("bank-close").addEventListener("click", () =>
{
bankOpen = false;
bankPanel.hidden = true;
});
document.getElementById("bank-close").addEventListener("click", () => closeBank());
document.getElementById("bank-claim").addEventListener("click", () =>
{
socket.send({ type: MessageType.claimInheritance });
});
document.getElementById("bank-tab-available").addEventListener("click", () => setBankTab("available"));
document.getElementById("bank-tab-reserved").addEventListener("click", () => setBankTab("reserved"));
document.getElementById("bank-tab-inherit").addEventListener("click", () => setBankTab("inherit"));
document.getElementById("transfer-close").addEventListener("click", () => closeTransfer());
transferBackdrop.addEventListener("click", () => closeTransfer());
document.getElementById("transfer-confirm").addEventListener("click", () => confirmTransfer());
document.getElementById("write-cheque-close").addEventListener("click", () => closeWriteCheque());
writeChequeBackdrop.addEventListener("click", () => closeWriteCheque());
document.getElementById("write-cheque-confirm").addEventListener("click", () => confirmWriteCheque());
document.getElementById("send-close").addEventListener("click", () => closeSend());
sendBackdrop.addEventListener("click", () => closeSend());
@@ -129,7 +146,6 @@ export function initInventory ({
function render ()
{
coins.textContent = `${bag.currency ?? 0} coins`;
bagGrid.innerHTML = "";
(bag.inventory ?? []).forEach((slot, index) =>
{
@@ -141,22 +157,27 @@ export function initInventory ({
const def = itemDefinition(slot.itemId);
const img = document.createElement("img");
img.src = itemAssetPathForStack(slot);
img.alt = def?.displayName ?? "";
img.alt = itemDisplayName(slot);
button.append(img);
if (slot.quantity > 1)
{
const count = document.createElement("span");
count.className = "qty";
count.textContent = String(slot.quantity);
count.textContent = formatQuantity(slot.quantity);
button.append(count);
}
}
button.addEventListener("click", () =>
{
if (!slot)
{ return; }
if (bankOpen)
{
transferSlot("inventory", index, null);
return;
}
selected = index;
hint.textContent = slot
? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}: ${itemDescription(slot, { localCharacterId })}`
: "Empty slot.";
hint.textContent = `${itemDisplayName(slot)}: ${itemDescription(slot, { localCharacterId })}`;
render();
});
button.addEventListener("contextmenu", (event) =>
@@ -167,7 +188,10 @@ export function initInventory ({
{ return; }
selected = index;
render();
showItemMenu(event.clientX, event.clientY, index, slot);
if (bankOpen)
{ showBankTransferMenu(event.clientX, event.clientY, "inventory", index, slot); }
else
{ showItemMenu(event.clientX, event.clientY, index, slot); }
});
bagGrid.append(button);
});
@@ -183,7 +207,7 @@ export function initInventory ({
const def = itemDefinition(worn.itemId);
const img = document.createElement("img");
img.src = itemAssetPathForStack(worn);
img.alt = def?.displayName ?? label;
img.alt = itemDisplayName(worn);
button.append(img);
}
button.addEventListener("click", () =>
@@ -202,7 +226,9 @@ export function initInventory ({
const isOwnLetter = slot.itemId === ItemId.letter
&& slot.instance?.kind === "letter"
&& Number(slot.instance.authorCharacterId) === Number(localCharacterId);
const canSend = slot.itemId !== ItemId.letter || isOwnLetter;
const canSend = slot.itemId !== ItemId.blankCheque
&& (slot.itemId !== ItemId.letter || isOwnLetter);
const canEquip = def?.equipment?.slot && slot.itemId !== ItemId.coins;
if (slot.itemId === ItemId.paper)
{
@@ -238,7 +264,21 @@ export function initInventory ({
});
}
}
if (def?.equipment?.slot)
if (slot.itemId === ItemId.blankCheque)
{
items.push({
label: "Write Cheque",
onSelect: () => openWriteCheque(slotIndex)
});
}
if (slot.itemId === ItemId.filledCheque && bankOpen)
{
items.push({
label: "Redeem Cheque",
onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex })
});
}
if (canEquip)
{
items.push({
label: "Equip",
@@ -252,6 +292,14 @@ export function initInventory ({
onSelect: () => openSend(slotIndex, slot)
});
}
const healing = itemDefinition(slot.itemId)?.healing ?? 0;
if (healing > 0)
{
items.push({
label: "Eat",
onSelect: () => socket.send({ type: MessageType.eatItem, slotIndex })
});
}
items.push({
label: "Drop",
onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex })
@@ -259,6 +307,221 @@ export function initInventory ({
contextMenu?.show(x, y, items);
}
function showBankTransferMenu (x, y, side, slotIndex, slot)
{
if (side === "inventory" && slot.itemId === ItemId.filledCheque)
{
contextMenu?.show(x, y, [{
label: "Redeem Cheque",
onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex })
}]);
return;
}
if (side === "inventory" && slot.itemId === ItemId.blankCheque)
{
contextMenu?.show(x, y, [
{
label: `Return ${slot.quantity | 0}`,
onSelect: () => socket.send({
type: MessageType.returnBlankCheques,
slotIndex,
quantity: slot.quantity | 0
})
},
{
label: "Write Cheque",
onSelect: () => openWriteCheque(slotIndex)
}
]);
return;
}
const qty = slot.quantity | 0;
const name = itemDisplayName(slot);
if (qty <= 1)
{
contextMenu?.show(x, y, [{
label: `Transfer ${name}`,
onSelect: () => transferSlot(side, slotIndex, 1)
}]);
return;
}
contextMenu?.show(x, y, [
{
label: `Transfer all ${name}`,
onSelect: () => transferSlot(side, slotIndex, null)
},
{
label: `Transfer half ${name}`,
onSelect: () => transferSlot(side, slotIndex, Math.max(1, Math.floor(qty / 2)))
},
{
label: `Transfer one ${name}`,
onSelect: () => transferSlot(side, slotIndex, 1)
},
{
label: `Transfer X ${name}`,
onSelect: () => openTransfer(side, slotIndex, slot)
}
]);
}
function transferSlot (side, slotIndex, quantity)
{
if (side === "inventory")
{
socket.send({
type: MessageType.bankDeposit,
slotIndex,
quantity
});
return;
}
socket.send({
type: MessageType.bankWithdraw,
slotIndex,
quantity
});
}
function openTransfer (side, slotIndex, slot)
{
transferState = { side, slotIndex, maxQty: slot.quantity | 0 };
document.getElementById("transfer-item-name").textContent = itemDisplayName(slot);
const input = document.getElementById("transfer-qty");
input.value = "1";
input.max = String(transferState.maxQty);
transferPanel.hidden = false;
transferBackdrop.hidden = false;
}
function closeTransfer ()
{
transferState = null;
transferPanel.hidden = true;
transferBackdrop.hidden = true;
}
function confirmTransfer ()
{
if (!transferState)
{ return; }
const quantity = Math.min(
transferState.maxQty,
Math.max(1, Number(document.getElementById("transfer-qty").value) | 0)
);
transferSlot(transferState.side, transferState.slotIndex, quantity);
closeTransfer();
}
function openWriteCheque (slotIndex)
{
writeChequeState = { slotIndex, vaultSlotIndex: null, maxQty: 1 };
document.getElementById("write-cheque-item").textContent = "No vault item selected.";
document.getElementById("write-cheque-qty").value = "1";
document.getElementById("write-cheque-confirm").disabled = true;
document.getElementById("write-cheque-status").textContent = "";
writeChequePanel.hidden = false;
writeChequeBackdrop.hidden = false;
renderWriteChequeVault();
}
function closeWriteCheque ()
{
writeChequeState = null;
writeChequePanel.hidden = true;
writeChequeBackdrop.hidden = true;
if (bankOpen)
{ renderBank(); }
}
function renderWriteChequeVault ()
{
if (!writeChequeVault)
{ return; }
writeChequeVault.innerHTML = "";
const slots = bag.vault ?? [];
if (!slots.some(Boolean))
{
const empty = document.createElement("p");
empty.className = "hint";
empty.textContent = "Your vault is empty. Deposit goods at a bank first.";
writeChequeVault.append(empty);
return;
}
slots.forEach((slot, index) =>
{
if (!slot)
{ return; }
const button = document.createElement("button");
button.className = "item-slot";
if (writeChequeState?.vaultSlotIndex === index)
{ button.classList.add("selected"); }
button.title = tooltip(slot);
const def = itemDefinition(slot.itemId);
const img = document.createElement("img");
img.src = itemAssetPathForStack(slot);
img.alt = itemDisplayName(slot);
button.append(img);
if (slot.quantity > 1)
{
const count = document.createElement("span");
count.className = "qty";
count.textContent = formatQuantity(slot.quantity);
button.append(count);
}
button.addEventListener("click", () =>
{
if (!writeChequeState)
{ return; }
writeChequeState.vaultSlotIndex = index;
writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableOf(slot.itemId);
document.getElementById("write-cheque-item").textContent =
`${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
const qtyInput = document.getElementById("write-cheque-qty");
qtyInput.value = "1";
qtyInput.max = String(writeChequeState.maxQty);
qtyInput.disabled = writeChequeState.maxQty <= 1;
document.getElementById("write-cheque-confirm").disabled = false;
renderWriteChequeVault();
});
writeChequeVault.append(button);
});
}
function confirmWriteCheque ()
{
if (!writeChequeState || writeChequeState.vaultSlotIndex == null)
{ return; }
const quantity = Math.max(1, Number(document.getElementById("write-cheque-qty").value) | 0);
socket.send({
type: MessageType.writeCheque,
slotIndex: writeChequeState.slotIndex,
vaultSlotIndex: writeChequeState.vaultSlotIndex,
quantity
});
document.getElementById("write-cheque-status").textContent = "Writing…";
closeWriteCheque();
}
function closeBank ()
{
bankOpen = false;
bankPanel.hidden = true;
closeWriteCheque();
closeTransfer();
}
function setBankTab (tab)
{
bankTab = tab;
document.getElementById("bank-tab-available").classList.toggle("active", tab === "available");
document.getElementById("bank-tab-reserved").classList.toggle("active", tab === "reserved");
document.getElementById("bank-tab-inherit").classList.toggle("active", tab === "inherit");
bankAvailablePane.hidden = tab !== "available";
bankReservedPane.hidden = tab !== "reserved";
bankInheritPane.hidden = tab !== "inherit";
}
function openSend (slotIndex, slot)
{
const def = itemDefinition(slot.itemId);
@@ -269,7 +532,7 @@ export function initInventory ({
destination: null
};
document.getElementById("send-item-img").src = itemAssetPathForStack(slot);
document.getElementById("send-item-name").textContent = def?.displayName ?? "Item";
document.getElementById("send-item-name").textContent = itemDisplayName(slot);
const qtyInput = document.getElementById("send-qty");
qtyInput.value = "1";
qtyInput.max = String(sendState.maxQty);
@@ -440,49 +703,118 @@ export function initInventory ({
letterBackdrop.hidden = true;
}
function renderVault (grid, slots)
function renderVault (grid, slots, { side = "vault", interactive = true } = {})
{
grid.innerHTML = "";
(slots ?? []).forEach((slot, index) =>
{
if (!slot)
{ return; }
const button = document.createElement("button");
button.className = "item-slot";
if (writeChequeState && side === "vault" && writeChequeState.vaultSlotIndex === index)
{ button.classList.add("selected"); }
button.title = tooltip(slot);
button.textContent = slot
? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`
: "";
button.addEventListener("click", () =>
const def = itemDefinition(slot.itemId);
const img = document.createElement("img");
img.src = itemAssetPathForStack(slot);
img.alt = itemDisplayName(slot);
button.append(img);
if (slot.quantity > 1)
{
if (!slot)
{ return; }
socket.send({ type: MessageType.bankWithdraw, slotIndex: index });
});
const count = document.createElement("span");
count.className = "qty";
count.textContent = formatQuantity(slot.quantity);
button.append(count);
}
if (interactive && side === "vault")
{
button.addEventListener("click", () =>
{
if (writeChequeState)
{
writeChequeState.vaultSlotIndex = index;
writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance
? 1
: availableOf(slot.itemId);
document.getElementById("write-cheque-item").textContent =
`${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
const qtyInput = document.getElementById("write-cheque-qty");
qtyInput.value = "1";
qtyInput.max = String(writeChequeState.maxQty);
qtyInput.disabled = writeChequeState.maxQty <= 1;
document.getElementById("write-cheque-confirm").disabled = false;
renderBank();
return;
}
transferSlot("vault", index, null);
});
button.addEventListener("contextmenu", (event) =>
{
event.preventDefault();
event.stopPropagation();
if (writeChequeState)
{ return; }
showBankTransferMenu(event.clientX, event.clientY, "vault", index, slot);
});
}
grid.append(button);
});
}
function availableOf (itemId)
{
let total = 0;
for (const slot of bag.vault ?? [])
{
if (slot?.itemId === itemId)
{ total += slot.quantity | 0; }
}
return total;
}
function renderBank ()
{
renderVault(vaultGrid, bag.vault, { side: "vault", interactive: true });
renderVault(vaultReservedGrid, bag.vaultReserved, { side: "reserved", interactive: false });
setBankTab(bankTab);
}
function tooltip (slot)
{
if (!slot)
{ return ""; }
const def = itemDefinition(slot.itemId);
return `${def?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`;
const base = `${itemDisplayName(slot)}${slot.quantity > 1 ? ` ×${formatQuantity(slot.quantity)}` : ""}`;
const origin = itemOriginSummary(slot);
const desc = itemDescription(slot, { localCharacterId });
const lines = [base];
if (origin)
{ lines.push(origin); }
if (desc)
{ lines.push(desc); }
return lines.join("\n");
}
return {
isOpen ()
{
return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden;
return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden
|| !sendTargetPanel.hidden || !transferPanel.hidden || !writeChequePanel.hidden;
},
isBlocking ()
{
// Send/letter dialogs cover the view — keep world clicks blocked.
if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden)
if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden
|| !transferPanel.hidden || !writeChequePanel.hidden)
{ return true; }
if (sendBackdrop && !sendBackdrop.hidden)
{ return true; }
if (letterBackdrop && !letterBackdrop.hidden)
{ return true; }
if (transferBackdrop && !transferBackdrop.hidden)
{ return true; }
if (writeChequeBackdrop && !writeChequeBackdrop.hidden)
{ return true; }
const x = GameInput.mousePosition.x;
const y = GameInput.mousePosition.y;
for (const element of [bagPanel, bankPanel])
@@ -499,49 +831,55 @@ export function initInventory ({
{
localCharacterId = characterId;
},
getInventorySlots ()
{
return bag.inventory ?? [];
},
handleInventory (message)
{
bag = { ...bag, ...message };
render();
if (bankOpen)
{ renderBank(); }
if (writeChequeState)
{ renderWriteChequeVault(); }
if (letterState && letterStatus.textContent === "Saving…")
{
letterStatus.textContent = "Saved.";
if (letterState.mode === "write")
{ closeLetter(); }
else if (letterState.mode === "edit")
else if (letterState.mode === "edit")
{
const slot = bag.inventory?.[letterState.slotIndex];
if (slot?.instance)
{
const slot = bag.inventory?.[letterState.slotIndex];
if (slot?.instance)
{
letterState.instance = slot.instance;
letterBody.value = slot.instance.body ?? "";
refreshLetterSignature();
fitLetterBody();
}
letterState.instance = slot.instance;
letterBody.value = slot.instance.body ?? "";
refreshLetterSignature();
fitLetterBody();
}
}
}
},
handleBank (message)
{
bankOpen = true;
bankPanel.hidden = false;
bag.vault = message.vault;
bag.vaultCurrency = message.vaultCurrency;
vaultCoins.textContent = `${message.vaultCurrency ?? 0} coins in vault · you carry ${message.currency ?? 0}`;
inheritCoins.textContent = `${message.inheritance?.currency ?? 0} coins waiting`;
renderVault(vaultGrid, message.vault);
renderVault(inheritGrid, message.inheritance?.slots ?? []);
bagPanel.hidden = false;
bag.vault = message.vault ?? [];
bag.vaultReserved = message.vaultReserved ?? [];
renderVault(inheritGrid, message.inheritance?.slots ?? [], { interactive: false });
inheritGrid.querySelectorAll("button").forEach((button) =>
{
button.onclick = null;
});
setBankTab("available");
renderBank();
render();
},
depositSelected ()
getBlankCheques ()
{
if (selected == null)
{ return; }
socket.send({ type: MessageType.bankDeposit, slotIndex: selected });
socket.send({ type: MessageType.getBlankCheques });
},
handlePigeonDispatched ()
{
@@ -569,8 +907,7 @@ export function initInventory ({
reset ()
{
bagPanel.hidden = true;
bankPanel.hidden = true;
bankOpen = false;
closeBank();
selected = null;
closeSend();
closeLetter();
@@ -1,7 +1,10 @@import {import { itemDefinition, itemDefinition, itemDescription, itemDescription, itemOriginSummary, itemAssetPathForStack, itemAssetPathForStack, itemDisplayName, formatQuantity, ItemId, ItemId, EQUIPMENT_SLOT, EQUIPMENT_SLOT, LETTER_MAX_BODY_CHARS LETTER_MAX_BODY_CHARS@@ -28,13 +31,14 @@ export function initInventory ({ const bagPanel = document.getElementById("bag-panel"); const bagPanel = document.getElementById("bag-panel"); const bagGrid = document.getElementById("bag-grid"); const bagGrid = document.getElementById("bag-grid"); const equipGrid = document.getElementById("equip-grid"); const equipGrid = document.getElementById("equip-grid"); const coins = document.getElementById("bag-coins"); const hint = document.getElementById("bag-hint"); const hint = document.getElementById("bag-hint"); const bankPanel = document.getElementById("bank-panel"); const bankPanel = document.getElementById("bank-panel"); const vaultGrid = document.getElementById("vault-grid"); const vaultGrid = document.getElementById("vault-grid"); const vaultCoins = document.getElementById("vault-coins"); const vaultReservedGrid = document.getElementById("vault-reserved-grid"); const inheritGrid = document.getElementById("inherit-grid"); const inheritGrid = document.getElementById("inherit-grid"); const inheritCoins = document.getElementById("inherit-coins"); const bankAvailablePane = document.getElementById("bank-available-pane"); const bankReservedPane = document.getElementById("bank-reserved-pane"); const bankInheritPane = document.getElementById("bank-inherit-pane"); const sendPanel = document.getElementById("send-panel"); const sendPanel = document.getElementById("send-panel"); const sendBackdrop = document.getElementById("send-backdrop"); const sendBackdrop = document.getElementById("send-backdrop");@@ -48,12 +52,20 @@ export function initInventory ({ const letterSave = document.getElementById("letter-save"); const letterSave = document.getElementById("letter-save"); const letterTitle = document.getElementById("letter-title"); const letterTitle = document.getElementById("letter-title"); const letterStatus = document.getElementById("letter-status"); const letterStatus = document.getElementById("letter-status"); const transferPanel = document.getElementById("transfer-panel"); const transferBackdrop = document.getElementById("transfer-backdrop"); const writeChequePanel = document.getElementById("write-cheque-panel"); const writeChequeBackdrop = document.getElementById("write-cheque-backdrop"); const writeChequeVault = document.getElementById("write-cheque-vault"); let bag = { inventory: [], equipment: { slots: {} }, currency: 0, vault: [], vaultCurrency: 0 }; let bag = { inventory: [], equipment: { slots: {} }, vault: [], vaultReserved: [] }; let selected = null; let selected = null; let bankOpen = false; let bankOpen = false; let bankTab = "available"; let sendState = null; let sendState = null; let letterState = null; let letterState = null; let transferState = null; let writeChequeState = null; let pendingSearch = false; let pendingSearch = false; let localCharacterId = null; let localCharacterId = null;@@ -73,15 +85,20 @@ export function initInventory ({ { return; } { return; } socket.send({ type: MessageType.equipItem, slotIndex: selected }); socket.send({ type: MessageType.equipItem, slotIndex: selected }); }); }); document.getElementById("bank-close").addEventListener("click", () => document.getElementById("bank-close").addEventListener("click", () => closeBank()); { bankOpen = false; bankPanel.hidden = true; }); document.getElementById("bank-claim").addEventListener("click", () => document.getElementById("bank-claim").addEventListener("click", () => { { socket.send({ type: MessageType.claimInheritance }); socket.send({ type: MessageType.claimInheritance }); }); }); document.getElementById("bank-tab-available").addEventListener("click", () => setBankTab("available")); document.getElementById("bank-tab-reserved").addEventListener("click", () => setBankTab("reserved")); document.getElementById("bank-tab-inherit").addEventListener("click", () => setBankTab("inherit")); document.getElementById("transfer-close").addEventListener("click", () => closeTransfer()); transferBackdrop.addEventListener("click", () => closeTransfer()); document.getElementById("transfer-confirm").addEventListener("click", () => confirmTransfer()); document.getElementById("write-cheque-close").addEventListener("click", () => closeWriteCheque()); writeChequeBackdrop.addEventListener("click", () => closeWriteCheque()); document.getElementById("write-cheque-confirm").addEventListener("click", () => confirmWriteCheque()); document.getElementById("send-close").addEventListener("click", () => closeSend()); document.getElementById("send-close").addEventListener("click", () => closeSend()); sendBackdrop.addEventListener("click", () => closeSend()); sendBackdrop.addEventListener("click", () => closeSend());@@ -129,7 +146,6 @@ export function initInventory ({ function render () function render () { { coins.textContent = `${bag.currency ?? 0} coins`; bagGrid.innerHTML = ""; bagGrid.innerHTML = ""; (bag.inventory ?? []).forEach((slot, index) => (bag.inventory ?? []).forEach((slot, index) => { {@@ -141,22 +157,27 @@ export function initInventory ({ const def = itemDefinition(slot.itemId); const def = itemDefinition(slot.itemId); const img = document.createElement("img"); const img = document.createElement("img"); img.src = itemAssetPathForStack(slot); img.src = itemAssetPathForStack(slot); img.alt = def?.displayName ?? ""; img.alt = itemDisplayName(slot); button.append(img); button.append(img); if (slot.quantity > 1) if (slot.quantity > 1) { { const count = document.createElement("span"); const count = document.createElement("span"); count.className = "qty"; count.className = "qty"; count.textContent = String(slot.quantity); count.textContent = formatQuantity(slot.quantity); button.append(count); button.append(count); } } } } button.addEventListener("click", () => button.addEventListener("click", () => { { if (!slot) { return; } if (bankOpen) { transferSlot("inventory", index, null); return; } selected = index; selected = index; hint.textContent = slot hint.textContent = `${itemDisplayName(slot)}: ${itemDescription(slot, { localCharacterId })}`; ? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}: ${itemDescription(slot, { localCharacterId })}` : "Empty slot."; render(); render(); }); }); button.addEventListener("contextmenu", (event) => button.addEventListener("contextmenu", (event) =>@@ -167,7 +188,10 @@ export function initInventory ({ { return; } { return; } selected = index; selected = index; render(); render(); showItemMenu(event.clientX, event.clientY, index, slot); if (bankOpen) { showBankTransferMenu(event.clientX, event.clientY, "inventory", index, slot); } else { showItemMenu(event.clientX, event.clientY, index, slot); } }); }); bagGrid.append(button); bagGrid.append(button); }); });@@ -183,7 +207,7 @@ export function initInventory ({ const def = itemDefinition(worn.itemId); const def = itemDefinition(worn.itemId); const img = document.createElement("img"); const img = document.createElement("img"); img.src = itemAssetPathForStack(worn); img.src = itemAssetPathForStack(worn); img.alt = def?.displayName ?? label; img.alt = itemDisplayName(worn); button.append(img); button.append(img); } } button.addEventListener("click", () => button.addEventListener("click", () =>@@ -202,7 +226,9 @@ export function initInventory ({ const isOwnLetter = slot.itemId === ItemId.letter const isOwnLetter = slot.itemId === ItemId.letter && slot.instance?.kind === "letter" && slot.instance?.kind === "letter" && Number(slot.instance.authorCharacterId) === Number(localCharacterId); && Number(slot.instance.authorCharacterId) === Number(localCharacterId); const canSend = slot.itemId !== ItemId.letter || isOwnLetter; const canSend = slot.itemId !== ItemId.blankCheque && (slot.itemId !== ItemId.letter || isOwnLetter); const canEquip = def?.equipment?.slot && slot.itemId !== ItemId.coins; if (slot.itemId === ItemId.paper) if (slot.itemId === ItemId.paper) { {@@ -238,7 +264,21 @@ export function initInventory ({ }); }); } } } } if (def?.equipment?.slot) if (slot.itemId === ItemId.blankCheque) { items.push({ label: "Write Cheque", onSelect: () => openWriteCheque(slotIndex) }); } if (slot.itemId === ItemId.filledCheque && bankOpen) { items.push({ label: "Redeem Cheque", onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex }) }); } if (canEquip) { { items.push({ items.push({ label: "Equip", label: "Equip",@@ -252,6 +292,14 @@ export function initInventory ({ onSelect: () => openSend(slotIndex, slot) onSelect: () => openSend(slotIndex, slot) }); }); } } const healing = itemDefinition(slot.itemId)?.healing ?? 0; if (healing > 0) { items.push({ label: "Eat", onSelect: () => socket.send({ type: MessageType.eatItem, slotIndex }) }); } items.push({ items.push({ label: "Drop", label: "Drop", onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex }) onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex })@@ -259,6 +307,221 @@ export function initInventory ({ contextMenu?.show(x, y, items); contextMenu?.show(x, y, items); } } function showBankTransferMenu (x, y, side, slotIndex, slot) { if (side === "inventory" && slot.itemId === ItemId.filledCheque) { contextMenu?.show(x, y, [{ label: "Redeem Cheque", onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex }) }]); return; } if (side === "inventory" && slot.itemId === ItemId.blankCheque) { contextMenu?.show(x, y, [ { label: `Return ${slot.quantity | 0}`, onSelect: () => socket.send({ type: MessageType.returnBlankCheques, slotIndex, quantity: slot.quantity | 0 }) }, { label: "Write Cheque", onSelect: () => openWriteCheque(slotIndex) } ]); return; } const qty = slot.quantity | 0; const name = itemDisplayName(slot); if (qty <= 1) { contextMenu?.show(x, y, [{ label: `Transfer ${name}`, onSelect: () => transferSlot(side, slotIndex, 1) }]); return; } contextMenu?.show(x, y, [ { label: `Transfer all ${name}`, onSelect: () => transferSlot(side, slotIndex, null) }, { label: `Transfer half ${name}`, onSelect: () => transferSlot(side, slotIndex, Math.max(1, Math.floor(qty / 2))) }, { label: `Transfer one ${name}`, onSelect: () => transferSlot(side, slotIndex, 1) }, { label: `Transfer X ${name}`, onSelect: () => openTransfer(side, slotIndex, slot) } ]); } function transferSlot (side, slotIndex, quantity) { if (side === "inventory") { socket.send({ type: MessageType.bankDeposit, slotIndex, quantity }); return; } socket.send({ type: MessageType.bankWithdraw, slotIndex, quantity }); } function openTransfer (side, slotIndex, slot) { transferState = { side, slotIndex, maxQty: slot.quantity | 0 }; document.getElementById("transfer-item-name").textContent = itemDisplayName(slot); const input = document.getElementById("transfer-qty"); input.value = "1"; input.max = String(transferState.maxQty); transferPanel.hidden = false; transferBackdrop.hidden = false; } function closeTransfer () { transferState = null; transferPanel.hidden = true; transferBackdrop.hidden = true; } function confirmTransfer () { if (!transferState) { return; } const quantity = Math.min( transferState.maxQty, Math.max(1, Number(document.getElementById("transfer-qty").value) | 0) ); transferSlot(transferState.side, transferState.slotIndex, quantity); closeTransfer(); } function openWriteCheque (slotIndex) { writeChequeState = { slotIndex, vaultSlotIndex: null, maxQty: 1 }; document.getElementById("write-cheque-item").textContent = "No vault item selected."; document.getElementById("write-cheque-qty").value = "1"; document.getElementById("write-cheque-confirm").disabled = true; document.getElementById("write-cheque-status").textContent = ""; writeChequePanel.hidden = false; writeChequeBackdrop.hidden = false; renderWriteChequeVault(); } function closeWriteCheque () { writeChequeState = null; writeChequePanel.hidden = true; writeChequeBackdrop.hidden = true; if (bankOpen) { renderBank(); } } function renderWriteChequeVault () { if (!writeChequeVault) { return; } writeChequeVault.innerHTML = ""; const slots = bag.vault ?? []; if (!slots.some(Boolean)) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "Your vault is empty. Deposit goods at a bank first."; writeChequeVault.append(empty); return; } slots.forEach((slot, index) => { if (!slot) { return; } const button = document.createElement("button"); button.className = "item-slot"; if (writeChequeState?.vaultSlotIndex === index) { button.classList.add("selected"); } button.title = tooltip(slot); const def = itemDefinition(slot.itemId); const img = document.createElement("img"); img.src = itemAssetPathForStack(slot); img.alt = itemDisplayName(slot); button.append(img); if (slot.quantity > 1) { const count = document.createElement("span"); count.className = "qty"; count.textContent = formatQuantity(slot.quantity); button.append(count); } button.addEventListener("click", () => { if (!writeChequeState) { return; } writeChequeState.vaultSlotIndex = index; writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableOf(slot.itemId); document.getElementById("write-cheque-item").textContent = `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`; const qtyInput = document.getElementById("write-cheque-qty"); qtyInput.value = "1"; qtyInput.max = String(writeChequeState.maxQty); qtyInput.disabled = writeChequeState.maxQty <= 1; document.getElementById("write-cheque-confirm").disabled = false; renderWriteChequeVault(); }); writeChequeVault.append(button); }); } function confirmWriteCheque () { if (!writeChequeState || writeChequeState.vaultSlotIndex == null) { return; } const quantity = Math.max(1, Number(document.getElementById("write-cheque-qty").value) | 0); socket.send({ type: MessageType.writeCheque, slotIndex: writeChequeState.slotIndex, vaultSlotIndex: writeChequeState.vaultSlotIndex, quantity }); document.getElementById("write-cheque-status").textContent = "Writing…"; closeWriteCheque(); } function closeBank () { bankOpen = false; bankPanel.hidden = true; closeWriteCheque(); closeTransfer(); } function setBankTab (tab) { bankTab = tab; document.getElementById("bank-tab-available").classList.toggle("active", tab === "available"); document.getElementById("bank-tab-reserved").classList.toggle("active", tab === "reserved"); document.getElementById("bank-tab-inherit").classList.toggle("active", tab === "inherit"); bankAvailablePane.hidden = tab !== "available"; bankReservedPane.hidden = tab !== "reserved"; bankInheritPane.hidden = tab !== "inherit"; } function openSend (slotIndex, slot) function openSend (slotIndex, slot) { { const def = itemDefinition(slot.itemId); const def = itemDefinition(slot.itemId);@@ -269,7 +532,7 @@ export function initInventory ({ destination: null destination: null }; }; document.getElementById("send-item-img").src = itemAssetPathForStack(slot); document.getElementById("send-item-img").src = itemAssetPathForStack(slot); document.getElementById("send-item-name").textContent = def?.displayName ?? "Item"; document.getElementById("send-item-name").textContent = itemDisplayName(slot); const qtyInput = document.getElementById("send-qty"); const qtyInput = document.getElementById("send-qty"); qtyInput.value = "1"; qtyInput.value = "1"; qtyInput.max = String(sendState.maxQty); qtyInput.max = String(sendState.maxQty);@@ -440,49 +703,118 @@ export function initInventory ({ letterBackdrop.hidden = true; letterBackdrop.hidden = true; } } function renderVault (grid, slots) function renderVault (grid, slots, { side = "vault", interactive = true } = {}) { { grid.innerHTML = ""; grid.innerHTML = ""; (slots ?? []).forEach((slot, index) => (slots ?? []).forEach((slot, index) => { { if (!slot) { return; } const button = document.createElement("button"); const button = document.createElement("button"); button.className = "item-slot"; button.className = "item-slot"; if (writeChequeState && side === "vault" && writeChequeState.vaultSlotIndex === index) { button.classList.add("selected"); } button.title = tooltip(slot); button.title = tooltip(slot); button.textContent = slot const def = itemDefinition(slot.itemId); ? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}` const img = document.createElement("img"); : ""; img.src = itemAssetPathForStack(slot); button.addEventListener("click", () => img.alt = itemDisplayName(slot); button.append(img); if (slot.quantity > 1) { { if (!slot) const count = document.createElement("span"); { return; } count.className = "qty"; socket.send({ type: MessageType.bankWithdraw, slotIndex: index }); count.textContent = formatQuantity(slot.quantity); }); button.append(count); } if (interactive && side === "vault") { button.addEventListener("click", () => { if (writeChequeState) { writeChequeState.vaultSlotIndex = index; writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance ? 1 : availableOf(slot.itemId); document.getElementById("write-cheque-item").textContent = `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`; const qtyInput = document.getElementById("write-cheque-qty"); qtyInput.value = "1"; qtyInput.max = String(writeChequeState.maxQty); qtyInput.disabled = writeChequeState.maxQty <= 1; document.getElementById("write-cheque-confirm").disabled = false; renderBank(); return; } transferSlot("vault", index, null); }); button.addEventListener("contextmenu", (event) => { event.preventDefault(); event.stopPropagation(); if (writeChequeState) { return; } showBankTransferMenu(event.clientX, event.clientY, "vault", index, slot); }); } grid.append(button); grid.append(button); }); }); } } function availableOf (itemId) { let total = 0; for (const slot of bag.vault ?? []) { if (slot?.itemId === itemId) { total += slot.quantity | 0; } } return total; } function renderBank () { renderVault(vaultGrid, bag.vault, { side: "vault", interactive: true }); renderVault(vaultReservedGrid, bag.vaultReserved, { side: "reserved", interactive: false }); setBankTab(bankTab); } function tooltip (slot) function tooltip (slot) { { if (!slot) if (!slot) { return ""; } { return ""; } const def = itemDefinition(slot.itemId); const def = itemDefinition(slot.itemId); return `${def?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`; const base = `${itemDisplayName(slot)}${slot.quantity > 1 ? ` ×${formatQuantity(slot.quantity)}` : ""}`; const origin = itemOriginSummary(slot); const desc = itemDescription(slot, { localCharacterId }); const lines = [base]; if (origin) { lines.push(origin); } if (desc) { lines.push(desc); } return lines.join("\n"); } } return { return { isOpen () isOpen () { { return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden; return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden || !transferPanel.hidden || !writeChequePanel.hidden; }, }, isBlocking () isBlocking () { { // Send/letter dialogs cover the view — keep world clicks blocked. if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden) || !transferPanel.hidden || !writeChequePanel.hidden) { return true; } { return true; } if (sendBackdrop && !sendBackdrop.hidden) if (sendBackdrop && !sendBackdrop.hidden) { return true; } { return true; } if (letterBackdrop && !letterBackdrop.hidden) if (letterBackdrop && !letterBackdrop.hidden) { return true; } { return true; } if (transferBackdrop && !transferBackdrop.hidden) { return true; } if (writeChequeBackdrop && !writeChequeBackdrop.hidden) { return true; } const x = GameInput.mousePosition.x; const x = GameInput.mousePosition.x; const y = GameInput.mousePosition.y; const y = GameInput.mousePosition.y; for (const element of [bagPanel, bankPanel]) for (const element of [bagPanel, bankPanel])@@ -499,49 +831,55 @@ export function initInventory ({ { { localCharacterId = characterId; localCharacterId = characterId; }, }, getInventorySlots () { return bag.inventory ?? []; }, handleInventory (message) handleInventory (message) { { bag = { ...bag, ...message }; bag = { ...bag, ...message }; render(); render(); if (bankOpen) { renderBank(); } if (writeChequeState) { renderWriteChequeVault(); } if (letterState && letterStatus.textContent === "Saving…") if (letterState && letterStatus.textContent === "Saving…") { { letterStatus.textContent = "Saved."; letterStatus.textContent = "Saved."; if (letterState.mode === "write") if (letterState.mode === "write") { closeLetter(); } { closeLetter(); } else if (letterState.mode === "edit") else if (letterState.mode === "edit") { const slot = bag.inventory?.[letterState.slotIndex]; if (slot?.instance) { { const slot = bag.inventory?.[letterState.slotIndex]; letterState.instance = slot.instance; if (slot?.instance) letterBody.value = slot.instance.body ?? ""; { refreshLetterSignature(); letterState.instance = slot.instance; fitLetterBody(); letterBody.value = slot.instance.body ?? ""; refreshLetterSignature(); fitLetterBody(); } } } } } } }, }, handleBank (message) handleBank (message) { { bankOpen = true; bankOpen = true; bankPanel.hidden = false; bankPanel.hidden = false; bag.vault = message.vault; bagPanel.hidden = false; bag.vaultCurrency = message.vaultCurrency; bag.vault = message.vault ?? []; vaultCoins.textContent = `${message.vaultCurrency ?? 0} coins in vault · you carry ${message.currency ?? 0}`; bag.vaultReserved = message.vaultReserved ?? []; inheritCoins.textContent = `${message.inheritance?.currency ?? 0} coins waiting`; renderVault(inheritGrid, message.inheritance?.slots ?? [], { interactive: false }); renderVault(vaultGrid, message.vault); renderVault(inheritGrid, message.inheritance?.slots ?? []); inheritGrid.querySelectorAll("button").forEach((button) => inheritGrid.querySelectorAll("button").forEach((button) => { { button.onclick = null; button.onclick = null; }); }); setBankTab("available"); renderBank(); render(); render(); }, }, depositSelected () getBlankCheques () { { if (selected == null) socket.send({ type: MessageType.getBlankCheques }); { return; } socket.send({ type: MessageType.bankDeposit, slotIndex: selected }); }, }, handlePigeonDispatched () handlePigeonDispatched () { {@@ -569,8 +907,7 @@ export function initInventory ({ reset () reset () { { bagPanel.hidden = true; bagPanel.hidden = true; bankPanel.hidden = true; closeBank(); bankOpen = false; selected = null; selected = null; closeSend(); closeSend(); closeLetter(); closeLetter();@@ -6,7 +6,11 @@ import { WorldView } from "../render/worldView.js";
import { initSocial } from "./social.js";
import { initChat } from "./chat.js";
import { initInventory } from "./inventory.js";
import { initSkills } from "./skills.js";
import { initCrafting } from "./crafting.js";
import { initContextMenu } from "./contextMenu.js";
import { CraftingStationId } from "/shared/definitions/craftingStations.js";
import { formatQuantity } from "/shared/items/formatQuantity.js";
const game = new Game();
const hud = document.getElementById("hud");
@@ -25,8 +29,12 @@ let catalog = { grounds: {}, blocks: {} };
let social;
let chat;
let inventory;
let skills;
let crafting;
let contextMenu;
let pendingPickup = null;
let pendingBank = null;
let pendingGetCheques = false;
function showError (message)
{
@@ -64,7 +72,8 @@ function renderCharacters (characters)
function uiBlocked ()
{
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() || contextMenu?.isOpen());
return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
|| crafting?.isBlocking() || contextMenu?.isOpen());
}
function clearPendingPickup ()
@@ -72,6 +81,63 @@ function clearPendingPickup ()
pendingPickup = null;
}
function clearPendingBank ()
{
pendingBank = null;
pendingGetCheques = false;
}
function requestOpenBank (tileX, tileY, { getCheques = false } = {})
{
clearPendingPickup();
pendingBank = { tileX, tileY };
pendingGetCheques = !!getCheques;
const local = view.entities.get(view.localEntityId);
if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
{
flushPendingBank();
return;
}
let best = null;
let bestDist = Infinity;
for (let dy = -1; dy <= 1; dy++)
{
for (let dx = -1; dx <= 1; dx++)
{
if (dx === 0 && dy === 0)
{ continue; }
const destX = tileX + dx;
const destY = tileY + dy;
const dist = local
? chebyshev(local.tileX, local.tileY, destX, destY)
: 0;
if (dist < bestDist)
{
bestDist = dist;
best = { tileX: destX, tileY: destY };
}
}
}
if (best)
{ socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); }
}
function flushPendingBank ()
{
if (!pendingBank || !view)
{ return; }
const local = view.entities.get(view.localEntityId);
if (!local)
{ return; }
if (chebyshev(local.tileX, local.tileY, pendingBank.tileX, pendingBank.tileY) > 1)
{ return; }
const getCheques = pendingGetCheques;
socket.send({ type: MessageType.openBank });
if (getCheques)
{ inventory?.getBlankCheques(); }
clearPendingBank();
}
function requestPickup (ground)
{
if (!ground)
@@ -115,6 +181,7 @@ function handleLeftClick (mouseX, mouseY)
if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
{
clearPendingPickup();
clearPendingBank();
if (entity.characterId)
{
social.inspect(entity);
@@ -125,7 +192,7 @@ function handleLeftClick (mouseX, mouseY)
socket.send({ type: MessageType.interact, targetEntityId: entity.entityId });
return;
}
if (entity.hostile)
if (entity.canFight)
{
socket.send({ type: MessageType.attack, targetEntityId: entity.entityId });
return;
@@ -133,18 +200,18 @@ function handleLeftClick (mouseX, mouseY)
}
const tile = view.screenToTile(mouseX, mouseY);
const local = view.entities.get(view.localEntityId);
const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
if (ground)
{ requestPickup(ground); }
else if (isBankTile(view, tile.tileX, tile.tileY) && local && chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= 1)
{
clearPendingPickup();
socket.send({ type: MessageType.openBank });
clearPendingBank();
requestPickup(ground);
}
else if (isBankTile(view, tile.tileX, tile.tileY))
{ requestOpenBank(tile.tileX, tile.tileY); }
else
{
clearPendingPickup();
clearPendingBank();
socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
}
}
@@ -222,6 +289,18 @@ function handleRightClick (event, mouseX, mouseY)
});
}
if (isBankTile(view, tile.tileX, tile.tileY))
{
items.push({
label: "Bank",
onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
});
items.push({
label: "Get Blank Cheques",
onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
});
}
contextMenu.show(event.clientX, event.clientY, items);
}
@@ -237,9 +316,10 @@ function entityLabel (entity)
function groundLabel (ground)
{
const name = (ground?.displayName ?? "").trim() || "item";
if ((ground?.quantity ?? 1) > 1)
{ return `${name} (${ground.quantity})`; }
return name;
const qty = ground?.quantity ?? 1;
if (qty <= 1)
{ return name; }
return `${name} (${formatQuantity(qty)})`;
}
function startPlay (payload)
@@ -276,6 +356,7 @@ function startPlay (payload)
if (playing)
{
flushPendingPickup();
flushPendingBank();
social?.updateNametag(view, scene, view.localEntityId);
chat?.update(view, scene);
}
@@ -347,7 +428,19 @@ async function main ()
return you.split("(")[0].trim() || "Unknown";
}
});
document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());
skills = initSkills();
crafting = initCrafting({
socket: { send (payload) { socket.send(payload); } },
MessageType,
getInventorySlots ()
{
return inventory?.getInventorySlots?.() ?? [];
},
getSkillLevel (skillId)
{
return skills?.skillLevel?.(skillId) ?? 1;
}
});
chat = initChat({
socket: { send (payload) { socket.send(payload); } },
MessageType,
@@ -404,6 +497,11 @@ async function main ()
break;
case MessageType.inventory:
inventory?.handleInventory(message);
crafting?.refresh();
break;
case MessageType.skills:
skills?.render(message.skills);
crafting?.refresh();
break;
case MessageType.bankSnapshot:
inventory?.handleBank(message);
@@ -417,6 +515,9 @@ async function main ()
case MessageType.characterSearchResult:
inventory?.handleCharacterSearch(message);
break;
case MessageType.craftResult:
crafting?.handleCraftResult(message);
break;
case MessageType.worldStatus:
if (view)
{
@@ -435,6 +536,8 @@ async function main ()
view?.spawnCombatSwing(message);
break;
case MessageType.combatHit:
view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
view?.flashDamage(message.targetId);
view?.addDynamicLight({
worldX: (message.tileX ?? 0) + 0.5,
worldY: (message.tileY ?? 0) + 0.5,
@@ -451,17 +554,33 @@ async function main ()
returnToMenu(message.reason);
break;
}
}, {
onClose (event)
{
if (playing)
{ returnToMenu(event.reason || "Disconnected from server."); }
}
});
await socket.connect();
if (typeof window !== "undefined")
{
window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
{
crafting?.openStation(stationId);
};
}
}
function returnToMenu (reason = "")
{
playing = false;
clearPendingPickup();
clearPendingBank();
social?.reset();
chat?.reset();
inventory?.reset();
crafting?.reset();
skills?.hide();
contextMenu?.hide();
if (view)
{
@@ -6,7 +6,11 @@ import { WorldView } from "../render/worldView.js";import { initSocial } from "./social.js";import { initSocial } from "./social.js";import { initChat } from "./chat.js";import { initChat } from "./chat.js";import { initInventory } from "./inventory.js";import { initInventory } from "./inventory.js";import { initSkills } from "./skills.js";import { initCrafting } from "./crafting.js";import { initContextMenu } from "./contextMenu.js";import { initContextMenu } from "./contextMenu.js";import { CraftingStationId } from "/shared/definitions/craftingStations.js";import { formatQuantity } from "/shared/items/formatQuantity.js";const game = new Game();const game = new Game();const hud = document.getElementById("hud");const hud = document.getElementById("hud");@@ -25,8 +29,12 @@ let catalog = { grounds: {}, blocks: {} };let social;let social;let chat;let chat;let inventory;let inventory;let skills;let crafting;let contextMenu;let contextMenu;let pendingPickup = null;let pendingPickup = null;let pendingBank = null;let pendingGetCheques = false;function showError (message)function showError (message){{@@ -64,7 +72,8 @@ function renderCharacters (characters)function uiBlocked ()function uiBlocked (){{ return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() || contextMenu?.isOpen()); return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() || crafting?.isBlocking() || contextMenu?.isOpen());}}function clearPendingPickup ()function clearPendingPickup ()@@ -72,6 +81,63 @@ function clearPendingPickup () pendingPickup = null; pendingPickup = null;}}function clearPendingBank (){ pendingBank = null; pendingGetCheques = false;}function requestOpenBank (tileX, tileY, { getCheques = false } = {}){ clearPendingPickup(); pendingBank = { tileX, tileY }; pendingGetCheques = !!getCheques; const local = view.entities.get(view.localEntityId); if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) { flushPendingBank(); return; } let best = null; let bestDist = Infinity; for (let dy = -1; dy <= 1; dy++) { for (let dx = -1; dx <= 1; dx++) { if (dx === 0 && dy === 0) { continue; } const destX = tileX + dx; const destY = tileY + dy; const dist = local ? chebyshev(local.tileX, local.tileY, destX, destY) : 0; if (dist < bestDist) { bestDist = dist; best = { tileX: destX, tileY: destY }; } } } if (best) { socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); }}function flushPendingBank (){ if (!pendingBank || !view) { return; } const local = view.entities.get(view.localEntityId); if (!local) { return; } if (chebyshev(local.tileX, local.tileY, pendingBank.tileX, pendingBank.tileY) > 1) { return; } const getCheques = pendingGetCheques; socket.send({ type: MessageType.openBank }); if (getCheques) { inventory?.getBlankCheques(); } clearPendingBank();}function requestPickup (ground)function requestPickup (ground){{ if (!ground) if (!ground)@@ -115,6 +181,7 @@ function handleLeftClick (mouseX, mouseY) if (entity && entity.entityId !== view.localEntityId && !entity.untargetable) if (entity && entity.entityId !== view.localEntityId && !entity.untargetable) { { clearPendingPickup(); clearPendingPickup(); clearPendingBank(); if (entity.characterId) if (entity.characterId) { { social.inspect(entity); social.inspect(entity);@@ -125,7 +192,7 @@ function handleLeftClick (mouseX, mouseY) socket.send({ type: MessageType.interact, targetEntityId: entity.entityId }); socket.send({ type: MessageType.interact, targetEntityId: entity.entityId }); return; return; } } if (entity.hostile) if (entity.canFight) { { socket.send({ type: MessageType.attack, targetEntityId: entity.entityId }); socket.send({ type: MessageType.attack, targetEntityId: entity.entityId }); return; return;@@ -133,18 +200,18 @@ function handleLeftClick (mouseX, mouseY) } } const tile = view.screenToTile(mouseX, mouseY); const tile = view.screenToTile(mouseX, mouseY); const local = view.entities.get(view.localEntityId); const ground = view.groundItemAtTile(tile.tileX, tile.tileY); const ground = view.groundItemAtTile(tile.tileX, tile.tileY); if (ground) if (ground) { requestPickup(ground); } else if (isBankTile(view, tile.tileX, tile.tileY) && local && chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= 1) { { clearPendingPickup(); clearPendingBank(); socket.send({ type: MessageType.openBank }); requestPickup(ground); } } else if (isBankTile(view, tile.tileX, tile.tileY)) { requestOpenBank(tile.tileX, tile.tileY); } else else { { clearPendingPickup(); clearPendingPickup(); clearPendingBank(); socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); } }}}@@ -222,6 +289,18 @@ function handleRightClick (event, mouseX, mouseY) }); }); } } if (isBankTile(view, tile.tileX, tile.tileY)) { items.push({ label: "Bank", onSelect: () => requestOpenBank(tile.tileX, tile.tileY) }); items.push({ label: "Get Blank Cheques", onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true }) }); } contextMenu.show(event.clientX, event.clientY, items); contextMenu.show(event.clientX, event.clientY, items);}}@@ -237,9 +316,10 @@ function entityLabel (entity)function groundLabel (ground)function groundLabel (ground){{ const name = (ground?.displayName ?? "").trim() || "item"; const name = (ground?.displayName ?? "").trim() || "item"; if ((ground?.quantity ?? 1) > 1) const qty = ground?.quantity ?? 1; { return `${name} (${ground.quantity})`; } if (qty <= 1) return name; { return name; } return `${name} (${formatQuantity(qty)})`;}}function startPlay (payload)function startPlay (payload)@@ -276,6 +356,7 @@ function startPlay (payload) if (playing) if (playing) { { flushPendingPickup(); flushPendingPickup(); flushPendingBank(); social?.updateNametag(view, scene, view.localEntityId); social?.updateNametag(view, scene, view.localEntityId); chat?.update(view, scene); chat?.update(view, scene); } }@@ -347,7 +428,19 @@ async function main () return you.split("(")[0].trim() || "Unknown"; return you.split("(")[0].trim() || "Unknown"; } } }); }); document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected()); skills = initSkills(); crafting = initCrafting({ socket: { send (payload) { socket.send(payload); } }, MessageType, getInventorySlots () { return inventory?.getInventorySlots?.() ?? []; }, getSkillLevel (skillId) { return skills?.skillLevel?.(skillId) ?? 1; } }); chat = initChat({ chat = initChat({ socket: { send (payload) { socket.send(payload); } }, socket: { send (payload) { socket.send(payload); } }, MessageType, MessageType,@@ -404,6 +497,11 @@ async function main () break; break; case MessageType.inventory: case MessageType.inventory: inventory?.handleInventory(message); inventory?.handleInventory(message); crafting?.refresh(); break; case MessageType.skills: skills?.render(message.skills); crafting?.refresh(); break; break; case MessageType.bankSnapshot: case MessageType.bankSnapshot: inventory?.handleBank(message); inventory?.handleBank(message);@@ -417,6 +515,9 @@ async function main () case MessageType.characterSearchResult: case MessageType.characterSearchResult: inventory?.handleCharacterSearch(message); inventory?.handleCharacterSearch(message); break; break; case MessageType.craftResult: crafting?.handleCraftResult(message); break; case MessageType.worldStatus: case MessageType.worldStatus: if (view) if (view) { {@@ -435,6 +536,8 @@ async function main () view?.spawnCombatSwing(message); view?.spawnCombatSwing(message); break; break; case MessageType.combatHit: case MessageType.combatHit: view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); view?.flashDamage(message.targetId); view?.addDynamicLight({ view?.addDynamicLight({ worldX: (message.tileX ?? 0) + 0.5, worldX: (message.tileX ?? 0) + 0.5, worldY: (message.tileY ?? 0) + 0.5, worldY: (message.tileY ?? 0) + 0.5,@@ -451,17 +554,33 @@ async function main () returnToMenu(message.reason); returnToMenu(message.reason); break; break; } } }, { onClose (event) { if (playing) { returnToMenu(event.reason || "Disconnected from server."); } } }); }); await socket.connect(); await socket.connect(); if (typeof window !== "undefined") { window.__craftDev = (stationId = CraftingStationId.craftingBench) => { crafting?.openStation(stationId); }; }}}function returnToMenu (reason = "")function returnToMenu (reason = ""){{ playing = false; playing = false; clearPendingPickup(); clearPendingPickup(); clearPendingBank(); social?.reset(); social?.reset(); chat?.reset(); chat?.reset(); inventory?.reset(); inventory?.reset(); crafting?.reset(); skills?.hide(); contextMenu?.hide(); contextMenu?.hide(); if (view) if (view) { {@@ -0,0 +1,64 @@
export function initSkills ()
{
const panel = document.getElementById("skills-panel");
const list = document.getElementById("skills-list");
let current = [];
document.getElementById("skills-toggle").addEventListener("click", () =>
{
panel.hidden = !panel.hidden;
});
function render (skills)
{
current = skills ?? [];
list.replaceChildren();
for (const skill of current)
{
list.append(renderSkillRow(skill));
}
}
return {
render,
skillLevel (skillId)
{
return current.find((entry) => entry.skillId === skillId)?.level ?? 1;
},
hide ()
{
panel.hidden = true;
}
};
}
function renderSkillRow (skill)
{
const row = document.createElement("div");
row.className = "skill-row";
const icon = document.createElement("img");
icon.className = "skill-icon";
icon.src = skill.icon;
icon.alt = "";
icon.loading = "lazy";
const body = document.createElement("div");
body.className = "skill-body";
const title = document.createElement("div");
title.className = "skill-title";
title.textContent = `${skill.displayName} — Level ${skill.level}`;
const track = document.createElement("div");
track.className = "skill-xp-track";
const fill = document.createElement("div");
fill.className = "skill-xp-fill";
const pct = skill.xpToNext > 0 ? Math.min(100, (skill.xp / skill.xpToNext) * 100) : 100;
fill.style.width = `${pct}%`;
track.title = `${skill.xp} / ${skill.xpToNext} XP to next level`;
track.append(fill);
body.append(title, track);
row.append(icon, body);
return row;
}
@@ -0,0 +1,64 @@export function initSkills (){ const panel = document.getElementById("skills-panel"); const list = document.getElementById("skills-list"); let current = []; document.getElementById("skills-toggle").addEventListener("click", () => { panel.hidden = !panel.hidden; }); function render (skills) { current = skills ?? []; list.replaceChildren(); for (const skill of current) { list.append(renderSkillRow(skill)); } } return { render, skillLevel (skillId) { return current.find((entry) => entry.skillId === skillId)?.level ?? 1; }, hide () { panel.hidden = true; } };}function renderSkillRow (skill){ const row = document.createElement("div"); row.className = "skill-row"; const icon = document.createElement("img"); icon.className = "skill-icon"; icon.src = skill.icon; icon.alt = ""; icon.loading = "lazy"; const body = document.createElement("div"); body.className = "skill-body"; const title = document.createElement("div"); title.className = "skill-title"; title.textContent = `${skill.displayName} — Level ${skill.level}`; const track = document.createElement("div"); track.className = "skill-xp-track"; const fill = document.createElement("div"); fill.className = "skill-xp-fill"; const pct = skill.xpToNext > 0 ? Math.min(100, (skill.xp / skill.xpToNext) * 100) : 100; fill.style.width = `${pct}%`; track.title = `${skill.xp} / ${skill.xpToNext} XP to next level`; track.append(fill); body.append(title, track); row.append(icon, body); return row;}@@ -1,4 +1,4 @@
import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
import { itemSpriteName } from "/shared/definitions/items.js";
import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
@@ -14,8 +14,17 @@ const SORT_BLOCK = 1;
const SORT_SHADE = 2;
const SORT_ENTITY = 3;
const SORT_SPRITE_SHADE = 4;
const SORT_HP_BAR = 5;
const RENDER_LAYER_BLOOM = "bloom";
const HP_BAR_W = 14;
const HP_BAR_H = 4;
const WALK_TILT_DEG = 6;
const RUN_TILT_DEG = 8;
const SHOVE_TILE_FRACTION = 0.25;
const SHOVE_MS = 280;
const DAMAGE_FLASH_MS = 180;
const SPRITE_SHADE_FRAG = [
"precision mediump float;",
"varying vec2 v_texCoord;",
@@ -28,7 +37,21 @@ const SPRITE_SHADE_FRAG = [
"}"
].join("\n");
const DAMAGE_FLASH_FRAG = [
"precision mediump float;",
"varying vec2 v_texCoord;",
"uniform sampler2D u_texture;",
"uniform float u_strength;",
"void main() {",
" vec4 color = texture2D(u_texture, v_texCoord);",
" if (color.a <= 0.0) { discard; }",
" vec3 flash = mix(color.rgb, vec3(1.0, 0.12, 0.12), u_strength);",
" gl_FragColor = vec4(flash, color.a);",
"}"
].join("\n");
let spriteShadeShader = null;
let damageFlashShader = null;
function getSpriteShadeShader ()
{
@@ -37,6 +60,13 @@ function getSpriteShadeShader ()
return spriteShadeShader;
}
function getDamageFlashShader ()
{
if (!damageFlashShader)
{ damageFlashShader = Shader.fragment(DAMAGE_FLASH_FRAG); }
return damageFlashShader;
}
export class WorldView
{
constructor (game, scene, catalog = { grounds: {}, blocks: {} })
@@ -181,6 +211,7 @@ export class WorldView
{ return; }
existing.object?.destroy();
existing.spriteShade?.destroy();
existing.hpBar?.destroy();
for (const shade of existing.overlayShades ?? [])
{ shade.destroy(); }
for (const overlay of existing.overlays ?? [])
@@ -190,6 +221,24 @@ export class WorldView
this.entities.delete(entityId);
}
updateEntityHealth (entityId, health, maxHealth)
{
const entity = this.entities.get(entityId);
if (!entity)
{ return; }
entity.health = health;
entity.maxHealth = maxHealth;
this.#syncHpBar(entity);
}
flashDamage (entityId)
{
const entity = this.entities.get(entityId);
if (!entity)
{ return; }
entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
}
setAppearance (payload)
{
const existing = this.entities.get(payload.entityId);
@@ -377,7 +426,8 @@ export class WorldView
entity.visualX = target.x;
entity.visualY = target.y;
}
this.#placeEntity(entity);
this.#updateShove(entity, now, size);
this.#placeEntity(entity, now);
}
this.#updateSwipes(now);
@@ -385,12 +435,47 @@ export class WorldView
this.#updateShade(deltaTime);
}
#updateShove (entity, now, tileSize)
{
if (!entity.shove)
{
entity.shoveOffsetX = 0;
entity.shoveOffsetY = 0;
return;
}
const elapsed = now - entity.shove.started;
const t = Math.min(1, elapsed / entity.shove.durationMs);
const maxDist = tileSize * SHOVE_TILE_FRACTION;
const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
const dist = Math.hypot(dx, dy) || 1;
const ux = dx / dist;
const uy = dy / dist;
let phase;
if (t < 0.45)
{ phase = t / 0.45; }
else
{ phase = 1 - (t - 0.45) / 0.55; }
entity.shoveOffsetX = ux * maxDist * phase;
entity.shoveOffsetY = uy * maxDist * phase;
if (t >= 1)
{ entity.shove = null; }
}
spawnCombatSwing (payload)
{
const attacker = this.entities.get(payload.attackerId);
const target = this.entities.get(payload.targetId);
if (!attacker || !target)
{ return; }
attacker.shove = {
startVisualX: attacker.visualX,
startVisualY: attacker.visualY,
targetVisualX: target.visualX,
targetVisualY: target.visualY,
started: performance.now(),
durationMs: SHOVE_MS
};
const midX = (attacker.visualX + target.visualX) / 2;
const midY = (attacker.visualY + target.visualY) / 2;
const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
@@ -506,9 +591,14 @@ export class WorldView
entity.characterId = payload.characterId ?? entity.characterId ?? null;
entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
entity.hostile = !!payload.hostile;
entity.canFight = !!payload.canFight;
entity.talkable = !!payload.talkable;
entity.untargetable = !!payload.untargetable;
entity.freeFlight = !!payload.freeFlight;
if (payload.health != null)
{ entity.health = payload.health; }
if (payload.maxHealth != null)
{ entity.maxHealth = payload.maxHealth; }
if (payload.firstName)
{ entity.firstName = payload.firstName; }
if (payload.lastName)
@@ -535,7 +625,8 @@ export class WorldView
entity.fromY = entity.visualY;
if (payload.layers)
{ this.#applyLayers(entity, payload.layers); }
this.#placeEntity(entity);
this.#syncHpBar(entity);
this.#placeEntity(entity, performance.now());
}
#applyLayers (entity, layers)
@@ -572,27 +663,121 @@ export class WorldView
}
}
#placeEntity (entity)
#placeEntity (entity, now = performance.now())
{
this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY);
for (const overlay of entity.overlays ?? [])
{ this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); }
const zoom = this.zoom;
const offsetX = entity.shoveOffsetX ?? 0;
const offsetY = entity.shoveOffsetY ?? 0;
const pivotX = entity.visualX + offsetX;
const pivotY = entity.visualY + offsetY;
let walkTilt = 0;
if (entity.lerpStarted != null)
{
const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
walkTilt = Math.sin(cycles) * tilt;
}
const flashStrength = (entity.damageFlashUntil ?? 0) > now
? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
: 0;
entity.object.transform.rotation = walkTilt;
this.#applyDamageFlash(entity.object, flashStrength);
this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
for (let index = 0; index < (entity.overlays ?? []).length; index++)
{
const overlay = entity.overlays[index];
overlay.transform.rotation = walkTilt;
this.#applyDamageFlash(overlay, flashStrength);
this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.001, SORT_ENTITY);
}
for (const overlay of entity.bloomOverlays ?? [])
{ this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY);
{
overlay.transform.rotation = walkTilt;
this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
}
entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, pivotX, pivotY);
const nextOverlayShades = [];
for (let index = 0; index < (entity.overlays ?? []).length; index++)
{
nextOverlayShades.push(this.#placeSpriteShade(
entity.overlayShades?.[index] ?? null,
entity.overlays[index],
entity.visualX,
entity.visualY + 0.001
pivotX,
pivotY + 0.001
));
}
for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)
{ entity.overlayShades[index]?.destroy(); }
entity.overlayShades = nextOverlayShades;
this.#placeHpBar(entity, pivotX, pivotY);
}
#applyDamageFlash (object, strength)
{
if (!object?.renderer)
{ return; }
if (strength > 0)
{
object.renderer.shader = getDamageFlashShader();
object.renderer.shaderUniforms = { u_strength: strength };
return;
}
if (object.renderer.shader === getDamageFlashShader())
{
object.renderer.shader = null;
object.renderer.shaderUniforms = null;
}
}
#syncHpBar (entity)
{
const current = entity.health;
const max = entity.maxHealth;
const show = entity.mobTypeId != null
&& current != null
&& max != null
&& max > 0
&& current < max;
if (!show)
{
entity.hpBar?.destroy();
entity.hpBar = null;
entity.hpBarCanvas = null;
return;
}
if (!entity.hpBarCanvas)
{
entity.hpBarCanvas = document.createElement("canvas");
entity.hpBarCanvas.width = HP_BAR_W;
entity.hpBarCanvas.height = HP_BAR_H;
const image = frameworkImageFromCanvas(entity.hpBarCanvas);
entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
this.scene.addObject(entity.hpBar);
}
drawHpBar(entity.hpBarCanvas, current, max);
invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
}
#placeHpBar (entity, pivotX, pivotY)
{
if (!entity.hpBar)
{ return; }
const sprite = entity.object?.renderer?.sprite;
if (!sprite)
{ return; }
const zoom = this.zoom;
const drawH = sprite.height * zoom;
const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
const spriteTop = centerY - drawH / 2;
const barW = HP_BAR_W * zoom;
const barH = HP_BAR_H * zoom;
entity.hpBar.transform.position.x = pivotX;
entity.hpBar.transform.position.y = spriteTop - barH / 2;
entity.hpBar.transform.size = new vector(barW, barH);
entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
this.#markSortDirty();
}
#rebuildChunk (snapshot)
@@ -1077,6 +1262,21 @@ function lerp (a, b, t)
return a + (b - a) * Math.min(1, Math.max(0, t));
}
function drawHpBar (canvas, current, max)
{
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
const fillW = Math.round(12 * ratio);
if (fillW > 0)
{
ctx.fillStyle = "#ff0000";
ctx.fillRect(1, 1, fillW, 2);
}
}
function copyCanvas (source, dest)
{
const ctx = dest.getContext("2d");
@@ -1,4 +1,4 @@import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";import { itemSpriteName } from "/shared/definitions/items.js";import { itemSpriteName } from "/shared/definitions/items.js";import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";@@ -14,8 +14,17 @@ const SORT_BLOCK = 1;const SORT_SHADE = 2;const SORT_SHADE = 2;const SORT_ENTITY = 3;const SORT_ENTITY = 3;const SORT_SPRITE_SHADE = 4;const SORT_SPRITE_SHADE = 4;const SORT_HP_BAR = 5;const RENDER_LAYER_BLOOM = "bloom";const RENDER_LAYER_BLOOM = "bloom";const HP_BAR_W = 14;const HP_BAR_H = 4;const WALK_TILT_DEG = 6;const RUN_TILT_DEG = 8;const SHOVE_TILE_FRACTION = 0.25;const SHOVE_MS = 280;const DAMAGE_FLASH_MS = 180;const SPRITE_SHADE_FRAG = [const SPRITE_SHADE_FRAG = [ "precision mediump float;", "precision mediump float;", "varying vec2 v_texCoord;", "varying vec2 v_texCoord;",@@ -28,7 +37,21 @@ const SPRITE_SHADE_FRAG = [ "}" "}"].join("\n");].join("\n");const DAMAGE_FLASH_FRAG = [ "precision mediump float;", "varying vec2 v_texCoord;", "uniform sampler2D u_texture;", "uniform float u_strength;", "void main() {", " vec4 color = texture2D(u_texture, v_texCoord);", " if (color.a <= 0.0) { discard; }", " vec3 flash = mix(color.rgb, vec3(1.0, 0.12, 0.12), u_strength);", " gl_FragColor = vec4(flash, color.a);", "}"].join("\n");let spriteShadeShader = null;let spriteShadeShader = null;let damageFlashShader = null;function getSpriteShadeShader ()function getSpriteShadeShader (){{@@ -37,6 +60,13 @@ function getSpriteShadeShader () return spriteShadeShader; return spriteShadeShader;}}function getDamageFlashShader (){ if (!damageFlashShader) { damageFlashShader = Shader.fragment(DAMAGE_FLASH_FRAG); } return damageFlashShader;}export class WorldViewexport class WorldView{{ constructor (game, scene, catalog = { grounds: {}, blocks: {} }) constructor (game, scene, catalog = { grounds: {}, blocks: {} })@@ -181,6 +211,7 @@ export class WorldView { return; } { return; } existing.object?.destroy(); existing.object?.destroy(); existing.spriteShade?.destroy(); existing.spriteShade?.destroy(); existing.hpBar?.destroy(); for (const shade of existing.overlayShades ?? []) for (const shade of existing.overlayShades ?? []) { shade.destroy(); } { shade.destroy(); } for (const overlay of existing.overlays ?? []) for (const overlay of existing.overlays ?? [])@@ -190,6 +221,24 @@ export class WorldView this.entities.delete(entityId); this.entities.delete(entityId); } } updateEntityHealth (entityId, health, maxHealth) { const entity = this.entities.get(entityId); if (!entity) { return; } entity.health = health; entity.maxHealth = maxHealth; this.#syncHpBar(entity); } flashDamage (entityId) { const entity = this.entities.get(entityId); if (!entity) { return; } entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS; } setAppearance (payload) setAppearance (payload) { { const existing = this.entities.get(payload.entityId); const existing = this.entities.get(payload.entityId);@@ -377,7 +426,8 @@ export class WorldView entity.visualX = target.x; entity.visualX = target.x; entity.visualY = target.y; entity.visualY = target.y; } } this.#placeEntity(entity); this.#updateShove(entity, now, size); this.#placeEntity(entity, now); } } this.#updateSwipes(now); this.#updateSwipes(now);@@ -385,12 +435,47 @@ export class WorldView this.#updateShade(deltaTime); this.#updateShade(deltaTime); } } #updateShove (entity, now, tileSize) { if (!entity.shove) { entity.shoveOffsetX = 0; entity.shoveOffsetY = 0; return; } const elapsed = now - entity.shove.started; const t = Math.min(1, elapsed / entity.shove.durationMs); const maxDist = tileSize * SHOVE_TILE_FRACTION; const dx = entity.shove.targetVisualX - entity.shove.startVisualX; const dy = entity.shove.targetVisualY - entity.shove.startVisualY; const dist = Math.hypot(dx, dy) || 1; const ux = dx / dist; const uy = dy / dist; let phase; if (t < 0.45) { phase = t / 0.45; } else { phase = 1 - (t - 0.45) / 0.55; } entity.shoveOffsetX = ux * maxDist * phase; entity.shoveOffsetY = uy * maxDist * phase; if (t >= 1) { entity.shove = null; } } spawnCombatSwing (payload) spawnCombatSwing (payload) { { const attacker = this.entities.get(payload.attackerId); const attacker = this.entities.get(payload.attackerId); const target = this.entities.get(payload.targetId); const target = this.entities.get(payload.targetId); if (!attacker || !target) if (!attacker || !target) { return; } { return; } attacker.shove = { startVisualX: attacker.visualX, startVisualY: attacker.visualY, targetVisualX: target.visualX, targetVisualY: target.visualY, started: performance.now(), durationMs: SHOVE_MS }; const midX = (attacker.visualX + target.visualX) / 2; const midX = (attacker.visualX + target.visualX) / 2; const midY = (attacker.visualY + target.visualY) / 2; const midY = (attacker.visualY + target.visualY) / 2; const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI); const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);@@ -506,9 +591,14 @@ export class WorldView entity.characterId = payload.characterId ?? entity.characterId ?? null; entity.characterId = payload.characterId ?? entity.characterId ?? null; entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null; entity.hostile = !!payload.hostile; entity.hostile = !!payload.hostile; entity.canFight = !!payload.canFight; entity.talkable = !!payload.talkable; entity.talkable = !!payload.talkable; entity.untargetable = !!payload.untargetable; entity.untargetable = !!payload.untargetable; entity.freeFlight = !!payload.freeFlight; entity.freeFlight = !!payload.freeFlight; if (payload.health != null) { entity.health = payload.health; } if (payload.maxHealth != null) { entity.maxHealth = payload.maxHealth; } if (payload.firstName) if (payload.firstName) { entity.firstName = payload.firstName; } { entity.firstName = payload.firstName; } if (payload.lastName) if (payload.lastName)@@ -535,7 +625,8 @@ export class WorldView entity.fromY = entity.visualY; entity.fromY = entity.visualY; if (payload.layers) if (payload.layers) { this.#applyLayers(entity, payload.layers); } { this.#applyLayers(entity, payload.layers); } this.#placeEntity(entity); this.#syncHpBar(entity); this.#placeEntity(entity, performance.now()); } } #applyLayers (entity, layers) #applyLayers (entity, layers)@@ -572,27 +663,121 @@ export class WorldView } } } } #placeEntity (entity) #placeEntity (entity, now = performance.now()) { { this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY); const zoom = this.zoom; for (const overlay of entity.overlays ?? []) const offsetX = entity.shoveOffsetX ?? 0; { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); } const offsetY = entity.shoveOffsetY ?? 0; const pivotX = entity.visualX + offsetX; const pivotY = entity.visualY + offsetY; let walkTilt = 0; if (entity.lerpStarted != null) { const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait)); const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2; const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG; walkTilt = Math.sin(cycles) * tilt; } const flashStrength = (entity.damageFlashUntil ?? 0) > now ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS : 0; entity.object.transform.rotation = walkTilt; this.#applyDamageFlash(entity.object, flashStrength); this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY); for (let index = 0; index < (entity.overlays ?? []).length; index++) { const overlay = entity.overlays[index]; overlay.transform.rotation = walkTilt; this.#applyDamageFlash(overlay, flashStrength); this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.001, SORT_ENTITY); } for (const overlay of entity.bloomOverlays ?? []) for (const overlay of entity.bloomOverlays ?? []) { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); } { entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY); overlay.transform.rotation = walkTilt; this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY); } entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, pivotX, pivotY); const nextOverlayShades = []; const nextOverlayShades = []; for (let index = 0; index < (entity.overlays ?? []).length; index++) for (let index = 0; index < (entity.overlays ?? []).length; index++) { { nextOverlayShades.push(this.#placeSpriteShade( nextOverlayShades.push(this.#placeSpriteShade( entity.overlayShades?.[index] ?? null, entity.overlayShades?.[index] ?? null, entity.overlays[index], entity.overlays[index], entity.visualX, pivotX, entity.visualY + 0.001 pivotY + 0.001 )); )); } } for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++) for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++) { entity.overlayShades[index]?.destroy(); } { entity.overlayShades[index]?.destroy(); } entity.overlayShades = nextOverlayShades; entity.overlayShades = nextOverlayShades; this.#placeHpBar(entity, pivotX, pivotY); } #applyDamageFlash (object, strength) { if (!object?.renderer) { return; } if (strength > 0) { object.renderer.shader = getDamageFlashShader(); object.renderer.shaderUniforms = { u_strength: strength }; return; } if (object.renderer.shader === getDamageFlashShader()) { object.renderer.shader = null; object.renderer.shaderUniforms = null; } } #syncHpBar (entity) { const current = entity.health; const max = entity.maxHealth; const show = entity.mobTypeId != null && current != null && max != null && max > 0 && current < max; if (!show) { entity.hpBar?.destroy(); entity.hpBar = null; entity.hpBarCanvas = null; return; } if (!entity.hpBarCanvas) { entity.hpBarCanvas = document.createElement("canvas"); entity.hpBarCanvas.width = HP_BAR_W; entity.hpBarCanvas.height = HP_BAR_H; const image = frameworkImageFromCanvas(entity.hpBarCanvas); entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR); this.scene.addObject(entity.hpBar); } drawHpBar(entity.hpBarCanvas, current, max); invalidateCanvasTexture(this.scene, entity.hpBarCanvas); } #placeHpBar (entity, pivotX, pivotY) { if (!entity.hpBar) { return; } const sprite = entity.object?.renderer?.sprite; if (!sprite) { return; } const zoom = this.zoom; const drawH = sprite.height * zoom; const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom); const spriteTop = centerY - drawH / 2; const barW = HP_BAR_W * zoom; const barH = HP_BAR_H * zoom; entity.hpBar.transform.position.x = pivotX; entity.hpBar.transform.position.y = spriteTop - barH / 2; entity.hpBar.transform.size = new vector(barW, barH); entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR); this.#markSortDirty(); } } #rebuildChunk (snapshot) #rebuildChunk (snapshot)@@ -1077,6 +1262,21 @@ function lerp (a, b, t) return a + (b - a) * Math.min(1, Math.max(0, t)); return a + (b - a) * Math.min(1, Math.max(0, t));}}function drawHpBar (canvas, current, max){ const ctx = canvas.getContext("2d"); ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H); ctx.fillStyle = "#000000"; ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H); const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0; const fillW = Math.round(12 * ratio); if (fillW > 0) { ctx.fillStyle = "#ff0000"; ctx.fillRect(1, 1, fillW, 2); }}function copyCanvas (source, dest)function copyCanvas (source, dest){{ const ctx = dest.getContext("2d"); const ctx = dest.getContext("2d");@@ -155,6 +155,76 @@ a { color: #d4c48a; }
padding: 0.75rem;
}
#skills-panel {
position: fixed;
z-index: 5;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: min(520px, 94vw);
max-height: calc(100vh - 80px);
overflow: auto;
background: #1a1e26;
border: 1px solid #2c3340;
padding: 0.75rem;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
}
.skills-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.55rem 0.75rem;
margin: 0.5rem 0;
}
.skill-row {
display: flex;
gap: 0.55rem;
align-items: stretch;
min-width: 0;
}
.skill-icon {
flex: 0 0 36px;
width: 36px;
height: 36px;
border-radius: 6px;
background: #101216;
border: 1px solid #3a4250;
}
.skill-body {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
gap: 0.25rem;
min-width: 0;
}
.skill-title {
font-size: 0.85rem;
line-height: 1.2;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.skill-xp-track {
height: 8px;
background: #101216;
border: 1px solid #3a4250;
border-radius: 4px;
overflow: hidden;
}
.skill-xp-fill {
height: 100%;
background: linear-gradient(90deg, #6a7a40, #d4c48a);
border-radius: 3px;
transition: width 0.25s ease-out;
}
#bag-panel, #bank-panel {
position: fixed;
z-index: 5;
@@ -180,6 +250,22 @@ a { color: #d4c48a; }
align-items: center;
}
.bank-tabs {
display: flex;
gap: 0.25rem;
margin: 0.4rem 0;
}
.bank-tab {
flex: 1;
font-size: 0.8rem;
padding: 0.3rem 0.4rem;
}
.bank-tab.active {
outline: 1px solid #d4c48a;
}
.item-grid {
display: grid;
grid-template-columns: repeat(8, 1fr);
@@ -231,7 +317,9 @@ a { color: #d4c48a; }
#send-panel,
#send-target-panel,
#letter-panel {
#letter-panel,
#transfer-panel,
#write-cheque-panel {
position: fixed;
z-index: 6;
top: 50%;
@@ -245,13 +333,163 @@ a { color: #d4c48a; }
padding: 0.85rem 1rem 1rem;
}
#craft-panel {
position: fixed;
z-index: 6;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: min(560px, 94vw);
max-height: min(85vh, 720px);
overflow: auto;
background: #1a1e26;
border: 1px solid #2c3340;
padding: 0.85rem 1rem 1rem;
}
#craft-panel header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0.5rem;
}
.craft-layout {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 0.75rem;
align-items: start;
}
@media (max-width: 520px) {
.craft-layout {
grid-template-columns: 1fr;
}
}
.craft-recipe-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 0.35rem;
}
.craft-recipe-cell {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.2rem;
padding: 0.35rem 0.25rem;
min-height: 72px;
background: #12151c;
border: 1px solid #2c3340;
cursor: pointer;
}
.craft-recipe-cell.selected {
outline: 2px solid #d4c48a;
}
.craft-recipe-cell img {
width: 32px;
height: 32px;
object-fit: contain;
image-rendering: pixelated;
}
.craft-recipe-name {
font-size: 0.72rem;
text-align: center;
line-height: 1.15;
word-break: break-word;
}
.craft-detail {
min-height: 160px;
padding: 0.35rem;
background: #12151c;
border: 1px solid #2c3340;
}
.craft-output {
display: flex;
flex-direction: column;
align-items: center;
gap: 0.25rem;
margin-bottom: 0.5rem;
}
.craft-output img {
width: 48px;
height: 48px;
object-fit: contain;
image-rendering: pixelated;
}
.craft-output h3 {
margin: 0;
font-size: 0.95rem;
text-align: center;
}
.craft-inputs {
list-style: none;
margin: 0 0 0.5rem;
padding: 0;
}
.craft-input-row {
display: flex;
align-items: center;
gap: 0.4rem;
margin-bottom: 0.35rem;
font-size: 0.85rem;
}
.craft-input-row.short {
color: #c07070;
}
.craft-input-row img {
width: 24px;
height: 24px;
object-fit: contain;
image-rendering: pixelated;
}
.craft-progress {
height: 8px;
margin: 0.4rem 0;
background: #0e1014;
border: 1px solid #2c3340;
border-radius: 2px;
overflow: hidden;
}
.craft-progress-fill {
height: 100%;
width: 0%;
background: linear-gradient(90deg, #6a7a40, #d4c48a);
transition: width 0.05s linear;
}
#craft-button {
width: 100%;
margin-top: 0.25rem;
}
#craft-button:disabled {
opacity: 0.45;
}
#send-target-panel {
z-index: 7;
}
#send-panel header,
#send-target-panel header,
#letter-panel header {
#letter-panel header,
#transfer-panel header,
#write-cheque-panel header {
display: flex;
justify-content: space-between;
align-items: center;
@@ -262,6 +500,8 @@ a { color: #d4c48a; }
#send-panel[hidden],
#send-target-panel[hidden],
#letter-panel[hidden],
#transfer-panel[hidden],
#write-cheque-panel[hidden],
.modal-backdrop[hidden] {
display: none !important;
}
@@ -396,8 +636,11 @@ a { color: #d4c48a; }
#inspect-modal[hidden],
#inspect-backdrop[hidden],
#friends-panel[hidden],
#skills-panel[hidden],
#bag-panel[hidden],
#bank-panel[hidden],
#craft-panel[hidden],
#craft-backdrop[hidden],
#nametag[hidden],
#chat-bar[hidden] {
display: none !important;
@@ -155,6 +155,76 @@ a { color: #d4c48a; } padding: 0.75rem; padding: 0.75rem;}}#skills-panel { position: fixed; z-index: 5; top: 50%; left: 50%; transform: translate(-50%, -50%); width: min(520px, 94vw); max-height: calc(100vh - 80px); overflow: auto; background: #1a1e26; border: 1px solid #2c3340; padding: 0.75rem; box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);}.skills-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0.55rem 0.75rem; margin: 0.5rem 0;}.skill-row { display: flex; gap: 0.55rem; align-items: stretch; min-width: 0;}.skill-icon { flex: 0 0 36px; width: 36px; height: 36px; border-radius: 6px; background: #101216; border: 1px solid #3a4250;}.skill-body { flex: 1; display: flex; flex-direction: column; justify-content: center; gap: 0.25rem; min-width: 0;}.skill-title { font-size: 0.85rem; line-height: 1.2; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;}.skill-xp-track { height: 8px; background: #101216; border: 1px solid #3a4250; border-radius: 4px; overflow: hidden;}.skill-xp-fill { height: 100%; background: linear-gradient(90deg, #6a7a40, #d4c48a); border-radius: 3px; transition: width 0.25s ease-out;}#bag-panel, #bank-panel {#bag-panel, #bank-panel { position: fixed; position: fixed; z-index: 5; z-index: 5;@@ -180,6 +250,22 @@ a { color: #d4c48a; } align-items: center; align-items: center;}}.bank-tabs { display: flex; gap: 0.25rem; margin: 0.4rem 0;}.bank-tab { flex: 1; font-size: 0.8rem; padding: 0.3rem 0.4rem;}.bank-tab.active { outline: 1px solid #d4c48a;}.item-grid {.item-grid { display: grid; display: grid; grid-template-columns: repeat(8, 1fr); grid-template-columns: repeat(8, 1fr);@@ -231,7 +317,9 @@ a { color: #d4c48a; }#send-panel,#send-panel,#send-target-panel,#send-target-panel,#letter-panel {#letter-panel,#transfer-panel,#write-cheque-panel { position: fixed; position: fixed; z-index: 6; z-index: 6; top: 50%; top: 50%;@@ -245,13 +333,163 @@ a { color: #d4c48a; } padding: 0.85rem 1rem 1rem; padding: 0.85rem 1rem 1rem;}}#craft-panel { position: fixed; z-index: 6; top: 50%; left: 50%; transform: translate(-50%, -50%); width: min(560px, 94vw); max-height: min(85vh, 720px); overflow: auto; background: #1a1e26; border: 1px solid #2c3340; padding: 0.85rem 1rem 1rem;}#craft-panel header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;}.craft-layout { display: grid; grid-template-columns: 1fr 1fr; gap: 0.75rem; align-items: start;}@media (max-width: 520px) { .craft-layout { grid-template-columns: 1fr; }}.craft-recipe-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 0.35rem;}.craft-recipe-cell { display: flex; flex-direction: column; align-items: center; gap: 0.2rem; padding: 0.35rem 0.25rem; min-height: 72px; background: #12151c; border: 1px solid #2c3340; cursor: pointer;}.craft-recipe-cell.selected { outline: 2px solid #d4c48a;}.craft-recipe-cell img { width: 32px; height: 32px; object-fit: contain; image-rendering: pixelated;}.craft-recipe-name { font-size: 0.72rem; text-align: center; line-height: 1.15; word-break: break-word;}.craft-detail { min-height: 160px; padding: 0.35rem; background: #12151c; border: 1px solid #2c3340;}.craft-output { display: flex; flex-direction: column; align-items: center; gap: 0.25rem; margin-bottom: 0.5rem;}.craft-output img { width: 48px; height: 48px; object-fit: contain; image-rendering: pixelated;}.craft-output h3 { margin: 0; font-size: 0.95rem; text-align: center;}.craft-inputs { list-style: none; margin: 0 0 0.5rem; padding: 0;}.craft-input-row { display: flex; align-items: center; gap: 0.4rem; margin-bottom: 0.35rem; font-size: 0.85rem;}.craft-input-row.short { color: #c07070;}.craft-input-row img { width: 24px; height: 24px; object-fit: contain; image-rendering: pixelated;}.craft-progress { height: 8px; margin: 0.4rem 0; background: #0e1014; border: 1px solid #2c3340; border-radius: 2px; overflow: hidden;}.craft-progress-fill { height: 100%; width: 0%; background: linear-gradient(90deg, #6a7a40, #d4c48a); transition: width 0.05s linear;}#craft-button { width: 100%; margin-top: 0.25rem;}#craft-button:disabled { opacity: 0.45;}#send-target-panel {#send-target-panel { z-index: 7; z-index: 7;}}#send-panel header,#send-panel header,#send-target-panel header,#send-target-panel header,#letter-panel header {#letter-panel header,#transfer-panel header,#write-cheque-panel header { display: flex; display: flex; justify-content: space-between; justify-content: space-between; align-items: center; align-items: center;@@ -262,6 +500,8 @@ a { color: #d4c48a; }#send-panel[hidden],#send-panel[hidden],#send-target-panel[hidden],#send-target-panel[hidden],#letter-panel[hidden],#letter-panel[hidden],#transfer-panel[hidden],#write-cheque-panel[hidden],.modal-backdrop[hidden] {.modal-backdrop[hidden] { display: none !important; display: none !important;}}@@ -396,8 +636,11 @@ a { color: #d4c48a; }#inspect-modal[hidden],#inspect-modal[hidden],#inspect-backdrop[hidden],#inspect-backdrop[hidden],#friends-panel[hidden],#friends-panel[hidden],#skills-panel[hidden],#bag-panel[hidden],#bag-panel[hidden],#bank-panel[hidden],#bank-panel[hidden],#craft-panel[hidden],#craft-backdrop[hidden],#nametag[hidden],#nametag[hidden],#chat-bar[hidden] {#chat-bar[hidden] { display: none !important; display: none !important;@@ -178,8 +178,20 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Spawners
**Status:** full
**Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Wildlife options are deer and hostile rats. Pigeons are not ambient wildlife.
**Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
**Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Wildlife options are deer and rats. Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked; courier pigeons cannot.
**Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
## Mob definitions (content schema)
**Status:** partial
**Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill` (one int driving hit chance and damage), `drops` (`{ itemId, chance }[]`), `sells` (item ID list), and `dialogue` trees. Dialogue nodes use `trigger`, `lines[]` (`{ isPlayer, text }`), and `responses[]` (`{ trigger, text, available? }` where `available` is an optional `(ctx) => boolean`). Response actions (later): start quest, give item, open trade, or start mob AI behaviour. Rendering fields (sprites, gait, flight) stay alongside gameplay fields until content tooling splits them.
**Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
## Quests
**Status:** not implemented
**Spec:** Quests are obtained from friendly mobs (dialogue action). Each quest has ordered progression states that advance when the player completes a requirement: obtain an item, fire a dialogue trigger, kill a quota of mobs, reach a tile, or interact with a block. Completion may award skill XP and items; if inventory is full, overflow items are sent to the character vault by carrier pigeon.
**Code:** —
## Character logout resume
@@ -187,17 +199,70 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
**Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn.
**Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
## Inventory, items, equipment, ground drops
## Combat resolution (rolls)
**Status:** full
**Spec:** 32-slot inventory, stacking, equipment slots with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. New characters start with paper, apples, a stick, a cloth shirt, and coins. Placeholder item/equipment PNGs until real art exists. Right-click bag items for Send / Equip / Drop; paper can be written into unique **letter** instances (signed on Save; only the signer may edit).
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
**Status:** partial
**Spec:** Authoritative server rolls; clients only show outcomes. **Melee & ranged (physical):** roll hit skill vs defender **Dexterity (agility)** — miss if attack roll < agility roll, hit on tie or higher; on hit roll damage skill (Strength for melee, Dexterity for ranged) for `baseDamage + roll − 1`; on hit defender rolls Defence — **block** if defence roll > attacker's to-hit roll; otherwise apply damage. **Effective combat levels** add worn equipment tier bonuses to damage/agility/defence rolls (e.g. Strength 10 + bronze weapon +1 → damage roll uses 11). Hit skills (Club/Sword fighting, Archery) use base skill only. XP only on damage hits. **Attack types** (slashing / piercing / blunt) are defined on weapons; mob weak/resist multipliers remain later. **Magic:** roll Magic vs per-spell **difficulty** (contest, tie or higher succeeds); on success roll Mind for damage; multiply by elemental weak ×2 / neutral ×1 / resistant ×0.5; non-damage spells only need a successful cast roll then apply an effect. Spell defs in `shared/definitions/spells.js`. Full casting UI, LOS, and effect system remain later.
**Code:** `shared/combat/rolls.js` (physical, live), `shared/combat/magic.js` (cast + damage rules, shared only), `shared/definitions/spells.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `server/src/combat/service.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/magic.test.js`, `server/tests/equipment.test.js`
## Combat, skills, groups, pigeons
**Status:** partial
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, and client dynamic-light hooks. Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank (nearest bank → sender vault) or Player (online inventory / offline money→vault / full inventory→reroute to bank). Flight speeds are world settings: takeoff / cruise / landing over the first and last `pigeonPhaseTiles` (defaults 3 / 8 / 3 tiles/s, phase 5). Durable `courier_transits`; ECS pigeon only in already-simulating chunks. Ranged/spells/groups remain design-only.
**Code:** `shared/courier/flight.js`, `server/src/courier/service.js`, bag pigeon UI, tests in `server/tests/courier.test.js` (+ combat/follow tests)
**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs retaliate when attacked and keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
## Equipment tiers and worn stat bonuses
**Status:** partial
**Spec:** Metal gear exists in six material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**. Bronze has no extra gate (min relevant skill 1). Every higher tier requires a minimum level of the item's **relevant skill** (weapons → their hit skill e.g. Sword fighting; metal armour & shields → Defence; bows → Archery; wizard cloth & staves → Magic; gathering tools → Woodcutting / Mining / Fishing). Tier min levels and per-tier stat bonuses live in `shared/definitions/materialTiers.js`. Worn items add flat bonuses to **effective** combat stats (not base skill XP): metal weapons & clubs → Strength; metal armour & shields → Defence; bows → Dexterity; wizard cloth → Magic; staves → Mind; leather armour → Dexterity (Agility); cloth armour → Defence. Item defs carry `equipment.tier`, `equipment.kind`, optional `equipment.bonus` override, and `attack.attackType`. Equip checks enforce min skill; combat rolls use `shared/equipment/stats.js`. **TODO:** full tiered item catalog (all metals, bows, shields, wizard sets, leather, tools); placeholder art per tier; client tooltip showing reqs/bonuses.
**Code:** `shared/definitions/materialTiers.js`, `shared/definitions/equipmentKinds.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `shared/definitions/items.js` (stick, cloth shirt), `server/src/items/bags.js`, `server/src/combat/service.js`, tests in `server/tests/equipment.test.js`
## Gathering, crafting, and production skills
**Status:** not implemented
**Spec:** Skill IDs exist for **Woodcutting**, **Mining**, **Fishing**, **Smithing**, **Crafting**, **Leatherworking**, **Tailoring**, and **Cooking**. **Axes** (Woodcutting) and **pickaxes** (Mining) are tools, not melee weapons — tier sets min Woodcutting/Mining to equip; better tools gather faster. **Fishing rods** and **nets** use Fishing. **Smithing** crafts metal items (min Smithing per recipe). **Crafting** makes misc items (e.g. arrows from smithed tips). **Leatherworking** makes leather armour (Dexterity bonus, not Defence). **Tailoring** makes cloth armour; separate **wizard cloth** tiers grant Magic bonus. **Cooking** prepares raw food at ovens and campfires (see **Crafting stations**). Gathering attempts always succeed when in range; non-cooking crafts always succeed when skill ≥ recipe min. Resources have a **minimum tier** (tool tier must meet or exceed). **Leather** needs no tool — drops from certain mobs. **TODO:** resource nodes (trees, ores, fish spots), gather commands, recipe data files, tool/item sprites, gather speed formula, mob leather drops, sheep shearing. Craft UI is specified under **Crafting stations**.
**Code:** `shared/definitions/skills.js` (skill IDs + panel entries only)
## Crafting stations
**Status:** UI shell + item/recipe scaffolding; server crafting not implemented
**Spec:** Recipes run at a **station** adjacent to or under the player (exact interaction radius TBD). Station IDs and linked skills live in `shared/definitions/craftingStations.js`.
| Station | Role | Skill |
| --- | --- | --- |
| **Furnace** | Smelt gathered **ore → bars** | Smithing |
| **Spinning wheel** | **Wool → thread** (wool from shorn sheep — sheep/WIP) | Tailoring |
| **Loom** | Weave **cloth clothing** | Tailoring |
| **Anvil** | Smith **metal items** from bars | Smithing |
| **Leatherworking station** | Craft **leather** goods | Leatherworking |
| **Crafting bench** | General **Crafting** (e.g. arrows + tips) | Crafting |
| **Oven** | Cook **raw meat** | Cooking |
| **Fireplace (campfire)** | Same cooking as oven | Cooking |
**Cooking:** Requires Cooking ≥ recipe minimum or the attempt can **burn** the food (lost). **Oven** uses a lower burn chance than **fireplace** for the same recipe/skill gap.
**Fireplace (portable):** Drop a **log** on the ground; **right-click the log → Start Fire** while carrying a **tinderbox** in inventory (consumes tinderbox use TBD). Creates a shared **campfire** on that tile for **10 minutes** (`FIREPLACE_DURATION_MS`). Any player may cook at it. **At most one fireplace per tile.** Fixed **oven** blocks are separate placeables (editor/content later).
**Station UI (shared across all stations):** Opening a station shows a **recipe grid** on the left — each cell is the output **item icon** with **display name** underneath. Clicking a recipe selects it; the **detail pane on the right** repeats the icon and name, lists **required materials** (icon + quantity per input), and a **Craft** button. Crafting is blocked unless the server confirms room for the product: `canCraftFitInventory()` simulates **consuming inputs first**, then inserting the output, so freed slots from spent materials count toward space (`shared/crafting/recipes.js`). While crafting, a **2 s** progress bar runs (`CRAFT_DURATION_MS`) for every recipe regardless of item. Only one craft at a time per player; closing the panel cancels in-progress craft (sends `CANCEL_CRAFT`). Cooking stations use the same shell; burn failure is an outcome after the timer, not a separate UI.
**Item scaffolding:** Reserved IDs and stub definitions for gathering/crafting content live in `shared/definitions/craftingItems.js` (`CraftingItemId`, `CRAFTING_ITEM_STUBS` merged into `ITEM_DEFINITIONS`). Replace stubs with full defs (sprites, equipment, tiers) as rules land. Recipe rows go in `shared/crafting/stationRecipes.js` (`CRAFT_RECIPES`); filter with `recipesForStation()`.
**Dev:** In the browser console, `__craftDev()` opens the crafting bench UI; pass any `CraftingStationId` string for other stations.
**TODO:** station block/entity types and sprites, real recipe tables per station, open/close from world interaction, server craft command + timer + adjacency checks, Cooking burn formula, log/tinderbox behaviour, campfire ground entity lifecycle & replication, spinning wheel wool input once sheep exist.
**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/craftingItems.js`, `shared/definitions/itemCategories.js`, `shared/crafting/recipes.js`, `shared/crafting/stationRecipes.js`, `client/src/play/crafting.js`, `client/ui/play.css` (#craft-panel)
## Stamina and running
**Status:** not implemented
**Spec:** **Stamina** skill sets max stamina (= skill level). Each stamina point equals **one second of running**. Running consumes stamina; running awards Stamina XP. Walking does not consume stamina. **TODO:** stamina component sync, run gate when empty, regen rules, Stamina XP on run ticks, client stamina bar.
**Code:** `shared/definitions/skills.js` (`playerMaxStamina` helper only)
## Inventory, items, equipment, ground drops
**Status:** full
**Spec:** 32-slot inventory, stacking, equipment slots (head, chest, legs, boots, weapon, **offhand** for shields) with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. New characters start with paper, apples, a stick, a cloth shirt, and coins. Placeholder item/equipment PNGs until real art exists. Right-click bag items for Send / Equip / Drop / Eat (food); paper can be written into unique **letter** instances (signed on Save; only the signer may edit). Equipping always takes **one** item from a stack (never the whole stack); unequipping returns one item and merges into an existing compatible inventory stack when stack rules allow. Equip enforces tier min-skill gates. Eating food heals (see Health skill).
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
## Proximity chat
@@ -214,8 +279,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
## Banking, cheques, shops, player-driven marketplace
**Status:** partial
**Spec:** Bank blocks can be placed in the editor. Standing next to a bank opens vault deposit/withdraw and inheritance claim. Filled cheques, shop NPCs, and the player marketplace are not in this slice.
**Code:** `server/src/items/bags.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`
**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. NPC shops and the player marketplace UI remain later; marketplace sell rules for cheques are already enforced in shared item definitions.
**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/origins.test.js`
## Player scripting hooks
@@ -178,8 +178,20 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Spawners## Spawners**Status:** full **Status:** full **Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Wildlife options are deer and hostile rats. Pigeons are not ambient wildlife. **Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Wildlife options are deer and rats. Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked; courier pigeons cannot. **Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`**Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`## Mob definitions (content schema)**Status:** partial **Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill` (one int driving hit chance and damage), `drops` (`{ itemId, chance }[]`), `sells` (item ID list), and `dialogue` trees. Dialogue nodes use `trigger`, `lines[]` (`{ isPlayer, text }`), and `responses[]` (`{ trigger, text, available? }` where `available` is an optional `(ctx) => boolean`). Response actions (later): start quest, give item, open trade, or start mob AI behaviour. Rendering fields (sprites, gait, flight) stay alongside gameplay fields until content tooling splits them. **Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`## Quests**Status:** not implemented **Spec:** Quests are obtained from friendly mobs (dialogue action). Each quest has ordered progression states that advance when the player completes a requirement: obtain an item, fire a dialogue trigger, kill a quota of mobs, reach a tile, or interact with a block. Completion may award skill XP and items; if inventory is full, overflow items are sent to the character vault by carrier pigeon. **Code:** —## Character logout resume## Character logout resume@@ -187,17 +199,70 @@ Each entry is a short note on behaviour and where the code lives. Update this fi**Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn. **Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn. **Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`**Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`## Inventory, items, equipment, ground drops## Combat resolution (rolls)**Status:** full **Status:** partial **Spec:** 32-slot inventory, stacking, equipment slots with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. New characters start with paper, apples, a stick, a cloth shirt, and coins. Placeholder item/equipment PNGs until real art exists. Right-click bag items for Send / Equip / Drop; paper can be written into unique **letter** instances (signed on Save; only the signer may edit). **Spec:** Authoritative server rolls; clients only show outcomes. **Melee & ranged (physical):** roll hit skill vs defender **Dexterity (agility)** — miss if attack roll < agility roll, hit on tie or higher; on hit roll damage skill (Strength for melee, Dexterity for ranged) for `baseDamage + roll − 1`; on hit defender rolls Defence — **block** if defence roll > attacker's to-hit roll; otherwise apply damage. **Effective combat levels** add worn equipment tier bonuses to damage/agility/defence rolls (e.g. Strength 10 + bronze weapon +1 → damage roll uses 11). Hit skills (Club/Sword fighting, Archery) use base skill only. XP only on damage hits. **Attack types** (slashing / piercing / blunt) are defined on weapons; mob weak/resist multipliers remain later. **Magic:** roll Magic vs per-spell **difficulty** (contest, tie or higher succeeds); on success roll Mind for damage; multiply by elemental weak ×2 / neutral ×1 / resistant ×0.5; non-damage spells only need a successful cast roll then apply an effect. Spell defs in `shared/definitions/spells.js`. Full casting UI, LOS, and effect system remain later. **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`**Code:** `shared/combat/rolls.js` (physical, live), `shared/combat/magic.js` (cast + damage rules, shared only), `shared/definitions/spells.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `server/src/combat/service.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/magic.test.js`, `server/tests/equipment.test.js`## Combat, skills, groups, pigeons## Combat, skills, groups, pigeons**Status:** partial **Status:** partial **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, and client dynamic-light hooks. Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank (nearest bank → sender vault) or Player (online inventory / offline money→vault / full inventory→reroute to bank). Flight speeds are world settings: takeoff / cruise / landing over the first and last `pigeonPhaseTiles` (defaults 3 / 8 / 3 tiles/s, phase 5). Durable `courier_transits`; ECS pigeon only in already-simulating chunks. Ranged/spells/groups remain design-only. **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, mob HP bars, and client dynamic-light hooks. Fightable mobs retaliate when attacked and keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later. **Code:** `shared/courier/flight.js`, `server/src/courier/service.js`, bag pigeon UI, tests in `server/tests/courier.test.js` (+ combat/follow tests)**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)## Equipment tiers and worn stat bonuses**Status:** partial **Spec:** Metal gear exists in six material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**. Bronze has no extra gate (min relevant skill 1). Every higher tier requires a minimum level of the item's **relevant skill** (weapons → their hit skill e.g. Sword fighting; metal armour & shields → Defence; bows → Archery; wizard cloth & staves → Magic; gathering tools → Woodcutting / Mining / Fishing). Tier min levels and per-tier stat bonuses live in `shared/definitions/materialTiers.js`. Worn items add flat bonuses to **effective** combat stats (not base skill XP): metal weapons & clubs → Strength; metal armour & shields → Defence; bows → Dexterity; wizard cloth → Magic; staves → Mind; leather armour → Dexterity (Agility); cloth armour → Defence. Item defs carry `equipment.tier`, `equipment.kind`, optional `equipment.bonus` override, and `attack.attackType`. Equip checks enforce min skill; combat rolls use `shared/equipment/stats.js`. **TODO:** full tiered item catalog (all metals, bows, shields, wizard sets, leather, tools); placeholder art per tier; client tooltip showing reqs/bonuses. **Code:** `shared/definitions/materialTiers.js`, `shared/definitions/equipmentKinds.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `shared/definitions/items.js` (stick, cloth shirt), `server/src/items/bags.js`, `server/src/combat/service.js`, tests in `server/tests/equipment.test.js`## Gathering, crafting, and production skills**Status:** not implemented **Spec:** Skill IDs exist for **Woodcutting**, **Mining**, **Fishing**, **Smithing**, **Crafting**, **Leatherworking**, **Tailoring**, and **Cooking**. **Axes** (Woodcutting) and **pickaxes** (Mining) are tools, not melee weapons — tier sets min Woodcutting/Mining to equip; better tools gather faster. **Fishing rods** and **nets** use Fishing. **Smithing** crafts metal items (min Smithing per recipe). **Crafting** makes misc items (e.g. arrows from smithed tips). **Leatherworking** makes leather armour (Dexterity bonus, not Defence). **Tailoring** makes cloth armour; separate **wizard cloth** tiers grant Magic bonus. **Cooking** prepares raw food at ovens and campfires (see **Crafting stations**). Gathering attempts always succeed when in range; non-cooking crafts always succeed when skill ≥ recipe min. Resources have a **minimum tier** (tool tier must meet or exceed). **Leather** needs no tool — drops from certain mobs. **TODO:** resource nodes (trees, ores, fish spots), gather commands, recipe data files, tool/item sprites, gather speed formula, mob leather drops, sheep shearing. Craft UI is specified under **Crafting stations**. **Code:** `shared/definitions/skills.js` (skill IDs + panel entries only)## Crafting stations**Status:** UI shell + item/recipe scaffolding; server crafting not implemented **Spec:** Recipes run at a **station** adjacent to or under the player (exact interaction radius TBD). Station IDs and linked skills live in `shared/definitions/craftingStations.js`.| Station | Role | Skill || --- | --- | --- || **Furnace** | Smelt gathered **ore → bars** | Smithing || **Spinning wheel** | **Wool → thread** (wool from shorn sheep — sheep/WIP) | Tailoring || **Loom** | Weave **cloth clothing** | Tailoring || **Anvil** | Smith **metal items** from bars | Smithing || **Leatherworking station** | Craft **leather** goods | Leatherworking || **Crafting bench** | General **Crafting** (e.g. arrows + tips) | Crafting || **Oven** | Cook **raw meat** | Cooking || **Fireplace (campfire)** | Same cooking as oven | Cooking |**Cooking:** Requires Cooking ≥ recipe minimum or the attempt can **burn** the food (lost). **Oven** uses a lower burn chance than **fireplace** for the same recipe/skill gap.**Fireplace (portable):** Drop a **log** on the ground; **right-click the log → Start Fire** while carrying a **tinderbox** in inventory (consumes tinderbox use TBD). Creates a shared **campfire** on that tile for **10 minutes** (`FIREPLACE_DURATION_MS`). Any player may cook at it. **At most one fireplace per tile.** Fixed **oven** blocks are separate placeables (editor/content later).**Station UI (shared across all stations):** Opening a station shows a **recipe grid** on the left — each cell is the output **item icon** with **display name** underneath. Clicking a recipe selects it; the **detail pane on the right** repeats the icon and name, lists **required materials** (icon + quantity per input), and a **Craft** button. Crafting is blocked unless the server confirms room for the product: `canCraftFitInventory()` simulates **consuming inputs first**, then inserting the output, so freed slots from spent materials count toward space (`shared/crafting/recipes.js`). While crafting, a **2 s** progress bar runs (`CRAFT_DURATION_MS`) for every recipe regardless of item. Only one craft at a time per player; closing the panel cancels in-progress craft (sends `CANCEL_CRAFT`). Cooking stations use the same shell; burn failure is an outcome after the timer, not a separate UI.**Item scaffolding:** Reserved IDs and stub definitions for gathering/crafting content live in `shared/definitions/craftingItems.js` (`CraftingItemId`, `CRAFTING_ITEM_STUBS` merged into `ITEM_DEFINITIONS`). Replace stubs with full defs (sprites, equipment, tiers) as rules land. Recipe rows go in `shared/crafting/stationRecipes.js` (`CRAFT_RECIPES`); filter with `recipesForStation()`.**Dev:** In the browser console, `__craftDev()` opens the crafting bench UI; pass any `CraftingStationId` string for other stations.**TODO:** station block/entity types and sprites, real recipe tables per station, open/close from world interaction, server craft command + timer + adjacency checks, Cooking burn formula, log/tinderbox behaviour, campfire ground entity lifecycle & replication, spinning wheel wool input once sheep exist. **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/craftingItems.js`, `shared/definitions/itemCategories.js`, `shared/crafting/recipes.js`, `shared/crafting/stationRecipes.js`, `client/src/play/crafting.js`, `client/ui/play.css` (#craft-panel)## Stamina and running**Status:** not implemented **Spec:** **Stamina** skill sets max stamina (= skill level). Each stamina point equals **one second of running**. Running consumes stamina; running awards Stamina XP. Walking does not consume stamina. **TODO:** stamina component sync, run gate when empty, regen rules, Stamina XP on run ticks, client stamina bar. **Code:** `shared/definitions/skills.js` (`playerMaxStamina` helper only)## Inventory, items, equipment, ground drops**Status:** full **Spec:** 32-slot inventory, stacking, equipment slots (head, chest, legs, boots, weapon, **offhand** for shields) with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. New characters start with paper, apples, a stick, a cloth shirt, and coins. Placeholder item/equipment PNGs until real art exists. Right-click bag items for Send / Equip / Drop / Eat (food); paper can be written into unique **letter** instances (signed on Save; only the signer may edit). Equipping always takes **one** item from a stack (never the whole stack); unequipping returns one item and merges into an existing compatible inventory stack when stack rules allow. Equip enforces tier min-skill gates. Eating food heals (see Health skill). **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`## Proximity chat## Proximity chat@@ -214,8 +279,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi## Banking, cheques, shops, player-driven marketplace## Banking, cheques, shops, player-driven marketplace**Status:** partial **Status:** partial **Spec:** Bank blocks can be placed in the editor. Standing next to a bank opens vault deposit/withdraw and inheritance claim. Filled cheques, shop NPCs, and the player marketplace are not in this slice. **Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. NPC shops and the player marketplace UI remain later; marketplace sell rules for cheques are already enforced in shared item definitions. **Code:** `server/src/items/bags.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/origins.test.js`## Player scripting hooks## Player scripting hooks@@ -1,7 +1,18 @@
import { Component } from "../ecs/components.js";
import { itemDefinition } from "../../../shared/definitions/items.js";
import { mobDefinition } from "../../../shared/definitions/mobs.js";
import { skillLevel, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
import {
mobCanFightType,
mobMeleeAttackProfile,
mobSkillLevels
} from "../../../shared/definitions/mobCombat.js";
import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
import {
effectiveSkillLevel,
equipmentBonusesFromSlots
} from "../../../shared/equipment/stats.js";
import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
import { chunkBoundsAround, findPath } from "../navigation/astar.js";
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
@@ -21,12 +32,57 @@ export function attackProfileOf (ecs, handle)
{ return { ...attack }; }
}
const creature = ecs.get(handle, Component.creature);
const mobAttack = creature ? mobDefinition(creature.mobTypeId)?.defaultAttack : null;
if (mobAttack)
{ return { ...mobAttack }; }
if (creature)
{
const def = mobDefinition(creature.mobTypeId);
if (mobCanFightType(creature.mobTypeId))
{ return mobMeleeAttackProfile(def); }
}
return { ...UNARMED_ATTACK };
}
export function ensureMobCombat (ecs, entityId)
{
const handle = ecs.handleOf(entityId);
if (handle == null)
{ return false; }
const creature = ecs.get(handle, Component.creature);
if (!creature || !mobCanFightType(creature.mobTypeId))
{ return false; }
const def = mobDefinition(creature.mobTypeId);
if (!ecs.get(handle, Component.combat))
{ ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
if (!ecs.get(handle, Component.skills))
{ ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); }
return true;
}
function attackerSkillLevel (skills, profile, skillId)
{
if (profile.mobAttackSkill != null)
{ return profile.mobAttackSkill; }
return skillLevel(skills, skillId);
}
function defenderSkillLevel (skills, skillId, equipment = null)
{
const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {};
return effectiveSkillLevel(skills, skillId, bonuses);
}
function playerCombatLevels (ecs, handle, profile)
{
const skills = ecs.get(handle, Component.skills);
const equipment = ecs.get(handle, Component.equipment);
const bonuses = equipmentBonusesFromSlots(equipment?.slots);
return {
hitLevel: skillLevel(skills, profile.hitSkillId),
damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses),
defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
};
}
export function isUntargetable (ecs, handle)
{
const creature = ecs.get(handle, Component.creature);
@@ -180,10 +236,43 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
fromTileY: from.tileY
});
const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
{ engageTarget(world.ecs, targetId, attackerId, now); }
const skills = world.ecs.get(attackerHandle, Component.skills);
const hitChance = Math.min(0.95, 0.45 + skillLevel(skills, profile.hitSkillId) * 0.03);
const hit = Math.random() < hitChance;
if (!hit)
const defenderSkills = world.ecs.get(targetHandle, Component.skills);
const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
const attackerLevels = attackerCharacter
? playerCombatLevels(world.ecs, attackerHandle, profile)
: {
hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
agilityLevel: skillLevel(skills, SkillId.dexterity),
defenceLevel: skillLevel(skills, SkillId.defence)
};
const hitLevel = attackerLevels.hitLevel;
const damageLevel = attackerLevels.damageLevel;
const agilityLevel = defenderSkillLevel(
defenderSkills,
SkillId.dexterity,
defenderEquipment
);
const defenceLevel = defenderSkillLevel(
defenderSkills,
SkillId.defence,
defenderEquipment
);
const resolved = resolvePhysicalAttack({
hitSkillLevel: hitLevel,
agilitySkillLevel: agilityLevel,
damageSkillLevel: damageLevel,
defenceSkillLevel: defenceLevel,
baseDamage: profile.baseDamage ?? 1
});
if (resolved.outcome === "miss")
{
events.push({
type: "combat-miss",
@@ -195,7 +284,22 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
return events;
}
const damage = Math.max(1, (profile.baseDamage | 0) + Math.floor(skillLevel(skills, profile.damageSkillId) / 5));
if (resolved.outcome === "block")
{
events.push({
type: "combat-block",
attackerId,
targetId,
tileX: to.tileX,
tileY: to.tileY
});
return events;
}
const damage = resolved.damage;
const targetCharacter = world.ecs.get(targetHandle, Component.character);
if (targetCharacter)
{ syncPlayerHealth(world.ecs, targetHandle); }
const health = world.ecs.get(targetHandle, Component.health);
if (health)
{
@@ -208,11 +312,45 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
damage,
tileX: to.tileX,
tileY: to.tileY,
health: health?.current ?? 0
health: health?.current ?? 0,
maxHealth: health?.max ?? 0
});
if (world.ecs.get(targetHandle, Component.combat))
{ engageTarget(world.ecs, targetId, attackerId, now); }
const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
if (healthXp)
{
events.push({
type: "skills-updated",
entityId: targetId,
characterId: healthXp.characterId,
skills: healthXp.view,
stored: healthXp.stored
});
if (health)
{
const hitEvent = events[events.length - 2];
if (hitEvent?.type === "combat-hit")
{
hitEvent.health = health.current;
hitEvent.maxHealth = health.max;
}
}
}
if (attackerCharacter)
{
const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
if (xpAward)
{
events.push({
type: "skills-updated",
entityId: attackerId,
characterId: attackerCharacter.characterId,
skills: xpAward.view,
stored: xpAward.stored
});
}
}
if (health && health.current <= 0)
{
@@ -1,7 +1,18 @@import { Component } from "../ecs/components.js";import { Component } from "../ecs/components.js";import { itemDefinition } from "../../../shared/definitions/items.js";import { itemDefinition } from "../../../shared/definitions/items.js";import { mobDefinition } from "../../../shared/definitions/mobs.js";import { mobDefinition } from "../../../shared/definitions/mobs.js";import { skillLevel, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";import { mobCanFightType, mobMeleeAttackProfile, mobSkillLevels} from "../../../shared/definitions/mobCombat.js";import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";import { effectiveSkillLevel, equipmentBonusesFromSlots} from "../../../shared/equipment/stats.js";import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";import { chunkBoundsAround, findPath } from "../navigation/astar.js";import { chunkBoundsAround, findPath } from "../navigation/astar.js";import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";@@ -21,12 +32,57 @@ export function attackProfileOf (ecs, handle) { return { ...attack }; } { return { ...attack }; } } } const creature = ecs.get(handle, Component.creature); const creature = ecs.get(handle, Component.creature); const mobAttack = creature ? mobDefinition(creature.mobTypeId)?.defaultAttack : null; if (creature) if (mobAttack) { { return { ...mobAttack }; } const def = mobDefinition(creature.mobTypeId); if (mobCanFightType(creature.mobTypeId)) { return mobMeleeAttackProfile(def); } } return { ...UNARMED_ATTACK }; return { ...UNARMED_ATTACK };}}export function ensureMobCombat (ecs, entityId){ const handle = ecs.handleOf(entityId); if (handle == null) { return false; } const creature = ecs.get(handle, Component.creature); if (!creature || !mobCanFightType(creature.mobTypeId)) { return false; } const def = mobDefinition(creature.mobTypeId); if (!ecs.get(handle, Component.combat)) { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } if (!ecs.get(handle, Component.skills)) { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); } return true;}function attackerSkillLevel (skills, profile, skillId){ if (profile.mobAttackSkill != null) { return profile.mobAttackSkill; } return skillLevel(skills, skillId);}function defenderSkillLevel (skills, skillId, equipment = null){ const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {}; return effectiveSkillLevel(skills, skillId, bonuses);}function playerCombatLevels (ecs, handle, profile){ const skills = ecs.get(handle, Component.skills); const equipment = ecs.get(handle, Component.equipment); const bonuses = equipmentBonusesFromSlots(equipment?.slots); return { hitLevel: skillLevel(skills, profile.hitSkillId), damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses), agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses), defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses) };}export function isUntargetable (ecs, handle)export function isUntargetable (ecs, handle){{ const creature = ecs.get(handle, Component.creature); const creature = ecs.get(handle, Component.creature);@@ -180,10 +236,43 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D fromTileY: from.tileY fromTileY: from.tileY }); }); const attackerCharacter = world.ecs.get(attackerHandle, Component.character); if (attackerCharacter && ensureMobCombat(world.ecs, targetId)) { engageTarget(world.ecs, targetId, attackerId, now); } const skills = world.ecs.get(attackerHandle, Component.skills); const skills = world.ecs.get(attackerHandle, Component.skills); const hitChance = Math.min(0.95, 0.45 + skillLevel(skills, profile.hitSkillId) * 0.03); const defenderSkills = world.ecs.get(targetHandle, Component.skills); const hit = Math.random() < hitChance; const defenderEquipment = world.ecs.get(targetHandle, Component.equipment); if (!hit) const attackerLevels = attackerCharacter ? playerCombatLevels(world.ecs, attackerHandle, profile) : { hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId), damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId), agilityLevel: skillLevel(skills, SkillId.dexterity), defenceLevel: skillLevel(skills, SkillId.defence) }; const hitLevel = attackerLevels.hitLevel; const damageLevel = attackerLevels.damageLevel; const agilityLevel = defenderSkillLevel( defenderSkills, SkillId.dexterity, defenderEquipment ); const defenceLevel = defenderSkillLevel( defenderSkills, SkillId.defence, defenderEquipment ); const resolved = resolvePhysicalAttack({ hitSkillLevel: hitLevel, agilitySkillLevel: agilityLevel, damageSkillLevel: damageLevel, defenceSkillLevel: defenceLevel, baseDamage: profile.baseDamage ?? 1 }); if (resolved.outcome === "miss") { { events.push({ events.push({ type: "combat-miss", type: "combat-miss",@@ -195,7 +284,22 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D return events; return events; } } const damage = Math.max(1, (profile.baseDamage | 0) + Math.floor(skillLevel(skills, profile.damageSkillId) / 5)); if (resolved.outcome === "block") { events.push({ type: "combat-block", attackerId, targetId, tileX: to.tileX, tileY: to.tileY }); return events; } const damage = resolved.damage; const targetCharacter = world.ecs.get(targetHandle, Component.character); if (targetCharacter) { syncPlayerHealth(world.ecs, targetHandle); } const health = world.ecs.get(targetHandle, Component.health); const health = world.ecs.get(targetHandle, Component.health); if (health) if (health) { {@@ -208,11 +312,45 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D damage, damage, tileX: to.tileX, tileX: to.tileX, tileY: to.tileY, tileY: to.tileY, health: health?.current ?? 0 health: health?.current ?? 0, maxHealth: health?.max ?? 0 }); }); if (world.ecs.get(targetHandle, Component.combat)) const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage); { engageTarget(world.ecs, targetId, attackerId, now); } if (healthXp) { events.push({ type: "skills-updated", entityId: targetId, characterId: healthXp.characterId, skills: healthXp.view, stored: healthXp.stored }); if (health) { const hitEvent = events[events.length - 2]; if (hitEvent?.type === "combat-hit") { hitEvent.health = health.current; hitEvent.maxHealth = health.max; } } } if (attackerCharacter) { const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile); if (xpAward) { events.push({ type: "skills-updated", entityId: attackerId, characterId: attackerCharacter.characterId, skills: xpAward.view, stored: xpAward.stored }); } } if (health && health.current <= 0) if (health && health.current <= 0) { {@@ -2,7 +2,7 @@ import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
import { insertStack, takeFromSlot, emptySlots } from "../../../shared/items/inventory.js";
import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
import { advanceCourierFlight } from "../../../shared/courier/flight.js";
import { GAIT } from "../../../shared/protocol/constants.js";
import { decodeChunkBlob } from "../world/chunkData.js";
@@ -81,21 +81,15 @@ export class CourierService
}
let takenCargo;
if (cargo?.kind === "money")
if (cargo?.kind === "item")
{
const amount = Math.max(0, cargo.amount | 0);
if (amount <= 0 || amount > (bag.currency | 0))
const slot = bag.inventory?.[cargo.slotIndex | 0];
if (slot?.itemId === ItemId.blankCheque)
{
const error = new Error("Not enough coins.");
const error = new Error("Blank cheques cannot be sent by pigeon.");
error.userFacing = true;
throw error;
}
bag.currency -= amount;
takenCargo = { kind: "money", amount };
}
else if (cargo?.kind === "item")
{
const slot = bag.inventory?.[cargo.slotIndex | 0];
if (slot?.itemId === ItemId.letter)
{
if (Number(slot.instance?.authorCharacterId) !== Number(characterId))
@@ -379,20 +373,24 @@ export class CourierService
return events;
}
#normalizeCargo (cargo)
{
if (cargo?.kind === "money")
{
return {
kind: "item",
stack: { itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) }
};
}
return cargo;
}
#tryDeliverToPlayer (characterId, cargo)
{
cargo = this.#normalizeCargo(cargo);
const onlineId = this.simulation.characterEntities.get(characterId);
if (onlineId)
{
if (cargo.kind === "money")
{
const bag = this.simulation.bagOf(onlineId);
if (!bag)
{ return false; }
bag.currency = (bag.currency | 0) + (cargo.amount | 0);
this.#persistBag(characterId, bag);
return true;
}
if (cargo.kind === "item")
{
const bag = this.simulation.bagOf(onlineId);
@@ -408,7 +406,7 @@ export class CourierService
}
}
if (cargo.kind === "money")
if (cargo.kind === "item")
{
this.#creditVault(characterId, cargo);
return true;
@@ -418,23 +416,24 @@ export class CourierService
#creditVault (characterId, cargo)
{
cargo = this.#normalizeCargo(cargo);
const onlineId = this.simulation.characterEntities.get(characterId);
const bag = onlineId
? this.simulation.bagOf(onlineId)
: this.stateDb.getBag(characterId);
if (!bag)
{ return; }
if (cargo.kind === "money")
{
bag.vaultCurrency = (bag.vaultCurrency | 0) + (cargo.amount | 0);
this.#persistBag(characterId, bag);
return;
}
if (cargo.kind === "item")
{
const def = itemDefinition(cargo.stack.itemId);
const result = insertStack(bag.vault ?? emptySlots(), cargo.stack, def);
bag.vault = result.ok ? result.slots : [...(bag.vault ?? []), cargo.stack];
const vault = normalizeVault(
bag.vaultReserved != null
? { slots: bag.vault, reserved: bag.vaultReserved }
: bag.vault
);
const result = insertStackGrowable(vault.slots, cargo.stack, def);
bag.vault = result.slots;
bag.vaultReserved = vault.reserved;
this.#persistBag(characterId, bag);
}
}
@@ -2,7 +2,7 @@ import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";import { insertStack, takeFromSlot, emptySlots } from "../../../shared/items/inventory.js";import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";import { advanceCourierFlight } from "../../../shared/courier/flight.js";import { advanceCourierFlight } from "../../../shared/courier/flight.js";import { GAIT } from "../../../shared/protocol/constants.js";import { GAIT } from "../../../shared/protocol/constants.js";import { decodeChunkBlob } from "../world/chunkData.js";import { decodeChunkBlob } from "../world/chunkData.js";@@ -81,21 +81,15 @@ export class CourierService } } let takenCargo; let takenCargo; if (cargo?.kind === "money") if (cargo?.kind === "item") { { const amount = Math.max(0, cargo.amount | 0); const slot = bag.inventory?.[cargo.slotIndex | 0]; if (amount <= 0 || amount > (bag.currency | 0)) if (slot?.itemId === ItemId.blankCheque) { { const error = new Error("Not enough coins."); const error = new Error("Blank cheques cannot be sent by pigeon."); error.userFacing = true; error.userFacing = true; throw error; throw error; } } bag.currency -= amount; takenCargo = { kind: "money", amount }; } else if (cargo?.kind === "item") { const slot = bag.inventory?.[cargo.slotIndex | 0]; if (slot?.itemId === ItemId.letter) if (slot?.itemId === ItemId.letter) { { if (Number(slot.instance?.authorCharacterId) !== Number(characterId)) if (Number(slot.instance?.authorCharacterId) !== Number(characterId))@@ -379,20 +373,24 @@ export class CourierService return events; return events; } } #normalizeCargo (cargo) { if (cargo?.kind === "money") { return { kind: "item", stack: { itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) } }; } return cargo; } #tryDeliverToPlayer (characterId, cargo) #tryDeliverToPlayer (characterId, cargo) { { cargo = this.#normalizeCargo(cargo); const onlineId = this.simulation.characterEntities.get(characterId); const onlineId = this.simulation.characterEntities.get(characterId); if (onlineId) if (onlineId) { { if (cargo.kind === "money") { const bag = this.simulation.bagOf(onlineId); if (!bag) { return false; } bag.currency = (bag.currency | 0) + (cargo.amount | 0); this.#persistBag(characterId, bag); return true; } if (cargo.kind === "item") if (cargo.kind === "item") { { const bag = this.simulation.bagOf(onlineId); const bag = this.simulation.bagOf(onlineId);@@ -408,7 +406,7 @@ export class CourierService } } } } if (cargo.kind === "money") if (cargo.kind === "item") { { this.#creditVault(characterId, cargo); this.#creditVault(characterId, cargo); return true; return true;@@ -418,23 +416,24 @@ export class CourierService #creditVault (characterId, cargo) #creditVault (characterId, cargo) { { cargo = this.#normalizeCargo(cargo); const onlineId = this.simulation.characterEntities.get(characterId); const onlineId = this.simulation.characterEntities.get(characterId); const bag = onlineId const bag = onlineId ? this.simulation.bagOf(onlineId) ? this.simulation.bagOf(onlineId) : this.stateDb.getBag(characterId); : this.stateDb.getBag(characterId); if (!bag) if (!bag) { return; } { return; } if (cargo.kind === "money") { bag.vaultCurrency = (bag.vaultCurrency | 0) + (cargo.amount | 0); this.#persistBag(characterId, bag); return; } if (cargo.kind === "item") if (cargo.kind === "item") { { const def = itemDefinition(cargo.stack.itemId); const def = itemDefinition(cargo.stack.itemId); const result = insertStack(bag.vault ?? emptySlots(), cargo.stack, def); const vault = normalizeVault( bag.vault = result.ok ? result.slots : [...(bag.vault ?? []), cargo.stack]; bag.vaultReserved != null ? { slots: bag.vault, reserved: bag.vaultReserved } : bag.vault ); const result = insertStackGrowable(vault.slots, cargo.stack, def); bag.vault = result.slots; bag.vaultReserved = vault.reserved; this.#persistBag(characterId, bag); this.#persistBag(characterId, bag); } } } }@@ -10,7 +10,6 @@ export const Component = Object.freeze({
persistent: "persistent",
inventory: "inventory",
equipment: "equipment",
currency: "currency",
vault: "vault",
health: "health",
creature: "creature",
@@ -10,7 +10,6 @@ export const Component = Object.freeze({ persistent: "persistent", persistent: "persistent", inventory: "inventory", inventory: "inventory", equipment: "equipment", equipment: "equipment", currency: "currency", vault: "vault", vault: "vault", health: "health", health: "health", creature: "creature", creature: "creature",@@ -2,6 +2,7 @@ import { Component } from "./components.js";
import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
import { mobDefinition } from "../../../shared/definitions/mobs.js";
import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
function bodySprite (sex)
{
@@ -63,8 +64,10 @@ export function publicEntityView (ecs, entityId)
const character = ecs.get(handle, Component.character);
const creature = ecs.get(handle, Component.creature);
const flight = ecs.get(handle, Component.flight);
const health = ecs.get(handle, Component.health);
const layers = appearanceLayers(ecs, handle, appearance);
const mob = creature ? mobDefinition(creature.mobTypeId) : null;
const isMob = !!creature && !character;
return {
entityId,
tileX: position.tileX,
@@ -77,10 +80,13 @@ export function publicEntityView (ecs, entityId)
lastName: appearance?.lastName ?? "",
characterId: character?.characterId ?? null,
mobTypeId: creature?.mobTypeId ?? null,
canFight: mob ? mobCanFight(mob) : false,
hostile: !!mob?.hostile,
talkable: !!mob?.talkable,
untargetable: !!mob?.untargetable,
freeFlight: !!mob?.freeFlight,
health: isMob && health ? health.current : undefined,
maxHealth: isMob && health ? health.max : undefined,
sprite: layers[0]?.sprite ?? null,
layers
};
@@ -122,10 +128,13 @@ export function replicationSpawn (view)
sprite: view.sprite ?? null,
layers: view.layers ?? [],
mobTypeId: view.mobTypeId ?? null,
canFight: !!view.canFight,
hostile: !!view.hostile,
talkable: !!view.talkable,
untargetable: !!view.untargetable,
freeFlight: !!view.freeFlight
freeFlight: !!view.freeFlight,
health: view.health,
maxHealth: view.maxHealth
};
}
@@ -2,6 +2,7 @@ import { Component } from "./components.js";import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";import { spriteImageName } from "../../../shared/definitions/tileSprites.js";import { spriteImageName } from "../../../shared/definitions/tileSprites.js";import { mobDefinition } from "../../../shared/definitions/mobs.js";import { mobDefinition } from "../../../shared/definitions/mobs.js";import { mobCanFight } from "../../../shared/definitions/mobCombat.js";function bodySprite (sex)function bodySprite (sex){{@@ -63,8 +64,10 @@ export function publicEntityView (ecs, entityId) const character = ecs.get(handle, Component.character); const character = ecs.get(handle, Component.character); const creature = ecs.get(handle, Component.creature); const creature = ecs.get(handle, Component.creature); const flight = ecs.get(handle, Component.flight); const flight = ecs.get(handle, Component.flight); const health = ecs.get(handle, Component.health); const layers = appearanceLayers(ecs, handle, appearance); const layers = appearanceLayers(ecs, handle, appearance); const mob = creature ? mobDefinition(creature.mobTypeId) : null; const mob = creature ? mobDefinition(creature.mobTypeId) : null; const isMob = !!creature && !character; return { return { entityId, entityId, tileX: position.tileX, tileX: position.tileX,@@ -77,10 +80,13 @@ export function publicEntityView (ecs, entityId) lastName: appearance?.lastName ?? "", lastName: appearance?.lastName ?? "", characterId: character?.characterId ?? null, characterId: character?.characterId ?? null, mobTypeId: creature?.mobTypeId ?? null, mobTypeId: creature?.mobTypeId ?? null, canFight: mob ? mobCanFight(mob) : false, hostile: !!mob?.hostile, hostile: !!mob?.hostile, talkable: !!mob?.talkable, talkable: !!mob?.talkable, untargetable: !!mob?.untargetable, untargetable: !!mob?.untargetable, freeFlight: !!mob?.freeFlight, freeFlight: !!mob?.freeFlight, health: isMob && health ? health.current : undefined, maxHealth: isMob && health ? health.max : undefined, sprite: layers[0]?.sprite ?? null, sprite: layers[0]?.sprite ?? null, layers layers }; };@@ -122,10 +128,13 @@ export function replicationSpawn (view) sprite: view.sprite ?? null, sprite: view.sprite ?? null, layers: view.layers ?? [], layers: view.layers ?? [], mobTypeId: view.mobTypeId ?? null, mobTypeId: view.mobTypeId ?? null, canFight: !!view.canFight, hostile: !!view.hostile, hostile: !!view.hostile, talkable: !!view.talkable, talkable: !!view.talkable, untargetable: !!view.untargetable, untargetable: !!view.untargetable, freeFlight: !!view.freeFlight freeFlight: !!view.freeFlight, health: view.health, maxHealth: view.maxHealth }; };}}@@ -3,6 +3,7 @@ import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
import { broadcastSpeech } from "../chat/speech.js";
import { publicSkillsView } from "../../../shared/skills/state.js";
let nextSessionId = 1;
@@ -160,6 +161,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
equipSlot: message.equipSlot
});
break;
case MessageType.eatItem:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "eat-item",
characterId: session.characterId,
slotIndex: message.slotIndex | 0
});
break;
case MessageType.openBank:
requirePlaying(session);
simulation.enqueue(session.id, {
@@ -170,21 +179,53 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
case MessageType.bankDeposit:
requirePlaying(session);
simulation.enqueue(session.id, {
type: message.money ? "bank-deposit-money" : "bank-deposit",
type: "bank-deposit",
characterId: session.characterId,
slotIndex: message.slotIndex | 0,
quantity: message.quantity ?? null,
amount: message.amount | 0
quantity: message.quantity ?? null
});
break;
case MessageType.bankWithdraw:
requirePlaying(session);
simulation.enqueue(session.id, {
type: message.money ? "bank-withdraw-money" : "bank-withdraw",
type: "bank-withdraw",
characterId: session.characterId,
slotIndex: message.slotIndex | 0,
quantity: message.quantity ?? null,
amount: message.amount | 0
quantity: message.quantity ?? null
});
break;
case MessageType.getBlankCheques:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "get-blank-cheques",
characterId: session.characterId
});
break;
case MessageType.returnBlankCheques:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "return-blank-cheques",
characterId: session.characterId,
slotIndex: message.slotIndex | 0,
quantity: message.quantity ?? null
});
break;
case MessageType.writeCheque:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "write-cheque",
characterId: session.characterId,
slotIndex: message.slotIndex | 0,
vaultSlotIndex: message.vaultSlotIndex | 0,
quantity: message.quantity ?? 1
});
break;
case MessageType.redeemCheque:
requirePlaying(session);
simulation.enqueue(session.id, {
type: "redeem-cheque",
characterId: session.characterId,
slotIndex: message.slotIndex | 0
});
break;
case MessageType.claimInheritance:
@@ -194,8 +235,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
simulation.enqueue(session.id, {
type: "claim-inheritance",
characterId: session.characterId,
stacks: (inheritance.slots ?? []).filter(Boolean),
currency: inheritance.currency | 0
stacks: (inheritance.slots ?? []).filter(Boolean)
});
}
break;
@@ -371,6 +411,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
const bag = simulation.bagOf(session.entityId);
if (bag)
{ send(session, { type: MessageType.inventory, ...bag }); }
const skills = simulation.skillsOf(session.entityId);
if (skills)
{ send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
publishReplication(simulation.drainReplication());
}
@@ -501,22 +544,28 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
type: MessageType.inventory,
inventory: event.inventory,
equipment: event.equipment,
currency: event.currency,
vault: event.vault,
vaultCurrency: event.vaultCurrency
vaultReserved: event.vaultReserved
});
if (event.bank)
{
send(session, {
type: MessageType.bankSnapshot,
vault: event.vault,
vaultCurrency: event.vaultCurrency,
currency: event.currency,
vaultReserved: event.vaultReserved,
inheritance: stateDb.getInheritance(session.account.account_id)
});
}
continue;
}
if (event.type === "skills")
{
const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
if (!session)
{ continue; }
send(session, { type: MessageType.skills, skills: event.skills ?? [] });
continue;
}
if (event.type === "pigeon-delivered")
{
for (const session of sessions.values())
@@ -534,7 +583,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
}
continue;
}
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")
if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")
{ publishEntity(event); }
}
if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -599,7 +648,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });
continue;
}
if (event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")
if (event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")
{
if (!seesTo && !seesFrom)
{ continue; }
@@ -607,13 +656,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
? MessageType.combatSwing
: event.type === "combat-hit"
? MessageType.combatHit
: MessageType.combatMiss;
: event.type === "combat-block"
? MessageType.combatBlock
: MessageType.combatMiss;
send(session, {
type,
attackerId: event.attackerId,
targetId: event.targetId,
damage: event.damage,
health: event.health,
maxHealth: event.maxHealth,
tileX: event.tileX,
tileY: event.tileY,
fromTileX: event.fromTileX,
@@ -667,10 +719,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
sprite: record.sprite ?? event.sprite ?? null,
layers: record.layers ?? event.layers ?? [],
mobTypeId: record.mobTypeId ?? event.mobTypeId ?? null,
canFight: !!(record.canFight ?? event.canFight),
hostile: !!(record.hostile ?? event.hostile),
talkable: !!(record.talkable ?? event.talkable),
untargetable: !!(record.untargetable ?? event.untargetable),
freeFlight: !!(record.freeFlight ?? event.freeFlight)
freeFlight: !!(record.freeFlight ?? event.freeFlight),
health: record.health ?? event.health,
maxHealth: record.maxHealth ?? event.maxHealth
};
}
@@ -680,18 +735,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
wss,
async shutdown ()
{
for (const session of [...sessions.values()])
await Promise.all([...sessions.values()].map(async (session) =>
{
send(session, {
await sendAsync(session, {
type: MessageType.forceLogout,
reason: "Server shutting down."
});
leaveWorld(session);
try
{ session.socket.close(1001, "Server shutting down"); }
catch
{ /* ignore */ }
}
await closeAsync(session, 1001, "Server shutting down.");
}));
sessions.clear();
await simulation.shutdown();
}
@@ -703,3 +755,33 @@ function send (session, payload)
if (session.socket.readyState === 1)
{ session.socket.send(JSON.stringify(payload)); }
}
function sendAsync (session, payload)
{
return new Promise((resolve) =>
{
if (session.socket.readyState !== 1)
{
resolve();
return;
}
session.socket.send(JSON.stringify(payload), () => resolve());
});
}
function closeAsync (session, code, reason)
{
return new Promise((resolve) =>
{
if (session.socket.readyState !== 1)
{
resolve();
return;
}
session.socket.once("close", resolve);
try
{ session.socket.close(code, reason); }
catch
{ resolve(); }
});
}
@@ -3,6 +3,7 @@ import { MessageType, GAIT } from "../../../shared/protocol/constants.js";import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";import { broadcastSpeech } from "../chat/speech.js";import { broadcastSpeech } from "../chat/speech.js";import { publicSkillsView } from "../../../shared/skills/state.js";let nextSessionId = 1;let nextSessionId = 1;@@ -160,6 +161,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, equipSlot: message.equipSlot equipSlot: message.equipSlot }); }); break; break; case MessageType.eatItem: requirePlaying(session); simulation.enqueue(session.id, { type: "eat-item", characterId: session.characterId, slotIndex: message.slotIndex | 0 }); break; case MessageType.openBank: case MessageType.openBank: requirePlaying(session); requirePlaying(session); simulation.enqueue(session.id, { simulation.enqueue(session.id, {@@ -170,21 +179,53 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, case MessageType.bankDeposit: case MessageType.bankDeposit: requirePlaying(session); requirePlaying(session); simulation.enqueue(session.id, { simulation.enqueue(session.id, { type: message.money ? "bank-deposit-money" : "bank-deposit", type: "bank-deposit", characterId: session.characterId, characterId: session.characterId, slotIndex: message.slotIndex | 0, slotIndex: message.slotIndex | 0, quantity: message.quantity ?? null, quantity: message.quantity ?? null amount: message.amount | 0 }); }); break; break; case MessageType.bankWithdraw: case MessageType.bankWithdraw: requirePlaying(session); requirePlaying(session); simulation.enqueue(session.id, { simulation.enqueue(session.id, { type: message.money ? "bank-withdraw-money" : "bank-withdraw", type: "bank-withdraw", characterId: session.characterId, characterId: session.characterId, slotIndex: message.slotIndex | 0, slotIndex: message.slotIndex | 0, quantity: message.quantity ?? null, quantity: message.quantity ?? null amount: message.amount | 0 }); break; case MessageType.getBlankCheques: requirePlaying(session); simulation.enqueue(session.id, { type: "get-blank-cheques", characterId: session.characterId }); break; case MessageType.returnBlankCheques: requirePlaying(session); simulation.enqueue(session.id, { type: "return-blank-cheques", characterId: session.characterId, slotIndex: message.slotIndex | 0, quantity: message.quantity ?? null }); break; case MessageType.writeCheque: requirePlaying(session); simulation.enqueue(session.id, { type: "write-cheque", characterId: session.characterId, slotIndex: message.slotIndex | 0, vaultSlotIndex: message.vaultSlotIndex | 0, quantity: message.quantity ?? 1 }); break; case MessageType.redeemCheque: requirePlaying(session); simulation.enqueue(session.id, { type: "redeem-cheque", characterId: session.characterId, slotIndex: message.slotIndex | 0 }); }); break; break; case MessageType.claimInheritance: case MessageType.claimInheritance:@@ -194,8 +235,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, simulation.enqueue(session.id, { simulation.enqueue(session.id, { type: "claim-inheritance", type: "claim-inheritance", characterId: session.characterId, characterId: session.characterId, stacks: (inheritance.slots ?? []).filter(Boolean), stacks: (inheritance.slots ?? []).filter(Boolean) currency: inheritance.currency | 0 }); }); } } break; break;@@ -371,6 +411,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, const bag = simulation.bagOf(session.entityId); const bag = simulation.bagOf(session.entityId); if (bag) if (bag) { send(session, { type: MessageType.inventory, ...bag }); } { send(session, { type: MessageType.inventory, ...bag }); } const skills = simulation.skillsOf(session.entityId); if (skills) { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); } publishReplication(simulation.drainReplication()); publishReplication(simulation.drainReplication()); } }@@ -501,22 +544,28 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, type: MessageType.inventory, type: MessageType.inventory, inventory: event.inventory, inventory: event.inventory, equipment: event.equipment, equipment: event.equipment, currency: event.currency, vault: event.vault, vault: event.vault, vaultCurrency: event.vaultCurrency vaultReserved: event.vaultReserved }); }); if (event.bank) if (event.bank) { { send(session, { send(session, { type: MessageType.bankSnapshot, type: MessageType.bankSnapshot, vault: event.vault, vault: event.vault, vaultCurrency: event.vaultCurrency, vaultReserved: event.vaultReserved, currency: event.currency, inheritance: stateDb.getInheritance(session.account.account_id) inheritance: stateDb.getInheritance(session.account.account_id) }); }); } } continue; continue; } } if (event.type === "skills") { const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId); if (!session) { continue; } send(session, { type: MessageType.skills, skills: event.skills ?? [] }); continue; } if (event.type === "pigeon-delivered") if (event.type === "pigeon-delivered") { { for (const session of sessions.values()) for (const session of sessions.values())@@ -534,7 +583,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, } } continue; continue; } } if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss") if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance" || event.type === "entity-despawn" || event.type === "entity-spawn" || event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block") { publishEntity(event); } { publishEntity(event); } } } if (simulation.tickIndex % simulation.settings.simulationTickHz === 0) if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)@@ -599,7 +648,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId }); send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId }); continue; continue; } } if (event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss") if (event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block") { { if (!seesTo && !seesFrom) if (!seesTo && !seesFrom) { continue; } { continue; }@@ -607,13 +656,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, ? MessageType.combatSwing ? MessageType.combatSwing : event.type === "combat-hit" : event.type === "combat-hit" ? MessageType.combatHit ? MessageType.combatHit : MessageType.combatMiss; : event.type === "combat-block" ? MessageType.combatBlock : MessageType.combatMiss; send(session, { send(session, { type, type, attackerId: event.attackerId, attackerId: event.attackerId, targetId: event.targetId, targetId: event.targetId, damage: event.damage, damage: event.damage, health: event.health, health: event.health, maxHealth: event.maxHealth, tileX: event.tileX, tileX: event.tileX, tileY: event.tileY, tileY: event.tileY, fromTileX: event.fromTileX, fromTileX: event.fromTileX,@@ -667,10 +719,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, sprite: record.sprite ?? event.sprite ?? null, sprite: record.sprite ?? event.sprite ?? null, layers: record.layers ?? event.layers ?? [], layers: record.layers ?? event.layers ?? [], mobTypeId: record.mobTypeId ?? event.mobTypeId ?? null, mobTypeId: record.mobTypeId ?? event.mobTypeId ?? null, canFight: !!(record.canFight ?? event.canFight), hostile: !!(record.hostile ?? event.hostile), hostile: !!(record.hostile ?? event.hostile), talkable: !!(record.talkable ?? event.talkable), talkable: !!(record.talkable ?? event.talkable), untargetable: !!(record.untargetable ?? event.untargetable), untargetable: !!(record.untargetable ?? event.untargetable), freeFlight: !!(record.freeFlight ?? event.freeFlight) freeFlight: !!(record.freeFlight ?? event.freeFlight), health: record.health ?? event.health, maxHealth: record.maxHealth ?? event.maxHealth }; }; } }@@ -680,18 +735,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends, wss, wss, async shutdown () async shutdown () { { for (const session of [...sessions.values()]) await Promise.all([...sessions.values()].map(async (session) => { { send(session, { await sendAsync(session, { type: MessageType.forceLogout, type: MessageType.forceLogout, reason: "Server shutting down." reason: "Server shutting down." }); }); leaveWorld(session); leaveWorld(session); try await closeAsync(session, 1001, "Server shutting down."); { session.socket.close(1001, "Server shutting down"); } })); catch { /* ignore */ } } sessions.clear(); sessions.clear(); await simulation.shutdown(); await simulation.shutdown(); } }@@ -703,3 +755,33 @@ function send (session, payload) if (session.socket.readyState === 1) if (session.socket.readyState === 1) { session.socket.send(JSON.stringify(payload)); } { session.socket.send(JSON.stringify(payload)); }}}function sendAsync (session, payload){ return new Promise((resolve) => { if (session.socket.readyState !== 1) { resolve(); return; } session.socket.send(JSON.stringify(payload), () => resolve()); });}function closeAsync (session, code, reason){ return new Promise((resolve) => { if (session.socket.readyState !== 1) { resolve(); return; } session.socket.once("close", resolve); try { session.socket.close(code, reason); } catch { resolve(); } });}@@ -1,13 +1,23 @@
import { Component } from "../ecs/components.js";
import { syncPlayerHealth } from "../skills/service.js";
import { canEquipItem } from "../../../shared/equipment/stats.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { ItemId, itemDefinition, itemSpriteName, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
import { ItemId, itemDefinition, itemSpriteName, stackDisplayLabel, LETTER_MAX_BODY_CHARS, BLANK_CHEQUE_CARRY_CAP } from "../../../shared/definitions/items.js";
import {
emptyEquipment,
emptySlots,
insertStack,
insertStackGrowable,
normalizeVault,
normalizeInventorySlots,
publicEquipment,
publicSlots,
takeFromSlot
takeFromSlot,
takeMatchingFromSlots,
countItemInSlots,
cloneStack,
singleItemFromStack,
stackQuantity
} from "../../../shared/items/inventory.js";
import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
@@ -22,7 +32,7 @@ export function publicGroundItem (item)
tileY: item.tileY,
itemId: item.stack.itemId,
quantity: item.stack.quantity,
displayName: def?.displayName ?? "Item",
displayName: stackDisplayLabel(item.stack),
sprite: itemSpriteName(item.stack.itemId, item.stack.instance),
expiresAt: item.expiresAt
};
@@ -30,29 +40,30 @@ export function publicGroundItem (item)
export function bagView (ecs, handle)
{
const vault = normalizeVault(ecs.get(handle, Component.vault));
return {
inventory: publicSlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots()),
inventory: publicSlots(normalizeInventorySlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots())),
equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()),
currency: ecs.get(handle, Component.currency)?.amount ?? 0,
vault: publicSlots(ecs.get(handle, Component.vault)?.slots ?? emptySlots()),
vaultCurrency: ecs.get(handle, Component.vault)?.currency ?? 0
vault: publicSlots(vault.slots),
vaultReserved: publicSlots(vault.reserved)
};
}
export function applyBagView (ecs, handle, bag)
{
const inventory = ensureInventory(ecs, handle);
inventory.slots = publicSlots(bag.inventory ?? emptySlots());
inventory.slots = normalizeInventorySlots(publicSlots(bag.inventory ?? emptySlots()));
const equipment = ensureEquipment(ecs, handle);
const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment());
equipment.slots = nextEquip.slots;
let currency = ecs.get(handle, Component.currency);
if (!currency)
{ currency = ecs.add(handle, Component.currency, { amount: 0 }); }
currency.amount = bag.currency | 0;
const vault = ensureVault(ecs, handle);
vault.slots = publicSlots(bag.vault ?? emptySlots());
vault.currency = bag.vaultCurrency | 0;
const normalized = normalizeVault(
bag.vaultReserved != null || (bag.vault && !Array.isArray(bag.vault))
? { slots: bag.vault, reserved: bag.vaultReserved }
: bag.vault
);
vault.slots = publicSlots(normalized.slots);
vault.reserved = publicSlots(normalized.reserved);
return bagView(ecs, handle);
}
@@ -74,10 +85,14 @@ export function handleItemCommand (world, sessionId, command, now)
return bankMove(world, sessionId, command, "inventory", "vault");
case "bank-withdraw":
return bankMove(world, sessionId, command, "vault", "inventory");
case "bank-deposit-money":
return bankMoney(world, sessionId, command, "currency", "vault");
case "bank-withdraw-money":
return bankMoney(world, sessionId, command, "vault", "currency");
case "get-blank-cheques":
return getBlankCheques(world, sessionId, command);
case "return-blank-cheques":
return returnBlankCheques(world, sessionId, command);
case "write-cheque":
return writeCheque(world, sessionId, command);
case "redeem-cheque":
return redeemCheque(world, sessionId, command);
case "claim-inheritance":
return claimInheritance(world, sessionId, command);
case "write-letter":
@@ -86,6 +101,8 @@ export function handleItemCommand (world, sessionId, command, now)
return editLetter(world, sessionId, command);
case "open-letter":
return openLetter(world, sessionId, command);
case "eat-item":
return eatItem(world, sessionId, command);
default:
return null;
}
@@ -196,13 +213,41 @@ function pickupItem (world, sessionId, command)
if (!def)
{ throw userError("Unknown item."); }
const inventory = ensureInventory(world.ecs, handle);
const inserted = insertStack(inventory.slots, item.stack, def);
let stackToAdd = item.stack;
if (item.stack.itemId === ItemId.blankCheque)
{
const have = countItemInSlots(inventory.slots, ItemId.blankCheque);
const room = BLANK_CHEQUE_CARRY_CAP - have;
if (room <= 0)
{ throw userError(`You already carry ${BLANK_CHEQUE_CARRY_CAP} blank cheques.`); }
const takeQty = Math.min(item.stack.quantity, room);
stackToAdd = { ...item.stack, quantity: takeQty };
}
const inserted = insertStack(inventory.slots, stackToAdd, def);
if (!inserted.ok)
{ throw userError("Your inventory cannot hold that."); }
inventory.slots = inserted.slots;
removeGroundItem(world, item.groundItemId);
const events = [];
if (item.stack.itemId === ItemId.blankCheque && stackToAdd.quantity < item.stack.quantity)
{
item.stack.quantity -= stackToAdd.quantity;
events.push({
type: "ground-item-appear",
...publicGroundItem(item),
stack: item.stack,
droppedAt: item.droppedAt,
source: item.source,
droppedByCharacterId: item.droppedByCharacterId,
expiresAt: item.expiresAt
});
}
else
{
removeGroundItem(world, item.groundItemId);
events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
}
return {
events: [{ type: "ground-item-despawn", ...publicGroundItem(item) }],
events,
private: bagView(world.ecs, handle)
};
}
@@ -212,30 +257,48 @@ function equipItem (world, sessionId, command)
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
const inventory = ensureInventory(world.ecs, handle);
const equipment = ensureEquipment(world.ecs, handle);
const taken = takeFromSlot(inventory.slots, command.slotIndex, 1);
if (!taken.ok)
const slotIndex = command.slotIndex | 0;
const source = inventory.slots[slotIndex];
if (!source || stackQuantity(source.quantity) <= 0)
{ throw userError("That inventory slot is empty."); }
const taken = takeFromSlot(inventory.slots, slotIndex, 1);
if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1)
{ throw userError("That inventory slot is empty."); }
if (taken.taken.itemId === ItemId.coins)
{
inventory.slots = insertStack(taken.slots, taken.taken, itemDefinition(ItemId.coins)).slots;
throw userError("Coins cannot be equipped.");
}
const def = itemDefinition(taken.taken.itemId);
const slot = def?.equipment?.slot;
if (!slot)
{
inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
throw userError("That item cannot be equipped.");
}
const skills = world.ecs.get(handle, Component.skills);
const equipCheck = canEquipItem(skills, def);
if (!equipCheck.ok)
{
inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
throw userError(equipCheck.reason);
}
const toEquip = singleItemFromStack(taken.taken);
const previous = equipment.slots[slot];
if (previous)
{
const back = insertStack(taken.slots, previous, itemDefinition(previous.itemId));
const previousSingle = singleItemFromStack(previous);
const back = insertStack(taken.slots, previousSingle, itemDefinition(previous.itemId));
if (!back.ok)
{
inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
inventory.slots = insertStack(inventory.slots, toEquip, def).slots;
throw userError("No inventory space to unequip the current item.");
}
inventory.slots = back.slots;
}
else
{ inventory.slots = taken.slots; }
equipment.slots[slot] = { ...taken.taken, quantity: 1 };
equipment.slots[slot] = toEquip;
return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
}
@@ -248,7 +311,8 @@ function unequipItem (world, sessionId, command)
if (!worn)
{ throw userError("Nothing is equipped there."); }
const def = itemDefinition(worn.itemId);
const inserted = insertStack(inventory.slots, worn, def);
const single = singleItemFromStack(worn);
const inserted = insertStack(inventory.slots, single, def);
if (!inserted.ok)
{ throw userError("Your inventory cannot hold that."); }
inventory.slots = inserted.slots;
@@ -256,6 +320,32 @@ function unequipItem (world, sessionId, command)
return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
}
function eatItem (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
syncPlayerHealth(world.ecs, handle);
const inventory = ensureInventory(world.ecs, handle);
const health = world.ecs.get(handle, Component.health);
if (!health)
{ throw userError("You cannot eat right now."); }
if ((health.current | 0) >= (health.max | 0))
{ throw userError("You are already at full health."); }
const slotIndex = command.slotIndex | 0;
const slot = inventory.slots[slotIndex];
if (!slot || stackQuantity(slot.quantity) <= 0)
{ throw userError("That inventory slot is empty."); }
const def = itemDefinition(slot.itemId);
const healing = def?.healing ?? 0;
if (healing <= 0)
{ throw userError("That cannot be eaten."); }
const taken = takeFromSlot(inventory.slots, slotIndex, 1);
if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1)
{ throw userError("That inventory slot is empty."); }
inventory.slots = taken.slots;
health.current = Math.min(health.max | 0, (health.current | 0) + healing);
return { events: [], private: bagView(world.ecs, handle) };
}
function openBank (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -271,45 +361,196 @@ function bankMove (world, sessionId, command, fromKey, toKey)
requireBank(world, handle);
const inventory = ensureInventory(world.ecs, handle);
const vault = ensureVault(world.ecs, handle);
if (fromKey === "inventory" && toKey === "vault")
{
const slot = inventory.slots[command.slotIndex | 0];
if (slot?.itemId === ItemId.filledCheque)
{ return redeemCheque(world, sessionId, command); }
}
const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots;
const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null);
if (!taken.ok)
{ throw userError("That slot is empty."); }
const def = itemDefinition(taken.taken.itemId);
const dest = toKey === "vault" ? vault : inventory;
const inserted = insertStack(dest.slots, taken.taken, def);
if (!inserted.ok)
{ throw userError("Not enough space."); }
if (fromKey === "vault")
{ vault.slots = taken.slots; }
if (toKey === "vault")
{
const inserted = insertStackGrowable(vault.slots, taken.taken, def);
inventory.slots = taken.slots;
vault.slots = inserted.slots;
}
else
{ inventory.slots = taken.slots; }
dest.slots = inserted.slots;
{
const inserted = insertStack(inventory.slots, taken.taken, def);
if (!inserted.ok)
{ throw userError("Not enough space."); }
vault.slots = taken.slots;
inventory.slots = inserted.slots;
}
return { events: [], private: bagView(world.ecs, handle), bank: true };
}
function getBlankCheques (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
requireBank(world, handle);
const inventory = ensureInventory(world.ecs, handle);
const have = countItemInSlots(inventory.slots, ItemId.blankCheque);
const need = Math.max(0, BLANK_CHEQUE_CARRY_CAP - have);
if (!need)
{ return { events: [], private: bagView(world.ecs, handle), bank: true }; }
const def = itemDefinition(ItemId.blankCheque);
const inserted = insertStack(inventory.slots, { itemId: ItemId.blankCheque, quantity: need }, def);
if (!inserted.ok)
{ throw userError("Need inventory space for blank cheques."); }
inventory.slots = inserted.slots;
return { events: [], private: bagView(world.ecs, handle), bank: true };
}
function bankMoney (world, sessionId, command, fromKey, toKey)
function returnBlankCheques (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
requireBank(world, handle);
const amount = Math.max(0, command.amount | 0);
if (!amount)
{ throw userError("Enter an amount."); }
const currency = world.ecs.get(handle, Component.currency) ?? world.ecs.add(handle, Component.currency, { amount: 0 });
const inventory = ensureInventory(world.ecs, handle);
const slot = inventory.slots[command.slotIndex | 0];
if (!slot || slot.itemId !== ItemId.blankCheque)
{ throw userError("Select blank cheques."); }
const quantity = command.quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, command.quantity | 0));
const taken = takeFromSlot(inventory.slots, command.slotIndex | 0, quantity);
if (!taken.ok)
{ throw userError("Select blank cheques."); }
inventory.slots = taken.slots;
return { events: [], private: bagView(world.ecs, handle), bank: true };
}
function writeCheque (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
const inventory = ensureInventory(world.ecs, handle);
const vault = ensureVault(world.ecs, handle);
const from = fromKey === "vault" ? vault : currency;
const to = toKey === "vault" ? vault : currency;
const fromAmount = fromKey === "vault" ? vault.currency : currency.amount;
if (fromAmount < amount)
{ throw userError("Not enough coins."); }
if (fromKey === "vault")
{ vault.currency -= amount; }
const slotIndex = command.slotIndex | 0;
const blankSlot = inventory.slots[slotIndex];
if (!blankSlot || blankSlot.itemId !== ItemId.blankCheque)
{ throw userError("Select a blank cheque."); }
const vaultSlot = vault.slots[command.vaultSlotIndex | 0];
if (!vaultSlot)
{ throw userError("Select vault goods to reserve."); }
const def = itemDefinition(vaultSlot.itemId);
if (!def)
{ throw userError("Unknown item."); }
const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);
const available = countItemInSlots(vault.slots, vaultSlot.itemId);
if (available < quantity)
{ throw userError("Not enough unreserved goods in the vault."); }
if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))
{ throw userError("Need a free inventory slot for the filled cheque."); }
const pulled = takeMatchingFromSlots(vault.slots, {
itemId: vaultSlot.itemId,
quantity,
instance: def.uniqueInstance ? vaultSlot.instance : null
});
if (!pulled.ok)
{ throw userError("Not enough unreserved goods in the vault."); }
const chequeId = randomUUID();
const reservedStack = {
itemId: pulled.taken.itemId,
quantity: pulled.taken.quantity,
origin: pulled.taken.origin ?? null,
instance: pulled.taken.instance ?? null,
chequeId
};
vault.slots = pulled.slots;
vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack];
const filled = {
itemId: ItemId.filledCheque,
quantity: 1,
origin: null,
instance: {
kind: "filled-cheque",
chequeId,
issuerCharacterId: command.characterId,
itemId: pulled.taken.itemId,
quantity: pulled.taken.quantity,
reservedInstance: pulled.taken.instance ?? null,
createdAt: Date.now()
}
};
const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1);
inventory.slots = blankTaken.slots;
if (!inventory.slots[slotIndex])
{ inventory.slots[slotIndex] = filled; }
else
{ currency.amount -= amount; }
if (toKey === "vault")
{ vault.currency += amount; }
{
const free = inventory.slots.findIndex((entry) => !entry);
inventory.slots[free] = filled;
}
return { events: [], private: bagView(world.ecs, handle) };
}
function redeemCheque (world, sessionId, command)
{
const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
requireBank(world, handle);
const inventory = ensureInventory(world.ecs, handle);
const vault = ensureVault(world.ecs, handle);
const slotIndex = command.slotIndex | 0;
const slot = inventory.slots[slotIndex];
if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")
{ throw userError("Select a filled cheque."); }
const chequeId = slot.instance.chequeId;
const issuerId = slot.instance.issuerCharacterId;
const goodsDef = itemDefinition(slot.instance.itemId);
if (!goodsDef)
{ throw userError("Unknown reserved goods."); }
const chequeTaken = takeFromSlot(inventory.slots, slotIndex, 1);
if (!chequeTaken.ok)
{ throw userError("Select a filled cheque."); }
inventory.slots = chequeTaken.slots;
let reservedStack = null;
if (Number(issuerId) === Number(command.characterId))
{
const index = (vault.reserved ?? []).findIndex((entry) => entry?.chequeId === chequeId);
if (index < 0)
{
inventory.slots[slotIndex] = chequeTaken.taken;
throw userError("That cheque cannot be redeemed.");
}
reservedStack = cloneStack(vault.reserved[index]);
vault.reserved = vault.reserved.filter((_, i) => i !== index);
}
else
{ currency.amount += amount; }
{
const release = world.releaseChequeReservation?.(issuerId, chequeId);
if (!release?.ok)
{
inventory.slots[slotIndex] = chequeTaken.taken;
throw userError(release?.error ?? "That cheque cannot be redeemed.");
}
reservedStack = release.stack;
}
const inserted = insertStackGrowable(vault.slots, {
itemId: reservedStack.itemId,
quantity: reservedStack.quantity,
origin: reservedStack.origin ?? null,
origins: reservedStack.origins ?? null,
instance: reservedStack.instance ?? null
}, goodsDef);
if (!inserted.ok)
{
inventory.slots[slotIndex] = chequeTaken.taken;
if (Number(issuerId) === Number(command.characterId))
{ vault.reserved = [...(vault.reserved ?? []), reservedStack]; }
else
{ world.restoreChequeReservation?.(issuerId, reservedStack); }
throw userError("Your vault cannot hold those goods.");
}
vault.slots = inserted.slots;
return { events: [], private: bagView(world.ecs, handle), bank: true };
}
@@ -327,13 +568,12 @@ function claimInheritance (world, sessionId, command)
remainder.push(stack);
continue;
}
const inserted = insertStack(vault.slots, stack, def);
const inserted = insertStackGrowable(vault.slots, stack, def);
if (inserted.ok)
{ vault.slots = inserted.slots; }
else
{ remainder.push(stack); }
}
vault.currency += command.currency | 0;
return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
}
@@ -443,7 +683,11 @@ function nearBank (world, tileX, tileY)
function ensureInventory (ecs, handle)
{
return ecs.get(handle, Component.inventory) ?? ecs.add(handle, Component.inventory, { slots: emptySlots() });
let inventory = ecs.get(handle, Component.inventory);
if (!inventory)
{ inventory = ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
return inventory;
}
function ensureEquipment (ecs, handle)
@@ -453,7 +697,14 @@ function ensureEquipment (ecs, handle)
function ensureVault (ecs, handle)
{
return ecs.get(handle, Component.vault) ?? ecs.add(handle, Component.vault, { slots: emptySlots(), currency: 0 });
let vault = ecs.get(handle, Component.vault);
if (!vault)
{ vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); }
if (!Array.isArray(vault.slots))
{ vault.slots = []; }
if (!Array.isArray(vault.reserved))
{ vault.reserved = []; }
return vault;
}
function userError (message)
@@ -1,13 +1,23 @@import { Component } from "../ecs/components.js";import { Component } from "../ecs/components.js";import { syncPlayerHealth } from "../skills/service.js";import { canEquipItem } from "../../../shared/equipment/stats.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { ItemId, itemDefinition, itemSpriteName, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";import { ItemId, itemDefinition, itemSpriteName, stackDisplayLabel, LETTER_MAX_BODY_CHARS, BLANK_CHEQUE_CARRY_CAP } from "../../../shared/definitions/items.js";import {import { emptyEquipment, emptyEquipment, emptySlots, emptySlots, insertStack, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicEquipment, publicEquipment, publicSlots, publicSlots, takeFromSlot takeFromSlot, takeMatchingFromSlots, countItemInSlots, cloneStack, singleItemFromStack, stackQuantity} from "../../../shared/items/inventory.js";} from "../../../shared/items/inventory.js";import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";@@ -22,7 +32,7 @@ export function publicGroundItem (item) tileY: item.tileY, tileY: item.tileY, itemId: item.stack.itemId, itemId: item.stack.itemId, quantity: item.stack.quantity, quantity: item.stack.quantity, displayName: def?.displayName ?? "Item", displayName: stackDisplayLabel(item.stack), sprite: itemSpriteName(item.stack.itemId, item.stack.instance), sprite: itemSpriteName(item.stack.itemId, item.stack.instance), expiresAt: item.expiresAt expiresAt: item.expiresAt }; };@@ -30,29 +40,30 @@ export function publicGroundItem (item)export function bagView (ecs, handle)export function bagView (ecs, handle){{ const vault = normalizeVault(ecs.get(handle, Component.vault)); return { return { inventory: publicSlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots()), inventory: publicSlots(normalizeInventorySlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots())), equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()), equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()), currency: ecs.get(handle, Component.currency)?.amount ?? 0, vault: publicSlots(vault.slots), vault: publicSlots(ecs.get(handle, Component.vault)?.slots ?? emptySlots()), vaultReserved: publicSlots(vault.reserved) vaultCurrency: ecs.get(handle, Component.vault)?.currency ?? 0 }; };}}export function applyBagView (ecs, handle, bag)export function applyBagView (ecs, handle, bag){{ const inventory = ensureInventory(ecs, handle); const inventory = ensureInventory(ecs, handle); inventory.slots = publicSlots(bag.inventory ?? emptySlots()); inventory.slots = normalizeInventorySlots(publicSlots(bag.inventory ?? emptySlots())); const equipment = ensureEquipment(ecs, handle); const equipment = ensureEquipment(ecs, handle); const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment()); const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment()); equipment.slots = nextEquip.slots; equipment.slots = nextEquip.slots; let currency = ecs.get(handle, Component.currency); if (!currency) { currency = ecs.add(handle, Component.currency, { amount: 0 }); } currency.amount = bag.currency | 0; const vault = ensureVault(ecs, handle); const vault = ensureVault(ecs, handle); vault.slots = publicSlots(bag.vault ?? emptySlots()); const normalized = normalizeVault( vault.currency = bag.vaultCurrency | 0; bag.vaultReserved != null || (bag.vault && !Array.isArray(bag.vault)) ? { slots: bag.vault, reserved: bag.vaultReserved } : bag.vault ); vault.slots = publicSlots(normalized.slots); vault.reserved = publicSlots(normalized.reserved); return bagView(ecs, handle); return bagView(ecs, handle);}}@@ -74,10 +85,14 @@ export function handleItemCommand (world, sessionId, command, now) return bankMove(world, sessionId, command, "inventory", "vault"); return bankMove(world, sessionId, command, "inventory", "vault"); case "bank-withdraw": case "bank-withdraw": return bankMove(world, sessionId, command, "vault", "inventory"); return bankMove(world, sessionId, command, "vault", "inventory"); case "bank-deposit-money": case "get-blank-cheques": return bankMoney(world, sessionId, command, "currency", "vault"); return getBlankCheques(world, sessionId, command); case "bank-withdraw-money": case "return-blank-cheques": return bankMoney(world, sessionId, command, "vault", "currency"); return returnBlankCheques(world, sessionId, command); case "write-cheque": return writeCheque(world, sessionId, command); case "redeem-cheque": return redeemCheque(world, sessionId, command); case "claim-inheritance": case "claim-inheritance": return claimInheritance(world, sessionId, command); return claimInheritance(world, sessionId, command); case "write-letter": case "write-letter":@@ -86,6 +101,8 @@ export function handleItemCommand (world, sessionId, command, now) return editLetter(world, sessionId, command); return editLetter(world, sessionId, command); case "open-letter": case "open-letter": return openLetter(world, sessionId, command); return openLetter(world, sessionId, command); case "eat-item": return eatItem(world, sessionId, command); default: default: return null; return null; } }@@ -196,13 +213,41 @@ function pickupItem (world, sessionId, command) if (!def) if (!def) { throw userError("Unknown item."); } { throw userError("Unknown item."); } const inventory = ensureInventory(world.ecs, handle); const inventory = ensureInventory(world.ecs, handle); const inserted = insertStack(inventory.slots, item.stack, def); let stackToAdd = item.stack; if (item.stack.itemId === ItemId.blankCheque) { const have = countItemInSlots(inventory.slots, ItemId.blankCheque); const room = BLANK_CHEQUE_CARRY_CAP - have; if (room <= 0) { throw userError(`You already carry ${BLANK_CHEQUE_CARRY_CAP} blank cheques.`); } const takeQty = Math.min(item.stack.quantity, room); stackToAdd = { ...item.stack, quantity: takeQty }; } const inserted = insertStack(inventory.slots, stackToAdd, def); if (!inserted.ok) if (!inserted.ok) { throw userError("Your inventory cannot hold that."); } { throw userError("Your inventory cannot hold that."); } inventory.slots = inserted.slots; inventory.slots = inserted.slots; removeGroundItem(world, item.groundItemId); const events = []; if (item.stack.itemId === ItemId.blankCheque && stackToAdd.quantity < item.stack.quantity) { item.stack.quantity -= stackToAdd.quantity; events.push({ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }); } else { removeGroundItem(world, item.groundItemId); events.push({ type: "ground-item-despawn", ...publicGroundItem(item) }); } return { return { events: [{ type: "ground-item-despawn", ...publicGroundItem(item) }], events, private: bagView(world.ecs, handle) private: bagView(world.ecs, handle) }; };}}@@ -212,30 +257,48 @@ function equipItem (world, sessionId, command) const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const inventory = ensureInventory(world.ecs, handle); const equipment = ensureEquipment(world.ecs, handle); const equipment = ensureEquipment(world.ecs, handle); const taken = takeFromSlot(inventory.slots, command.slotIndex, 1); const slotIndex = command.slotIndex | 0; if (!taken.ok) const source = inventory.slots[slotIndex]; if (!source || stackQuantity(source.quantity) <= 0) { throw userError("That inventory slot is empty."); } { throw userError("That inventory slot is empty."); } const taken = takeFromSlot(inventory.slots, slotIndex, 1); if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1) { throw userError("That inventory slot is empty."); } if (taken.taken.itemId === ItemId.coins) { inventory.slots = insertStack(taken.slots, taken.taken, itemDefinition(ItemId.coins)).slots; throw userError("Coins cannot be equipped."); } const def = itemDefinition(taken.taken.itemId); const def = itemDefinition(taken.taken.itemId); const slot = def?.equipment?.slot; const slot = def?.equipment?.slot; if (!slot) if (!slot) { { inventory.slots = insertStack(inventory.slots, taken.taken, def).slots; inventory.slots = insertStack(taken.slots, taken.taken, def).slots; throw userError("That item cannot be equipped."); throw userError("That item cannot be equipped."); } } const skills = world.ecs.get(handle, Component.skills); const equipCheck = canEquipItem(skills, def); if (!equipCheck.ok) { inventory.slots = insertStack(taken.slots, taken.taken, def).slots; throw userError(equipCheck.reason); } const toEquip = singleItemFromStack(taken.taken); const previous = equipment.slots[slot]; const previous = equipment.slots[slot]; if (previous) if (previous) { { const back = insertStack(taken.slots, previous, itemDefinition(previous.itemId)); const previousSingle = singleItemFromStack(previous); const back = insertStack(taken.slots, previousSingle, itemDefinition(previous.itemId)); if (!back.ok) if (!back.ok) { { inventory.slots = insertStack(inventory.slots, taken.taken, def).slots; inventory.slots = insertStack(inventory.slots, toEquip, def).slots; throw userError("No inventory space to unequip the current item."); throw userError("No inventory space to unequip the current item."); } } inventory.slots = back.slots; inventory.slots = back.slots; } } else else { inventory.slots = taken.slots; } { inventory.slots = taken.slots; } equipment.slots[slot] = { ...taken.taken, quantity: 1 }; equipment.slots[slot] = toEquip; return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true }; return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };}}@@ -248,7 +311,8 @@ function unequipItem (world, sessionId, command) if (!worn) if (!worn) { throw userError("Nothing is equipped there."); } { throw userError("Nothing is equipped there."); } const def = itemDefinition(worn.itemId); const def = itemDefinition(worn.itemId); const inserted = insertStack(inventory.slots, worn, def); const single = singleItemFromStack(worn); const inserted = insertStack(inventory.slots, single, def); if (!inserted.ok) if (!inserted.ok) { throw userError("Your inventory cannot hold that."); } { throw userError("Your inventory cannot hold that."); } inventory.slots = inserted.slots; inventory.slots = inserted.slots;@@ -256,6 +320,32 @@ function unequipItem (world, sessionId, command) return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true }; return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };}}function eatItem (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); syncPlayerHealth(world.ecs, handle); const inventory = ensureInventory(world.ecs, handle); const health = world.ecs.get(handle, Component.health); if (!health) { throw userError("You cannot eat right now."); } if ((health.current | 0) >= (health.max | 0)) { throw userError("You are already at full health."); } const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || stackQuantity(slot.quantity) <= 0) { throw userError("That inventory slot is empty."); } const def = itemDefinition(slot.itemId); const healing = def?.healing ?? 0; if (healing <= 0) { throw userError("That cannot be eaten."); } const taken = takeFromSlot(inventory.slots, slotIndex, 1); if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1) { throw userError("That inventory slot is empty."); } inventory.slots = taken.slots; health.current = Math.min(health.max | 0, (health.current | 0) + healing); return { events: [], private: bagView(world.ecs, handle) };}function openBank (world, sessionId, command)function openBank (world, sessionId, command){{ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const { handle } = world.requireOwnedEntity(sessionId, command.characterId);@@ -271,45 +361,196 @@ function bankMove (world, sessionId, command, fromKey, toKey) requireBank(world, handle); requireBank(world, handle); const inventory = ensureInventory(world.ecs, handle); const inventory = ensureInventory(world.ecs, handle); const vault = ensureVault(world.ecs, handle); const vault = ensureVault(world.ecs, handle); if (fromKey === "inventory" && toKey === "vault") { const slot = inventory.slots[command.slotIndex | 0]; if (slot?.itemId === ItemId.filledCheque) { return redeemCheque(world, sessionId, command); } } const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots; const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots; const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null); const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null); if (!taken.ok) if (!taken.ok) { throw userError("That slot is empty."); } { throw userError("That slot is empty."); } const def = itemDefinition(taken.taken.itemId); const def = itemDefinition(taken.taken.itemId); const dest = toKey === "vault" ? vault : inventory; if (toKey === "vault") const inserted = insertStack(dest.slots, taken.taken, def); { if (!inserted.ok) const inserted = insertStackGrowable(vault.slots, taken.taken, def); { throw userError("Not enough space."); } inventory.slots = taken.slots; if (fromKey === "vault") vault.slots = inserted.slots; { vault.slots = taken.slots; } } else else { inventory.slots = taken.slots; } { dest.slots = inserted.slots; const inserted = insertStack(inventory.slots, taken.taken, def); if (!inserted.ok) { throw userError("Not enough space."); } vault.slots = taken.slots; inventory.slots = inserted.slots; } return { events: [], private: bagView(world.ecs, handle), bank: true };}function getBlankCheques (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); const inventory = ensureInventory(world.ecs, handle); const have = countItemInSlots(inventory.slots, ItemId.blankCheque); const need = Math.max(0, BLANK_CHEQUE_CARRY_CAP - have); if (!need) { return { events: [], private: bagView(world.ecs, handle), bank: true }; } const def = itemDefinition(ItemId.blankCheque); const inserted = insertStack(inventory.slots, { itemId: ItemId.blankCheque, quantity: need }, def); if (!inserted.ok) { throw userError("Need inventory space for blank cheques."); } inventory.slots = inserted.slots; return { events: [], private: bagView(world.ecs, handle), bank: true }; return { events: [], private: bagView(world.ecs, handle), bank: true };}}function bankMoney (world, sessionId, command, fromKey, toKey)function returnBlankCheques (world, sessionId, command){{ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); requireBank(world, handle); const amount = Math.max(0, command.amount | 0); const inventory = ensureInventory(world.ecs, handle); if (!amount) const slot = inventory.slots[command.slotIndex | 0]; { throw userError("Enter an amount."); } if (!slot || slot.itemId !== ItemId.blankCheque) const currency = world.ecs.get(handle, Component.currency) ?? world.ecs.add(handle, Component.currency, { amount: 0 }); { throw userError("Select blank cheques."); } const quantity = command.quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, command.quantity | 0)); const taken = takeFromSlot(inventory.slots, command.slotIndex | 0, quantity); if (!taken.ok) { throw userError("Select blank cheques."); } inventory.slots = taken.slots; return { events: [], private: bagView(world.ecs, handle), bank: true };}function writeCheque (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); const inventory = ensureInventory(world.ecs, handle); const vault = ensureVault(world.ecs, handle); const vault = ensureVault(world.ecs, handle); const from = fromKey === "vault" ? vault : currency; const slotIndex = command.slotIndex | 0; const to = toKey === "vault" ? vault : currency; const blankSlot = inventory.slots[slotIndex]; const fromAmount = fromKey === "vault" ? vault.currency : currency.amount; if (!blankSlot || blankSlot.itemId !== ItemId.blankCheque) if (fromAmount < amount) { throw userError("Select a blank cheque."); } { throw userError("Not enough coins."); } const vaultSlot = vault.slots[command.vaultSlotIndex | 0]; if (fromKey === "vault") if (!vaultSlot) { vault.currency -= amount; } { throw userError("Select vault goods to reserve."); } const def = itemDefinition(vaultSlot.itemId); if (!def) { throw userError("Unknown item."); } const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0); const available = countItemInSlots(vault.slots, vaultSlot.itemId); if (available < quantity) { throw userError("Not enough unreserved goods in the vault."); } if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry)) { throw userError("Need a free inventory slot for the filled cheque."); } const pulled = takeMatchingFromSlots(vault.slots, { itemId: vaultSlot.itemId, quantity, instance: def.uniqueInstance ? vaultSlot.instance : null }); if (!pulled.ok) { throw userError("Not enough unreserved goods in the vault."); } const chequeId = randomUUID(); const reservedStack = { itemId: pulled.taken.itemId, quantity: pulled.taken.quantity, origin: pulled.taken.origin ?? null, instance: pulled.taken.instance ?? null, chequeId }; vault.slots = pulled.slots; vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack]; const filled = { itemId: ItemId.filledCheque, quantity: 1, origin: null, instance: { kind: "filled-cheque", chequeId, issuerCharacterId: command.characterId, itemId: pulled.taken.itemId, quantity: pulled.taken.quantity, reservedInstance: pulled.taken.instance ?? null, createdAt: Date.now() } }; const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1); inventory.slots = blankTaken.slots; if (!inventory.slots[slotIndex]) { inventory.slots[slotIndex] = filled; } else else { currency.amount -= amount; } { if (toKey === "vault") const free = inventory.slots.findIndex((entry) => !entry); { vault.currency += amount; } inventory.slots[free] = filled; } return { events: [], private: bagView(world.ecs, handle) };}function redeemCheque (world, sessionId, command){ const { handle } = world.requireOwnedEntity(sessionId, command.characterId); requireBank(world, handle); const inventory = ensureInventory(world.ecs, handle); const vault = ensureVault(world.ecs, handle); const slotIndex = command.slotIndex | 0; const slot = inventory.slots[slotIndex]; if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque") { throw userError("Select a filled cheque."); } const chequeId = slot.instance.chequeId; const issuerId = slot.instance.issuerCharacterId; const goodsDef = itemDefinition(slot.instance.itemId); if (!goodsDef) { throw userError("Unknown reserved goods."); } const chequeTaken = takeFromSlot(inventory.slots, slotIndex, 1); if (!chequeTaken.ok) { throw userError("Select a filled cheque."); } inventory.slots = chequeTaken.slots; let reservedStack = null; if (Number(issuerId) === Number(command.characterId)) { const index = (vault.reserved ?? []).findIndex((entry) => entry?.chequeId === chequeId); if (index < 0) { inventory.slots[slotIndex] = chequeTaken.taken; throw userError("That cheque cannot be redeemed."); } reservedStack = cloneStack(vault.reserved[index]); vault.reserved = vault.reserved.filter((_, i) => i !== index); } else else { currency.amount += amount; } { const release = world.releaseChequeReservation?.(issuerId, chequeId); if (!release?.ok) { inventory.slots[slotIndex] = chequeTaken.taken; throw userError(release?.error ?? "That cheque cannot be redeemed."); } reservedStack = release.stack; } const inserted = insertStackGrowable(vault.slots, { itemId: reservedStack.itemId, quantity: reservedStack.quantity, origin: reservedStack.origin ?? null, origins: reservedStack.origins ?? null, instance: reservedStack.instance ?? null }, goodsDef); if (!inserted.ok) { inventory.slots[slotIndex] = chequeTaken.taken; if (Number(issuerId) === Number(command.characterId)) { vault.reserved = [...(vault.reserved ?? []), reservedStack]; } else { world.restoreChequeReservation?.(issuerId, reservedStack); } throw userError("Your vault cannot hold those goods."); } vault.slots = inserted.slots; return { events: [], private: bagView(world.ecs, handle), bank: true }; return { events: [], private: bagView(world.ecs, handle), bank: true };}}@@ -327,13 +568,12 @@ function claimInheritance (world, sessionId, command) remainder.push(stack); remainder.push(stack); continue; continue; } } const inserted = insertStack(vault.slots, stack, def); const inserted = insertStackGrowable(vault.slots, stack, def); if (inserted.ok) if (inserted.ok) { vault.slots = inserted.slots; } { vault.slots = inserted.slots; } else else { remainder.push(stack); } { remainder.push(stack); } } } vault.currency += command.currency | 0; return { events: [], private: bagView(world.ecs, handle), bank: true, remainder }; return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };}}@@ -443,7 +683,11 @@ function nearBank (world, tileX, tileY)function ensureInventory (ecs, handle)function ensureInventory (ecs, handle){{ return ecs.get(handle, Component.inventory) ?? ecs.add(handle, Component.inventory, { slots: emptySlots() }); let inventory = ecs.get(handle, Component.inventory); if (!inventory) { inventory = ecs.add(handle, Component.inventory, { slots: emptySlots() }); } inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots()); return inventory;}}function ensureEquipment (ecs, handle)function ensureEquipment (ecs, handle)@@ -453,7 +697,14 @@ function ensureEquipment (ecs, handle)function ensureVault (ecs, handle)function ensureVault (ecs, handle){{ return ecs.get(handle, Component.vault) ?? ecs.add(handle, Component.vault, { slots: emptySlots(), currency: 0 }); let vault = ecs.get(handle, Component.vault); if (!vault) { vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); } if (!Array.isArray(vault.slots)) { vault.slots = []; } if (!Array.isArray(vault.reserved)) { vault.reserved = []; } return vault;}}function userError (message)function userError (message)@@ -1,6 +1,7 @@
import { openDatabase } from "./database.js";
import { emptyEquipment, emptySlots, insertStack, publicSlots } from "../../../shared/items/inventory.js";
import { STARTER_CURRENCY, STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";
import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
import { STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";
import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
const STATE_SCHEMA = `
CREATE TABLE IF NOT EXISTS accounts (
@@ -56,7 +57,8 @@ CREATE TABLE IF NOT EXISTS character_bags (
equipment_blob TEXT NOT NULL,
currency INTEGER NOT NULL DEFAULT 0,
vault_blob TEXT NOT NULL,
vault_currency INTEGER NOT NULL DEFAULT 0
vault_currency INTEGER NOT NULL DEFAULT 0,
skills_blob TEXT NOT NULL DEFAULT '{}'
);
CREATE TABLE IF NOT EXISTS account_inheritance (
@@ -100,6 +102,16 @@ export class StateDatabase
{
this.db = openDatabase(filePath);
this.db.exec(STATE_SCHEMA);
this.#migrateSchema();
}
#migrateSchema ()
{
const columns = this.db.prepare("PRAGMA table_info(character_bags)").all();
if (!columns.some((column) => column.name === "skills_blob"))
{
this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
}
}
getAccountBySubject (authSubject)
@@ -390,14 +402,14 @@ export class StateDatabase
}
this.db.prepare(`
INSERT INTO character_bags (
character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency
) VALUES (?, ?, ?, ?, ?, 0)
character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
) VALUES (?, ?, ?, 0, ?, 0, ?)
`).run(
characterId,
JSON.stringify(slots),
JSON.stringify(emptyEquipment()),
STARTER_CURRENCY,
JSON.stringify(emptySlots())
JSON.stringify({ slots: [], reserved: [] }),
JSON.stringify(storedSkillXp(defaultPlayerSkills()))
);
return this.getBag(characterId);
}
@@ -415,16 +427,43 @@ export class StateDatabase
saveBag (characterId, bag)
{
this.#ensureBag(characterId);
const migrated = migrateBagCoins(bag);
const vault = normalizeVault(
migrated.vaultReserved != null
? { slots: migrated.vault, reserved: migrated.vaultReserved }
: migrated.vault
);
this.db.prepare(`
UPDATE character_bags
SET inventory_blob = ?, equipment_blob = ?, currency = ?, vault_blob = ?, vault_currency = ?
SET inventory_blob = ?, equipment_blob = ?, currency = 0, vault_blob = ?, vault_currency = 0
WHERE character_id = ?
`).run(
JSON.stringify(bag.inventory ?? emptySlots()),
JSON.stringify(bag.equipment ?? emptyEquipment()),
bag.currency ?? 0,
JSON.stringify(bag.vault ?? emptySlots()),
bag.vaultCurrency ?? 0,
JSON.stringify(normalizeInventorySlots(migrated.inventory ?? emptySlots())),
JSON.stringify(migrated.equipment ?? emptyEquipment()),
JSON.stringify({ slots: vault.slots, reserved: vault.reserved }),
characterId
);
}
getSkills (characterId)
{
const row = this.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?").get(characterId);
if (row)
{ return normalizePlayerSkills(JSON.parse(row.skills_blob || "{}")); }
if (this.getCharacter(characterId))
{
this.#ensureBag(characterId);
return this.getSkills(characterId);
}
return null;
}
saveSkills (characterId, skills)
{
this.#ensureBag(characterId);
const xp = storedSkillXp(skills?.xp ? skills : { xp: skills });
this.db.prepare("UPDATE character_bags SET skills_blob = ? WHERE character_id = ?").run(
JSON.stringify({ xp }),
characterId
);
}
@@ -433,21 +472,22 @@ export class StateDatabase
{
const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
if (!row)
{ return { accountId, slots: emptySlots(), currency: 0 }; }
return {
{ return { accountId, slots: emptySlots() }; }
return migrateInheritanceCoins({
accountId,
slots: JSON.parse(row.slots_blob),
currency: row.currency
};
});
}
saveInheritance (accountId, inheritance)
{
const migrated = migrateInheritanceCoins(inheritance);
this.db.prepare(`
INSERT INTO account_inheritance (account_id, slots_blob, currency)
VALUES (?, ?, ?)
ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = excluded.currency
`).run(accountId, JSON.stringify(inheritance.slots ?? emptySlots()), inheritance.currency ?? 0);
VALUES (?, ?, 0)
ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = 0
`).run(accountId, JSON.stringify(migrated.slots ?? emptySlots()));
}
#moveGoodsToInheritance (character)
@@ -455,15 +495,35 @@ export class StateDatabase
const bag = this.getBag(character.character_id) ?? {
inventory: emptySlots(),
equipment: emptyEquipment(),
currency: 0,
vault: emptySlots(),
vaultCurrency: 0
vault: [],
vaultReserved: []
};
const inheritance = this.getInheritance(character.account_id);
const vault = normalizeVault(
bag.vaultReserved != null
? { slots: bag.vault, reserved: bag.vaultReserved }
: bag.vault
);
// Void outstanding cheques issued by this character: reservations return to available vault.
for (const reserved of vault.reserved ?? [])
{
const stack = {
itemId: reserved.itemId,
quantity: reserved.quantity,
origin: reserved.origin ?? null,
instance: reserved.instance ?? null
};
const def = itemDefinition(stack.itemId);
if (!def)
{ continue; }
const restored = insertStackGrowable(vault.slots, stack, def);
vault.slots = restored.slots;
}
vault.reserved = [];
const incoming = [
...(bag.inventory ?? []),
...Object.values(bag.equipment?.slots ?? {}),
...(bag.vault ?? [])
...(vault.slots ?? [])
].filter(Boolean);
let slots = inheritance.slots ?? emptySlots();
for (const stack of incoming)
@@ -486,8 +546,7 @@ export class StateDatabase
}
}
this.saveInheritance(character.account_id, {
slots: publicSlots(slots),
currency: (inheritance.currency ?? 0) + (bag.currency ?? 0) + (bag.vaultCurrency ?? 0)
slots: publicSlots(slots)
});
}
@@ -630,14 +689,16 @@ function parseGroundItem (row)
function parseBag (row, characterId)
{
return {
const vault = normalizeVault(JSON.parse(row.vault_blob));
return migrateBagCoins({
characterId,
inventory: JSON.parse(row.inventory_blob),
inventory: normalizeInventorySlots(JSON.parse(row.inventory_blob)),
equipment: JSON.parse(row.equipment_blob),
currency: row.currency,
vault: JSON.parse(row.vault_blob),
vault: vault.slots,
vaultReserved: vault.reserved,
vaultCurrency: row.vault_currency
};
});
}
function parseCourierTransit (row)
@@ -1,6 +1,7 @@import { openDatabase } from "./database.js";import { openDatabase } from "./database.js";import { emptyEquipment, emptySlots, insertStack, publicSlots } from "../../../shared/items/inventory.js";import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";import { STARTER_CURRENCY, STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";import { STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";const STATE_SCHEMA = `const STATE_SCHEMA = `CREATE TABLE IF NOT EXISTS accounts (CREATE TABLE IF NOT EXISTS accounts (@@ -56,7 +57,8 @@ CREATE TABLE IF NOT EXISTS character_bags ( equipment_blob TEXT NOT NULL, equipment_blob TEXT NOT NULL, currency INTEGER NOT NULL DEFAULT 0, currency INTEGER NOT NULL DEFAULT 0, vault_blob TEXT NOT NULL, vault_blob TEXT NOT NULL, vault_currency INTEGER NOT NULL DEFAULT 0 vault_currency INTEGER NOT NULL DEFAULT 0, skills_blob TEXT NOT NULL DEFAULT '{}'););CREATE TABLE IF NOT EXISTS account_inheritance (CREATE TABLE IF NOT EXISTS account_inheritance (@@ -100,6 +102,16 @@ export class StateDatabase { { this.db = openDatabase(filePath); this.db = openDatabase(filePath); this.db.exec(STATE_SCHEMA); this.db.exec(STATE_SCHEMA); this.#migrateSchema(); } #migrateSchema () { const columns = this.db.prepare("PRAGMA table_info(character_bags)").all(); if (!columns.some((column) => column.name === "skills_blob")) { this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'"); } } } getAccountBySubject (authSubject) getAccountBySubject (authSubject)@@ -390,14 +402,14 @@ export class StateDatabase } } this.db.prepare(` this.db.prepare(` INSERT INTO character_bags ( INSERT INTO character_bags ( character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob ) VALUES (?, ?, ?, ?, ?, 0) ) VALUES (?, ?, ?, 0, ?, 0, ?) `).run( `).run( characterId, characterId, JSON.stringify(slots), JSON.stringify(slots), JSON.stringify(emptyEquipment()), JSON.stringify(emptyEquipment()), STARTER_CURRENCY, JSON.stringify({ slots: [], reserved: [] }), JSON.stringify(emptySlots()) JSON.stringify(storedSkillXp(defaultPlayerSkills())) ); ); return this.getBag(characterId); return this.getBag(characterId); } }@@ -415,16 +427,43 @@ export class StateDatabase saveBag (characterId, bag) saveBag (characterId, bag) { { this.#ensureBag(characterId); this.#ensureBag(characterId); const migrated = migrateBagCoins(bag); const vault = normalizeVault( migrated.vaultReserved != null ? { slots: migrated.vault, reserved: migrated.vaultReserved } : migrated.vault ); this.db.prepare(` this.db.prepare(` UPDATE character_bags UPDATE character_bags SET inventory_blob = ?, equipment_blob = ?, currency = ?, vault_blob = ?, vault_currency = ? SET inventory_blob = ?, equipment_blob = ?, currency = 0, vault_blob = ?, vault_currency = 0 WHERE character_id = ? WHERE character_id = ? `).run( `).run( JSON.stringify(bag.inventory ?? emptySlots()), JSON.stringify(normalizeInventorySlots(migrated.inventory ?? emptySlots())), JSON.stringify(bag.equipment ?? emptyEquipment()), JSON.stringify(migrated.equipment ?? emptyEquipment()), bag.currency ?? 0, JSON.stringify({ slots: vault.slots, reserved: vault.reserved }), JSON.stringify(bag.vault ?? emptySlots()), characterId bag.vaultCurrency ?? 0, ); } getSkills (characterId) { const row = this.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?").get(characterId); if (row) { return normalizePlayerSkills(JSON.parse(row.skills_blob || "{}")); } if (this.getCharacter(characterId)) { this.#ensureBag(characterId); return this.getSkills(characterId); } return null; } saveSkills (characterId, skills) { this.#ensureBag(characterId); const xp = storedSkillXp(skills?.xp ? skills : { xp: skills }); this.db.prepare("UPDATE character_bags SET skills_blob = ? WHERE character_id = ?").run( JSON.stringify({ xp }), characterId characterId ); ); } }@@ -433,21 +472,22 @@ export class StateDatabase { { const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId); const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId); if (!row) if (!row) { return { accountId, slots: emptySlots(), currency: 0 }; } { return { accountId, slots: emptySlots() }; } return { return migrateInheritanceCoins({ accountId, accountId, slots: JSON.parse(row.slots_blob), slots: JSON.parse(row.slots_blob), currency: row.currency currency: row.currency }; }); } } saveInheritance (accountId, inheritance) saveInheritance (accountId, inheritance) { { const migrated = migrateInheritanceCoins(inheritance); this.db.prepare(` this.db.prepare(` INSERT INTO account_inheritance (account_id, slots_blob, currency) INSERT INTO account_inheritance (account_id, slots_blob, currency) VALUES (?, ?, ?) VALUES (?, ?, 0) ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = excluded.currency ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = 0 `).run(accountId, JSON.stringify(inheritance.slots ?? emptySlots()), inheritance.currency ?? 0); `).run(accountId, JSON.stringify(migrated.slots ?? emptySlots())); } } #moveGoodsToInheritance (character) #moveGoodsToInheritance (character)@@ -455,15 +495,35 @@ export class StateDatabase const bag = this.getBag(character.character_id) ?? { const bag = this.getBag(character.character_id) ?? { inventory: emptySlots(), inventory: emptySlots(), equipment: emptyEquipment(), equipment: emptyEquipment(), currency: 0, vault: [], vault: emptySlots(), vaultReserved: [] vaultCurrency: 0 }; }; const inheritance = this.getInheritance(character.account_id); const inheritance = this.getInheritance(character.account_id); const vault = normalizeVault( bag.vaultReserved != null ? { slots: bag.vault, reserved: bag.vaultReserved } : bag.vault ); // Void outstanding cheques issued by this character: reservations return to available vault. for (const reserved of vault.reserved ?? []) { const stack = { itemId: reserved.itemId, quantity: reserved.quantity, origin: reserved.origin ?? null, instance: reserved.instance ?? null }; const def = itemDefinition(stack.itemId); if (!def) { continue; } const restored = insertStackGrowable(vault.slots, stack, def); vault.slots = restored.slots; } vault.reserved = []; const incoming = [ const incoming = [ ...(bag.inventory ?? []), ...(bag.inventory ?? []), ...Object.values(bag.equipment?.slots ?? {}), ...Object.values(bag.equipment?.slots ?? {}), ...(bag.vault ?? []) ...(vault.slots ?? []) ].filter(Boolean); ].filter(Boolean); let slots = inheritance.slots ?? emptySlots(); let slots = inheritance.slots ?? emptySlots(); for (const stack of incoming) for (const stack of incoming)@@ -486,8 +546,7 @@ export class StateDatabase } } } } this.saveInheritance(character.account_id, { this.saveInheritance(character.account_id, { slots: publicSlots(slots), slots: publicSlots(slots) currency: (inheritance.currency ?? 0) + (bag.currency ?? 0) + (bag.vaultCurrency ?? 0) }); }); } }@@ -630,14 +689,16 @@ function parseGroundItem (row)function parseBag (row, characterId)function parseBag (row, characterId){{ return { const vault = normalizeVault(JSON.parse(row.vault_blob)); return migrateBagCoins({ characterId, characterId, inventory: JSON.parse(row.inventory_blob), inventory: normalizeInventorySlots(JSON.parse(row.inventory_blob)), equipment: JSON.parse(row.equipment_blob), equipment: JSON.parse(row.equipment_blob), currency: row.currency, currency: row.currency, vault: JSON.parse(row.vault_blob), vault: vault.slots, vaultReserved: vault.reserved, vaultCurrency: row.vault_currency vaultCurrency: row.vault_currency }; });}}function parseCourierTransit (row)function parseCourierTransit (row)@@ -20,6 +20,7 @@ export const WorkerMessage = Object.freeze({
entitiesInRegion: "entitiesInRegion",
inspect: "inspect",
inspectBag: "inspectBag",
inspectSkills: "inspectSkills",
applyBag: "applyBag",
updateFlight: "updateFlight",
chunkIsSimulating: "chunkIsSimulating",
@@ -20,6 +20,7 @@ export const WorkerMessage = Object.freeze({ entitiesInRegion: "entitiesInRegion", entitiesInRegion: "entitiesInRegion", inspect: "inspect", inspect: "inspect", inspectBag: "inspectBag", inspectBag: "inspectBag", inspectSkills: "inspectSkills", applyBag: "applyBag", applyBag: "applyBag", updateFlight: "updateFlight", updateFlight: "updateFlight", chunkIsSimulating: "chunkIsSimulating", chunkIsSimulating: "chunkIsSimulating",@@ -29,7 +29,8 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";
import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
import { mobComponents } from "./spawners.js";
import { DEFAULT_PLAYER_SKILL_LEVELS } from "../../../shared/definitions/skills.js";
import { defaultPlayerSkills } from "../../../shared/skills/state.js";
import { playerMaxHealth } from "../../../shared/definitions/skills.js";
import { CourierService } from "../courier/service.js";
export class Simulation
@@ -72,6 +73,13 @@ export class Simulation
});
this.workers.push(worker);
}
for (const worker of this.workers)
{
if (!worker.world)
{ continue; }
worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId);
worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
}
this.courier = new CourierService({
stateDb: this.stateDb,
worldDb: this.worldDb,
@@ -154,8 +162,11 @@ export class Simulation
{ this.#applyMoveToDirectory(event); }
if (event.type === "entity-despawn")
{ this.#forget(event.entityId); }
if (event.type === "skills-updated")
{ this.#applySkillsUpdated(event); }
this.#persistGroundEvent(event);
events.push(event);
if (event.type !== "skills-updated")
{ events.push(event); }
}
for (const request of result?.transferRequests ?? [])
{ transfers.push({ ...request, fromWorkerId: worker.workerId }); }
@@ -244,10 +255,11 @@ export class Simulation
const bag = this.stateDb.getBag(character.character_id) ?? {
inventory: emptySlots(),
equipment: emptyEquipment(),
currency: 0,
vault: emptySlots(),
vaultCurrency: 0
vault: [],
vaultReserved: []
};
const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
const maxHealth = playerMaxHealth(skills);
const entityId = this.nextEntityId++;
const components = {
position: { tileX, tileY },
@@ -266,11 +278,13 @@ export class Simulation
chunkLoader: { ...DEFAULT_CHUNK_LOADER },
inventory: { slots: bag.inventory ?? emptySlots() },
equipment: bag.equipment ?? emptyEquipment(),
currency: { amount: bag.currency ?? 0 },
vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 },
health: { current: 20, max: 20 },
vault: {
slots: bag.vault ?? [],
reserved: bag.vaultReserved ?? []
},
health: { current: maxHealth, max: maxHealth },
combat: { targetEntityId: null, nextSwingAt: 0 },
skills: { levels: { ...DEFAULT_PLAYER_SKILL_LEVELS } }
skills,
};
this.#ensureCoverage(tileX, tileY, components.chunkLoader);
const workerId = this.#ownerOfTile(tileX, tileY);
@@ -406,6 +420,26 @@ export class Simulation
});
}
pushSkills (characterId, skills)
{
this.pendingPrivate.push({
type: "skills",
characterId,
skills
});
}
skillsOf (entityId)
{
const record = this.directory.get(entityId);
if (!record)
{ return null; }
return this.workers[record.workerId].call({
type: WorkerMessage.inspectSkills,
entityId
});
}
pushInventory (characterId, bag)
{
this.pendingPrivate.push({
@@ -413,9 +447,8 @@ export class Simulation
characterId,
inventory: bag.inventory,
equipment: bag.equipment,
currency: bag.currency,
vault: bag.vault,
vaultCurrency: bag.vaultCurrency
vaultReserved: bag.vaultReserved
});
}
@@ -665,7 +698,7 @@ export class Simulation
{
this.stateDb.saveInheritance(
this.stateDb.getCharacter(item.command.characterId).account_id,
{ slots: result.remainder, currency: 0 }
{ slots: result.remainder }
);
}
for (const event of result?.events ?? [])
@@ -1128,6 +1161,20 @@ export class Simulation
if (!bag || !record?.characterId)
{ return; }
this.#saveBagFromView(record.characterId, bag);
const skills = this.workers[workerId].call({
type: WorkerMessage.inspectSkills,
entityId
});
if (skills)
{ this.stateDb.saveSkills(record.characterId, skills); }
}
#applySkillsUpdated (event)
{
if (!event?.characterId || !event.stored)
{ return; }
this.stateDb.saveSkills(event.characterId, { xp: event.stored });
this.pushSkills(event.characterId, event.skills ?? []);
}
#saveBagFromView (characterId, bag)
@@ -1135,12 +1182,47 @@ export class Simulation
this.stateDb.saveBag(characterId, {
inventory: bag.inventory,
equipment: bag.equipment,
currency: bag.currency,
vault: bag.vault,
vaultCurrency: bag.vaultCurrency
vaultReserved: bag.vaultReserved
});
}
releaseChequeReservation (issuerCharacterId, chequeId)
{
const onlineId = this.characterEntities.get(issuerCharacterId);
const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
if (!bag)
{ return { ok: false, error: "Issuer vault not found." }; }
const reserved = [...(bag.vaultReserved ?? [])];
const index = reserved.findIndex((entry) => entry?.chequeId === chequeId);
if (index < 0)
{ return { ok: false, error: "That cheque cannot be redeemed." }; }
const [stack] = reserved.splice(index, 1);
bag.vaultReserved = reserved;
this.stateDb.saveBag(issuerCharacterId, bag);
if (onlineId)
{
this.applyBag(onlineId, bag);
this.pushInventory(issuerCharacterId, bag);
}
return { ok: true, stack };
}
restoreChequeReservation (issuerCharacterId, stack)
{
const onlineId = this.characterEntities.get(issuerCharacterId);
const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
if (!bag)
{ return; }
bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
this.stateDb.saveBag(issuerCharacterId, bag);
if (onlineId)
{
this.applyBag(onlineId, bag);
this.pushInventory(issuerCharacterId, bag);
}
}
#remember (view, workerId)
{
if (!view)
@@ -29,7 +29,8 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";import { mobComponents } from "./spawners.js";import { mobComponents } from "./spawners.js";import { DEFAULT_PLAYER_SKILL_LEVELS } from "../../../shared/definitions/skills.js";import { defaultPlayerSkills } from "../../../shared/skills/state.js";import { playerMaxHealth } from "../../../shared/definitions/skills.js";import { CourierService } from "../courier/service.js";import { CourierService } from "../courier/service.js";export class Simulationexport class Simulation@@ -72,6 +73,13 @@ export class Simulation }); }); this.workers.push(worker); this.workers.push(worker); } } for (const worker of this.workers) { if (!worker.world) { continue; } worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId); worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack); } this.courier = new CourierService({ this.courier = new CourierService({ stateDb: this.stateDb, stateDb: this.stateDb, worldDb: this.worldDb, worldDb: this.worldDb,@@ -154,8 +162,11 @@ export class Simulation { this.#applyMoveToDirectory(event); } { this.#applyMoveToDirectory(event); } if (event.type === "entity-despawn") if (event.type === "entity-despawn") { this.#forget(event.entityId); } { this.#forget(event.entityId); } if (event.type === "skills-updated") { this.#applySkillsUpdated(event); } this.#persistGroundEvent(event); this.#persistGroundEvent(event); events.push(event); if (event.type !== "skills-updated") { events.push(event); } } } for (const request of result?.transferRequests ?? []) for (const request of result?.transferRequests ?? []) { transfers.push({ ...request, fromWorkerId: worker.workerId }); } { transfers.push({ ...request, fromWorkerId: worker.workerId }); }@@ -244,10 +255,11 @@ export class Simulation const bag = this.stateDb.getBag(character.character_id) ?? { const bag = this.stateDb.getBag(character.character_id) ?? { inventory: emptySlots(), inventory: emptySlots(), equipment: emptyEquipment(), equipment: emptyEquipment(), currency: 0, vault: [], vault: emptySlots(), vaultReserved: [] vaultCurrency: 0 }; }; const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills(); const maxHealth = playerMaxHealth(skills); const entityId = this.nextEntityId++; const entityId = this.nextEntityId++; const components = { const components = { position: { tileX, tileY }, position: { tileX, tileY },@@ -266,11 +278,13 @@ export class Simulation chunkLoader: { ...DEFAULT_CHUNK_LOADER }, chunkLoader: { ...DEFAULT_CHUNK_LOADER }, inventory: { slots: bag.inventory ?? emptySlots() }, inventory: { slots: bag.inventory ?? emptySlots() }, equipment: bag.equipment ?? emptyEquipment(), equipment: bag.equipment ?? emptyEquipment(), currency: { amount: bag.currency ?? 0 }, vault: { vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 }, slots: bag.vault ?? [], health: { current: 20, max: 20 }, reserved: bag.vaultReserved ?? [] }, health: { current: maxHealth, max: maxHealth }, combat: { targetEntityId: null, nextSwingAt: 0 }, combat: { targetEntityId: null, nextSwingAt: 0 }, skills: { levels: { ...DEFAULT_PLAYER_SKILL_LEVELS } } skills, }; }; this.#ensureCoverage(tileX, tileY, components.chunkLoader); this.#ensureCoverage(tileX, tileY, components.chunkLoader); const workerId = this.#ownerOfTile(tileX, tileY); const workerId = this.#ownerOfTile(tileX, tileY);@@ -406,6 +420,26 @@ export class Simulation }); }); } } pushSkills (characterId, skills) { this.pendingPrivate.push({ type: "skills", characterId, skills }); } skillsOf (entityId) { const record = this.directory.get(entityId); if (!record) { return null; } return this.workers[record.workerId].call({ type: WorkerMessage.inspectSkills, entityId }); } pushInventory (characterId, bag) pushInventory (characterId, bag) { { this.pendingPrivate.push({ this.pendingPrivate.push({@@ -413,9 +447,8 @@ export class Simulation characterId, characterId, inventory: bag.inventory, inventory: bag.inventory, equipment: bag.equipment, equipment: bag.equipment, currency: bag.currency, vault: bag.vault, vault: bag.vault, vaultCurrency: bag.vaultCurrency vaultReserved: bag.vaultReserved }); }); } }@@ -665,7 +698,7 @@ export class Simulation { { this.stateDb.saveInheritance( this.stateDb.saveInheritance( this.stateDb.getCharacter(item.command.characterId).account_id, this.stateDb.getCharacter(item.command.characterId).account_id, { slots: result.remainder, currency: 0 } { slots: result.remainder } ); ); } } for (const event of result?.events ?? []) for (const event of result?.events ?? [])@@ -1128,6 +1161,20 @@ export class Simulation if (!bag || !record?.characterId) if (!bag || !record?.characterId) { return; } { return; } this.#saveBagFromView(record.characterId, bag); this.#saveBagFromView(record.characterId, bag); const skills = this.workers[workerId].call({ type: WorkerMessage.inspectSkills, entityId }); if (skills) { this.stateDb.saveSkills(record.characterId, skills); } } #applySkillsUpdated (event) { if (!event?.characterId || !event.stored) { return; } this.stateDb.saveSkills(event.characterId, { xp: event.stored }); this.pushSkills(event.characterId, event.skills ?? []); } } #saveBagFromView (characterId, bag) #saveBagFromView (characterId, bag)@@ -1135,12 +1182,47 @@ export class Simulation this.stateDb.saveBag(characterId, { this.stateDb.saveBag(characterId, { inventory: bag.inventory, inventory: bag.inventory, equipment: bag.equipment, equipment: bag.equipment, currency: bag.currency, vault: bag.vault, vault: bag.vault, vaultCurrency: bag.vaultCurrency vaultReserved: bag.vaultReserved }); }); } } releaseChequeReservation (issuerCharacterId, chequeId) { const onlineId = this.characterEntities.get(issuerCharacterId); const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); if (!bag) { return { ok: false, error: "Issuer vault not found." }; } const reserved = [...(bag.vaultReserved ?? [])]; const index = reserved.findIndex((entry) => entry?.chequeId === chequeId); if (index < 0) { return { ok: false, error: "That cheque cannot be redeemed." }; } const [stack] = reserved.splice(index, 1); bag.vaultReserved = reserved; this.stateDb.saveBag(issuerCharacterId, bag); if (onlineId) { this.applyBag(onlineId, bag); this.pushInventory(issuerCharacterId, bag); } return { ok: true, stack }; } restoreChequeReservation (issuerCharacterId, stack) { const onlineId = this.characterEntities.get(issuerCharacterId); const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId); if (!bag) { return; } bag.vaultReserved = [...(bag.vaultReserved ?? []), stack]; this.stateDb.saveBag(issuerCharacterId, bag); if (onlineId) { this.applyBag(onlineId, bag); this.pushInventory(issuerCharacterId, bag); } } #remember (view, workerId) #remember (view, workerId) { { if (!view) if (!view)@@ -1,5 +1,6 @@
import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
import { BlockType } from "../../../shared/definitions/tiles.js";
import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";
import {
defaultSpawnerConfig,
listAmbientMobTypes,
@@ -80,10 +81,10 @@ export function mobComponents (request)
lastAt: 0
};
}
if (!def.untargetable && (def.hostile || def.defaultAttack || def.skillLevels))
if (mobCanFight(def))
{
components.combat = { targetEntityId: null, nextSwingAt: 0 };
components.skills = { levels: { ...(def.skillLevels ?? {}) } };
components.skills = { levels: mobSkillLevels(def) };
}
return components;
}
@@ -1,5 +1,6 @@import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { BlockType } from "../../../shared/definitions/tiles.js";import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";import {import { defaultSpawnerConfig, defaultSpawnerConfig, listAmbientMobTypes, listAmbientMobTypes,@@ -80,10 +81,10 @@ export function mobComponents (request) lastAt: 0 lastAt: 0 }; }; } } if (!def.untargetable && (def.hostile || def.defaultAttack || def.skillLevels)) if (mobCanFight(def)) { { components.combat = { targetEntityId: null, nextSwingAt: 0 }; components.combat = { targetEntityId: null, nextSwingAt: 0 }; components.skills = { levels: { ...(def.skillLevels ?? {}) } }; components.skills = { levels: mobSkillLevels(def) }; } } return components; return components;}}@@ -31,6 +31,7 @@ import {
import {
clearEngage,
engageTarget,
ensureMobCombat,
isUntargetable,
stepCombat
} from "../combat/service.js";
@@ -93,6 +94,8 @@ export class WorkerWorld
return { ok: true };
case WorkerMessage.inspectBag:
return this.#inspectBag(message.entityId);
case WorkerMessage.inspectSkills:
return this.#inspectSkills(message.entityId);
case WorkerMessage.applyBag:
return this.#applyBag(message.entityId, message.bag);
case WorkerMessage.updateFlight:
@@ -183,6 +186,9 @@ export class WorkerWorld
const dropped = [];
for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
{
const components = record.payload?.components;
if (components?.creature && !components?.character && components?.health)
{ components.health.current = components.health.max; }
dropped.push(record);
this.#destroyEntity(record.entityId);
}
@@ -352,6 +358,17 @@ export class WorkerWorld
return bagView(this.ecs, handle);
}
#inspectSkills (entityId)
{
const handle = this.ecs.handleOf(entityId);
if (handle == null)
{ return null; }
const skills = this.ecs.get(handle, Component.skills);
if (!skills?.xp)
{ return null; }
return skills;
}
#applyBag (entityId, bag)
{
const handle = this.ecs.handleOf(entityId);
@@ -476,7 +493,7 @@ export class WorkerWorld
{ this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
clearFollow(this.ecs, entityId);
engageTarget(this.ecs, entityId, targetEntityId, now);
if (this.ecs.get(targetHandle, Component.combat))
if (ensureMobCombat(this.ecs, targetEntityId))
{ engageTarget(this.ecs, targetEntityId, entityId, now); }
const path = this.ecs.get(handle, Component.path);
if (path)
@@ -31,6 +31,7 @@ import {import {import { clearEngage, clearEngage, engageTarget, engageTarget, ensureMobCombat, isUntargetable, isUntargetable, stepCombat stepCombat} from "../combat/service.js";} from "../combat/service.js";@@ -93,6 +94,8 @@ export class WorkerWorld return { ok: true }; return { ok: true }; case WorkerMessage.inspectBag: case WorkerMessage.inspectBag: return this.#inspectBag(message.entityId); return this.#inspectBag(message.entityId); case WorkerMessage.inspectSkills: return this.#inspectSkills(message.entityId); case WorkerMessage.applyBag: case WorkerMessage.applyBag: return this.#applyBag(message.entityId, message.bag); return this.#applyBag(message.entityId, message.bag); case WorkerMessage.updateFlight: case WorkerMessage.updateFlight:@@ -183,6 +186,9 @@ export class WorkerWorld const dropped = []; const dropped = []; for (const record of this.#entitiesInRegion(message.regionX, message.regionY)) for (const record of this.#entitiesInRegion(message.regionX, message.regionY)) { { const components = record.payload?.components; if (components?.creature && !components?.character && components?.health) { components.health.current = components.health.max; } dropped.push(record); dropped.push(record); this.#destroyEntity(record.entityId); this.#destroyEntity(record.entityId); } }@@ -352,6 +358,17 @@ export class WorkerWorld return bagView(this.ecs, handle); return bagView(this.ecs, handle); } } #inspectSkills (entityId) { const handle = this.ecs.handleOf(entityId); if (handle == null) { return null; } const skills = this.ecs.get(handle, Component.skills); if (!skills?.xp) { return null; } return skills; } #applyBag (entityId, bag) #applyBag (entityId, bag) { { const handle = this.ecs.handleOf(entityId); const handle = this.ecs.handleOf(entityId);@@ -476,7 +493,7 @@ export class WorkerWorld { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); } clearFollow(this.ecs, entityId); clearFollow(this.ecs, entityId); engageTarget(this.ecs, entityId, targetEntityId, now); engageTarget(this.ecs, entityId, targetEntityId, now); if (this.ecs.get(targetHandle, Component.combat)) if (ensureMobCombat(this.ecs, targetEntityId)) { engageTarget(this.ecs, targetEntityId, entityId, now); } { engageTarget(this.ecs, targetEntityId, entityId, now); } const path = this.ecs.get(handle, Component.path); const path = this.ecs.get(handle, Component.path); if (path) if (path)@@ -0,0 +1,55 @@
import { Component } from "../ecs/components.js";
import { SkillId, playerMaxHealth } from "../../../shared/definitions/skills.js";
import { combatHitXpPerSkill } from "../../../shared/skills/progression.js";
import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
export function syncPlayerHealth (ecs, handle)
{
const character = ecs.get(handle, Component.character);
if (!character)
{ return; }
const skills = ecs.get(handle, Component.skills);
const health = ecs.get(handle, Component.health);
if (!skills || !health)
{ return; }
const max = playerMaxHealth(skills);
health.max = max;
health.current = Math.min(health.current | 0, max);
}
export function awardCombatHitXp (ecs, attackerHandle, profile)
{
const skills = ecs.get(attackerHandle, Component.skills);
if (!skills?.xp)
{ return null; }
const perSkill = combatHitXpPerSkill();
const hit = addSkillXp(skills, profile.hitSkillId, perSkill);
const damage = addSkillXp(skills, profile.damageSkillId, perSkill);
if (!hit && !damage)
{ return null; }
return {
view: publicSkillsView(skills),
stored: storedSkillXp(skills)
};
}
export function awardDamageHealthXp (ecs, targetHandle, damage)
{
const amount = Math.max(0, Math.floor(Number(damage) || 0));
if (!amount)
{ return null; }
const character = ecs.get(targetHandle, Component.character);
if (!character)
{ return null; }
const skills = ecs.get(targetHandle, Component.skills);
if (!skills?.xp)
{ return null; }
if (!addSkillXp(skills, SkillId.health, amount))
{ return null; }
syncPlayerHealth(ecs, targetHandle);
return {
characterId: character.characterId,
view: publicSkillsView(skills),
stored: storedSkillXp(skills)
};
}
@@ -0,0 +1,55 @@import { Component } from "../ecs/components.js";import { SkillId, playerMaxHealth } from "../../../shared/definitions/skills.js";import { combatHitXpPerSkill } from "../../../shared/skills/progression.js";import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";export function syncPlayerHealth (ecs, handle){ const character = ecs.get(handle, Component.character); if (!character) { return; } const skills = ecs.get(handle, Component.skills); const health = ecs.get(handle, Component.health); if (!skills || !health) { return; } const max = playerMaxHealth(skills); health.max = max; health.current = Math.min(health.current | 0, max);}export function awardCombatHitXp (ecs, attackerHandle, profile){ const skills = ecs.get(attackerHandle, Component.skills); if (!skills?.xp) { return null; } const perSkill = combatHitXpPerSkill(); const hit = addSkillXp(skills, profile.hitSkillId, perSkill); const damage = addSkillXp(skills, profile.damageSkillId, perSkill); if (!hit && !damage) { return null; } return { view: publicSkillsView(skills), stored: storedSkillXp(skills) };}export function awardDamageHealthXp (ecs, targetHandle, damage){ const amount = Math.max(0, Math.floor(Number(damage) || 0)); if (!amount) { return null; } const character = ecs.get(targetHandle, Component.character); if (!character) { return null; } const skills = ecs.get(targetHandle, Component.skills); if (!skills?.xp) { return null; } if (!addSkillXp(skills, SkillId.health, amount)) { return null; } syncPlayerHealth(ecs, targetHandle); return { characterId: character.characterId, view: publicSkillsView(skills), stored: storedSkillXp(skills) };}@@ -0,0 +1,291 @@
import test from "node:test";
import assert from "node:assert/strict";
import { BlockType } from "../../shared/definitions/tiles.js";
import { ItemId } from "../../shared/definitions/items.js";
import { emptyEquipment } from "../../shared/items/inventory.js";
import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
import {
makeCharacter,
makeSimulation
} from "./helpers/simulationHarness.js";
function placeBank (worldDb, tileX, tileY)
{
const chunkX = Math.floor(tileX / 16);
const chunkY = Math.floor(tileY / 16);
const data = createEmptyChunkData();
data.open = true;
const localX = tileX - chunkX * 16;
const localY = tileY - chunkY * 16;
data.blocks[localY * 16 + localX] = { typeId: BlockType.bank, state: 0 };
worldDb.saveChunkVersion(
chunkX,
chunkY,
worldDb.getActiveRevisionId(),
true,
encodeChunkBlob(data)
);
}
function countItem (slots, itemId)
{
return (slots ?? [])
.filter((slot) => slot?.itemId === itemId)
.reduce((sum, slot) => sum + (slot.quantity | 0), 0);
}
test("blank cheques top up inventory to 99 at a bank", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeBank(harness.worldDb, 8, 8);
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
const entityId = harness.simulation.spawnCharacter(1, character);
harness.simulation.enqueue(1, {
type: "get-blank-cheques",
characterId: character.character_id
});
harness.simulation.step();
const bag = harness.simulation.bagOf(entityId);
assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99);
}
finally
{ harness.close(); }
});
test("bank deposit and withdraw move stacks with quantity", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeBank(harness.worldDb, 8, 8);
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
const entityId = harness.simulation.spawnCharacter(1, character);
const before = harness.simulation.bagOf(entityId);
const appleIndex = before.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
assert.ok(appleIndex >= 0);
const qty = before.inventory[appleIndex].quantity;
harness.simulation.enqueue(1, {
type: "bank-deposit",
characterId: character.character_id,
slotIndex: appleIndex,
quantity: 1
});
harness.simulation.step();
let bag = harness.simulation.bagOf(entityId);
assert.equal(countItem(bag.vault, ItemId.apple), 1);
assert.equal(bag.inventory[appleIndex]?.quantity ?? 0, qty - 1);
const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple);
harness.simulation.enqueue(1, {
type: "bank-withdraw",
characterId: character.character_id,
slotIndex: vaultIndex,
quantity: 1
});
harness.simulation.step();
bag = harness.simulation.bagOf(entityId);
assert.equal(countItem(bag.vault, ItemId.apple), 0);
}
finally
{ harness.close(); }
});
test("write cheque reserves vault goods and redeem returns them", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeBank(harness.worldDb, 8, 8);
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
const entityId = harness.simulation.spawnCharacter(1, character);
harness.simulation.enqueue(1, {
type: "get-blank-cheques",
characterId: character.character_id
});
harness.simulation.step();
let bag = harness.simulation.bagOf(entityId);
const appleIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
harness.simulation.enqueue(1, {
type: "bank-deposit",
characterId: character.character_id,
slotIndex: appleIndex,
quantity: null
});
harness.simulation.step();
bag = harness.simulation.bagOf(entityId);
const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple);
harness.simulation.enqueue(1, {
type: "write-cheque",
characterId: character.character_id,
slotIndex: blankIndex,
vaultSlotIndex: vaultIndex,
quantity: 2
});
harness.simulation.step();
bag = harness.simulation.bagOf(entityId);
assert.equal((bag.vaultReserved ?? []).length, 1);
assert.equal(bag.vaultReserved[0].quantity, 2);
const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
assert.ok(chequeIndex >= 0);
harness.simulation.enqueue(1, {
type: "redeem-cheque",
characterId: character.character_id,
slotIndex: chequeIndex
});
harness.simulation.step();
bag = harness.simulation.bagOf(entityId);
assert.equal((bag.vaultReserved ?? []).length, 0);
assert.ok(countItem(bag.vault, ItemId.apple) >= 2);
}
finally
{ harness.close(); }
});
test("bank deposit of a filled cheque redeems reserved goods", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeBank(harness.worldDb, 8, 8);
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
const entityId = harness.simulation.spawnCharacter(1, character);
harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
harness.simulation.step();
let bag = harness.simulation.bagOf(entityId);
const appleIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
harness.simulation.enqueue(1, {
type: "bank-deposit",
characterId: character.character_id,
slotIndex: appleIndex,
quantity: null
});
harness.simulation.step();
bag = harness.simulation.bagOf(entityId);
const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple);
harness.simulation.enqueue(1, {
type: "write-cheque",
characterId: character.character_id,
slotIndex: blankIndex,
vaultSlotIndex: vaultIndex,
quantity: 2
});
harness.simulation.step();
bag = harness.simulation.bagOf(entityId);
const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
assert.ok(chequeIndex >= 0);
harness.simulation.enqueue(1, {
type: "bank-deposit",
characterId: character.character_id,
slotIndex: chequeIndex,
quantity: null
});
harness.simulation.step();
bag = harness.simulation.bagOf(entityId);
assert.equal(bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque), -1);
assert.equal((bag.vaultReserved ?? []).length, 0);
assert.ok(countItem(bag.vault, ItemId.apple) >= 2);
}
finally
{ harness.close(); }
});
test("new characters start with coin stacks in inventory", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const bag = harness.stateDb.getBag(character.character_id);
assert.equal(countItem(bag.inventory, ItemId.coins), 25);
}
finally
{ harness.close(); }
});
test("legacy currency counters migrate into coin stacks", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
harness.stateDb.saveBag(character.character_id, {
inventory: [],
equipment: emptyEquipment(),
currency: 100,
vault: [],
vaultReserved: [],
vaultCurrency: 50
});
const bag = harness.stateDb.getBag(character.character_id);
assert.equal(countItem(bag.inventory, ItemId.coins), 100);
assert.equal(countItem(bag.vault, ItemId.coins), 50);
}
finally
{ harness.close(); }
});
test("stored inventory with excess blank cheques is capped on load", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
harness.stateDb.saveBag(character.character_id, {
inventory: [{ itemId: ItemId.blankCheque, quantity: 120 }],
equipment: emptyEquipment(),
vault: [],
vaultReserved: []
});
const bag = harness.stateDb.getBag(character.character_id);
assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99);
}
finally
{ harness.close(); }
});
test("blank cheque ground pickup stops at 99 carried", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
placeBank(harness.worldDb, 8, 8);
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
const entityId = harness.simulation.spawnCharacter(1, character);
harness.simulation.enqueue(1, {
type: "get-blank-cheques",
characterId: character.character_id
});
harness.simulation.step();
let bag = harness.simulation.bagOf(entityId);
const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
assert.ok(blankIndex >= 0);
harness.simulation.enqueue(1, {
type: "drop-item",
characterId: character.character_id,
slotIndex: blankIndex,
quantity: 10
});
const dropEvents = harness.simulation.step().events;
const appear = dropEvents.find((event) => event.type === "ground-item-appear");
assert.ok(appear);
harness.simulation.enqueue(1, {
type: "pickup-item",
characterId: character.character_id,
groundItemId: appear.groundItemId
});
harness.simulation.step();
bag = harness.simulation.bagOf(entityId);
assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99);
const snapshot = harness.simulation.snapshotChunk(0, 0);
assert.equal((snapshot.groundItems ?? []).length, 0);
}
finally
{ harness.close(); }
});
@@ -0,0 +1,291 @@import test from "node:test";import assert from "node:assert/strict";import { BlockType } from "../../shared/definitions/tiles.js";import { ItemId } from "../../shared/definitions/items.js";import { emptyEquipment } from "../../shared/items/inventory.js";import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";import { makeCharacter, makeSimulation} from "./helpers/simulationHarness.js";function placeBank (worldDb, tileX, tileY){ const chunkX = Math.floor(tileX / 16); const chunkY = Math.floor(tileY / 16); const data = createEmptyChunkData(); data.open = true; const localX = tileX - chunkX * 16; const localY = tileY - chunkY * 16; data.blocks[localY * 16 + localX] = { typeId: BlockType.bank, state: 0 }; worldDb.saveChunkVersion( chunkX, chunkY, worldDb.getActiveRevisionId(), true, encodeChunkBlob(data) );}function countItem (slots, itemId){ return (slots ?? []) .filter((slot) => slot?.itemId === itemId) .reduce((sum, slot) => sum + (slot.quantity | 0), 0);}test("blank cheques top up inventory to 99 at a bank", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { placeBank(harness.worldDb, 8, 8); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const entityId = harness.simulation.spawnCharacter(1, character); harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id }); harness.simulation.step(); const bag = harness.simulation.bagOf(entityId); assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99); } finally { harness.close(); }});test("bank deposit and withdraw move stacks with quantity", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { placeBank(harness.worldDb, 8, 8); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const entityId = harness.simulation.spawnCharacter(1, character); const before = harness.simulation.bagOf(entityId); const appleIndex = before.inventory.findIndex((slot) => slot?.itemId === ItemId.apple); assert.ok(appleIndex >= 0); const qty = before.inventory[appleIndex].quantity; harness.simulation.enqueue(1, { type: "bank-deposit", characterId: character.character_id, slotIndex: appleIndex, quantity: 1 }); harness.simulation.step(); let bag = harness.simulation.bagOf(entityId); assert.equal(countItem(bag.vault, ItemId.apple), 1); assert.equal(bag.inventory[appleIndex]?.quantity ?? 0, qty - 1); const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple); harness.simulation.enqueue(1, { type: "bank-withdraw", characterId: character.character_id, slotIndex: vaultIndex, quantity: 1 }); harness.simulation.step(); bag = harness.simulation.bagOf(entityId); assert.equal(countItem(bag.vault, ItemId.apple), 0); } finally { harness.close(); }});test("write cheque reserves vault goods and redeem returns them", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { placeBank(harness.worldDb, 8, 8); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const entityId = harness.simulation.spawnCharacter(1, character); harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id }); harness.simulation.step(); let bag = harness.simulation.bagOf(entityId); const appleIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple); harness.simulation.enqueue(1, { type: "bank-deposit", characterId: character.character_id, slotIndex: appleIndex, quantity: null }); harness.simulation.step(); bag = harness.simulation.bagOf(entityId); const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque); const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple); harness.simulation.enqueue(1, { type: "write-cheque", characterId: character.character_id, slotIndex: blankIndex, vaultSlotIndex: vaultIndex, quantity: 2 }); harness.simulation.step(); bag = harness.simulation.bagOf(entityId); assert.equal((bag.vaultReserved ?? []).length, 1); assert.equal(bag.vaultReserved[0].quantity, 2); const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque); assert.ok(chequeIndex >= 0); harness.simulation.enqueue(1, { type: "redeem-cheque", characterId: character.character_id, slotIndex: chequeIndex }); harness.simulation.step(); bag = harness.simulation.bagOf(entityId); assert.equal((bag.vaultReserved ?? []).length, 0); assert.ok(countItem(bag.vault, ItemId.apple) >= 2); } finally { harness.close(); }});test("bank deposit of a filled cheque redeems reserved goods", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { placeBank(harness.worldDb, 8, 8); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const entityId = harness.simulation.spawnCharacter(1, character); harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id }); harness.simulation.step(); let bag = harness.simulation.bagOf(entityId); const appleIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple); harness.simulation.enqueue(1, { type: "bank-deposit", characterId: character.character_id, slotIndex: appleIndex, quantity: null }); harness.simulation.step(); bag = harness.simulation.bagOf(entityId); const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque); const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple); harness.simulation.enqueue(1, { type: "write-cheque", characterId: character.character_id, slotIndex: blankIndex, vaultSlotIndex: vaultIndex, quantity: 2 }); harness.simulation.step(); bag = harness.simulation.bagOf(entityId); const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque); assert.ok(chequeIndex >= 0); harness.simulation.enqueue(1, { type: "bank-deposit", characterId: character.character_id, slotIndex: chequeIndex, quantity: null }); harness.simulation.step(); bag = harness.simulation.bagOf(entityId); assert.equal(bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque), -1); assert.equal((bag.vaultReserved ?? []).length, 0); assert.ok(countItem(bag.vault, ItemId.apple) >= 2); } finally { harness.close(); }});test("new characters start with coin stacks in inventory", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const bag = harness.stateDb.getBag(character.character_id); assert.equal(countItem(bag.inventory, ItemId.coins), 25); } finally { harness.close(); }});test("legacy currency counters migrate into coin stacks", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); harness.stateDb.saveBag(character.character_id, { inventory: [], equipment: emptyEquipment(), currency: 100, vault: [], vaultReserved: [], vaultCurrency: 50 }); const bag = harness.stateDb.getBag(character.character_id); assert.equal(countItem(bag.inventory, ItemId.coins), 100); assert.equal(countItem(bag.vault, ItemId.coins), 50); } finally { harness.close(); }});test("stored inventory with excess blank cheques is capped on load", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); harness.stateDb.saveBag(character.character_id, { inventory: [{ itemId: ItemId.blankCheque, quantity: 120 }], equipment: emptyEquipment(), vault: [], vaultReserved: [] }); const bag = harness.stateDb.getBag(character.character_id); assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99); } finally { harness.close(); }});test("blank cheque ground pickup stops at 99 carried", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { placeBank(harness.worldDb, 8, 8); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const entityId = harness.simulation.spawnCharacter(1, character); harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id }); harness.simulation.step(); let bag = harness.simulation.bagOf(entityId); const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque); assert.ok(blankIndex >= 0); harness.simulation.enqueue(1, { type: "drop-item", characterId: character.character_id, slotIndex: blankIndex, quantity: 10 }); const dropEvents = harness.simulation.step().events; const appear = dropEvents.find((event) => event.type === "ground-item-appear"); assert.ok(appear); harness.simulation.enqueue(1, { type: "pickup-item", characterId: character.character_id, groundItemId: appear.groundItemId }); harness.simulation.step(); bag = harness.simulation.bagOf(entityId); assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99); const snapshot = harness.simulation.snapshotChunk(0, 0); assert.equal((snapshot.groundItems ?? []).length, 0); } finally { harness.close(); }});@@ -0,0 +1,39 @@
import test from "node:test";
import assert from "node:assert/strict";
import { formatQuantity } from "../../shared/items/formatQuantity.js";
import { ItemId, coinSpriteTierForQuantity, COIN_MAX_STACK } from "../../shared/definitions/items.js";
import { addCoinsToSlots, emptySlots, countCoinsInSlots } from "../../shared/items/inventory.js";
test("formatQuantity uses compact notation", () =>
{
assert.equal(formatQuantity(1), "1");
assert.equal(formatQuantity(500), "500");
assert.equal(formatQuantity(1000), "1k");
assert.equal(formatQuantity(1500), "1.5k");
assert.equal(formatQuantity(2000), "2k");
assert.equal(formatQuantity(50000), "50k");
assert.equal(formatQuantity(100000), "100k");
assert.equal(formatQuantity(1000000), "1M");
assert.equal(formatQuantity(1500000), "1.5M");
});
test("coin stacks split above max stack size", () =>
{
const amount = COIN_MAX_STACK + 1;
const result = addCoinsToSlots(emptySlots(), amount, { growable: false });
assert.equal(result.ok, true);
assert.equal(countCoinsInSlots(result.slots), amount);
const stacks = result.slots.filter((slot) => slot?.itemId === ItemId.coins);
assert.equal(stacks.length, 2);
assert.equal(stacks[0].quantity, COIN_MAX_STACK);
assert.equal(stacks[1].quantity, 1);
});
test("coin sprite tier picks the largest denomination not exceeding stack size", () =>
{
assert.equal(coinSpriteTierForQuantity(1), 1);
assert.equal(coinSpriteTierForQuantity(500), 500);
assert.equal(coinSpriteTierForQuantity(1500), 1500);
assert.equal(coinSpriteTierForQuantity(999), 500);
assert.equal(coinSpriteTierForQuantity(50_000_000), 50_000_000);
});
@@ -0,0 +1,39 @@import test from "node:test";import assert from "node:assert/strict";import { formatQuantity } from "../../shared/items/formatQuantity.js";import { ItemId, coinSpriteTierForQuantity, COIN_MAX_STACK } from "../../shared/definitions/items.js";import { addCoinsToSlots, emptySlots, countCoinsInSlots } from "../../shared/items/inventory.js";test("formatQuantity uses compact notation", () =>{ assert.equal(formatQuantity(1), "1"); assert.equal(formatQuantity(500), "500"); assert.equal(formatQuantity(1000), "1k"); assert.equal(formatQuantity(1500), "1.5k"); assert.equal(formatQuantity(2000), "2k"); assert.equal(formatQuantity(50000), "50k"); assert.equal(formatQuantity(100000), "100k"); assert.equal(formatQuantity(1000000), "1M"); assert.equal(formatQuantity(1500000), "1.5M");});test("coin stacks split above max stack size", () =>{ const amount = COIN_MAX_STACK + 1; const result = addCoinsToSlots(emptySlots(), amount, { growable: false }); assert.equal(result.ok, true); assert.equal(countCoinsInSlots(result.slots), amount); const stacks = result.slots.filter((slot) => slot?.itemId === ItemId.coins); assert.equal(stacks.length, 2); assert.equal(stacks[0].quantity, COIN_MAX_STACK); assert.equal(stacks[1].quantity, 1);});test("coin sprite tier picks the largest denomination not exceeding stack size", () =>{ assert.equal(coinSpriteTierForQuantity(1), 1); assert.equal(coinSpriteTierForQuantity(500), 500); assert.equal(coinSpriteTierForQuantity(1500), 1500); assert.equal(coinSpriteTierForQuantity(999), 500); assert.equal(coinSpriteTierForQuantity(50_000_000), 50_000_000);});@@ -3,6 +3,11 @@ import assert from "node:assert/strict";
import { mobComponents } from "../src/simulation/spawners.js";
import { MobId } from "../../shared/definitions/mobs.js";
import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
import { Component } from "../src/ecs/components.js";
import { WorkerMessage } from "../src/simulation/protocol.js";
import { tileToRegion } from "../src/world/coordinates.js";
import { SkillId } from "../../shared/definitions/skills.js";
import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
function workerOf (simulation, entityId)
@@ -96,7 +101,10 @@ test("melee swing only resolves at Chebyshev distance 1", () =>
});
const nearEvents = harness.simulation.step().events;
assert.ok(nearEvents.some((event) => event.type === "combat-swing"));
assert.ok(nearEvents.some((event) => event.type === "combat-hit" || event.type === "combat-miss"));
assert.ok(nearEvents.some((event) =>
event.type === "combat-hit"
|| event.type === "combat-miss"
|| event.type === "combat-block"));
}
finally
{ harness.close(); }
@@ -139,6 +147,71 @@ test("pigeons are untargetable free-flight and never get path tiles", () =>
{ harness.close(); }
});
test("deer retaliate when attacked", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const deerId = harness.simulation.spawnEntity(mobComponents({
tileX: 9,
tileY: 8,
mobTypeId: MobId.deer,
spawnerId: null
}));
harness.simulation.enqueue(1, {
type: "attack",
characterId: character.character_id,
targetEntityId: deerId
});
harness.simulation.step();
const deer = componentsOf(harness.simulation, deerId);
assert.equal(deer.combat?.targetEntityId, playerId);
assert.ok(deer.skills?.levels?.unarmed >= 1);
}
finally
{ harness.close(); }
});
test("cancel attack stops the player but the mob keeps pursuing", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const ratId = harness.simulation.spawnEntity(mobComponents({
tileX: 9,
tileY: 8,
mobTypeId: MobId.rat,
spawnerId: null
}));
harness.simulation.enqueue(1, {
type: "attack",
characterId: character.character_id,
targetEntityId: ratId
});
harness.simulation.step();
harness.simulation.enqueue(1, {
type: "cancel-attack",
characterId: character.character_id
});
harness.simulation.step();
const player = componentsOf(harness.simulation, playerId);
const rat = componentsOf(harness.simulation, ratId);
assert.equal(player.combat?.targetEntityId, null);
assert.equal(rat.combat?.targetEntityId, playerId);
}
finally
{ harness.close(); }
});
test("player combat and skills components are present on spawn", () =>
{
const harness = makeSimulation({ workerCount: 1 });
@@ -148,9 +221,70 @@ test("player combat and skills components are present on spawn", () =>
const playerId = harness.simulation.spawnCharacter(1, character);
const comps = componentsOf(harness.simulation, playerId);
assert.ok(comps.combat);
assert.ok(comps.skills?.levels?.clubfighting);
assert.equal(comps.skills?.xp?.clubfighting, 0);
assert.ok(comps.health);
}
finally
{ harness.close(); }
});
test("mobs heal to full when their region unloads", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const ratId = harness.simulation.spawnEntity(mobComponents({
tileX: 8,
tileY: 8,
mobTypeId: MobId.rat
}));
const worker = workerOf(harness.simulation, ratId);
const handle = worker.world.ecs.handleOf(ratId);
worker.world.ecs.get(handle, Component.health).current = 2;
const result = worker.call({
type: WorkerMessage.dropRegion,
regionX: tileToRegion(8),
regionY: tileToRegion(8)
});
const record = result.dropped.find((entry) => entry.entityId === ratId);
assert.ok(record);
assert.equal(
record.payload.components.health.current,
record.payload.components.health.max
);
}
finally
{ harness.close(); }
});
test("taking damage awards Health XP equal to damage dealt", () =>
{
const harness = makeSimulation({ workerCount: 1 });
const random = Math.random;
Math.random = () => 0;
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const ratId = harness.simulation.spawnEntity(mobComponents({
mobTypeId: MobId.rat,
tileX: 9,
tileY: 8
}));
const worker = harness.simulation.workers[0];
const playerHandle = worker.world.ecs.handleOf(playerId);
const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
const hit = events.find((event) => event.type === "combat-hit");
assert.ok(hit);
const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
assert.ok(updated);
assert.equal(updated.stored[SkillId.health] - before, hit.damage);
}
finally
{
Math.random = random;
harness.close();
}
});
@@ -3,6 +3,11 @@ import assert from "node:assert/strict";import { mobComponents } from "../src/simulation/spawners.js";import { mobComponents } from "../src/simulation/spawners.js";import { MobId } from "../../shared/definitions/mobs.js";import { MobId } from "../../shared/definitions/mobs.js";import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";import { Component } from "../src/ecs/components.js";import { WorkerMessage } from "../src/simulation/protocol.js";import { tileToRegion } from "../src/world/coordinates.js";import { SkillId } from "../../shared/definitions/skills.js";import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";function workerOf (simulation, entityId)function workerOf (simulation, entityId)@@ -96,7 +101,10 @@ test("melee swing only resolves at Chebyshev distance 1", () => }); }); const nearEvents = harness.simulation.step().events; const nearEvents = harness.simulation.step().events; assert.ok(nearEvents.some((event) => event.type === "combat-swing")); assert.ok(nearEvents.some((event) => event.type === "combat-swing")); assert.ok(nearEvents.some((event) => event.type === "combat-hit" || event.type === "combat-miss")); assert.ok(nearEvents.some((event) => event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")); } } finally finally { harness.close(); } { harness.close(); }@@ -139,6 +147,71 @@ test("pigeons are untargetable free-flight and never get path tiles", () => { harness.close(); } { harness.close(); }});});test("deer retaliate when attacked", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const deerId = harness.simulation.spawnEntity(mobComponents({ tileX: 9, tileY: 8, mobTypeId: MobId.deer, spawnerId: null })); harness.simulation.enqueue(1, { type: "attack", characterId: character.character_id, targetEntityId: deerId }); harness.simulation.step(); const deer = componentsOf(harness.simulation, deerId); assert.equal(deer.combat?.targetEntityId, playerId); assert.ok(deer.skills?.levels?.unarmed >= 1); } finally { harness.close(); }});test("cancel attack stops the player but the mob keeps pursuing", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const ratId = harness.simulation.spawnEntity(mobComponents({ tileX: 9, tileY: 8, mobTypeId: MobId.rat, spawnerId: null })); harness.simulation.enqueue(1, { type: "attack", characterId: character.character_id, targetEntityId: ratId }); harness.simulation.step(); harness.simulation.enqueue(1, { type: "cancel-attack", characterId: character.character_id }); harness.simulation.step(); const player = componentsOf(harness.simulation, playerId); const rat = componentsOf(harness.simulation, ratId); assert.equal(player.combat?.targetEntityId, null); assert.equal(rat.combat?.targetEntityId, playerId); } finally { harness.close(); }});test("player combat and skills components are present on spawn", () =>test("player combat and skills components are present on spawn", () =>{{ const harness = makeSimulation({ workerCount: 1 }); const harness = makeSimulation({ workerCount: 1 });@@ -148,9 +221,70 @@ test("player combat and skills components are present on spawn", () => const playerId = harness.simulation.spawnCharacter(1, character); const playerId = harness.simulation.spawnCharacter(1, character); const comps = componentsOf(harness.simulation, playerId); const comps = componentsOf(harness.simulation, playerId); assert.ok(comps.combat); assert.ok(comps.combat); assert.ok(comps.skills?.levels?.clubfighting); assert.equal(comps.skills?.xp?.clubfighting, 0); assert.ok(comps.health); assert.ok(comps.health); } } finally finally { harness.close(); } { harness.close(); }});});test("mobs heal to full when their region unloads", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const ratId = harness.simulation.spawnEntity(mobComponents({ tileX: 8, tileY: 8, mobTypeId: MobId.rat })); const worker = workerOf(harness.simulation, ratId); const handle = worker.world.ecs.handleOf(ratId); worker.world.ecs.get(handle, Component.health).current = 2; const result = worker.call({ type: WorkerMessage.dropRegion, regionX: tileToRegion(8), regionY: tileToRegion(8) }); const record = result.dropped.find((entry) => entry.entityId === ratId); assert.ok(record); assert.equal( record.payload.components.health.current, record.payload.components.health.max ); } finally { harness.close(); }});test("taking damage awards Health XP equal to damage dealt", () =>{ const harness = makeSimulation({ workerCount: 1 }); const random = Math.random; Math.random = () => 0; try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const ratId = harness.simulation.spawnEntity(mobComponents({ mobTypeId: MobId.rat, tileX: 9, tileY: 8 })); const worker = harness.simulation.workers[0]; const playerHandle = worker.world.ecs.handleOf(playerId); const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health]; const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId)); const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now()); const hit = events.find((event) => event.type === "combat-hit"); assert.ok(hit); const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId); assert.ok(updated); assert.equal(updated.stored[SkillId.health] - before, hit.damage); } finally { Math.random = random; harness.close(); }});@@ -0,0 +1,108 @@
import test from "node:test";
import assert from "node:assert/strict";
import { resolvePhysicalAttack, rollSkill } from "../../shared/combat/rolls.js";
test("rollSkill returns values within 1..skillLevel", () =>
{
const seen = new Set();
for (let i = 0; i < 200; i++)
{ seen.add(rollSkill(5, () => Math.random())); }
for (const value of seen)
{
assert.ok(value >= 1 && value <= 5);
}
});
test("deterministic rng produces stable rolls", () =>
{
let i = 0;
const seq = [0, 0.99, 0.5];
const rng = () => seq[i++ % seq.length];
assert.equal(rollSkill(4, rng), 1);
assert.equal(rollSkill(4, rng), 4);
assert.equal(rollSkill(4, rng), 3);
});
test("physical attack miss when agility roll beats hit roll", () =>
{
let i = 0;
const rng = () => [0.25, 0.45][i++];
const result = resolvePhysicalAttack({
hitSkillLevel: 5,
agilitySkillLevel: 10,
damageSkillLevel: 10,
defenceSkillLevel: 1,
baseDamage: 2,
rng
});
assert.equal(result.outcome, "miss");
assert.equal(result.toHitRoll, 2);
assert.equal(result.agilityRoll, 5);
assert.equal(result.damage, 0);
});
test("equal hit and agility rolls count as a hit", () =>
{
let i = 0;
const rng = () => [0.4, 0.4, 0, 0][i++];
const result = resolvePhysicalAttack({
hitSkillLevel: 5,
agilitySkillLevel: 5,
damageSkillLevel: 5,
defenceSkillLevel: 1,
baseDamage: 1,
rng
});
assert.equal(result.toHitRoll, result.agilityRoll);
assert.equal(result.outcome, "hit");
});
test("physical attack block prevents damage after winning the hit contest", () =>
{
let i = 0;
const rolls = [0.4, 0, 0, 0.95];
const rng = () => rolls[i++];
const result = resolvePhysicalAttack({
hitSkillLevel: 10,
agilitySkillLevel: 3,
damageSkillLevel: 8,
defenceSkillLevel: 10,
baseDamage: 1,
rng
});
assert.equal(result.outcome, "block");
assert.equal(result.damage, 0);
assert.ok(result.defenceRoll > result.toHitRoll);
});
test("physical attack hit applies rolled damage when not blocked", () =>
{
let i = 0;
const rolls = [0.9, 0, 0, 0];
const rng = () => rolls[i++];
const result = resolvePhysicalAttack({
hitSkillLevel: 10,
agilitySkillLevel: 1,
damageSkillLevel: 5,
defenceSkillLevel: 1,
baseDamage: 2,
rng
});
assert.equal(result.outcome, "hit");
assert.equal(result.damage, 2);
});
test("skill level 1 contest can still land a hit on equal agility", () =>
{
const result = resolvePhysicalAttack({
hitSkillLevel: 1,
agilitySkillLevel: 1,
damageSkillLevel: 1,
defenceSkillLevel: 1,
baseDamage: 1,
rng: () => 0
});
assert.equal(result.outcome, "hit");
assert.equal(result.toHitRoll, 1);
assert.equal(result.agilityRoll, 1);
});
@@ -0,0 +1,108 @@import test from "node:test";import assert from "node:assert/strict";import { resolvePhysicalAttack, rollSkill } from "../../shared/combat/rolls.js";test("rollSkill returns values within 1..skillLevel", () =>{ const seen = new Set(); for (let i = 0; i < 200; i++) { seen.add(rollSkill(5, () => Math.random())); } for (const value of seen) { assert.ok(value >= 1 && value <= 5); }});test("deterministic rng produces stable rolls", () =>{ let i = 0; const seq = [0, 0.99, 0.5]; const rng = () => seq[i++ % seq.length]; assert.equal(rollSkill(4, rng), 1); assert.equal(rollSkill(4, rng), 4); assert.equal(rollSkill(4, rng), 3);});test("physical attack miss when agility roll beats hit roll", () =>{ let i = 0; const rng = () => [0.25, 0.45][i++]; const result = resolvePhysicalAttack({ hitSkillLevel: 5, agilitySkillLevel: 10, damageSkillLevel: 10, defenceSkillLevel: 1, baseDamage: 2, rng }); assert.equal(result.outcome, "miss"); assert.equal(result.toHitRoll, 2); assert.equal(result.agilityRoll, 5); assert.equal(result.damage, 0);});test("equal hit and agility rolls count as a hit", () =>{ let i = 0; const rng = () => [0.4, 0.4, 0, 0][i++]; const result = resolvePhysicalAttack({ hitSkillLevel: 5, agilitySkillLevel: 5, damageSkillLevel: 5, defenceSkillLevel: 1, baseDamage: 1, rng }); assert.equal(result.toHitRoll, result.agilityRoll); assert.equal(result.outcome, "hit");});test("physical attack block prevents damage after winning the hit contest", () =>{ let i = 0; const rolls = [0.4, 0, 0, 0.95]; const rng = () => rolls[i++]; const result = resolvePhysicalAttack({ hitSkillLevel: 10, agilitySkillLevel: 3, damageSkillLevel: 8, defenceSkillLevel: 10, baseDamage: 1, rng }); assert.equal(result.outcome, "block"); assert.equal(result.damage, 0); assert.ok(result.defenceRoll > result.toHitRoll);});test("physical attack hit applies rolled damage when not blocked", () =>{ let i = 0; const rolls = [0.9, 0, 0, 0]; const rng = () => rolls[i++]; const result = resolvePhysicalAttack({ hitSkillLevel: 10, agilitySkillLevel: 1, damageSkillLevel: 5, defenceSkillLevel: 1, baseDamage: 2, rng }); assert.equal(result.outcome, "hit"); assert.equal(result.damage, 2);});test("skill level 1 contest can still land a hit on equal agility", () =>{ const result = resolvePhysicalAttack({ hitSkillLevel: 1, agilitySkillLevel: 1, damageSkillLevel: 1, defenceSkillLevel: 1, baseDamage: 1, rng: () => 0 }); assert.equal(result.outcome, "hit"); assert.equal(result.toHitRoll, 1); assert.equal(result.agilityRoll, 1);});@@ -54,7 +54,7 @@ function placeBank (worldDb, tileX, tileY)
);
}
test("pigeon to bank deposits money into the sender vault", () =>
test("pigeon to bank deposits coin stacks into the sender vault", () =>
{
const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
try
@@ -71,24 +71,34 @@ test("pigeon to bank deposits money into the sender vault", () =>
const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
const entityId = harness.simulation.spawnCharacter(1, character);
const before = harness.simulation.bagOf(entityId);
assert.ok((before.currency | 0) >= 5);
const coinSlot = before.inventory.findIndex((slot) => slot?.itemId === ItemId.coins);
assert.ok(coinSlot >= 0);
assert.ok(before.inventory[coinSlot].quantity >= 5);
const beforeCoins = before.inventory[coinSlot].quantity;
const result = harness.simulation.dispatchPigeon({
characterId: character.character_id,
destination: { kind: "bank" },
cargo: { kind: "money", amount: 5 }
cargo: { kind: "item", slotIndex: coinSlot, quantity: 5 }
});
assert.equal(result.transit.destinationKind, "bank");
assert.equal(harness.simulation.bagOf(entityId).currency, before.currency - 5);
assert.equal(harness.simulation.bagOf(entityId).inventory[coinSlot].quantity, beforeCoins - 5);
stepTimes(harness.simulation, 80);
const after = harness.stateDb.getBag(character.character_id);
assert.equal(after.vaultCurrency, (before.vaultCurrency | 0) + 5);
assert.equal(countItem(after.vault, ItemId.coins), 5);
assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
}
finally
{ harness.close(); }
});
function countItem (slots, itemId)
{
return (slots ?? [])
.filter((slot) => slot?.itemId === itemId)
.reduce((sum, slot) => sum + (slot.quantity | 0), 0);
}
test("pigeon delivers an item to an online player inventory", () =>
{
const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
@@ -131,3 +141,33 @@ test("pigeon delivers an item to an online player inventory", () =>
finally
{ harness.close(); }
});
test("pigeon rejects blank cheques", () =>
{
const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
try
{
placeBank(harness.worldDb, 8, 8);
harness.simulation.reloadWorld();
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
const entityId = harness.simulation.spawnCharacter(1, character);
harness.simulation.enqueue(1, {
type: "get-blank-cheques",
characterId: character.character_id
});
harness.simulation.step();
const bag = harness.simulation.bagOf(entityId);
const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
assert.ok(blankIndex >= 0);
assert.throws(
() => harness.simulation.dispatchPigeon({
characterId: character.character_id,
destination: { kind: "bank" },
cargo: { kind: "item", slotIndex: blankIndex, quantity: 1 }
}),
(err) => err.message === "Blank cheques cannot be sent by pigeon."
);
}
finally
{ harness.close(); }
});
@@ -54,7 +54,7 @@ function placeBank (worldDb, tileX, tileY) ); );}}test("pigeon to bank deposits money into the sender vault", () =>test("pigeon to bank deposits coin stacks into the sender vault", () =>{{ const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 }); const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 }); try try@@ -71,24 +71,34 @@ test("pigeon to bank deposits money into the sender vault", () => const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 }); const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 }); const entityId = harness.simulation.spawnCharacter(1, character); const entityId = harness.simulation.spawnCharacter(1, character); const before = harness.simulation.bagOf(entityId); const before = harness.simulation.bagOf(entityId); assert.ok((before.currency | 0) >= 5); const coinSlot = before.inventory.findIndex((slot) => slot?.itemId === ItemId.coins); assert.ok(coinSlot >= 0); assert.ok(before.inventory[coinSlot].quantity >= 5); const beforeCoins = before.inventory[coinSlot].quantity; const result = harness.simulation.dispatchPigeon({ const result = harness.simulation.dispatchPigeon({ characterId: character.character_id, characterId: character.character_id, destination: { kind: "bank" }, destination: { kind: "bank" }, cargo: { kind: "money", amount: 5 } cargo: { kind: "item", slotIndex: coinSlot, quantity: 5 } }); }); assert.equal(result.transit.destinationKind, "bank"); assert.equal(result.transit.destinationKind, "bank"); assert.equal(harness.simulation.bagOf(entityId).currency, before.currency - 5); assert.equal(harness.simulation.bagOf(entityId).inventory[coinSlot].quantity, beforeCoins - 5); stepTimes(harness.simulation, 80); stepTimes(harness.simulation, 80); const after = harness.stateDb.getBag(character.character_id); const after = harness.stateDb.getBag(character.character_id); assert.equal(after.vaultCurrency, (before.vaultCurrency | 0) + 5); assert.equal(countItem(after.vault, ItemId.coins), 5); assert.equal(harness.stateDb.listActiveCourierTransits().length, 0); assert.equal(harness.stateDb.listActiveCourierTransits().length, 0); } } finally finally { harness.close(); } { harness.close(); }});});function countItem (slots, itemId){ return (slots ?? []) .filter((slot) => slot?.itemId === itemId) .reduce((sum, slot) => sum + (slot.quantity | 0), 0);}test("pigeon delivers an item to an online player inventory", () =>test("pigeon delivers an item to an online player inventory", () =>{{ const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 }); const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });@@ -131,3 +141,33 @@ test("pigeon delivers an item to an online player inventory", () => finally finally { harness.close(); } { harness.close(); }});});test("pigeon rejects blank cheques", () =>{ const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 }); try { placeBank(harness.worldDb, 8, 8); harness.simulation.reloadWorld(); const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 }); const entityId = harness.simulation.spawnCharacter(1, character); harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id }); harness.simulation.step(); const bag = harness.simulation.bagOf(entityId); const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque); assert.ok(blankIndex >= 0); assert.throws( () => harness.simulation.dispatchPigeon({ characterId: character.character_id, destination: { kind: "bank" }, cargo: { kind: "item", slotIndex: blankIndex, quantity: 1 } }), (err) => err.message === "Blank cheques cannot be sent by pigeon." ); } finally { harness.close(); }});@@ -0,0 +1,86 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
CraftingStationId,
FIREPLACE_DURATION_MS,
CRAFT_DURATION_MS,
craftingStationDefinition
} from "../../shared/definitions/craftingStations.js";
import { SkillId } from "../../shared/definitions/skills.js";
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
import { emptySlots } from "../../shared/items/inventory.js";
import { canCraftFitInventory, CRAFT_DURATION_MS as RECIPE_CRAFT_MS, canStartCraft } from "../../shared/crafting/recipes.js";
import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
test("crafting stations map to the expected skills", () =>
{
assert.equal(craftingStationDefinition(CraftingStationId.furnace).skillId, SkillId.smithing);
assert.equal(craftingStationDefinition(CraftingStationId.anvil).skillId, SkillId.smithing);
assert.equal(craftingStationDefinition(CraftingStationId.loom).skillId, SkillId.tailoring);
assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);
assert.equal(craftingStationDefinition(CraftingStationId.oven).skillId, SkillId.cooking);
assert.equal(craftingStationDefinition(CraftingStationId.fireplace).skillId, SkillId.cooking);
});
test("fireplace is portable with a ten minute lifetime", () =>
{
const def = craftingStationDefinition(CraftingStationId.fireplace);
assert.equal(def.portable, true);
assert.equal(def.maxPerTile, 1);
assert.equal(def.durationMs, FIREPLACE_DURATION_MS);
assert.equal(FIREPLACE_DURATION_MS, 10 * 60 * 1000);
});
test("every craft takes two seconds", () =>
{
assert.equal(CRAFT_DURATION_MS, 2000);
assert.equal(RECIPE_CRAFT_MS, CRAFT_DURATION_MS);
});
test("canCraftFitInventory accounts for space freed by consumed materials", () =>
{
const recipe = {
output: { itemId: ItemId.stick, quantity: 1 },
inputs: [{ itemId: ItemId.paper, quantity: 2 }]
};
const slots = emptySlots();
slots[0] = { itemId: ItemId.paper, quantity: 10 };
for (let i = 1; i < 32; i++)
{ slots[i] = { itemId: ItemId.coins, quantity: 1 }; }
assert.equal(canCraftFitInventory(slots, recipe), false);
slots[31] = null;
assert.equal(canCraftFitInventory(slots, recipe), true);
});
test("canCraftFitInventory rejects missing inputs", () =>
{
const slots = emptySlots();
slots[0] = { itemId: ItemId.paper, quantity: 1 };
assert.equal(canCraftFitInventory(slots, {
output: { itemId: ItemId.stick, quantity: 1 },
inputs: [{ itemId: ItemId.paper, quantity: 2 }]
}), false);
});
test("recipesForStation lists bench recipes", () =>
{
const bench = recipesForStation(CraftingStationId.craftingBench);
assert.ok(bench.length >= 1);
assert.equal(bench[0].recipeId, "dev-stick-from-paper");
});
test("canStartCraft enforces minimum skill level", () =>
{
const slots = emptySlots();
slots[0] = { itemId: ItemId.paper, quantity: 5 };
const recipe = recipeDefinition("dev-stick-from-paper");
assert.equal(canStartCraft(slots, recipe, 1), true);
assert.equal(canStartCraft(slots, recipe, 0), false);
});
test("crafting item stubs are registered", () =>
{
assert.equal(itemDefinition(CraftingItemId.log)?.stub, true);
assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");
});
@@ -0,0 +1,86 @@import test from "node:test";import assert from "node:assert/strict";import { CraftingStationId, FIREPLACE_DURATION_MS, CRAFT_DURATION_MS, craftingStationDefinition} from "../../shared/definitions/craftingStations.js";import { SkillId } from "../../shared/definitions/skills.js";import { ItemId, itemDefinition } from "../../shared/definitions/items.js";import { emptySlots } from "../../shared/items/inventory.js";import { canCraftFitInventory, CRAFT_DURATION_MS as RECIPE_CRAFT_MS, canStartCraft } from "../../shared/crafting/recipes.js";import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";import { CraftingItemId } from "../../shared/definitions/craftingItems.js";test("crafting stations map to the expected skills", () =>{ assert.equal(craftingStationDefinition(CraftingStationId.furnace).skillId, SkillId.smithing); assert.equal(craftingStationDefinition(CraftingStationId.anvil).skillId, SkillId.smithing); assert.equal(craftingStationDefinition(CraftingStationId.loom).skillId, SkillId.tailoring); assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting); assert.equal(craftingStationDefinition(CraftingStationId.oven).skillId, SkillId.cooking); assert.equal(craftingStationDefinition(CraftingStationId.fireplace).skillId, SkillId.cooking);});test("fireplace is portable with a ten minute lifetime", () =>{ const def = craftingStationDefinition(CraftingStationId.fireplace); assert.equal(def.portable, true); assert.equal(def.maxPerTile, 1); assert.equal(def.durationMs, FIREPLACE_DURATION_MS); assert.equal(FIREPLACE_DURATION_MS, 10 * 60 * 1000);});test("every craft takes two seconds", () =>{ assert.equal(CRAFT_DURATION_MS, 2000); assert.equal(RECIPE_CRAFT_MS, CRAFT_DURATION_MS);});test("canCraftFitInventory accounts for space freed by consumed materials", () =>{ const recipe = { output: { itemId: ItemId.stick, quantity: 1 }, inputs: [{ itemId: ItemId.paper, quantity: 2 }] }; const slots = emptySlots(); slots[0] = { itemId: ItemId.paper, quantity: 10 }; for (let i = 1; i < 32; i++) { slots[i] = { itemId: ItemId.coins, quantity: 1 }; } assert.equal(canCraftFitInventory(slots, recipe), false); slots[31] = null; assert.equal(canCraftFitInventory(slots, recipe), true);});test("canCraftFitInventory rejects missing inputs", () =>{ const slots = emptySlots(); slots[0] = { itemId: ItemId.paper, quantity: 1 }; assert.equal(canCraftFitInventory(slots, { output: { itemId: ItemId.stick, quantity: 1 }, inputs: [{ itemId: ItemId.paper, quantity: 2 }] }), false);});test("recipesForStation lists bench recipes", () =>{ const bench = recipesForStation(CraftingStationId.craftingBench); assert.ok(bench.length >= 1); assert.equal(bench[0].recipeId, "dev-stick-from-paper");});test("canStartCraft enforces minimum skill level", () =>{ const slots = emptySlots(); slots[0] = { itemId: ItemId.paper, quantity: 5 }; const recipe = recipeDefinition("dev-stick-from-paper"); assert.equal(canStartCraft(slots, recipe, 1), true); assert.equal(canStartCraft(slots, recipe, 0), false);});test("crafting item stubs are registered", () =>{ assert.equal(itemDefinition(CraftingItemId.log)?.stub, true); assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");});@@ -0,0 +1,60 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
import { MaterialTier, tierStatBonus } from "../../shared/definitions/materialTiers.js";
import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
import { SkillId } from "../../shared/definitions/skills.js";
import { normalizePlayerSkills } from "../../shared/skills/state.js";
import {
canEquipItem,
effectiveSkillLevel,
equipmentBonusesFromSlots
} from "../../shared/equipment/stats.js";
import { emptyEquipment } from "../../shared/items/inventory.js";
test("tier stat bonuses scale by material", () =>
{
assert.equal(tierStatBonus(MaterialTier.bronze), 1);
assert.equal(tierStatBonus(MaterialTier.iron), 2);
assert.ok(tierStatBonus(MaterialTier.orichalcum) > tierStatBonus(MaterialTier.mithril));
});
test("equipped weapons and armour add effective combat stats", () =>
{
const skills = normalizePlayerSkills(null);
const slots = {
...emptyEquipment().slots,
weapon: { itemId: ItemId.stick, quantity: 1 },
chest: { itemId: ItemId.clothShirt, quantity: 1 }
};
const bonuses = equipmentBonusesFromSlots(slots);
assert.equal(bonuses[SkillId.strength], tierStatBonus(MaterialTier.bronze));
assert.equal(bonuses[SkillId.defence], tierStatBonus(MaterialTier.bronze));
assert.equal(
effectiveSkillLevel(skills, SkillId.strength, bonuses),
1 + tierStatBonus(MaterialTier.bronze)
);
});
test("bronze gear equips at level 1", () =>
{
const skills = normalizePlayerSkills(null);
assert.equal(canEquipItem(skills, itemDefinition(ItemId.stick)).ok, true);
assert.equal(canEquipItem(skills, itemDefinition(ItemId.clothShirt)).ok, true);
});
test("higher tiers require the relevant skill level", () =>
{
const ironSword = {
equipment: {
slot: "weapon",
tier: MaterialTier.iron,
kind: EquipmentKind.metalWeapon,
attack: { hitSkillId: SkillId.swordfighting }
}
};
const skills = normalizePlayerSkills(null);
assert.equal(canEquipItem(skills, ironSword).ok, false);
skills.xp[SkillId.swordfighting] = 999999;
assert.equal(canEquipItem(skills, ironSword).ok, true);
});
@@ -0,0 +1,60 @@import test from "node:test";import assert from "node:assert/strict";import { ItemId, itemDefinition } from "../../shared/definitions/items.js";import { MaterialTier, tierStatBonus } from "../../shared/definitions/materialTiers.js";import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";import { SkillId } from "../../shared/definitions/skills.js";import { normalizePlayerSkills } from "../../shared/skills/state.js";import { canEquipItem, effectiveSkillLevel, equipmentBonusesFromSlots} from "../../shared/equipment/stats.js";import { emptyEquipment } from "../../shared/items/inventory.js";test("tier stat bonuses scale by material", () =>{ assert.equal(tierStatBonus(MaterialTier.bronze), 1); assert.equal(tierStatBonus(MaterialTier.iron), 2); assert.ok(tierStatBonus(MaterialTier.orichalcum) > tierStatBonus(MaterialTier.mithril));});test("equipped weapons and armour add effective combat stats", () =>{ const skills = normalizePlayerSkills(null); const slots = { ...emptyEquipment().slots, weapon: { itemId: ItemId.stick, quantity: 1 }, chest: { itemId: ItemId.clothShirt, quantity: 1 } }; const bonuses = equipmentBonusesFromSlots(slots); assert.equal(bonuses[SkillId.strength], tierStatBonus(MaterialTier.bronze)); assert.equal(bonuses[SkillId.defence], tierStatBonus(MaterialTier.bronze)); assert.equal( effectiveSkillLevel(skills, SkillId.strength, bonuses), 1 + tierStatBonus(MaterialTier.bronze) );});test("bronze gear equips at level 1", () =>{ const skills = normalizePlayerSkills(null); assert.equal(canEquipItem(skills, itemDefinition(ItemId.stick)).ok, true); assert.equal(canEquipItem(skills, itemDefinition(ItemId.clothShirt)).ok, true);});test("higher tiers require the relevant skill level", () =>{ const ironSword = { equipment: { slot: "weapon", tier: MaterialTier.iron, kind: EquipmentKind.metalWeapon, attack: { hitSkillId: SkillId.swordfighting } } }; const skills = normalizePlayerSkills(null); assert.equal(canEquipItem(skills, ironSword).ok, false); skills.xp[SkillId.swordfighting] = 999999; assert.equal(canEquipItem(skills, ironSword).ok, true);});@@ -1,8 +1,10 @@
import test from "node:test";
import assert from "node:assert/strict";
import { emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
import { emptyEquipment, emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
import { ItemOriginKind } from "../../shared/items/origin.js";
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
import { BlockType } from "../../shared/definitions/tiles.js";
import { Component } from "../src/ecs/components.js";
import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
import {
makeCharacter,
@@ -10,6 +12,13 @@ import {
stepTimes
} from "./helpers/simulationHarness.js";
function workerOf (simulation, entityId)
{
const record = simulation.entityRecord(entityId);
assert.ok(record, "entity must be remembered");
return simulation.workers[record.workerId];
}
test("stackable items merge until max stack then need a new slot", () =>
{
const slots = emptySlots();
@@ -106,6 +115,129 @@ test("equip uses the item key-equip sprite for appearance layers", () =>
{ harness.close(); }
});
test("equipping from a stack takes one item and leaves the remainder", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb);
harness.stateDb.saveBag(character.character_id, {
inventory: (() =>
{
const slots = emptySlots();
slots[0] = {
itemId: ItemId.stick,
quantity: 3,
origins: [{ origin: { kind: ItemOriginKind.crafted, displayName: "Ada" }, quantity: 3 }]
};
return slots;
})(),
equipment: emptyEquipment(),
vault: [],
vaultReserved: []
});
const entityId = harness.simulation.spawnCharacter(1, character);
harness.simulation.enqueue(1, {
type: "equip-item",
characterId: character.character_id,
slotIndex: 0
});
harness.simulation.step();
const bag = harness.simulation.bagOf(entityId);
assert.equal(bag.inventory[0].quantity, 2);
assert.equal(bag.equipment.slots.weapon.quantity, 1);
assert.deepEqual(bag.equipment.slots.weapon.origins, [{
origin: { kind: ItemOriginKind.crafted, displayName: "Ada" },
quantity: 1
}]);
}
finally
{ harness.close(); }
});
test("unequipping returns one item to inventory", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb);
const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" };
harness.stateDb.saveBag(character.character_id, {
inventory: emptySlots(),
equipment: {
slots: {
weapon: {
itemId: ItemId.stick,
quantity: 1,
origins: [{ origin, quantity: 1 }]
}
}
},
vault: [],
vaultReserved: []
});
const entityId = harness.simulation.spawnCharacter(1, character);
harness.simulation.enqueue(1, {
type: "unequip-item",
characterId: character.character_id,
equipSlot: "weapon"
});
harness.simulation.step();
const bag = harness.simulation.bagOf(entityId);
assert.equal(bag.equipment.slots.weapon, null);
assert.equal(bag.inventory[0].quantity, 1);
assert.deepEqual(bag.inventory[0].origins, [{ origin, quantity: 1 }]);
}
finally
{ harness.close(); }
});
test("unequipping uses a second slot when the item cannot stack in inventory", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb);
const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" };
harness.stateDb.saveBag(character.character_id, {
inventory: (() =>
{
const slots = emptySlots();
slots[0] = {
itemId: ItemId.stick,
quantity: 1,
origins: [{ origin, quantity: 1 }]
};
return slots;
})(),
equipment: {
slots: {
weapon: {
itemId: ItemId.stick,
quantity: 1,
origins: [{ origin, quantity: 1 }]
}
}
},
vault: [],
vaultReserved: []
});
const entityId = harness.simulation.spawnCharacter(1, character);
harness.simulation.enqueue(1, {
type: "unequip-item",
characterId: character.character_id,
equipSlot: "weapon"
});
harness.simulation.step();
const bag = harness.simulation.bagOf(entityId);
assert.equal(bag.inventory[0].quantity, 1);
assert.equal(bag.inventory[1].quantity, 1);
assert.equal(bag.inventory.filter(Boolean).length, 2);
}
finally
{ harness.close(); }
});
test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
{
const harness = makeSimulation({ workerCount: 1 });
@@ -133,3 +265,33 @@ test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
finally
{ harness.close(); }
});
test("eating food restores player health", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = workerOf(harness.simulation, playerId);
const handle = worker.world.ecs.handleOf(playerId);
const health = worker.world.ecs.get(handle, Component.health);
health.current = 6;
const bag = harness.simulation.bagOf(playerId);
const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
assert.ok(appleSlot >= 0);
harness.simulation.enqueue(1, {
type: "eat-item",
characterId: character.character_id,
slotIndex: appleSlot
});
harness.simulation.step();
const after = worker.world.ecs.get(handle, Component.health);
assert.equal(after.current, 10);
assert.equal(after.max, 10);
const afterBag = harness.simulation.bagOf(playerId);
assert.equal(afterBag.inventory[appleSlot].quantity, 2);
}
finally
{ harness.close(); }
});
@@ -1,8 +1,10 @@import test from "node:test";import test from "node:test";import assert from "node:assert/strict";import assert from "node:assert/strict";import { emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";import { emptyEquipment, emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";import { ItemOriginKind } from "../../shared/items/origin.js";import { ItemId, itemDefinition } from "../../shared/definitions/items.js";import { ItemId, itemDefinition } from "../../shared/definitions/items.js";import { BlockType } from "../../shared/definitions/tiles.js";import { BlockType } from "../../shared/definitions/tiles.js";import { Component } from "../src/ecs/components.js";import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";import {import { makeCharacter, makeCharacter,@@ -10,6 +12,13 @@ import { stepTimes stepTimes} from "./helpers/simulationHarness.js";} from "./helpers/simulationHarness.js";function workerOf (simulation, entityId){ const record = simulation.entityRecord(entityId); assert.ok(record, "entity must be remembered"); return simulation.workers[record.workerId];}test("stackable items merge until max stack then need a new slot", () =>test("stackable items merge until max stack then need a new slot", () =>{{ const slots = emptySlots(); const slots = emptySlots();@@ -106,6 +115,129 @@ test("equip uses the item key-equip sprite for appearance layers", () => { harness.close(); } { harness.close(); }});});test("equipping from a stack takes one item and leaves the remainder", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb); harness.stateDb.saveBag(character.character_id, { inventory: (() => { const slots = emptySlots(); slots[0] = { itemId: ItemId.stick, quantity: 3, origins: [{ origin: { kind: ItemOriginKind.crafted, displayName: "Ada" }, quantity: 3 }] }; return slots; })(), equipment: emptyEquipment(), vault: [], vaultReserved: [] }); const entityId = harness.simulation.spawnCharacter(1, character); harness.simulation.enqueue(1, { type: "equip-item", characterId: character.character_id, slotIndex: 0 }); harness.simulation.step(); const bag = harness.simulation.bagOf(entityId); assert.equal(bag.inventory[0].quantity, 2); assert.equal(bag.equipment.slots.weapon.quantity, 1); assert.deepEqual(bag.equipment.slots.weapon.origins, [{ origin: { kind: ItemOriginKind.crafted, displayName: "Ada" }, quantity: 1 }]); } finally { harness.close(); }});test("unequipping returns one item to inventory", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb); const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" }; harness.stateDb.saveBag(character.character_id, { inventory: emptySlots(), equipment: { slots: { weapon: { itemId: ItemId.stick, quantity: 1, origins: [{ origin, quantity: 1 }] } } }, vault: [], vaultReserved: [] }); const entityId = harness.simulation.spawnCharacter(1, character); harness.simulation.enqueue(1, { type: "unequip-item", characterId: character.character_id, equipSlot: "weapon" }); harness.simulation.step(); const bag = harness.simulation.bagOf(entityId); assert.equal(bag.equipment.slots.weapon, null); assert.equal(bag.inventory[0].quantity, 1); assert.deepEqual(bag.inventory[0].origins, [{ origin, quantity: 1 }]); } finally { harness.close(); }});test("unequipping uses a second slot when the item cannot stack in inventory", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb); const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" }; harness.stateDb.saveBag(character.character_id, { inventory: (() => { const slots = emptySlots(); slots[0] = { itemId: ItemId.stick, quantity: 1, origins: [{ origin, quantity: 1 }] }; return slots; })(), equipment: { slots: { weapon: { itemId: ItemId.stick, quantity: 1, origins: [{ origin, quantity: 1 }] } } }, vault: [], vaultReserved: [] }); const entityId = harness.simulation.spawnCharacter(1, character); harness.simulation.enqueue(1, { type: "unequip-item", characterId: character.character_id, equipSlot: "weapon" }); harness.simulation.step(); const bag = harness.simulation.bagOf(entityId); assert.equal(bag.inventory[0].quantity, 1); assert.equal(bag.inventory[1].quantity, 1); assert.equal(bag.inventory.filter(Boolean).length, 2); } finally { harness.close(); }});test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>{{ const harness = makeSimulation({ workerCount: 1 }); const harness = makeSimulation({ workerCount: 1 });@@ -133,3 +265,33 @@ test("a spawner in a simulating open chunk creates deer up to maxAlive", () => finally finally { harness.close(); } { harness.close(); }});});test("eating food restores player health", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const worker = workerOf(harness.simulation, playerId); const handle = worker.world.ecs.handleOf(playerId); const health = worker.world.ecs.get(handle, Component.health); health.current = 6; const bag = harness.simulation.bagOf(playerId); const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple); assert.ok(appleSlot >= 0); harness.simulation.enqueue(1, { type: "eat-item", characterId: character.character_id, slotIndex: appleSlot }); harness.simulation.step(); const after = worker.world.ecs.get(handle, Component.health); assert.equal(after.current, 10); assert.equal(after.max, 10); const afterBag = harness.simulation.bagOf(playerId); assert.equal(afterBag.inventory[appleSlot].quantity, 2); } finally { harness.close(); }});@@ -0,0 +1,91 @@
import test from "node:test";
import assert from "node:assert/strict";
import { resolveMagicAttack, resolveMagicEffect, resolveSpellCast } from "../../shared/combat/magic.js";
import { spellDefinition, SpellId } from "../../shared/definitions/spells.js";
test("spell cast fails when difficulty roll beats magic roll", () =>
{
let i = 0;
const rng = () => [0.25, 0.45][i++];
const cast = resolveSpellCast({ magicSkillLevel: 5, spellDifficulty: 10, rng });
assert.equal(cast.success, false);
assert.equal(cast.magicRoll, 2);
assert.equal(cast.difficultyRoll, 5);
});
test("spell cast succeeds on equal magic and difficulty rolls", () =>
{
let i = 0;
const rng = () => [0.4, 0.4][i++];
const cast = resolveSpellCast({ magicSkillLevel: 5, spellDifficulty: 5, rng });
assert.equal(cast.magicRoll, cast.difficultyRoll);
assert.equal(cast.success, true);
});
test("fizzled magic attack deals no damage", () =>
{
let i = 0;
const rng = () => [0, 0.99][i++];
const result = resolveMagicAttack({
magicSkillLevel: 3,
spellDifficulty: 10,
mindSkillLevel: 10,
baseDamage: 5,
element: "fire",
rng
});
assert.equal(result.outcome, "fizzle");
assert.equal(result.damage, 0);
});
test("successful magic attack rolls mind damage and elemental multiplier", () =>
{
let i = 0;
const rng = () => [0.9, 0, 0, 0][i++];
const neutral = resolveMagicAttack({
magicSkillLevel: 10,
spellDifficulty: 1,
mindSkillLevel: 5,
baseDamage: 2,
element: "fire",
targetAffinities: {},
rng
});
assert.equal(neutral.outcome, "hit");
assert.equal(neutral.multiplier, 1);
let j = 0;
const rngWeak = () => [0.9, 0, 0, 0][j++];
const weak = resolveMagicAttack({
magicSkillLevel: 10,
spellDifficulty: 1,
mindSkillLevel: 5,
baseDamage: 2,
element: "fire",
targetAffinities: { fire: "weak" },
rng: rngWeak
});
assert.equal(weak.multiplier, 2);
assert.equal(weak.damage, neutral.damage * 2);
});
test("non-damage spell applies effect only after a successful cast roll", () =>
{
let i = 0;
const rng = () => [0.9, 0][i++];
const result = resolveMagicEffect({
magicSkillLevel: 10,
spellDifficulty: 3,
effectId: "slow",
rng
});
assert.equal(result.outcome, "effect");
assert.equal(result.effectId, "slow");
});
test("spell definitions expose per-spell difficulty", () =>
{
const spark = spellDefinition(SpellId.spark);
assert.equal(spark.difficulty, 4);
assert.equal(spark.element, "fire");
});
@@ -0,0 +1,91 @@import test from "node:test";import assert from "node:assert/strict";import { resolveMagicAttack, resolveMagicEffect, resolveSpellCast } from "../../shared/combat/magic.js";import { spellDefinition, SpellId } from "../../shared/definitions/spells.js";test("spell cast fails when difficulty roll beats magic roll", () =>{ let i = 0; const rng = () => [0.25, 0.45][i++]; const cast = resolveSpellCast({ magicSkillLevel: 5, spellDifficulty: 10, rng }); assert.equal(cast.success, false); assert.equal(cast.magicRoll, 2); assert.equal(cast.difficultyRoll, 5);});test("spell cast succeeds on equal magic and difficulty rolls", () =>{ let i = 0; const rng = () => [0.4, 0.4][i++]; const cast = resolveSpellCast({ magicSkillLevel: 5, spellDifficulty: 5, rng }); assert.equal(cast.magicRoll, cast.difficultyRoll); assert.equal(cast.success, true);});test("fizzled magic attack deals no damage", () =>{ let i = 0; const rng = () => [0, 0.99][i++]; const result = resolveMagicAttack({ magicSkillLevel: 3, spellDifficulty: 10, mindSkillLevel: 10, baseDamage: 5, element: "fire", rng }); assert.equal(result.outcome, "fizzle"); assert.equal(result.damage, 0);});test("successful magic attack rolls mind damage and elemental multiplier", () =>{ let i = 0; const rng = () => [0.9, 0, 0, 0][i++]; const neutral = resolveMagicAttack({ magicSkillLevel: 10, spellDifficulty: 1, mindSkillLevel: 5, baseDamage: 2, element: "fire", targetAffinities: {}, rng }); assert.equal(neutral.outcome, "hit"); assert.equal(neutral.multiplier, 1); let j = 0; const rngWeak = () => [0.9, 0, 0, 0][j++]; const weak = resolveMagicAttack({ magicSkillLevel: 10, spellDifficulty: 1, mindSkillLevel: 5, baseDamage: 2, element: "fire", targetAffinities: { fire: "weak" }, rng: rngWeak }); assert.equal(weak.multiplier, 2); assert.equal(weak.damage, neutral.damage * 2);});test("non-damage spell applies effect only after a successful cast roll", () =>{ let i = 0; const rng = () => [0.9, 0][i++]; const result = resolveMagicEffect({ magicSkillLevel: 10, spellDifficulty: 3, effectId: "slow", rng }); assert.equal(result.outcome, "effect"); assert.equal(result.effectId, "slow");});test("spell definitions expose per-spell difficulty", () =>{ const spark = spellDefinition(SpellId.spark); assert.equal(spark.difficulty, 4); assert.equal(spark.element, "fire");});@@ -0,0 +1,30 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ItemId } from "../../shared/definitions/items.js";
import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
test("blank cheques cannot be listed on the marketplace", () =>
{
const stack = { itemId: ItemId.blankCheque, quantity: 1 };
assert.equal(canSellOnMarketplace(stack), false);
assert.throws(
() => assertMarketplaceSellable(stack),
(err) => err.message === "Blank cheques cannot be sold on the marketplace."
);
});
test("written cheques can be listed on the marketplace", () =>
{
const stack = {
itemId: ItemId.filledCheque,
quantity: 1,
instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 2 }
};
assert.equal(canSellOnMarketplace(stack), true);
assert.doesNotThrow(() => assertMarketplaceSellable(stack));
});
test("normal items are marketplace sellable by default", () =>
{
assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);
});
@@ -0,0 +1,30 @@import test from "node:test";import assert from "node:assert/strict";import { ItemId } from "../../shared/definitions/items.js";import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";test("blank cheques cannot be listed on the marketplace", () =>{ const stack = { itemId: ItemId.blankCheque, quantity: 1 }; assert.equal(canSellOnMarketplace(stack), false); assert.throws( () => assertMarketplaceSellable(stack), (err) => err.message === "Blank cheques cannot be sold on the marketplace." );});test("written cheques can be listed on the marketplace", () =>{ const stack = { itemId: ItemId.filledCheque, quantity: 1, instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 2 } }; assert.equal(canSellOnMarketplace(stack), true); assert.doesNotThrow(() => assertMarketplaceSellable(stack));});test("normal items are marketplace sellable by default", () =>{ assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);});@@ -0,0 +1,18 @@
import test from "node:test";
import assert from "node:assert/strict";
import { mobCanFight, mobMeleeAttackProfile } from "../../shared/definitions/mobCombat.js";
import { MobId, mobDefinition } from "../../shared/definitions/mobs.js";
test("living targetable mobs can fight except pigeons", () =>
{
assert.equal(mobCanFight(mobDefinition(MobId.deer)), true);
assert.equal(mobCanFight(mobDefinition(MobId.rat)), true);
assert.equal(mobCanFight(mobDefinition(MobId.pigeon)), false);
});
test("mob attack profile uses one attackSkill for hit and damage rolls", () =>
{
const profile = mobMeleeAttackProfile(mobDefinition(MobId.rat));
assert.equal(profile.mobAttackSkill, 3);
assert.equal(profile.baseDamage, 2);
});
@@ -0,0 +1,18 @@import test from "node:test";import assert from "node:assert/strict";import { mobCanFight, mobMeleeAttackProfile } from "../../shared/definitions/mobCombat.js";import { MobId, mobDefinition } from "../../shared/definitions/mobs.js";test("living targetable mobs can fight except pigeons", () =>{ assert.equal(mobCanFight(mobDefinition(MobId.deer)), true); assert.equal(mobCanFight(mobDefinition(MobId.rat)), true); assert.equal(mobCanFight(mobDefinition(MobId.pigeon)), false);});test("mob attack profile uses one attackSkill for hit and damage rolls", () =>{ const profile = mobMeleeAttackProfile(mobDefinition(MobId.rat)); assert.equal(profile.mobAttackSkill, 3); assert.equal(profile.baseDamage, 2);});@@ -0,0 +1,125 @@
import test from "node:test";
import assert from "node:assert/strict";
import { ItemOriginKind, formatOriginBreakdown, mergeOriginLists, splitOrigins } from "../../shared/items/origin.js";
import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";
import { stackRulesFor } from "../../shared/items/stackRules.js";
import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
const crafterA = { kind: ItemOriginKind.crafted, displayName: "Ada" };
const crafterB = { kind: ItemOriginKind.crafted, displayName: "Bob" };
test("mixed-origin stacks merge and show a breakdown label", () =>
{
const slots = emptySlots();
const def = itemDefinition(ItemId.apple);
const first = insertStack(slots, {
itemId: ItemId.apple,
quantity: 5,
origins: [{ origin: crafterA, quantity: 5 }]
}, def);
const second = insertStack(first.slots, {
itemId: ItemId.apple,
quantity: 3,
origins: [{ origin: crafterB, quantity: 3 }]
}, def);
assert.equal(second.ok, true);
assert.equal(second.slots[0].quantity, 8);
assert.equal(formatOriginBreakdown(second.slots[0]), "5 made by Ada, 3 made by Bob");
});
test("splitting a stack distributes origins FIFO", () =>
{
const slots = emptySlots();
const def = itemDefinition(ItemId.apple);
const inserted = insertStack(slots, {
itemId: ItemId.apple,
quantity: 8,
origins: [
{ origin: crafterA, quantity: 5 },
{ origin: crafterB, quantity: 3 }
]
}, def);
const taken = takeFromSlot(inserted.slots, 0, 6);
assert.equal(taken.taken.quantity, 6);
assert.deepEqual(taken.taken.origins, [
{ origin: crafterA, quantity: 5 },
{ origin: crafterB, quantity: 1 }
]);
assert.deepEqual(taken.slots[0].origins, [
{ origin: crafterB, quantity: 2 }
]);
});
test("equipment stacks only in inventory, but can stack in the vault", () =>
{
const shirt = itemDefinition(ItemId.clothShirt);
const invRules = stackRulesFor(shirt, { inVault: false });
const vaultRules = stackRulesFor(shirt, { inVault: true });
assert.equal(invRules.maxStackSize, 1);
assert.equal(invRules.stackable, false);
assert.equal(vaultRules.stackable, true);
assert.equal(vaultRules.maxStackSize, Number.POSITIVE_INFINITY);
const inv = insertStack(emptySlots(), { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
const invSecond = insertStack(inv.slots, { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
assert.equal(invSecond.slots.filter(Boolean).length, 2);
const vault = insertStackGrowable([], { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
const vaultSecond = insertStackGrowable(vault.slots, { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
assert.equal(vaultSecond.slots.length, 1);
assert.equal(vaultSecond.slots[0].quantity, 2);
});
test("unique items never stack, even in the vault", () =>
{
const letter = itemDefinition(ItemId.letter);
const vaultRules = stackRulesFor(letter, { inVault: true });
assert.equal(vaultRules.uniqueInstance, true);
assert.equal(vaultRules.stackable, false);
const first = insertStackGrowable([], {
itemId: ItemId.letter,
quantity: 1,
instance: { kind: "letter", letterId: "a", body: "Hi" }
}, letter);
const second = insertStackGrowable(first.slots, {
itemId: ItemId.letter,
quantity: 1,
instance: { kind: "letter", letterId: "b", body: "Bye" }
}, letter);
assert.equal(second.slots.length, 2);
});
test("mergeOriginLists combines matching crafters", () =>
{
const merged = mergeOriginLists(
[{ origin: crafterA, quantity: 2 }],
[{ origin: crafterA, quantity: 3 }, { origin: crafterB, quantity: 1 }]
);
assert.deepEqual(merged, [
{ origin: crafterA, quantity: 5 },
{ origin: crafterB, quantity: 1 }
]);
const split = splitOrigins(merged, 6);
assert.deepEqual(split.taken, [
{ origin: crafterA, quantity: 5 },
{ origin: crafterB, quantity: 1 }
]);
});
test("unequip-style insert merges stackable items within max stack size", () =>
{
const def = itemDefinition(ItemId.apple);
const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" };
let slots = emptySlots();
slots[0] = { itemId: ItemId.apple, quantity: 5, origins: [{ origin, quantity: 5 }] };
const worn = singleItemFromStack({
itemId: ItemId.apple,
quantity: 1,
origins: [{ origin, quantity: 1 }]
});
const inserted = insertStack(slots, worn, def);
assert.equal(inserted.ok, true);
assert.equal(inserted.slots[0].quantity, 6);
assert.equal(inserted.slots.filter(Boolean).length, 1);
});
@@ -0,0 +1,125 @@import test from "node:test";import assert from "node:assert/strict";import { ItemOriginKind, formatOriginBreakdown, mergeOriginLists, splitOrigins } from "../../shared/items/origin.js";import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";import { stackRulesFor } from "../../shared/items/stackRules.js";import { ItemId, itemDefinition } from "../../shared/definitions/items.js";const crafterA = { kind: ItemOriginKind.crafted, displayName: "Ada" };const crafterB = { kind: ItemOriginKind.crafted, displayName: "Bob" };test("mixed-origin stacks merge and show a breakdown label", () =>{ const slots = emptySlots(); const def = itemDefinition(ItemId.apple); const first = insertStack(slots, { itemId: ItemId.apple, quantity: 5, origins: [{ origin: crafterA, quantity: 5 }] }, def); const second = insertStack(first.slots, { itemId: ItemId.apple, quantity: 3, origins: [{ origin: crafterB, quantity: 3 }] }, def); assert.equal(second.ok, true); assert.equal(second.slots[0].quantity, 8); assert.equal(formatOriginBreakdown(second.slots[0]), "5 made by Ada, 3 made by Bob");});test("splitting a stack distributes origins FIFO", () =>{ const slots = emptySlots(); const def = itemDefinition(ItemId.apple); const inserted = insertStack(slots, { itemId: ItemId.apple, quantity: 8, origins: [ { origin: crafterA, quantity: 5 }, { origin: crafterB, quantity: 3 } ] }, def); const taken = takeFromSlot(inserted.slots, 0, 6); assert.equal(taken.taken.quantity, 6); assert.deepEqual(taken.taken.origins, [ { origin: crafterA, quantity: 5 }, { origin: crafterB, quantity: 1 } ]); assert.deepEqual(taken.slots[0].origins, [ { origin: crafterB, quantity: 2 } ]);});test("equipment stacks only in inventory, but can stack in the vault", () =>{ const shirt = itemDefinition(ItemId.clothShirt); const invRules = stackRulesFor(shirt, { inVault: false }); const vaultRules = stackRulesFor(shirt, { inVault: true }); assert.equal(invRules.maxStackSize, 1); assert.equal(invRules.stackable, false); assert.equal(vaultRules.stackable, true); assert.equal(vaultRules.maxStackSize, Number.POSITIVE_INFINITY); const inv = insertStack(emptySlots(), { itemId: ItemId.clothShirt, quantity: 1 }, shirt); const invSecond = insertStack(inv.slots, { itemId: ItemId.clothShirt, quantity: 1 }, shirt); assert.equal(invSecond.slots.filter(Boolean).length, 2); const vault = insertStackGrowable([], { itemId: ItemId.clothShirt, quantity: 1 }, shirt); const vaultSecond = insertStackGrowable(vault.slots, { itemId: ItemId.clothShirt, quantity: 1 }, shirt); assert.equal(vaultSecond.slots.length, 1); assert.equal(vaultSecond.slots[0].quantity, 2);});test("unique items never stack, even in the vault", () =>{ const letter = itemDefinition(ItemId.letter); const vaultRules = stackRulesFor(letter, { inVault: true }); assert.equal(vaultRules.uniqueInstance, true); assert.equal(vaultRules.stackable, false); const first = insertStackGrowable([], { itemId: ItemId.letter, quantity: 1, instance: { kind: "letter", letterId: "a", body: "Hi" } }, letter); const second = insertStackGrowable(first.slots, { itemId: ItemId.letter, quantity: 1, instance: { kind: "letter", letterId: "b", body: "Bye" } }, letter); assert.equal(second.slots.length, 2);});test("mergeOriginLists combines matching crafters", () =>{ const merged = mergeOriginLists( [{ origin: crafterA, quantity: 2 }], [{ origin: crafterA, quantity: 3 }, { origin: crafterB, quantity: 1 }] ); assert.deepEqual(merged, [ { origin: crafterA, quantity: 5 }, { origin: crafterB, quantity: 1 } ]); const split = splitOrigins(merged, 6); assert.deepEqual(split.taken, [ { origin: crafterA, quantity: 5 }, { origin: crafterB, quantity: 1 } ]);});test("unequip-style insert merges stackable items within max stack size", () =>{ const def = itemDefinition(ItemId.apple); const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" }; let slots = emptySlots(); slots[0] = { itemId: ItemId.apple, quantity: 5, origins: [{ origin, quantity: 5 }] }; const worn = singleItemFromStack({ itemId: ItemId.apple, quantity: 1, origins: [{ origin, quantity: 1 }] }); const inserted = insertStack(slots, worn, def); assert.equal(inserted.ok, true); assert.equal(inserted.slots[0].quantity, 6); assert.equal(inserted.slots.filter(Boolean).length, 1);});@@ -0,0 +1,146 @@
import test from "node:test";
import assert from "node:assert/strict";
import {
SKILL_XP_BASE,
xpToAdvanceFromLevel,
totalXpForLevel,
xpProgress,
levelFromTotalXp,
combatHitXpPerSkill
} from "../../shared/skills/progression.js";
import {
normalizeSkillXp,
normalizePlayerSkills,
defaultPlayerSkills,
addSkillXp,
publicSkillsView
} from "../../shared/skills/state.js";
import { skillLevel, SkillId, playerMaxHealth } from "../../shared/definitions/skills.js";
import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
import { mobComponents } from "../src/simulation/spawners.js";
import { MobId } from "../../shared/definitions/mobs.js";
import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
test("xp to advance doubles each level starting at 50", () =>
{
assert.equal(xpToAdvanceFromLevel(1), 50);
assert.equal(xpToAdvanceFromLevel(2), 100);
assert.equal(xpToAdvanceFromLevel(3), 200);
assert.equal(xpToAdvanceFromLevel(99), 0);
});
test("level is derived from total xp", () =>
{
assert.equal(levelFromTotalXp(0), 1);
assert.equal(levelFromTotalXp(SKILL_XP_BASE - 1), 1);
assert.equal(levelFromTotalXp(SKILL_XP_BASE), 2);
assert.equal(totalXpForLevel(2), SKILL_XP_BASE);
assert.equal(totalXpForLevel(3), SKILL_XP_BASE + xpToAdvanceFromLevel(2));
});
test("skills cap at level 99", () =>
{
const capped = totalXpForLevel(100) - 1;
assert.equal(levelFromTotalXp(capped), 99);
const progress = xpProgress(capped);
assert.equal(progress.level, 99);
assert.equal(progress.xpToNext, 0);
});
test("xp progress reports in-level remainder", () =>
{
const progress = xpProgress(SKILL_XP_BASE + 25);
assert.equal(progress.level, 2);
assert.equal(progress.xpInLevel, 25);
assert.equal(progress.xpToNext, xpToAdvanceFromLevel(2));
});
test("normalizeSkillXp fills every skill id", () =>
{
const xp = normalizeSkillXp({ [SkillId.strength]: 42 });
assert.equal(xp[SkillId.strength], 42);
assert.equal(xp[SkillId.magic], 0);
});
test("skillLevel reads player xp and mob levels", () =>
{
assert.equal(skillLevel(normalizePlayerSkills(null), SkillId.clubfighting), 1);
assert.equal(skillLevel({ xp: { [SkillId.strength]: SKILL_XP_BASE } }, SkillId.strength), 2);
assert.equal(skillLevel({ levels: { [SkillId.unarmed]: 5 } }, SkillId.unarmed), 5);
});
test("new characters start with Health level 10", () =>
{
const skills = defaultPlayerSkills();
assert.equal(skillLevel(skills, SkillId.health), 10);
assert.equal(skillLevel(skills, SkillId.strength), 1);
assert.equal(playerMaxHealth(skills), 10);
});
test("publicSkillsView exposes progress fields for the client", () =>
{
const view = publicSkillsView(normalizePlayerSkills({ [SkillId.clubfighting]: 50 }));
const club = view.find((entry) => entry.skillId === SkillId.clubfighting);
assert.equal(club.level, 2);
assert.equal(club.xp, 0);
assert.equal(club.xpToNext, xpToAdvanceFromLevel(2));
assert.match(club.icon, /clubfighting\.svg$/);
});
test("addSkillXp mutates the player skills component", () =>
{
const skills = normalizePlayerSkills(null);
addSkillXp(skills, SkillId.strength, 10);
assert.equal(skills.xp[SkillId.strength], 10);
});
test("combat hit xp is split equally", () =>
{
assert.equal(combatHitXpPerSkill(), 5);
});
test("successful player melee hits award split xp", () =>
{
const harness = makeSimulation({ workerCount: 1 });
const random = Math.random;
Math.random = () => 0;
try
{
const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
const playerId = harness.simulation.spawnCharacter(1, character);
const ratId = harness.simulation.spawnEntity(mobComponents({
mobTypeId: MobId.rat,
position: { tileX: 9, tileY: 8 }
}));
const worker = harness.simulation.workers[0];
const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(playerId));
const events = resolveMeleeSwing(worker.world, playerId, ratId, profile, Date.now());
const updated = events.find((event) => event.type === "skills-updated");
assert.ok(updated);
assert.equal(updated.stored[profile.hitSkillId], combatHitXpPerSkill());
assert.equal(updated.stored[profile.damageSkillId], combatHitXpPerSkill());
}
finally
{
Math.random = random;
harness.close();
}
});
test("skills persist when a character despawns", () =>
{
const harness = makeSimulation({ workerCount: 1 });
try
{
const character = makeCharacter(harness.stateDb);
const playerId = harness.simulation.spawnCharacter(1, character);
const worker = harness.simulation.workers[0];
const skills = worker.world.ecs.get(worker.world.ecs.handleOf(playerId), "skills");
skills.xp[SkillId.strength] = SKILL_XP_BASE + 10;
harness.simulation.despawnCharacter(character.character_id);
const stored = harness.stateDb.getSkills(character.character_id);
assert.equal(stored.xp[SkillId.strength], SKILL_XP_BASE + 10);
}
finally
{ harness.close(); }
});
@@ -0,0 +1,146 @@import test from "node:test";import assert from "node:assert/strict";import { SKILL_XP_BASE, xpToAdvanceFromLevel, totalXpForLevel, xpProgress, levelFromTotalXp, combatHitXpPerSkill} from "../../shared/skills/progression.js";import { normalizeSkillXp, normalizePlayerSkills, defaultPlayerSkills, addSkillXp, publicSkillsView} from "../../shared/skills/state.js";import { skillLevel, SkillId, playerMaxHealth } from "../../shared/definitions/skills.js";import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";import { mobComponents } from "../src/simulation/spawners.js";import { MobId } from "../../shared/definitions/mobs.js";import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";test("xp to advance doubles each level starting at 50", () =>{ assert.equal(xpToAdvanceFromLevel(1), 50); assert.equal(xpToAdvanceFromLevel(2), 100); assert.equal(xpToAdvanceFromLevel(3), 200); assert.equal(xpToAdvanceFromLevel(99), 0);});test("level is derived from total xp", () =>{ assert.equal(levelFromTotalXp(0), 1); assert.equal(levelFromTotalXp(SKILL_XP_BASE - 1), 1); assert.equal(levelFromTotalXp(SKILL_XP_BASE), 2); assert.equal(totalXpForLevel(2), SKILL_XP_BASE); assert.equal(totalXpForLevel(3), SKILL_XP_BASE + xpToAdvanceFromLevel(2));});test("skills cap at level 99", () =>{ const capped = totalXpForLevel(100) - 1; assert.equal(levelFromTotalXp(capped), 99); const progress = xpProgress(capped); assert.equal(progress.level, 99); assert.equal(progress.xpToNext, 0);});test("xp progress reports in-level remainder", () =>{ const progress = xpProgress(SKILL_XP_BASE + 25); assert.equal(progress.level, 2); assert.equal(progress.xpInLevel, 25); assert.equal(progress.xpToNext, xpToAdvanceFromLevel(2));});test("normalizeSkillXp fills every skill id", () =>{ const xp = normalizeSkillXp({ [SkillId.strength]: 42 }); assert.equal(xp[SkillId.strength], 42); assert.equal(xp[SkillId.magic], 0);});test("skillLevel reads player xp and mob levels", () =>{ assert.equal(skillLevel(normalizePlayerSkills(null), SkillId.clubfighting), 1); assert.equal(skillLevel({ xp: { [SkillId.strength]: SKILL_XP_BASE } }, SkillId.strength), 2); assert.equal(skillLevel({ levels: { [SkillId.unarmed]: 5 } }, SkillId.unarmed), 5);});test("new characters start with Health level 10", () =>{ const skills = defaultPlayerSkills(); assert.equal(skillLevel(skills, SkillId.health), 10); assert.equal(skillLevel(skills, SkillId.strength), 1); assert.equal(playerMaxHealth(skills), 10);});test("publicSkillsView exposes progress fields for the client", () =>{ const view = publicSkillsView(normalizePlayerSkills({ [SkillId.clubfighting]: 50 })); const club = view.find((entry) => entry.skillId === SkillId.clubfighting); assert.equal(club.level, 2); assert.equal(club.xp, 0); assert.equal(club.xpToNext, xpToAdvanceFromLevel(2)); assert.match(club.icon, /clubfighting\.svg$/);});test("addSkillXp mutates the player skills component", () =>{ const skills = normalizePlayerSkills(null); addSkillXp(skills, SkillId.strength, 10); assert.equal(skills.xp[SkillId.strength], 10);});test("combat hit xp is split equally", () =>{ assert.equal(combatHitXpPerSkill(), 5);});test("successful player melee hits award split xp", () =>{ const harness = makeSimulation({ workerCount: 1 }); const random = Math.random; Math.random = () => 0; try { const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 }); const playerId = harness.simulation.spawnCharacter(1, character); const ratId = harness.simulation.spawnEntity(mobComponents({ mobTypeId: MobId.rat, position: { tileX: 9, tileY: 8 } })); const worker = harness.simulation.workers[0]; const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(playerId)); const events = resolveMeleeSwing(worker.world, playerId, ratId, profile, Date.now()); const updated = events.find((event) => event.type === "skills-updated"); assert.ok(updated); assert.equal(updated.stored[profile.hitSkillId], combatHitXpPerSkill()); assert.equal(updated.stored[profile.damageSkillId], combatHitXpPerSkill()); } finally { Math.random = random; harness.close(); }});test("skills persist when a character despawns", () =>{ const harness = makeSimulation({ workerCount: 1 }); try { const character = makeCharacter(harness.stateDb); const playerId = harness.simulation.spawnCharacter(1, character); const worker = harness.simulation.workers[0]; const skills = worker.world.ecs.get(worker.world.ecs.handleOf(playerId), "skills"); skills.xp[SkillId.strength] = SKILL_XP_BASE + 10; harness.simulation.despawnCharacter(character.character_id); const stored = harness.stateDb.getSkills(character.character_id); assert.equal(stored.xp[SkillId.strength], SKILL_XP_BASE + 10); } finally { harness.close(); }});