BlueGit

timfa questward

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.

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
d215c5031d50c46366c6b942e447c07fd565b2bd
Parent
47f357e3
106 files changed +5560 −345
client/assets/fx/melee-swipe/melee-swipe.png Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-1.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-1000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-10000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-1000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-10000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-1000000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-10000000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-100000000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-1000000000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-10000000000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-100000000000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-15.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-150.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-1500.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-2000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-20000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-5.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-50.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-500.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-5000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-50000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-50000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-500000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-500000000000000.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/coins/coins-999999999999999.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/filled-cheque/filled-cheque.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/skills/archery.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/axefighting.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/clubfighting.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/cooking.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/crafting.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/defence.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/dexterity.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/fishing.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/health.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/leatherworking.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/magic.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/mind.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/mining.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/smithing.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/stamina.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/strength.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/swordfighting.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/tailoring.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/unarmed.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/assets/skills/woodcutting.svg added +1 −0
@@ -0,0 +1 @@
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 @@
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>
client/index.html +83 −9
@@ -11,19 +11,19 @@
11 11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
12 12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13 13 <button id="friends-toggle" type="button">Friends</button>
14 <button id="skills-toggle" type="button">Skills</button>
14 15 <button id="bag-toggle" type="button">Bag</button>
15 16 <button id="leave" type="button">Leave world</button>
16 17 </div>
17 18 <aside id="bag-panel" hidden>
18 19 <h2>Bag</h2>
19 <p id="bag-coins">0 coins</p>
20 <p id="bag-coins" hidden>0 coins</p>
20 21 <div id="equip-grid" class="item-grid equip"></div>
21 22 <div id="bag-grid" class="item-grid"></div>
22 23 <p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p>
23 24 <div class="bag-actions">
24 25 <button id="bag-drop" type="button">Drop</button>
25 26 <button id="bag-equip" type="button">Equip</button>
26 <button id="bag-bank" type="button">Deposit selected</button>
27 27 </div>
28 28 </aside>
29 29 <aside id="bank-panel" hidden>
@@ -31,13 +31,25 @@
31 31 <h2>Bank</h2>
32 32 <button id="bank-close" type="button">Close</button>
33 33 </header>
34 <p id="vault-coins"></p>
35 <div id="vault-grid" class="item-grid"></div>
36 <h3>Inheritance</h3>
37 <p id="inherit-coins"></p>
38 <div id="inherit-grid" class="item-grid"></div>
39 <button id="bank-claim" type="button">Claim inheritance into vault</button>
40 <p class="hint">Stand next to a bank block. Click a vault slot to withdraw. Deposit uses the selected bag slot.</p>
34 <p id="vault-coins" hidden></p>
35 <div class="bank-tabs">
36 <button id="bank-tab-available" type="button" class="bank-tab active">Available</button>
37 <button id="bank-tab-reserved" type="button" class="bank-tab">Reserved</button>
38 <button id="bank-tab-inherit" type="button" class="bank-tab">Inheritance</button>
39 </div>
40 <div id="bank-available-pane">
41 <div id="vault-grid" class="item-grid"></div>
42 <p class="hint">Click an item to move it to your bag. Right-click for partial transfers.</p>
43 </div>
44 <div id="bank-reserved-pane" hidden>
45 <div id="vault-reserved-grid" class="item-grid"></div>
46 <p class="hint">Goods reserved by outstanding cheques. Redeem a cheque at the bank to claim them.</p>
47 </div>
48 <div id="bank-inherit-pane" hidden>
49 <p id="inherit-coins" hidden></p>
50 <div id="inherit-grid" class="item-grid"></div>
51 <button id="bank-claim" type="button">Claim inheritance into vault</button>
52 </div>
41 53 </aside>
42 54 <aside id="friends-panel" hidden>
43 55 <h2>Friends</h2>
@@ -48,6 +60,11 @@
48 60 <div id="outgoing-list"></div>
49 61 <p class="hint">Right-click a bag item and choose Send to deliver by pigeon to the bank or a player.</p>
50 62 </aside>
63 <aside id="skills-panel" hidden>
64 <h2>Skills</h2>
65 <div id="skills-list" class="skills-grid"></div>
66 <p class="hint">Successful melee hits split XP between the weapon skill and Strength.</p>
67 </aside>
51 68
52 69 <div id="send-backdrop" class="modal-backdrop" hidden></div>
53 70 <aside id="send-panel" hidden>
@@ -82,6 +99,35 @@
82 99 <div id="send-search-result"></div>
83 100 </aside>
84 101
102 <div id="transfer-backdrop" class="modal-backdrop" hidden></div>
103 <aside id="transfer-panel" hidden>
104 <header>
105 <h2>Transfer</h2>
106 <button id="transfer-close" type="button">Close</button>
107 </header>
108 <p id="transfer-item-name"></p>
109 <label class="send-row">Quantity
110 <input id="transfer-qty" type="number" min="1" step="1" value="1">
111 </label>
112 <button id="transfer-confirm" type="button">Transfer</button>
113 </aside>
114
115 <div id="write-cheque-backdrop" class="modal-backdrop" hidden></div>
116 <aside id="write-cheque-panel" hidden>
117 <header>
118 <h2>Write cheque</h2>
119 <button id="write-cheque-close" type="button">Close</button>
120 </header>
121 <p id="write-cheque-hint" class="hint">Choose goods from your vault to reserve on this cheque.</p>
122 <div id="write-cheque-vault" class="item-grid"></div>
123 <p id="write-cheque-item"></p>
124 <label class="send-row">Quantity
125 <input id="write-cheque-qty" type="number" min="1" step="1" value="1">
126 </label>
127 <button id="write-cheque-confirm" type="button" disabled>Write</button>
128 <p id="write-cheque-status" class="hint"></p>
129 </aside>
130
85 131 <div id="letter-backdrop" class="modal-backdrop" hidden></div>
86 132 <aside id="letter-panel" hidden>
87 133 <header>
@@ -98,6 +144,34 @@
98 144 <p id="letter-status" class="hint"></p>
99 145 </aside>
100 146
147 <div id="craft-backdrop" class="modal-backdrop" hidden></div>
148 <aside id="craft-panel" hidden>
149 <header>
150 <h2 id="craft-station-name">Crafting</h2>
151 <button id="craft-close" type="button">Close</button>
152 </header>
153 <div class="craft-layout">
154 <div class="craft-recipes">
155 <div id="craft-recipe-grid" class="craft-recipe-grid"></div>
156 </div>
157 <div class="craft-detail">
158 <p id="craft-detail-empty" class="hint">Select a recipe.</p>
159 <div id="craft-detail-body" hidden>
160 <div class="craft-output">
161 <img id="craft-output-img" alt="">
162 <h3 id="craft-output-name"></h3>
163 </div>
164 <ul id="craft-inputs" class="craft-inputs"></ul>
165 <p id="craft-status" class="hint"></p>
166 <div id="craft-progress" class="craft-progress" hidden>
167 <div id="craft-progress-fill" class="craft-progress-fill"></div>
168 </div>
169 <button id="craft-button" type="button" disabled>Craft</button>
170 </div>
171 </div>
172 </div>
173 </aside>
174
101 175 <div id="nametag" hidden></div>
102 176 <div id="chat-bubbles"></div>
103 177 <div id="chat-bar" hidden>
@@ -11,19 +11,19 @@
11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13 <button id="friends-toggle" type="button">Friends</button>
13 <button id="friends-toggle" type="button">Friends</button>
14 <button id="skills-toggle" type="button">Skills</button>
14 <button id="bag-toggle" type="button">Bag</button>
15 <button id="bag-toggle" type="button">Bag</button>
15 <button id="leave" type="button">Leave world</button>
16 <button id="leave" type="button">Leave world</button>
16 </div>
17 </div>
17 <aside id="bag-panel" hidden>
18 <aside id="bag-panel" hidden>
18 <h2>Bag</h2>
19 <h2>Bag</h2>
19 <p id="bag-coins">0 coins</p>
20 <p id="bag-coins" hidden>0 coins</p>
20 <div id="equip-grid" class="item-grid equip"></div>
21 <div id="equip-grid" class="item-grid equip"></div>
21 <div id="bag-grid" class="item-grid"></div>
22 <div id="bag-grid" class="item-grid"></div>
22 <p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p>
23 <p id="bag-hint" class="hint">Left-click to select. Right-click an item for Send, Equip, Drop, or Write letter.</p>
23 <div class="bag-actions">
24 <div class="bag-actions">
24 <button id="bag-drop" type="button">Drop</button>
25 <button id="bag-drop" type="button">Drop</button>
25 <button id="bag-equip" type="button">Equip</button>
26 <button id="bag-equip" type="button">Equip</button>
26 <button id="bag-bank" type="button">Deposit selected</button>
27 </div>
27 </div>
28 </aside>
28 </aside>
29 <aside id="bank-panel" hidden>
29 <aside id="bank-panel" hidden>
@@ -31,13 +31,25 @@
31 <h2>Bank</h2>
31 <h2>Bank</h2>
32 <button id="bank-close" type="button">Close</button>
32 <button id="bank-close" type="button">Close</button>
33 </header>
33 </header>
34 <p id="vault-coins"></p>
34 <p id="vault-coins" hidden></p>
35 <div id="vault-grid" class="item-grid"></div>
35 <div class="bank-tabs">
36 <h3>Inheritance</h3>
36 <button id="bank-tab-available" type="button" class="bank-tab active">Available</button>
37 <p id="inherit-coins"></p>
37 <button id="bank-tab-reserved" type="button" class="bank-tab">Reserved</button>
38 <div id="inherit-grid" class="item-grid"></div>
38 <button id="bank-tab-inherit" type="button" class="bank-tab">Inheritance</button>
39 <button id="bank-claim" type="button">Claim inheritance into vault</button>
39 </div>
40 <p class="hint">Stand next to a bank block. Click a vault slot to withdraw. Deposit uses the selected bag slot.</p>
40 <div id="bank-available-pane">
41 <div id="vault-grid" class="item-grid"></div>
42 <p class="hint">Click an item to move it to your bag. Right-click for partial transfers.</p>
43 </div>
44 <div id="bank-reserved-pane" hidden>
45 <div id="vault-reserved-grid" class="item-grid"></div>
46 <p class="hint">Goods reserved by outstanding cheques. Redeem a cheque at the bank to claim them.</p>
47 </div>
48 <div id="bank-inherit-pane" hidden>
49 <p id="inherit-coins" hidden></p>
50 <div id="inherit-grid" class="item-grid"></div>
51 <button id="bank-claim" type="button">Claim inheritance into vault</button>
52 </div>
41 </aside>
53 </aside>
42 <aside id="friends-panel" hidden>
54 <aside id="friends-panel" hidden>
43 <h2>Friends</h2>
55 <h2>Friends</h2>
@@ -48,6 +60,11 @@
48 <div id="outgoing-list"></div>
60 <div id="outgoing-list"></div>
49 <p class="hint">Right-click a bag item and choose Send to deliver by pigeon to the bank or a player.</p>
61 <p class="hint">Right-click a bag item and choose Send to deliver by pigeon to the bank or a player.</p>
50 </aside>
62 </aside>
63 <aside id="skills-panel" hidden>
64 <h2>Skills</h2>
65 <div id="skills-list" class="skills-grid"></div>
66 <p class="hint">Successful melee hits split XP between the weapon skill and Strength.</p>
67 </aside>
51
68
52 <div id="send-backdrop" class="modal-backdrop" hidden></div>
69 <div id="send-backdrop" class="modal-backdrop" hidden></div>
53 <aside id="send-panel" hidden>
70 <aside id="send-panel" hidden>
@@ -82,6 +99,35 @@
82 <div id="send-search-result"></div>
99 <div id="send-search-result"></div>
83 </aside>
100 </aside>
84
101
102 <div id="transfer-backdrop" class="modal-backdrop" hidden></div>
103 <aside id="transfer-panel" hidden>
104 <header>
105 <h2>Transfer</h2>
106 <button id="transfer-close" type="button">Close</button>
107 </header>
108 <p id="transfer-item-name"></p>
109 <label class="send-row">Quantity
110 <input id="transfer-qty" type="number" min="1" step="1" value="1">
111 </label>
112 <button id="transfer-confirm" type="button">Transfer</button>
113 </aside>
114
115 <div id="write-cheque-backdrop" class="modal-backdrop" hidden></div>
116 <aside id="write-cheque-panel" hidden>
117 <header>
118 <h2>Write cheque</h2>
119 <button id="write-cheque-close" type="button">Close</button>
120 </header>
121 <p id="write-cheque-hint" class="hint">Choose goods from your vault to reserve on this cheque.</p>
122 <div id="write-cheque-vault" class="item-grid"></div>
123 <p id="write-cheque-item"></p>
124 <label class="send-row">Quantity
125 <input id="write-cheque-qty" type="number" min="1" step="1" value="1">
126 </label>
127 <button id="write-cheque-confirm" type="button" disabled>Write</button>
128 <p id="write-cheque-status" class="hint"></p>
129 </aside>
130
85 <div id="letter-backdrop" class="modal-backdrop" hidden></div>
131 <div id="letter-backdrop" class="modal-backdrop" hidden></div>
86 <aside id="letter-panel" hidden>
132 <aside id="letter-panel" hidden>
87 <header>
133 <header>
@@ -98,6 +144,34 @@
98 <p id="letter-status" class="hint"></p>
144 <p id="letter-status" class="hint"></p>
99 </aside>
145 </aside>
100
146
147 <div id="craft-backdrop" class="modal-backdrop" hidden></div>
148 <aside id="craft-panel" hidden>
149 <header>
150 <h2 id="craft-station-name">Crafting</h2>
151 <button id="craft-close" type="button">Close</button>
152 </header>
153 <div class="craft-layout">
154 <div class="craft-recipes">
155 <div id="craft-recipe-grid" class="craft-recipe-grid"></div>
156 </div>
157 <div class="craft-detail">
158 <p id="craft-detail-empty" class="hint">Select a recipe.</p>
159 <div id="craft-detail-body" hidden>
160 <div class="craft-output">
161 <img id="craft-output-img" alt="">
162 <h3 id="craft-output-name"></h3>
163 </div>
164 <ul id="craft-inputs" class="craft-inputs"></ul>
165 <p id="craft-status" class="hint"></p>
166 <div id="craft-progress" class="craft-progress" hidden>
167 <div id="craft-progress-fill" class="craft-progress-fill"></div>
168 </div>
169 <button id="craft-button" type="button" disabled>Craft</button>
170 </div>
171 </div>
172 </div>
173 </aside>
174
101 <div id="nametag" hidden></div>
175 <div id="nametag" hidden></div>
102 <div id="chat-bubbles"></div>
176 <div id="chat-bubbles"></div>
103 <div id="chat-bar" hidden>
177 <div id="chat-bar" hidden>
client/scripts/generate-skill-icons.mjs added +62 −0
@@ -0,0 +1,62 @@
1 import { mkdirSync, writeFileSync } from "node:fs";
2 import { ALL_SKILL_IDS } from "../../shared/definitions/skills.js";
3
4 const labels = {
5 clubfighting: "CL",
6 swordfighting: "SW",
7 axefighting: "AX",
8 archery: "AR",
9 unarmed: "UN",
10 magic: "MG",
11 strength: "ST",
12 dexterity: "DX",
13 mind: "MN",
14 defence: "DF",
15 health: "HP",
16 stamina: "SM",
17 woodcutting: "WC",
18 mining: "MI",
19 fishing: "FS",
20 smithing: "SI",
21 crafting: "CR",
22 leatherworking: "LW",
23 tailoring: "TL",
24 cooking: "CK"
25 };
26
27 const colors = {
28 clubfighting: "#8b6914",
29 swordfighting: "#7a8a9a",
30 axefighting: "#9a5030",
31 archery: "#4a7a40",
32 unarmed: "#6a6050",
33 magic: "#6050a0",
34 strength: "#a04040",
35 dexterity: "#4080a0",
36 mind: "#8060a0",
37 defence: "#506080",
38 health: "#a03030",
39 stamina: "#408060",
40 woodcutting: "#5a7040",
41 mining: "#606060",
42 fishing: "#3070a0",
43 smithing: "#806040",
44 crafting: "#806080",
45 leatherworking: "#8a6040",
46 tailoring: "#7070a0",
47 cooking: "#a06030"
48 };
49
50 mkdirSync(new URL("../assets/skills/", import.meta.url), { recursive: true });
51 const dir = new URL("../assets/skills/", import.meta.url);
52
53 for (const id of ALL_SKILL_IDS)
54 {
55 const svg = [
56 "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\">",
57 `<rect width="32" height="32" rx="6" fill="${colors[id] ?? "#2a3344"}"/>`,
58 `<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>`,
59 "</svg>"
60 ].join("");
61 writeFileSync(new URL(`${id}.svg`, dir), svg);
62 }
@@ -0,0 +1,62 @@
1import { mkdirSync, writeFileSync } from "node:fs";
2import { ALL_SKILL_IDS } from "../../shared/definitions/skills.js";
3
4const labels = {
5 clubfighting: "CL",
6 swordfighting: "SW",
7 axefighting: "AX",
8 archery: "AR",
9 unarmed: "UN",
10 magic: "MG",
11 strength: "ST",
12 dexterity: "DX",
13 mind: "MN",
14 defence: "DF",
15 health: "HP",
16 stamina: "SM",
17 woodcutting: "WC",
18 mining: "MI",
19 fishing: "FS",
20 smithing: "SI",
21 crafting: "CR",
22 leatherworking: "LW",
23 tailoring: "TL",
24 cooking: "CK"
25};
26
27const colors = {
28 clubfighting: "#8b6914",
29 swordfighting: "#7a8a9a",
30 axefighting: "#9a5030",
31 archery: "#4a7a40",
32 unarmed: "#6a6050",
33 magic: "#6050a0",
34 strength: "#a04040",
35 dexterity: "#4080a0",
36 mind: "#8060a0",
37 defence: "#506080",
38 health: "#a03030",
39 stamina: "#408060",
40 woodcutting: "#5a7040",
41 mining: "#606060",
42 fishing: "#3070a0",
43 smithing: "#806040",
44 crafting: "#806080",
45 leatherworking: "#8a6040",
46 tailoring: "#7070a0",
47 cooking: "#a06030"
48};
49
50mkdirSync(new URL("../assets/skills/", import.meta.url), { recursive: true });
51const dir = new URL("../assets/skills/", import.meta.url);
52
53for (const id of ALL_SKILL_IDS)
54{
55 const svg = [
56 "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"32\" height=\"32\" viewBox=\"0 0 32 32\">",
57 `<rect width="32" height="32" rx="6" fill="${colors[id] ?? "#2a3344"}"/>`,
58 `<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>`,
59 "</svg>"
60 ].join("");
61 writeFileSync(new URL(`${id}.svg`, dir), svg);
62}
client/src/net/socket.js +6 −1
@@ -1,9 +1,10 @@
1 1 export class GameSocket
2 2 {
3 constructor (url, onMessage)
3 constructor (url, onMessage, { onClose } = {})
4 4 {
5 5 this.url = url;
6 6 this.onMessage = onMessage;
7 this.onClose = onClose;
7 8 this.socket = null;
8 9 }
9 10
@@ -14,6 +15,10 @@ export class GameSocket
14 15 {
15 16 this.onMessage(JSON.parse(event.data));
16 17 });
18 this.socket.addEventListener("close", (event) =>
19 {
20 this.onClose?.(event);
21 });
17 22 return new Promise((resolve, reject) =>
18 23 {
19 24 this.socket.addEventListener("open", resolve, { once: true });
@@ -1,9 +1,10 @@
1export class GameSocket
1export class GameSocket
2{
2{
3 constructor (url, onMessage)
3 constructor (url, onMessage, { onClose } = {})
4 {
4 {
5 this.url = url;
5 this.url = url;
6 this.onMessage = onMessage;
6 this.onMessage = onMessage;
7 this.onClose = onClose;
7 this.socket = null;
8 this.socket = null;
8 }
9 }
9
10
@@ -14,6 +15,10 @@ export class GameSocket
14 {
15 {
15 this.onMessage(JSON.parse(event.data));
16 this.onMessage(JSON.parse(event.data));
16 });
17 });
18 this.socket.addEventListener("close", (event) =>
19 {
20 this.onClose?.(event);
21 });
17 return new Promise((resolve, reject) =>
22 return new Promise((resolve, reject) =>
18 {
23 {
19 this.socket.addEventListener("open", resolve, { once: true });
24 this.socket.addEventListener("open", resolve, { once: true });
client/src/play/crafting.js added +340 −0
@@ -0,0 +1,340 @@
1 import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity
6 } from "/shared/definitions/items.js";
7 import { craftingStationDefinition } from "/shared/definitions/craftingStations.js";
8 import {
9 CRAFT_DURATION_MS,
10 canStartCraft,
11 countItemInSlots,
12 hasRecipeInputs,
13 recipesForStation
14 } from "/shared/crafting/recipes.js";
15
16 export function initCrafting ({
17 socket,
18 MessageType,
19 getInventorySlots,
20 getSkillLevel
21 })
22 {
23 const backdrop = document.getElementById("craft-backdrop");
24 const panel = document.getElementById("craft-panel");
25 const stationName = document.getElementById("craft-station-name");
26 const recipeGrid = document.getElementById("craft-recipe-grid");
27 const detailEmpty = document.getElementById("craft-detail-empty");
28 const detailBody = document.getElementById("craft-detail-body");
29 const outputImg = document.getElementById("craft-output-img");
30 const outputName = document.getElementById("craft-output-name");
31 const inputsList = document.getElementById("craft-inputs");
32 const statusEl = document.getElementById("craft-status");
33 const progressWrap = document.getElementById("craft-progress");
34 const progressFill = document.getElementById("craft-progress-fill");
35 const craftButton = document.getElementById("craft-button");
36
37 let open = false;
38 let stationId = null;
39 let recipes = [];
40 let selectedRecipeId = null;
41 let crafting = false;
42 let craftTimer = null;
43 let craftAnimFrame = null;
44 let craftStartedAt = 0;
45
46 document.getElementById("craft-close").addEventListener("click", () => close());
47 backdrop.addEventListener("click", () => close());
48 craftButton.addEventListener("click", () => startCraft());
49
50 function selectedRecipe ()
51 {
52 return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
53 }
54
55 function stationSkillLevel ()
56 {
57 const def = craftingStationDefinition(stationId);
58 return getSkillLevel?.(def?.skillId) ?? 1;
59 }
60
61 function refresh ()
62 {
63 if (!open)
64 { return; }
65 renderRecipeGrid();
66 renderDetail();
67 }
68
69 function renderRecipeGrid ()
70 {
71 recipeGrid.replaceChildren();
72 for (const recipe of recipes)
73 {
74 recipeGrid.append(renderRecipeCell(recipe));
75 }
76 }
77
78 function renderRecipeCell (recipe)
79 {
80 const def = itemDefinition(recipe.output.itemId);
81 const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };
82 const cell = document.createElement("button");
83 cell.type = "button";
84 cell.className = "craft-recipe-cell";
85 if (recipe.recipeId === selectedRecipeId)
86 { cell.classList.add("selected"); }
87
88 const img = document.createElement("img");
89 img.src = itemAssetPathForStack(stack);
90 img.alt = def?.displayName ?? "Item";
91
92 const label = document.createElement("span");
93 label.className = "craft-recipe-name";
94 label.textContent = def?.displayName ?? "Item";
95
96 cell.append(img, label);
97 cell.addEventListener("click", () =>
98 {
99 if (crafting)
100 { return; }
101 selectedRecipeId = recipe.recipeId;
102 renderRecipeGrid();
103 renderDetail();
104 });
105 return cell;
106 }
107
108 function renderDetail ()
109 {
110 const recipe = selectedRecipe();
111 if (!recipe)
112 {
113 detailEmpty.hidden = false;
114 detailBody.hidden = true;
115 return;
116 }
117 detailEmpty.hidden = true;
118 detailBody.hidden = false;
119
120 const outputStack = {
121 itemId: recipe.output.itemId,
122 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
123 };
124 outputImg.src = itemAssetPathForStack(outputStack);
125 outputImg.alt = itemDisplayName(outputStack);
126 const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
127 outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
128
129 inputsList.replaceChildren();
130 const slots = getInventorySlots?.() ?? [];
131 for (const input of recipe.inputs ?? [])
132 {
133 inputsList.append(renderInputRow(input, slots));
134 }
135
136 updateCraftState(slots, recipe);
137 }
138
139 function renderInputRow (input, slots)
140 {
141 const need = input.quantity | 0;
142 const have = countItemInSlots(slots, input.itemId);
143 const stack = { itemId: input.itemId, quantity: need };
144 const row = document.createElement("li");
145 row.className = "craft-input-row";
146 if (have < need)
147 { row.classList.add("short"); }
148
149 const img = document.createElement("img");
150 img.src = itemAssetPathForStack(stack);
151 img.alt = itemDisplayName(stack);
152
153 const text = document.createElement("span");
154 text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
155 row.append(img, text);
156 return row;
157 }
158
159 function updateCraftState (slots, recipe)
160 {
161 if (crafting)
162 {
163 craftButton.disabled = true;
164 return;
165 }
166 const skill = stationSkillLevel();
167 const minLevel = recipe.minSkillLevel | 0 || 1;
168 if (skill < minLevel)
169 {
170 statusEl.textContent = `Requires skill level ${minLevel} (you have ${skill}).`;
171 craftButton.disabled = true;
172 return;
173 }
174 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
175 if (canStartCraft(slotsSnapshot, recipe, skill))
176 {
177 statusEl.textContent = `Crafting takes ${CRAFT_DURATION_MS / 1000} seconds.`;
178 craftButton.disabled = false;
179 return;
180 }
181 if (!hasRecipeInputs(slotsSnapshot, recipe))
182 {
183 statusEl.textContent = "Missing materials.";
184 }
185 else
186 {
187 statusEl.textContent = "Not enough bag space for the result.";
188 }
189 craftButton.disabled = true;
190 }
191
192 function startCraft ()
193 {
194 const recipe = selectedRecipe();
195 if (!recipe || crafting)
196 { return; }
197 const slots = getInventorySlots?.() ?? [];
198 if (!canStartCraft(slots, recipe, stationSkillLevel()))
199 {
200 renderDetail();
201 return;
202 }
203 crafting = true;
204 craftButton.disabled = true;
205 progressWrap.hidden = false;
206 progressFill.style.width = "0%";
207 statusEl.textContent = "Crafting…";
208 craftStartedAt = performance.now();
209 socket.send({
210 type: MessageType.startCraft,
211 stationId,
212 recipeId: recipe.recipeId
213 });
214 animateProgress();
215 craftTimer = window.setTimeout(() => finishCraft(true), CRAFT_DURATION_MS);
216 }
217
218 function animateProgress ()
219 {
220 const tick = (now) =>
221 {
222 if (!crafting)
223 { return; }
224 const elapsed = now - craftStartedAt;
225 const pct = Math.min(100, (elapsed / CRAFT_DURATION_MS) * 100);
226 progressFill.style.width = `${pct}%`;
227 if (pct < 100)
228 { craftAnimFrame = requestAnimationFrame(tick); }
229 };
230 craftAnimFrame = requestAnimationFrame(tick);
231 }
232
233 function stopCraftAnimation ()
234 {
235 if (craftTimer != null)
236 {
237 clearTimeout(craftTimer);
238 craftTimer = null;
239 }
240 if (craftAnimFrame != null)
241 {
242 cancelAnimationFrame(craftAnimFrame);
243 craftAnimFrame = null;
244 }
245 crafting = false;
246 progressWrap.hidden = true;
247 progressFill.style.width = "0%";
248 }
249
250 function finishCraft (timedOut)
251 {
252 stopCraftAnimation();
253 if (timedOut)
254 {
255 statusEl.textContent = "Waiting for server…";
256 }
257 renderDetail();
258 }
259
260 function openStation (nextStationId)
261 {
262 const def = craftingStationDefinition(nextStationId);
263 if (!def)
264 { return; }
265 stationId = nextStationId;
266 recipes = recipesForStation(nextStationId);
267 selectedRecipeId = recipes[0]?.recipeId ?? null;
268 stationName.textContent = def.displayName;
269 open = true;
270 panel.hidden = false;
271 backdrop.hidden = false;
272 statusEl.textContent = recipes.length
273 ? "Select a recipe."
274 : "No recipes defined for this station yet.";
275 renderRecipeGrid();
276 renderDetail();
277 }
278
279 function close ()
280 {
281 if (crafting)
282 {
283 socket.send({ type: MessageType.cancelCraft });
284 stopCraftAnimation();
285 }
286 open = false;
287 stationId = null;
288 recipes = [];
289 selectedRecipeId = null;
290 panel.hidden = true;
291 backdrop.hidden = true;
292 detailEmpty.hidden = false;
293 detailBody.hidden = true;
294 statusEl.textContent = "";
295 }
296
297 function handleCraftResult (message)
298 {
299 if (!open || message.recipeId !== selectedRecipeId)
300 { return; }
301 stopCraftAnimation();
302 if (message.ok)
303 {
304 statusEl.textContent = message.burned
305 ? "The food burned."
306 : "Craft complete.";
307 }
308 else
309 {
310 statusEl.textContent = message.error ?? "Could not craft.";
311 }
312 renderDetail();
313 }
314
315 return {
316 openStation,
317 close,
318 refresh,
319 handleCraftResult,
320 isOpen ()
321 {
322 return open;
323 },
324 isBlocking ()
325 {
326 if (!open)
327 { return false; }
328 if (backdrop && !backdrop.hidden)
329 { return true; }
330 const x = GameInput.mousePosition.x;
331 const y = GameInput.mousePosition.y;
332 const box = panel.getBoundingClientRect();
333 return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
334 },
335 reset ()
336 {
337 close();
338 }
339 };
340 }
@@ -0,0 +1,340 @@
1import {
2 itemDefinition,
3 itemDisplayName,
4 itemAssetPathForStack,
5 formatQuantity
6} from "/shared/definitions/items.js";
7import { craftingStationDefinition } from "/shared/definitions/craftingStations.js";
8import {
9 CRAFT_DURATION_MS,
10 canStartCraft,
11 countItemInSlots,
12 hasRecipeInputs,
13 recipesForStation
14} from "/shared/crafting/recipes.js";
15
16export function initCrafting ({
17 socket,
18 MessageType,
19 getInventorySlots,
20 getSkillLevel
21})
22{
23 const backdrop = document.getElementById("craft-backdrop");
24 const panel = document.getElementById("craft-panel");
25 const stationName = document.getElementById("craft-station-name");
26 const recipeGrid = document.getElementById("craft-recipe-grid");
27 const detailEmpty = document.getElementById("craft-detail-empty");
28 const detailBody = document.getElementById("craft-detail-body");
29 const outputImg = document.getElementById("craft-output-img");
30 const outputName = document.getElementById("craft-output-name");
31 const inputsList = document.getElementById("craft-inputs");
32 const statusEl = document.getElementById("craft-status");
33 const progressWrap = document.getElementById("craft-progress");
34 const progressFill = document.getElementById("craft-progress-fill");
35 const craftButton = document.getElementById("craft-button");
36
37 let open = false;
38 let stationId = null;
39 let recipes = [];
40 let selectedRecipeId = null;
41 let crafting = false;
42 let craftTimer = null;
43 let craftAnimFrame = null;
44 let craftStartedAt = 0;
45
46 document.getElementById("craft-close").addEventListener("click", () => close());
47 backdrop.addEventListener("click", () => close());
48 craftButton.addEventListener("click", () => startCraft());
49
50 function selectedRecipe ()
51 {
52 return recipes.find((recipe) => recipe.recipeId === selectedRecipeId) ?? null;
53 }
54
55 function stationSkillLevel ()
56 {
57 const def = craftingStationDefinition(stationId);
58 return getSkillLevel?.(def?.skillId) ?? 1;
59 }
60
61 function refresh ()
62 {
63 if (!open)
64 { return; }
65 renderRecipeGrid();
66 renderDetail();
67 }
68
69 function renderRecipeGrid ()
70 {
71 recipeGrid.replaceChildren();
72 for (const recipe of recipes)
73 {
74 recipeGrid.append(renderRecipeCell(recipe));
75 }
76 }
77
78 function renderRecipeCell (recipe)
79 {
80 const def = itemDefinition(recipe.output.itemId);
81 const stack = { itemId: recipe.output.itemId, quantity: recipe.output.quantity | 0 || 1 };
82 const cell = document.createElement("button");
83 cell.type = "button";
84 cell.className = "craft-recipe-cell";
85 if (recipe.recipeId === selectedRecipeId)
86 { cell.classList.add("selected"); }
87
88 const img = document.createElement("img");
89 img.src = itemAssetPathForStack(stack);
90 img.alt = def?.displayName ?? "Item";
91
92 const label = document.createElement("span");
93 label.className = "craft-recipe-name";
94 label.textContent = def?.displayName ?? "Item";
95
96 cell.append(img, label);
97 cell.addEventListener("click", () =>
98 {
99 if (crafting)
100 { return; }
101 selectedRecipeId = recipe.recipeId;
102 renderRecipeGrid();
103 renderDetail();
104 });
105 return cell;
106 }
107
108 function renderDetail ()
109 {
110 const recipe = selectedRecipe();
111 if (!recipe)
112 {
113 detailEmpty.hidden = false;
114 detailBody.hidden = true;
115 return;
116 }
117 detailEmpty.hidden = true;
118 detailBody.hidden = false;
119
120 const outputStack = {
121 itemId: recipe.output.itemId,
122 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
123 };
124 outputImg.src = itemAssetPathForStack(outputStack);
125 outputImg.alt = itemDisplayName(outputStack);
126 const qtySuffix = outputStack.quantity > 1 ? ` ×${formatQuantity(outputStack.quantity)}` : "";
127 outputName.textContent = `${itemDisplayName(outputStack)}${qtySuffix}`;
128
129 inputsList.replaceChildren();
130 const slots = getInventorySlots?.() ?? [];
131 for (const input of recipe.inputs ?? [])
132 {
133 inputsList.append(renderInputRow(input, slots));
134 }
135
136 updateCraftState(slots, recipe);
137 }
138
139 function renderInputRow (input, slots)
140 {
141 const need = input.quantity | 0;
142 const have = countItemInSlots(slots, input.itemId);
143 const stack = { itemId: input.itemId, quantity: need };
144 const row = document.createElement("li");
145 row.className = "craft-input-row";
146 if (have < need)
147 { row.classList.add("short"); }
148
149 const img = document.createElement("img");
150 img.src = itemAssetPathForStack(stack);
151 img.alt = itemDisplayName(stack);
152
153 const text = document.createElement("span");
154 text.textContent = `${itemDisplayName(stack)} — ${formatQuantity(have)} / ${formatQuantity(need)}`;
155 row.append(img, text);
156 return row;
157 }
158
159 function updateCraftState (slots, recipe)
160 {
161 if (crafting)
162 {
163 craftButton.disabled = true;
164 return;
165 }
166 const skill = stationSkillLevel();
167 const minLevel = recipe.minSkillLevel | 0 || 1;
168 if (skill < minLevel)
169 {
170 statusEl.textContent = `Requires skill level ${minLevel} (you have ${skill}).`;
171 craftButton.disabled = true;
172 return;
173 }
174 const slotsSnapshot = slots ?? getInventorySlots?.() ?? [];
175 if (canStartCraft(slotsSnapshot, recipe, skill))
176 {
177 statusEl.textContent = `Crafting takes ${CRAFT_DURATION_MS / 1000} seconds.`;
178 craftButton.disabled = false;
179 return;
180 }
181 if (!hasRecipeInputs(slotsSnapshot, recipe))
182 {
183 statusEl.textContent = "Missing materials.";
184 }
185 else
186 {
187 statusEl.textContent = "Not enough bag space for the result.";
188 }
189 craftButton.disabled = true;
190 }
191
192 function startCraft ()
193 {
194 const recipe = selectedRecipe();
195 if (!recipe || crafting)
196 { return; }
197 const slots = getInventorySlots?.() ?? [];
198 if (!canStartCraft(slots, recipe, stationSkillLevel()))
199 {
200 renderDetail();
201 return;
202 }
203 crafting = true;
204 craftButton.disabled = true;
205 progressWrap.hidden = false;
206 progressFill.style.width = "0%";
207 statusEl.textContent = "Crafting…";
208 craftStartedAt = performance.now();
209 socket.send({
210 type: MessageType.startCraft,
211 stationId,
212 recipeId: recipe.recipeId
213 });
214 animateProgress();
215 craftTimer = window.setTimeout(() => finishCraft(true), CRAFT_DURATION_MS);
216 }
217
218 function animateProgress ()
219 {
220 const tick = (now) =>
221 {
222 if (!crafting)
223 { return; }
224 const elapsed = now - craftStartedAt;
225 const pct = Math.min(100, (elapsed / CRAFT_DURATION_MS) * 100);
226 progressFill.style.width = `${pct}%`;
227 if (pct < 100)
228 { craftAnimFrame = requestAnimationFrame(tick); }
229 };
230 craftAnimFrame = requestAnimationFrame(tick);
231 }
232
233 function stopCraftAnimation ()
234 {
235 if (craftTimer != null)
236 {
237 clearTimeout(craftTimer);
238 craftTimer = null;
239 }
240 if (craftAnimFrame != null)
241 {
242 cancelAnimationFrame(craftAnimFrame);
243 craftAnimFrame = null;
244 }
245 crafting = false;
246 progressWrap.hidden = true;
247 progressFill.style.width = "0%";
248 }
249
250 function finishCraft (timedOut)
251 {
252 stopCraftAnimation();
253 if (timedOut)
254 {
255 statusEl.textContent = "Waiting for server…";
256 }
257 renderDetail();
258 }
259
260 function openStation (nextStationId)
261 {
262 const def = craftingStationDefinition(nextStationId);
263 if (!def)
264 { return; }
265 stationId = nextStationId;
266 recipes = recipesForStation(nextStationId);
267 selectedRecipeId = recipes[0]?.recipeId ?? null;
268 stationName.textContent = def.displayName;
269 open = true;
270 panel.hidden = false;
271 backdrop.hidden = false;
272 statusEl.textContent = recipes.length
273 ? "Select a recipe."
274 : "No recipes defined for this station yet.";
275 renderRecipeGrid();
276 renderDetail();
277 }
278
279 function close ()
280 {
281 if (crafting)
282 {
283 socket.send({ type: MessageType.cancelCraft });
284 stopCraftAnimation();
285 }
286 open = false;
287 stationId = null;
288 recipes = [];
289 selectedRecipeId = null;
290 panel.hidden = true;
291 backdrop.hidden = true;
292 detailEmpty.hidden = false;
293 detailBody.hidden = true;
294 statusEl.textContent = "";
295 }
296
297 function handleCraftResult (message)
298 {
299 if (!open || message.recipeId !== selectedRecipeId)
300 { return; }
301 stopCraftAnimation();
302 if (message.ok)
303 {
304 statusEl.textContent = message.burned
305 ? "The food burned."
306 : "Craft complete.";
307 }
308 else
309 {
310 statusEl.textContent = message.error ?? "Could not craft.";
311 }
312 renderDetail();
313 }
314
315 return {
316 openStation,
317 close,
318 refresh,
319 handleCraftResult,
320 isOpen ()
321 {
322 return open;
323 },
324 isBlocking ()
325 {
326 if (!open)
327 { return false; }
328 if (backdrop && !backdrop.hidden)
329 { return true; }
330 const x = GameInput.mousePosition.x;
331 const y = GameInput.mousePosition.y;
332 const box = panel.getBoundingClientRect();
333 return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
334 },
335 reset ()
336 {
337 close();
338 }
339 };
340}
client/src/play/inventory.js +391 −54
@@ -1,7 +1,10 @@
1 1 import {
2 2 itemDefinition,
3 3 itemDescription,
4 itemOriginSummary,
4 5 itemAssetPathForStack,
6 itemDisplayName,
7 formatQuantity,
5 8 ItemId,
6 9 EQUIPMENT_SLOT,
7 10 LETTER_MAX_BODY_CHARS
@@ -28,13 +31,14 @@ export function initInventory ({
28 31 const bagPanel = document.getElementById("bag-panel");
29 32 const bagGrid = document.getElementById("bag-grid");
30 33 const equipGrid = document.getElementById("equip-grid");
31 const coins = document.getElementById("bag-coins");
32 34 const hint = document.getElementById("bag-hint");
33 35 const bankPanel = document.getElementById("bank-panel");
34 36 const vaultGrid = document.getElementById("vault-grid");
35 const vaultCoins = document.getElementById("vault-coins");
37 const vaultReservedGrid = document.getElementById("vault-reserved-grid");
36 38 const inheritGrid = document.getElementById("inherit-grid");
37 const inheritCoins = document.getElementById("inherit-coins");
39 const bankAvailablePane = document.getElementById("bank-available-pane");
40 const bankReservedPane = document.getElementById("bank-reserved-pane");
41 const bankInheritPane = document.getElementById("bank-inherit-pane");
38 42
39 43 const sendPanel = document.getElementById("send-panel");
40 44 const sendBackdrop = document.getElementById("send-backdrop");
@@ -48,12 +52,20 @@ export function initInventory ({
48 52 const letterSave = document.getElementById("letter-save");
49 53 const letterTitle = document.getElementById("letter-title");
50 54 const letterStatus = document.getElementById("letter-status");
55 const transferPanel = document.getElementById("transfer-panel");
56 const transferBackdrop = document.getElementById("transfer-backdrop");
57 const writeChequePanel = document.getElementById("write-cheque-panel");
58 const writeChequeBackdrop = document.getElementById("write-cheque-backdrop");
59 const writeChequeVault = document.getElementById("write-cheque-vault");
51 60
52 let bag = { inventory: [], equipment: { slots: {} }, currency: 0, vault: [], vaultCurrency: 0 };
61 let bag = { inventory: [], equipment: { slots: {} }, vault: [], vaultReserved: [] };
53 62 let selected = null;
54 63 let bankOpen = false;
64 let bankTab = "available";
55 65 let sendState = null;
56 66 let letterState = null;
67 let transferState = null;
68 let writeChequeState = null;
57 69 let pendingSearch = false;
58 70 let localCharacterId = null;
59 71
@@ -73,15 +85,20 @@ export function initInventory ({
73 85 { return; }
74 86 socket.send({ type: MessageType.equipItem, slotIndex: selected });
75 87 });
76 document.getElementById("bank-close").addEventListener("click", () =>
77 {
78 bankOpen = false;
79 bankPanel.hidden = true;
80 });
88 document.getElementById("bank-close").addEventListener("click", () => closeBank());
81 89 document.getElementById("bank-claim").addEventListener("click", () =>
82 90 {
83 91 socket.send({ type: MessageType.claimInheritance });
84 92 });
93 document.getElementById("bank-tab-available").addEventListener("click", () => setBankTab("available"));
94 document.getElementById("bank-tab-reserved").addEventListener("click", () => setBankTab("reserved"));
95 document.getElementById("bank-tab-inherit").addEventListener("click", () => setBankTab("inherit"));
96 document.getElementById("transfer-close").addEventListener("click", () => closeTransfer());
97 transferBackdrop.addEventListener("click", () => closeTransfer());
98 document.getElementById("transfer-confirm").addEventListener("click", () => confirmTransfer());
99 document.getElementById("write-cheque-close").addEventListener("click", () => closeWriteCheque());
100 writeChequeBackdrop.addEventListener("click", () => closeWriteCheque());
101 document.getElementById("write-cheque-confirm").addEventListener("click", () => confirmWriteCheque());
85 102
86 103 document.getElementById("send-close").addEventListener("click", () => closeSend());
87 104 sendBackdrop.addEventListener("click", () => closeSend());
@@ -129,7 +146,6 @@ export function initInventory ({
129 146
130 147 function render ()
131 148 {
132 coins.textContent = `${bag.currency ?? 0} coins`;
133 149 bagGrid.innerHTML = "";
134 150 (bag.inventory ?? []).forEach((slot, index) =>
135 151 {
@@ -141,22 +157,27 @@ export function initInventory ({
141 157 const def = itemDefinition(slot.itemId);
142 158 const img = document.createElement("img");
143 159 img.src = itemAssetPathForStack(slot);
144 img.alt = def?.displayName ?? "";
160 img.alt = itemDisplayName(slot);
145 161 button.append(img);
146 162 if (slot.quantity > 1)
147 163 {
148 164 const count = document.createElement("span");
149 165 count.className = "qty";
150 count.textContent = String(slot.quantity);
166 count.textContent = formatQuantity(slot.quantity);
151 167 button.append(count);
152 168 }
153 169 }
154 170 button.addEventListener("click", () =>
155 171 {
172 if (!slot)
173 { return; }
174 if (bankOpen)
175 {
176 transferSlot("inventory", index, null);
177 return;
178 }
156 179 selected = index;
157 hint.textContent = slot
158 ? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}: ${itemDescription(slot, { localCharacterId })}`
159 : "Empty slot.";
180 hint.textContent = `${itemDisplayName(slot)}: ${itemDescription(slot, { localCharacterId })}`;
160 181 render();
161 182 });
162 183 button.addEventListener("contextmenu", (event) =>
@@ -167,7 +188,10 @@ export function initInventory ({
167 188 { return; }
168 189 selected = index;
169 190 render();
170 showItemMenu(event.clientX, event.clientY, index, slot);
191 if (bankOpen)
192 { showBankTransferMenu(event.clientX, event.clientY, "inventory", index, slot); }
193 else
194 { showItemMenu(event.clientX, event.clientY, index, slot); }
171 195 });
172 196 bagGrid.append(button);
173 197 });
@@ -183,7 +207,7 @@ export function initInventory ({
183 207 const def = itemDefinition(worn.itemId);
184 208 const img = document.createElement("img");
185 209 img.src = itemAssetPathForStack(worn);
186 img.alt = def?.displayName ?? label;
210 img.alt = itemDisplayName(worn);
187 211 button.append(img);
188 212 }
189 213 button.addEventListener("click", () =>
@@ -202,7 +226,9 @@ export function initInventory ({
202 226 const isOwnLetter = slot.itemId === ItemId.letter
203 227 && slot.instance?.kind === "letter"
204 228 && Number(slot.instance.authorCharacterId) === Number(localCharacterId);
205 const canSend = slot.itemId !== ItemId.letter || isOwnLetter;
229 const canSend = slot.itemId !== ItemId.blankCheque
230 && (slot.itemId !== ItemId.letter || isOwnLetter);
231 const canEquip = def?.equipment?.slot && slot.itemId !== ItemId.coins;
206 232
207 233 if (slot.itemId === ItemId.paper)
208 234 {
@@ -238,7 +264,21 @@ export function initInventory ({
238 264 });
239 265 }
240 266 }
241 if (def?.equipment?.slot)
267 if (slot.itemId === ItemId.blankCheque)
268 {
269 items.push({
270 label: "Write Cheque",
271 onSelect: () => openWriteCheque(slotIndex)
272 });
273 }
274 if (slot.itemId === ItemId.filledCheque && bankOpen)
275 {
276 items.push({
277 label: "Redeem Cheque",
278 onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex })
279 });
280 }
281 if (canEquip)
242 282 {
243 283 items.push({
244 284 label: "Equip",
@@ -252,6 +292,14 @@ export function initInventory ({
252 292 onSelect: () => openSend(slotIndex, slot)
253 293 });
254 294 }
295 const healing = itemDefinition(slot.itemId)?.healing ?? 0;
296 if (healing > 0)
297 {
298 items.push({
299 label: "Eat",
300 onSelect: () => socket.send({ type: MessageType.eatItem, slotIndex })
301 });
302 }
255 303 items.push({
256 304 label: "Drop",
257 305 onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex })
@@ -259,6 +307,221 @@ export function initInventory ({
259 307 contextMenu?.show(x, y, items);
260 308 }
261 309
310 function showBankTransferMenu (x, y, side, slotIndex, slot)
311 {
312 if (side === "inventory" && slot.itemId === ItemId.filledCheque)
313 {
314 contextMenu?.show(x, y, [{
315 label: "Redeem Cheque",
316 onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex })
317 }]);
318 return;
319 }
320 if (side === "inventory" && slot.itemId === ItemId.blankCheque)
321 {
322 contextMenu?.show(x, y, [
323 {
324 label: `Return ${slot.quantity | 0}`,
325 onSelect: () => socket.send({
326 type: MessageType.returnBlankCheques,
327 slotIndex,
328 quantity: slot.quantity | 0
329 })
330 },
331 {
332 label: "Write Cheque",
333 onSelect: () => openWriteCheque(slotIndex)
334 }
335 ]);
336 return;
337 }
338 const qty = slot.quantity | 0;
339 const name = itemDisplayName(slot);
340 if (qty <= 1)
341 {
342 contextMenu?.show(x, y, [{
343 label: `Transfer ${name}`,
344 onSelect: () => transferSlot(side, slotIndex, 1)
345 }]);
346 return;
347 }
348 contextMenu?.show(x, y, [
349 {
350 label: `Transfer all ${name}`,
351 onSelect: () => transferSlot(side, slotIndex, null)
352 },
353 {
354 label: `Transfer half ${name}`,
355 onSelect: () => transferSlot(side, slotIndex, Math.max(1, Math.floor(qty / 2)))
356 },
357 {
358 label: `Transfer one ${name}`,
359 onSelect: () => transferSlot(side, slotIndex, 1)
360 },
361 {
362 label: `Transfer X ${name}`,
363 onSelect: () => openTransfer(side, slotIndex, slot)
364 }
365 ]);
366 }
367
368 function transferSlot (side, slotIndex, quantity)
369 {
370 if (side === "inventory")
371 {
372 socket.send({
373 type: MessageType.bankDeposit,
374 slotIndex,
375 quantity
376 });
377 return;
378 }
379 socket.send({
380 type: MessageType.bankWithdraw,
381 slotIndex,
382 quantity
383 });
384 }
385
386 function openTransfer (side, slotIndex, slot)
387 {
388 transferState = { side, slotIndex, maxQty: slot.quantity | 0 };
389 document.getElementById("transfer-item-name").textContent = itemDisplayName(slot);
390 const input = document.getElementById("transfer-qty");
391 input.value = "1";
392 input.max = String(transferState.maxQty);
393 transferPanel.hidden = false;
394 transferBackdrop.hidden = false;
395 }
396
397 function closeTransfer ()
398 {
399 transferState = null;
400 transferPanel.hidden = true;
401 transferBackdrop.hidden = true;
402 }
403
404 function confirmTransfer ()
405 {
406 if (!transferState)
407 { return; }
408 const quantity = Math.min(
409 transferState.maxQty,
410 Math.max(1, Number(document.getElementById("transfer-qty").value) | 0)
411 );
412 transferSlot(transferState.side, transferState.slotIndex, quantity);
413 closeTransfer();
414 }
415
416 function openWriteCheque (slotIndex)
417 {
418 writeChequeState = { slotIndex, vaultSlotIndex: null, maxQty: 1 };
419 document.getElementById("write-cheque-item").textContent = "No vault item selected.";
420 document.getElementById("write-cheque-qty").value = "1";
421 document.getElementById("write-cheque-confirm").disabled = true;
422 document.getElementById("write-cheque-status").textContent = "";
423 writeChequePanel.hidden = false;
424 writeChequeBackdrop.hidden = false;
425 renderWriteChequeVault();
426 }
427
428 function closeWriteCheque ()
429 {
430 writeChequeState = null;
431 writeChequePanel.hidden = true;
432 writeChequeBackdrop.hidden = true;
433 if (bankOpen)
434 { renderBank(); }
435 }
436
437 function renderWriteChequeVault ()
438 {
439 if (!writeChequeVault)
440 { return; }
441 writeChequeVault.innerHTML = "";
442 const slots = bag.vault ?? [];
443 if (!slots.some(Boolean))
444 {
445 const empty = document.createElement("p");
446 empty.className = "hint";
447 empty.textContent = "Your vault is empty. Deposit goods at a bank first.";
448 writeChequeVault.append(empty);
449 return;
450 }
451 slots.forEach((slot, index) =>
452 {
453 if (!slot)
454 { return; }
455 const button = document.createElement("button");
456 button.className = "item-slot";
457 if (writeChequeState?.vaultSlotIndex === index)
458 { button.classList.add("selected"); }
459 button.title = tooltip(slot);
460 const def = itemDefinition(slot.itemId);
461 const img = document.createElement("img");
462 img.src = itemAssetPathForStack(slot);
463 img.alt = itemDisplayName(slot);
464 button.append(img);
465 if (slot.quantity > 1)
466 {
467 const count = document.createElement("span");
468 count.className = "qty";
469 count.textContent = formatQuantity(slot.quantity);
470 button.append(count);
471 }
472 button.addEventListener("click", () =>
473 {
474 if (!writeChequeState)
475 { return; }
476 writeChequeState.vaultSlotIndex = index;
477 writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableOf(slot.itemId);
478 document.getElementById("write-cheque-item").textContent =
479 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
480 const qtyInput = document.getElementById("write-cheque-qty");
481 qtyInput.value = "1";
482 qtyInput.max = String(writeChequeState.maxQty);
483 qtyInput.disabled = writeChequeState.maxQty <= 1;
484 document.getElementById("write-cheque-confirm").disabled = false;
485 renderWriteChequeVault();
486 });
487 writeChequeVault.append(button);
488 });
489 }
490
491 function confirmWriteCheque ()
492 {
493 if (!writeChequeState || writeChequeState.vaultSlotIndex == null)
494 { return; }
495 const quantity = Math.max(1, Number(document.getElementById("write-cheque-qty").value) | 0);
496 socket.send({
497 type: MessageType.writeCheque,
498 slotIndex: writeChequeState.slotIndex,
499 vaultSlotIndex: writeChequeState.vaultSlotIndex,
500 quantity
501 });
502 document.getElementById("write-cheque-status").textContent = "Writing…";
503 closeWriteCheque();
504 }
505
506 function closeBank ()
507 {
508 bankOpen = false;
509 bankPanel.hidden = true;
510 closeWriteCheque();
511 closeTransfer();
512 }
513
514 function setBankTab (tab)
515 {
516 bankTab = tab;
517 document.getElementById("bank-tab-available").classList.toggle("active", tab === "available");
518 document.getElementById("bank-tab-reserved").classList.toggle("active", tab === "reserved");
519 document.getElementById("bank-tab-inherit").classList.toggle("active", tab === "inherit");
520 bankAvailablePane.hidden = tab !== "available";
521 bankReservedPane.hidden = tab !== "reserved";
522 bankInheritPane.hidden = tab !== "inherit";
523 }
524
262 525 function openSend (slotIndex, slot)
263 526 {
264 527 const def = itemDefinition(slot.itemId);
@@ -269,7 +532,7 @@ export function initInventory ({
269 532 destination: null
270 533 };
271 534 document.getElementById("send-item-img").src = itemAssetPathForStack(slot);
272 document.getElementById("send-item-name").textContent = def?.displayName ?? "Item";
535 document.getElementById("send-item-name").textContent = itemDisplayName(slot);
273 536 const qtyInput = document.getElementById("send-qty");
274 537 qtyInput.value = "1";
275 538 qtyInput.max = String(sendState.maxQty);
@@ -440,49 +703,118 @@ export function initInventory ({
440 703 letterBackdrop.hidden = true;
441 704 }
442 705
443 function renderVault (grid, slots)
706 function renderVault (grid, slots, { side = "vault", interactive = true } = {})
444 707 {
445 708 grid.innerHTML = "";
446 709 (slots ?? []).forEach((slot, index) =>
447 710 {
711 if (!slot)
712 { return; }
448 713 const button = document.createElement("button");
449 714 button.className = "item-slot";
715 if (writeChequeState && side === "vault" && writeChequeState.vaultSlotIndex === index)
716 { button.classList.add("selected"); }
450 717 button.title = tooltip(slot);
451 button.textContent = slot
452 ? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`
453 : "";
454 button.addEventListener("click", () =>
718 const def = itemDefinition(slot.itemId);
719 const img = document.createElement("img");
720 img.src = itemAssetPathForStack(slot);
721 img.alt = itemDisplayName(slot);
722 button.append(img);
723 if (slot.quantity > 1)
455 724 {
456 if (!slot)
457 { return; }
458 socket.send({ type: MessageType.bankWithdraw, slotIndex: index });
459 });
725 const count = document.createElement("span");
726 count.className = "qty";
727 count.textContent = formatQuantity(slot.quantity);
728 button.append(count);
729 }
730 if (interactive && side === "vault")
731 {
732 button.addEventListener("click", () =>
733 {
734 if (writeChequeState)
735 {
736 writeChequeState.vaultSlotIndex = index;
737 writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance
738 ? 1
739 : availableOf(slot.itemId);
740 document.getElementById("write-cheque-item").textContent =
741 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
742 const qtyInput = document.getElementById("write-cheque-qty");
743 qtyInput.value = "1";
744 qtyInput.max = String(writeChequeState.maxQty);
745 qtyInput.disabled = writeChequeState.maxQty <= 1;
746 document.getElementById("write-cheque-confirm").disabled = false;
747 renderBank();
748 return;
749 }
750 transferSlot("vault", index, null);
751 });
752 button.addEventListener("contextmenu", (event) =>
753 {
754 event.preventDefault();
755 event.stopPropagation();
756 if (writeChequeState)
757 { return; }
758 showBankTransferMenu(event.clientX, event.clientY, "vault", index, slot);
759 });
760 }
460 761 grid.append(button);
461 762 });
462 763 }
463 764
765 function availableOf (itemId)
766 {
767 let total = 0;
768 for (const slot of bag.vault ?? [])
769 {
770 if (slot?.itemId === itemId)
771 { total += slot.quantity | 0; }
772 }
773 return total;
774 }
775
776 function renderBank ()
777 {
778 renderVault(vaultGrid, bag.vault, { side: "vault", interactive: true });
779 renderVault(vaultReservedGrid, bag.vaultReserved, { side: "reserved", interactive: false });
780 setBankTab(bankTab);
781 }
782
464 783 function tooltip (slot)
465 784 {
466 785 if (!slot)
467 786 { return ""; }
468 787 const def = itemDefinition(slot.itemId);
469 return `${def?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`;
788 const base = `${itemDisplayName(slot)}${slot.quantity > 1 ? ` ×${formatQuantity(slot.quantity)}` : ""}`;
789 const origin = itemOriginSummary(slot);
790 const desc = itemDescription(slot, { localCharacterId });
791 const lines = [base];
792 if (origin)
793 { lines.push(origin); }
794 if (desc)
795 { lines.push(desc); }
796 return lines.join("\n");
470 797 }
471 798
472 799 return {
473 800 isOpen ()
474 801 {
475 return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden;
802 return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden
803 || !sendTargetPanel.hidden || !transferPanel.hidden || !writeChequePanel.hidden;
476 804 },
477 805 isBlocking ()
478 806 {
479 // Send/letter dialogs cover the view — keep world clicks blocked.
480 if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden)
807 if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden
808 || !transferPanel.hidden || !writeChequePanel.hidden)
481 809 { return true; }
482 810 if (sendBackdrop && !sendBackdrop.hidden)
483 811 { return true; }
484 812 if (letterBackdrop && !letterBackdrop.hidden)
485 813 { return true; }
814 if (transferBackdrop && !transferBackdrop.hidden)
815 { return true; }
816 if (writeChequeBackdrop && !writeChequeBackdrop.hidden)
817 { return true; }
486 818 const x = GameInput.mousePosition.x;
487 819 const y = GameInput.mousePosition.y;
488 820 for (const element of [bagPanel, bankPanel])
@@ -499,49 +831,55 @@ export function initInventory ({
499 831 {
500 832 localCharacterId = characterId;
501 833 },
834 getInventorySlots ()
835 {
836 return bag.inventory ?? [];
837 },
502 838 handleInventory (message)
503 839 {
504 840 bag = { ...bag, ...message };
505 841 render();
842 if (bankOpen)
843 { renderBank(); }
844 if (writeChequeState)
845 { renderWriteChequeVault(); }
506 846 if (letterState && letterStatus.textContent === "Saving…")
507 847 {
508 848 letterStatus.textContent = "Saved.";
509 849 if (letterState.mode === "write")
510 850 { closeLetter(); }
511 else if (letterState.mode === "edit")
851 else if (letterState.mode === "edit")
852 {
853 const slot = bag.inventory?.[letterState.slotIndex];
854 if (slot?.instance)
512 855 {
513 const slot = bag.inventory?.[letterState.slotIndex];
514 if (slot?.instance)
515 {
516 letterState.instance = slot.instance;
517 letterBody.value = slot.instance.body ?? "";
518 refreshLetterSignature();
519 fitLetterBody();
520 }
856 letterState.instance = slot.instance;
857 letterBody.value = slot.instance.body ?? "";
858 refreshLetterSignature();
859 fitLetterBody();
521 860 }
861 }
522 862 }
523 863 },
524 864 handleBank (message)
525 865 {
526 866 bankOpen = true;
527 867 bankPanel.hidden = false;
528 bag.vault = message.vault;
529 bag.vaultCurrency = message.vaultCurrency;
530 vaultCoins.textContent = `${message.vaultCurrency ?? 0} coins in vault · you carry ${message.currency ?? 0}`;
531 inheritCoins.textContent = `${message.inheritance?.currency ?? 0} coins waiting`;
532 renderVault(vaultGrid, message.vault);
533 renderVault(inheritGrid, message.inheritance?.slots ?? []);
868 bagPanel.hidden = false;
869 bag.vault = message.vault ?? [];
870 bag.vaultReserved = message.vaultReserved ?? [];
871 renderVault(inheritGrid, message.inheritance?.slots ?? [], { interactive: false });
534 872 inheritGrid.querySelectorAll("button").forEach((button) =>
535 873 {
536 874 button.onclick = null;
537 875 });
876 setBankTab("available");
877 renderBank();
538 878 render();
539 879 },
540 depositSelected ()
880 getBlankCheques ()
541 881 {
542 if (selected == null)
543 { return; }
544 socket.send({ type: MessageType.bankDeposit, slotIndex: selected });
882 socket.send({ type: MessageType.getBlankCheques });
545 883 },
546 884 handlePigeonDispatched ()
547 885 {
@@ -569,8 +907,7 @@ export function initInventory ({
569 907 reset ()
570 908 {
571 909 bagPanel.hidden = true;
572 bankPanel.hidden = true;
573 bankOpen = false;
910 closeBank();
574 911 selected = null;
575 912 closeSend();
576 913 closeLetter();
@@ -1,7 +1,10 @@
1import {
1import {
2 itemDefinition,
2 itemDefinition,
3 itemDescription,
3 itemDescription,
4 itemOriginSummary,
4 itemAssetPathForStack,
5 itemAssetPathForStack,
6 itemDisplayName,
7 formatQuantity,
5 ItemId,
8 ItemId,
6 EQUIPMENT_SLOT,
9 EQUIPMENT_SLOT,
7 LETTER_MAX_BODY_CHARS
10 LETTER_MAX_BODY_CHARS
@@ -28,13 +31,14 @@ export function initInventory ({
28 const bagPanel = document.getElementById("bag-panel");
31 const bagPanel = document.getElementById("bag-panel");
29 const bagGrid = document.getElementById("bag-grid");
32 const bagGrid = document.getElementById("bag-grid");
30 const equipGrid = document.getElementById("equip-grid");
33 const equipGrid = document.getElementById("equip-grid");
31 const coins = document.getElementById("bag-coins");
32 const hint = document.getElementById("bag-hint");
34 const hint = document.getElementById("bag-hint");
33 const bankPanel = document.getElementById("bank-panel");
35 const bankPanel = document.getElementById("bank-panel");
34 const vaultGrid = document.getElementById("vault-grid");
36 const vaultGrid = document.getElementById("vault-grid");
35 const vaultCoins = document.getElementById("vault-coins");
37 const vaultReservedGrid = document.getElementById("vault-reserved-grid");
36 const inheritGrid = document.getElementById("inherit-grid");
38 const inheritGrid = document.getElementById("inherit-grid");
37 const inheritCoins = document.getElementById("inherit-coins");
39 const bankAvailablePane = document.getElementById("bank-available-pane");
40 const bankReservedPane = document.getElementById("bank-reserved-pane");
41 const bankInheritPane = document.getElementById("bank-inherit-pane");
38
42
39 const sendPanel = document.getElementById("send-panel");
43 const sendPanel = document.getElementById("send-panel");
40 const sendBackdrop = document.getElementById("send-backdrop");
44 const sendBackdrop = document.getElementById("send-backdrop");
@@ -48,12 +52,20 @@ export function initInventory ({
48 const letterSave = document.getElementById("letter-save");
52 const letterSave = document.getElementById("letter-save");
49 const letterTitle = document.getElementById("letter-title");
53 const letterTitle = document.getElementById("letter-title");
50 const letterStatus = document.getElementById("letter-status");
54 const letterStatus = document.getElementById("letter-status");
55 const transferPanel = document.getElementById("transfer-panel");
56 const transferBackdrop = document.getElementById("transfer-backdrop");
57 const writeChequePanel = document.getElementById("write-cheque-panel");
58 const writeChequeBackdrop = document.getElementById("write-cheque-backdrop");
59 const writeChequeVault = document.getElementById("write-cheque-vault");
51
60
52 let bag = { inventory: [], equipment: { slots: {} }, currency: 0, vault: [], vaultCurrency: 0 };
61 let bag = { inventory: [], equipment: { slots: {} }, vault: [], vaultReserved: [] };
53 let selected = null;
62 let selected = null;
54 let bankOpen = false;
63 let bankOpen = false;
64 let bankTab = "available";
55 let sendState = null;
65 let sendState = null;
56 let letterState = null;
66 let letterState = null;
67 let transferState = null;
68 let writeChequeState = null;
57 let pendingSearch = false;
69 let pendingSearch = false;
58 let localCharacterId = null;
70 let localCharacterId = null;
59
71
@@ -73,15 +85,20 @@ export function initInventory ({
73 { return; }
85 { return; }
74 socket.send({ type: MessageType.equipItem, slotIndex: selected });
86 socket.send({ type: MessageType.equipItem, slotIndex: selected });
75 });
87 });
76 document.getElementById("bank-close").addEventListener("click", () =>
88 document.getElementById("bank-close").addEventListener("click", () => closeBank());
77 {
78 bankOpen = false;
79 bankPanel.hidden = true;
80 });
81 document.getElementById("bank-claim").addEventListener("click", () =>
89 document.getElementById("bank-claim").addEventListener("click", () =>
82 {
90 {
83 socket.send({ type: MessageType.claimInheritance });
91 socket.send({ type: MessageType.claimInheritance });
84 });
92 });
93 document.getElementById("bank-tab-available").addEventListener("click", () => setBankTab("available"));
94 document.getElementById("bank-tab-reserved").addEventListener("click", () => setBankTab("reserved"));
95 document.getElementById("bank-tab-inherit").addEventListener("click", () => setBankTab("inherit"));
96 document.getElementById("transfer-close").addEventListener("click", () => closeTransfer());
97 transferBackdrop.addEventListener("click", () => closeTransfer());
98 document.getElementById("transfer-confirm").addEventListener("click", () => confirmTransfer());
99 document.getElementById("write-cheque-close").addEventListener("click", () => closeWriteCheque());
100 writeChequeBackdrop.addEventListener("click", () => closeWriteCheque());
101 document.getElementById("write-cheque-confirm").addEventListener("click", () => confirmWriteCheque());
85
102
86 document.getElementById("send-close").addEventListener("click", () => closeSend());
103 document.getElementById("send-close").addEventListener("click", () => closeSend());
87 sendBackdrop.addEventListener("click", () => closeSend());
104 sendBackdrop.addEventListener("click", () => closeSend());
@@ -129,7 +146,6 @@ export function initInventory ({
129
146
130 function render ()
147 function render ()
131 {
148 {
132 coins.textContent = `${bag.currency ?? 0} coins`;
133 bagGrid.innerHTML = "";
149 bagGrid.innerHTML = "";
134 (bag.inventory ?? []).forEach((slot, index) =>
150 (bag.inventory ?? []).forEach((slot, index) =>
135 {
151 {
@@ -141,22 +157,27 @@ export function initInventory ({
141 const def = itemDefinition(slot.itemId);
157 const def = itemDefinition(slot.itemId);
142 const img = document.createElement("img");
158 const img = document.createElement("img");
143 img.src = itemAssetPathForStack(slot);
159 img.src = itemAssetPathForStack(slot);
144 img.alt = def?.displayName ?? "";
160 img.alt = itemDisplayName(slot);
145 button.append(img);
161 button.append(img);
146 if (slot.quantity > 1)
162 if (slot.quantity > 1)
147 {
163 {
148 const count = document.createElement("span");
164 const count = document.createElement("span");
149 count.className = "qty";
165 count.className = "qty";
150 count.textContent = String(slot.quantity);
166 count.textContent = formatQuantity(slot.quantity);
151 button.append(count);
167 button.append(count);
152 }
168 }
153 }
169 }
154 button.addEventListener("click", () =>
170 button.addEventListener("click", () =>
155 {
171 {
172 if (!slot)
173 { return; }
174 if (bankOpen)
175 {
176 transferSlot("inventory", index, null);
177 return;
178 }
156 selected = index;
179 selected = index;
157 hint.textContent = slot
180 hint.textContent = `${itemDisplayName(slot)}: ${itemDescription(slot, { localCharacterId })}`;
158 ? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}: ${itemDescription(slot, { localCharacterId })}`
159 : "Empty slot.";
160 render();
181 render();
161 });
182 });
162 button.addEventListener("contextmenu", (event) =>
183 button.addEventListener("contextmenu", (event) =>
@@ -167,7 +188,10 @@ export function initInventory ({
167 { return; }
188 { return; }
168 selected = index;
189 selected = index;
169 render();
190 render();
170 showItemMenu(event.clientX, event.clientY, index, slot);
191 if (bankOpen)
192 { showBankTransferMenu(event.clientX, event.clientY, "inventory", index, slot); }
193 else
194 { showItemMenu(event.clientX, event.clientY, index, slot); }
171 });
195 });
172 bagGrid.append(button);
196 bagGrid.append(button);
173 });
197 });
@@ -183,7 +207,7 @@ export function initInventory ({
183 const def = itemDefinition(worn.itemId);
207 const def = itemDefinition(worn.itemId);
184 const img = document.createElement("img");
208 const img = document.createElement("img");
185 img.src = itemAssetPathForStack(worn);
209 img.src = itemAssetPathForStack(worn);
186 img.alt = def?.displayName ?? label;
210 img.alt = itemDisplayName(worn);
187 button.append(img);
211 button.append(img);
188 }
212 }
189 button.addEventListener("click", () =>
213 button.addEventListener("click", () =>
@@ -202,7 +226,9 @@ export function initInventory ({
202 const isOwnLetter = slot.itemId === ItemId.letter
226 const isOwnLetter = slot.itemId === ItemId.letter
203 && slot.instance?.kind === "letter"
227 && slot.instance?.kind === "letter"
204 && Number(slot.instance.authorCharacterId) === Number(localCharacterId);
228 && Number(slot.instance.authorCharacterId) === Number(localCharacterId);
205 const canSend = slot.itemId !== ItemId.letter || isOwnLetter;
229 const canSend = slot.itemId !== ItemId.blankCheque
230 && (slot.itemId !== ItemId.letter || isOwnLetter);
231 const canEquip = def?.equipment?.slot && slot.itemId !== ItemId.coins;
206
232
207 if (slot.itemId === ItemId.paper)
233 if (slot.itemId === ItemId.paper)
208 {
234 {
@@ -238,7 +264,21 @@ export function initInventory ({
238 });
264 });
239 }
265 }
240 }
266 }
241 if (def?.equipment?.slot)
267 if (slot.itemId === ItemId.blankCheque)
268 {
269 items.push({
270 label: "Write Cheque",
271 onSelect: () => openWriteCheque(slotIndex)
272 });
273 }
274 if (slot.itemId === ItemId.filledCheque && bankOpen)
275 {
276 items.push({
277 label: "Redeem Cheque",
278 onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex })
279 });
280 }
281 if (canEquip)
242 {
282 {
243 items.push({
283 items.push({
244 label: "Equip",
284 label: "Equip",
@@ -252,6 +292,14 @@ export function initInventory ({
252 onSelect: () => openSend(slotIndex, slot)
292 onSelect: () => openSend(slotIndex, slot)
253 });
293 });
254 }
294 }
295 const healing = itemDefinition(slot.itemId)?.healing ?? 0;
296 if (healing > 0)
297 {
298 items.push({
299 label: "Eat",
300 onSelect: () => socket.send({ type: MessageType.eatItem, slotIndex })
301 });
302 }
255 items.push({
303 items.push({
256 label: "Drop",
304 label: "Drop",
257 onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex })
305 onSelect: () => socket.send({ type: MessageType.dropItem, slotIndex })
@@ -259,6 +307,221 @@ export function initInventory ({
259 contextMenu?.show(x, y, items);
307 contextMenu?.show(x, y, items);
260 }
308 }
261
309
310 function showBankTransferMenu (x, y, side, slotIndex, slot)
311 {
312 if (side === "inventory" && slot.itemId === ItemId.filledCheque)
313 {
314 contextMenu?.show(x, y, [{
315 label: "Redeem Cheque",
316 onSelect: () => socket.send({ type: MessageType.redeemCheque, slotIndex })
317 }]);
318 return;
319 }
320 if (side === "inventory" && slot.itemId === ItemId.blankCheque)
321 {
322 contextMenu?.show(x, y, [
323 {
324 label: `Return ${slot.quantity | 0}`,
325 onSelect: () => socket.send({
326 type: MessageType.returnBlankCheques,
327 slotIndex,
328 quantity: slot.quantity | 0
329 })
330 },
331 {
332 label: "Write Cheque",
333 onSelect: () => openWriteCheque(slotIndex)
334 }
335 ]);
336 return;
337 }
338 const qty = slot.quantity | 0;
339 const name = itemDisplayName(slot);
340 if (qty <= 1)
341 {
342 contextMenu?.show(x, y, [{
343 label: `Transfer ${name}`,
344 onSelect: () => transferSlot(side, slotIndex, 1)
345 }]);
346 return;
347 }
348 contextMenu?.show(x, y, [
349 {
350 label: `Transfer all ${name}`,
351 onSelect: () => transferSlot(side, slotIndex, null)
352 },
353 {
354 label: `Transfer half ${name}`,
355 onSelect: () => transferSlot(side, slotIndex, Math.max(1, Math.floor(qty / 2)))
356 },
357 {
358 label: `Transfer one ${name}`,
359 onSelect: () => transferSlot(side, slotIndex, 1)
360 },
361 {
362 label: `Transfer X ${name}`,
363 onSelect: () => openTransfer(side, slotIndex, slot)
364 }
365 ]);
366 }
367
368 function transferSlot (side, slotIndex, quantity)
369 {
370 if (side === "inventory")
371 {
372 socket.send({
373 type: MessageType.bankDeposit,
374 slotIndex,
375 quantity
376 });
377 return;
378 }
379 socket.send({
380 type: MessageType.bankWithdraw,
381 slotIndex,
382 quantity
383 });
384 }
385
386 function openTransfer (side, slotIndex, slot)
387 {
388 transferState = { side, slotIndex, maxQty: slot.quantity | 0 };
389 document.getElementById("transfer-item-name").textContent = itemDisplayName(slot);
390 const input = document.getElementById("transfer-qty");
391 input.value = "1";
392 input.max = String(transferState.maxQty);
393 transferPanel.hidden = false;
394 transferBackdrop.hidden = false;
395 }
396
397 function closeTransfer ()
398 {
399 transferState = null;
400 transferPanel.hidden = true;
401 transferBackdrop.hidden = true;
402 }
403
404 function confirmTransfer ()
405 {
406 if (!transferState)
407 { return; }
408 const quantity = Math.min(
409 transferState.maxQty,
410 Math.max(1, Number(document.getElementById("transfer-qty").value) | 0)
411 );
412 transferSlot(transferState.side, transferState.slotIndex, quantity);
413 closeTransfer();
414 }
415
416 function openWriteCheque (slotIndex)
417 {
418 writeChequeState = { slotIndex, vaultSlotIndex: null, maxQty: 1 };
419 document.getElementById("write-cheque-item").textContent = "No vault item selected.";
420 document.getElementById("write-cheque-qty").value = "1";
421 document.getElementById("write-cheque-confirm").disabled = true;
422 document.getElementById("write-cheque-status").textContent = "";
423 writeChequePanel.hidden = false;
424 writeChequeBackdrop.hidden = false;
425 renderWriteChequeVault();
426 }
427
428 function closeWriteCheque ()
429 {
430 writeChequeState = null;
431 writeChequePanel.hidden = true;
432 writeChequeBackdrop.hidden = true;
433 if (bankOpen)
434 { renderBank(); }
435 }
436
437 function renderWriteChequeVault ()
438 {
439 if (!writeChequeVault)
440 { return; }
441 writeChequeVault.innerHTML = "";
442 const slots = bag.vault ?? [];
443 if (!slots.some(Boolean))
444 {
445 const empty = document.createElement("p");
446 empty.className = "hint";
447 empty.textContent = "Your vault is empty. Deposit goods at a bank first.";
448 writeChequeVault.append(empty);
449 return;
450 }
451 slots.forEach((slot, index) =>
452 {
453 if (!slot)
454 { return; }
455 const button = document.createElement("button");
456 button.className = "item-slot";
457 if (writeChequeState?.vaultSlotIndex === index)
458 { button.classList.add("selected"); }
459 button.title = tooltip(slot);
460 const def = itemDefinition(slot.itemId);
461 const img = document.createElement("img");
462 img.src = itemAssetPathForStack(slot);
463 img.alt = itemDisplayName(slot);
464 button.append(img);
465 if (slot.quantity > 1)
466 {
467 const count = document.createElement("span");
468 count.className = "qty";
469 count.textContent = formatQuantity(slot.quantity);
470 button.append(count);
471 }
472 button.addEventListener("click", () =>
473 {
474 if (!writeChequeState)
475 { return; }
476 writeChequeState.vaultSlotIndex = index;
477 writeChequeState.maxQty = def?.uniqueInstance ? 1 : availableOf(slot.itemId);
478 document.getElementById("write-cheque-item").textContent =
479 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
480 const qtyInput = document.getElementById("write-cheque-qty");
481 qtyInput.value = "1";
482 qtyInput.max = String(writeChequeState.maxQty);
483 qtyInput.disabled = writeChequeState.maxQty <= 1;
484 document.getElementById("write-cheque-confirm").disabled = false;
485 renderWriteChequeVault();
486 });
487 writeChequeVault.append(button);
488 });
489 }
490
491 function confirmWriteCheque ()
492 {
493 if (!writeChequeState || writeChequeState.vaultSlotIndex == null)
494 { return; }
495 const quantity = Math.max(1, Number(document.getElementById("write-cheque-qty").value) | 0);
496 socket.send({
497 type: MessageType.writeCheque,
498 slotIndex: writeChequeState.slotIndex,
499 vaultSlotIndex: writeChequeState.vaultSlotIndex,
500 quantity
501 });
502 document.getElementById("write-cheque-status").textContent = "Writing…";
503 closeWriteCheque();
504 }
505
506 function closeBank ()
507 {
508 bankOpen = false;
509 bankPanel.hidden = true;
510 closeWriteCheque();
511 closeTransfer();
512 }
513
514 function setBankTab (tab)
515 {
516 bankTab = tab;
517 document.getElementById("bank-tab-available").classList.toggle("active", tab === "available");
518 document.getElementById("bank-tab-reserved").classList.toggle("active", tab === "reserved");
519 document.getElementById("bank-tab-inherit").classList.toggle("active", tab === "inherit");
520 bankAvailablePane.hidden = tab !== "available";
521 bankReservedPane.hidden = tab !== "reserved";
522 bankInheritPane.hidden = tab !== "inherit";
523 }
524
262 function openSend (slotIndex, slot)
525 function openSend (slotIndex, slot)
263 {
526 {
264 const def = itemDefinition(slot.itemId);
527 const def = itemDefinition(slot.itemId);
@@ -269,7 +532,7 @@ export function initInventory ({
269 destination: null
532 destination: null
270 };
533 };
271 document.getElementById("send-item-img").src = itemAssetPathForStack(slot);
534 document.getElementById("send-item-img").src = itemAssetPathForStack(slot);
272 document.getElementById("send-item-name").textContent = def?.displayName ?? "Item";
535 document.getElementById("send-item-name").textContent = itemDisplayName(slot);
273 const qtyInput = document.getElementById("send-qty");
536 const qtyInput = document.getElementById("send-qty");
274 qtyInput.value = "1";
537 qtyInput.value = "1";
275 qtyInput.max = String(sendState.maxQty);
538 qtyInput.max = String(sendState.maxQty);
@@ -440,49 +703,118 @@ export function initInventory ({
440 letterBackdrop.hidden = true;
703 letterBackdrop.hidden = true;
441 }
704 }
442
705
443 function renderVault (grid, slots)
706 function renderVault (grid, slots, { side = "vault", interactive = true } = {})
444 {
707 {
445 grid.innerHTML = "";
708 grid.innerHTML = "";
446 (slots ?? []).forEach((slot, index) =>
709 (slots ?? []).forEach((slot, index) =>
447 {
710 {
711 if (!slot)
712 { return; }
448 const button = document.createElement("button");
713 const button = document.createElement("button");
449 button.className = "item-slot";
714 button.className = "item-slot";
715 if (writeChequeState && side === "vault" && writeChequeState.vaultSlotIndex === index)
716 { button.classList.add("selected"); }
450 button.title = tooltip(slot);
717 button.title = tooltip(slot);
451 button.textContent = slot
718 const def = itemDefinition(slot.itemId);
452 ? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`
719 const img = document.createElement("img");
453 : "";
720 img.src = itemAssetPathForStack(slot);
454 button.addEventListener("click", () =>
721 img.alt = itemDisplayName(slot);
722 button.append(img);
723 if (slot.quantity > 1)
455 {
724 {
456 if (!slot)
725 const count = document.createElement("span");
457 { return; }
726 count.className = "qty";
458 socket.send({ type: MessageType.bankWithdraw, slotIndex: index });
727 count.textContent = formatQuantity(slot.quantity);
459 });
728 button.append(count);
729 }
730 if (interactive && side === "vault")
731 {
732 button.addEventListener("click", () =>
733 {
734 if (writeChequeState)
735 {
736 writeChequeState.vaultSlotIndex = index;
737 writeChequeState.maxQty = itemDefinition(slot.itemId)?.uniqueInstance
738 ? 1
739 : availableOf(slot.itemId);
740 document.getElementById("write-cheque-item").textContent =
741 `${itemDisplayName(slot)} (up to ${formatQuantity(writeChequeState.maxQty)})`;
742 const qtyInput = document.getElementById("write-cheque-qty");
743 qtyInput.value = "1";
744 qtyInput.max = String(writeChequeState.maxQty);
745 qtyInput.disabled = writeChequeState.maxQty <= 1;
746 document.getElementById("write-cheque-confirm").disabled = false;
747 renderBank();
748 return;
749 }
750 transferSlot("vault", index, null);
751 });
752 button.addEventListener("contextmenu", (event) =>
753 {
754 event.preventDefault();
755 event.stopPropagation();
756 if (writeChequeState)
757 { return; }
758 showBankTransferMenu(event.clientX, event.clientY, "vault", index, slot);
759 });
760 }
460 grid.append(button);
761 grid.append(button);
461 });
762 });
462 }
763 }
463
764
765 function availableOf (itemId)
766 {
767 let total = 0;
768 for (const slot of bag.vault ?? [])
769 {
770 if (slot?.itemId === itemId)
771 { total += slot.quantity | 0; }
772 }
773 return total;
774 }
775
776 function renderBank ()
777 {
778 renderVault(vaultGrid, bag.vault, { side: "vault", interactive: true });
779 renderVault(vaultReservedGrid, bag.vaultReserved, { side: "reserved", interactive: false });
780 setBankTab(bankTab);
781 }
782
464 function tooltip (slot)
783 function tooltip (slot)
465 {
784 {
466 if (!slot)
785 if (!slot)
467 { return ""; }
786 { return ""; }
468 const def = itemDefinition(slot.itemId);
787 const def = itemDefinition(slot.itemId);
469 return `${def?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`;
788 const base = `${itemDisplayName(slot)}${slot.quantity > 1 ? ` ×${formatQuantity(slot.quantity)}` : ""}`;
789 const origin = itemOriginSummary(slot);
790 const desc = itemDescription(slot, { localCharacterId });
791 const lines = [base];
792 if (origin)
793 { lines.push(origin); }
794 if (desc)
795 { lines.push(desc); }
796 return lines.join("\n");
470 }
797 }
471
798
472 return {
799 return {
473 isOpen ()
800 isOpen ()
474 {
801 {
475 return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden;
802 return !bagPanel.hidden || bankOpen || !sendPanel.hidden || !letterPanel.hidden
803 || !sendTargetPanel.hidden || !transferPanel.hidden || !writeChequePanel.hidden;
476 },
804 },
477 isBlocking ()
805 isBlocking ()
478 {
806 {
479 // Send/letter dialogs cover the view — keep world clicks blocked.
807 if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden
480 if (!sendPanel.hidden || !letterPanel.hidden || !sendTargetPanel.hidden)
808 || !transferPanel.hidden || !writeChequePanel.hidden)
481 { return true; }
809 { return true; }
482 if (sendBackdrop && !sendBackdrop.hidden)
810 if (sendBackdrop && !sendBackdrop.hidden)
483 { return true; }
811 { return true; }
484 if (letterBackdrop && !letterBackdrop.hidden)
812 if (letterBackdrop && !letterBackdrop.hidden)
485 { return true; }
813 { return true; }
814 if (transferBackdrop && !transferBackdrop.hidden)
815 { return true; }
816 if (writeChequeBackdrop && !writeChequeBackdrop.hidden)
817 { return true; }
486 const x = GameInput.mousePosition.x;
818 const x = GameInput.mousePosition.x;
487 const y = GameInput.mousePosition.y;
819 const y = GameInput.mousePosition.y;
488 for (const element of [bagPanel, bankPanel])
820 for (const element of [bagPanel, bankPanel])
@@ -499,49 +831,55 @@ export function initInventory ({
499 {
831 {
500 localCharacterId = characterId;
832 localCharacterId = characterId;
501 },
833 },
834 getInventorySlots ()
835 {
836 return bag.inventory ?? [];
837 },
502 handleInventory (message)
838 handleInventory (message)
503 {
839 {
504 bag = { ...bag, ...message };
840 bag = { ...bag, ...message };
505 render();
841 render();
842 if (bankOpen)
843 { renderBank(); }
844 if (writeChequeState)
845 { renderWriteChequeVault(); }
506 if (letterState && letterStatus.textContent === "Saving…")
846 if (letterState && letterStatus.textContent === "Saving…")
507 {
847 {
508 letterStatus.textContent = "Saved.";
848 letterStatus.textContent = "Saved.";
509 if (letterState.mode === "write")
849 if (letterState.mode === "write")
510 { closeLetter(); }
850 { closeLetter(); }
511 else if (letterState.mode === "edit")
851 else if (letterState.mode === "edit")
852 {
853 const slot = bag.inventory?.[letterState.slotIndex];
854 if (slot?.instance)
512 {
855 {
513 const slot = bag.inventory?.[letterState.slotIndex];
856 letterState.instance = slot.instance;
514 if (slot?.instance)
857 letterBody.value = slot.instance.body ?? "";
515 {
858 refreshLetterSignature();
516 letterState.instance = slot.instance;
859 fitLetterBody();
517 letterBody.value = slot.instance.body ?? "";
518 refreshLetterSignature();
519 fitLetterBody();
520 }
521 }
860 }
861 }
522 }
862 }
523 },
863 },
524 handleBank (message)
864 handleBank (message)
525 {
865 {
526 bankOpen = true;
866 bankOpen = true;
527 bankPanel.hidden = false;
867 bankPanel.hidden = false;
528 bag.vault = message.vault;
868 bagPanel.hidden = false;
529 bag.vaultCurrency = message.vaultCurrency;
869 bag.vault = message.vault ?? [];
530 vaultCoins.textContent = `${message.vaultCurrency ?? 0} coins in vault · you carry ${message.currency ?? 0}`;
870 bag.vaultReserved = message.vaultReserved ?? [];
531 inheritCoins.textContent = `${message.inheritance?.currency ?? 0} coins waiting`;
871 renderVault(inheritGrid, message.inheritance?.slots ?? [], { interactive: false });
532 renderVault(vaultGrid, message.vault);
533 renderVault(inheritGrid, message.inheritance?.slots ?? []);
534 inheritGrid.querySelectorAll("button").forEach((button) =>
872 inheritGrid.querySelectorAll("button").forEach((button) =>
535 {
873 {
536 button.onclick = null;
874 button.onclick = null;
537 });
875 });
876 setBankTab("available");
877 renderBank();
538 render();
878 render();
539 },
879 },
540 depositSelected ()
880 getBlankCheques ()
541 {
881 {
542 if (selected == null)
882 socket.send({ type: MessageType.getBlankCheques });
543 { return; }
544 socket.send({ type: MessageType.bankDeposit, slotIndex: selected });
545 },
883 },
546 handlePigeonDispatched ()
884 handlePigeonDispatched ()
547 {
885 {
@@ -569,8 +907,7 @@ export function initInventory ({
569 reset ()
907 reset ()
570 {
908 {
571 bagPanel.hidden = true;
909 bagPanel.hidden = true;
572 bankPanel.hidden = true;
910 closeBank();
573 bankOpen = false;
574 selected = null;
911 selected = null;
575 closeSend();
912 closeSend();
576 closeLetter();
913 closeLetter();
client/src/play/main.js +130 −11
@@ -6,7 +6,11 @@ import { WorldView } from "../render/worldView.js";
6 6 import { initSocial } from "./social.js";
7 7 import { initChat } from "./chat.js";
8 8 import { initInventory } from "./inventory.js";
9 import { initSkills } from "./skills.js";
10 import { initCrafting } from "./crafting.js";
9 11 import { initContextMenu } from "./contextMenu.js";
12 import { CraftingStationId } from "/shared/definitions/craftingStations.js";
13 import { formatQuantity } from "/shared/items/formatQuantity.js";
10 14
11 15 const game = new Game();
12 16 const hud = document.getElementById("hud");
@@ -25,8 +29,12 @@ let catalog = { grounds: {}, blocks: {} };
25 29 let social;
26 30 let chat;
27 31 let inventory;
32 let skills;
33 let crafting;
28 34 let contextMenu;
29 35 let pendingPickup = null;
36 let pendingBank = null;
37 let pendingGetCheques = false;
30 38
31 39 function showError (message)
32 40 {
@@ -64,7 +72,8 @@ function renderCharacters (characters)
64 72
65 73 function uiBlocked ()
66 74 {
67 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() || contextMenu?.isOpen());
75 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
76 || crafting?.isBlocking() || contextMenu?.isOpen());
68 77 }
69 78
70 79 function clearPendingPickup ()
@@ -72,6 +81,63 @@ function clearPendingPickup ()
72 81 pendingPickup = null;
73 82 }
74 83
84 function clearPendingBank ()
85 {
86 pendingBank = null;
87 pendingGetCheques = false;
88 }
89
90 function requestOpenBank (tileX, tileY, { getCheques = false } = {})
91 {
92 clearPendingPickup();
93 pendingBank = { tileX, tileY };
94 pendingGetCheques = !!getCheques;
95 const local = view.entities.get(view.localEntityId);
96 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
97 {
98 flushPendingBank();
99 return;
100 }
101 let best = null;
102 let bestDist = Infinity;
103 for (let dy = -1; dy <= 1; dy++)
104 {
105 for (let dx = -1; dx <= 1; dx++)
106 {
107 if (dx === 0 && dy === 0)
108 { continue; }
109 const destX = tileX + dx;
110 const destY = tileY + dy;
111 const dist = local
112 ? chebyshev(local.tileX, local.tileY, destX, destY)
113 : 0;
114 if (dist < bestDist)
115 {
116 bestDist = dist;
117 best = { tileX: destX, tileY: destY };
118 }
119 }
120 }
121 if (best)
122 { socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); }
123 }
124
125 function flushPendingBank ()
126 {
127 if (!pendingBank || !view)
128 { return; }
129 const local = view.entities.get(view.localEntityId);
130 if (!local)
131 { return; }
132 if (chebyshev(local.tileX, local.tileY, pendingBank.tileX, pendingBank.tileY) > 1)
133 { return; }
134 const getCheques = pendingGetCheques;
135 socket.send({ type: MessageType.openBank });
136 if (getCheques)
137 { inventory?.getBlankCheques(); }
138 clearPendingBank();
139 }
140
75 141 function requestPickup (ground)
76 142 {
77 143 if (!ground)
@@ -115,6 +181,7 @@ function handleLeftClick (mouseX, mouseY)
115 181 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
116 182 {
117 183 clearPendingPickup();
184 clearPendingBank();
118 185 if (entity.characterId)
119 186 {
120 187 social.inspect(entity);
@@ -125,7 +192,7 @@ function handleLeftClick (mouseX, mouseY)
125 192 socket.send({ type: MessageType.interact, targetEntityId: entity.entityId });
126 193 return;
127 194 }
128 if (entity.hostile)
195 if (entity.canFight)
129 196 {
130 197 socket.send({ type: MessageType.attack, targetEntityId: entity.entityId });
131 198 return;
@@ -133,18 +200,18 @@ function handleLeftClick (mouseX, mouseY)
133 200 }
134 201
135 202 const tile = view.screenToTile(mouseX, mouseY);
136 const local = view.entities.get(view.localEntityId);
137 203 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
138 204 if (ground)
139 { requestPickup(ground); }
140 else if (isBankTile(view, tile.tileX, tile.tileY) && local && chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= 1)
141 205 {
142 clearPendingPickup();
143 socket.send({ type: MessageType.openBank });
206 clearPendingBank();
207 requestPickup(ground);
144 208 }
209 else if (isBankTile(view, tile.tileX, tile.tileY))
210 { requestOpenBank(tile.tileX, tile.tileY); }
145 211 else
146 212 {
147 213 clearPendingPickup();
214 clearPendingBank();
148 215 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
149 216 }
150 217 }
@@ -222,6 +289,18 @@ function handleRightClick (event, mouseX, mouseY)
222 289 });
223 290 }
224 291
292 if (isBankTile(view, tile.tileX, tile.tileY))
293 {
294 items.push({
295 label: "Bank",
296 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
297 });
298 items.push({
299 label: "Get Blank Cheques",
300 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
301 });
302 }
303
225 304 contextMenu.show(event.clientX, event.clientY, items);
226 305 }
227 306
@@ -237,9 +316,10 @@ function entityLabel (entity)
237 316 function groundLabel (ground)
238 317 {
239 318 const name = (ground?.displayName ?? "").trim() || "item";
240 if ((ground?.quantity ?? 1) > 1)
241 { return `${name} (${ground.quantity})`; }
242 return name;
319 const qty = ground?.quantity ?? 1;
320 if (qty <= 1)
321 { return name; }
322 return `${name} (${formatQuantity(qty)})`;
243 323 }
244 324
245 325 function startPlay (payload)
@@ -276,6 +356,7 @@ function startPlay (payload)
276 356 if (playing)
277 357 {
278 358 flushPendingPickup();
359 flushPendingBank();
279 360 social?.updateNametag(view, scene, view.localEntityId);
280 361 chat?.update(view, scene);
281 362 }
@@ -347,7 +428,19 @@ async function main ()
347 428 return you.split("(")[0].trim() || "Unknown";
348 429 }
349 430 });
350 document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());
431 skills = initSkills();
432 crafting = initCrafting({
433 socket: { send (payload) { socket.send(payload); } },
434 MessageType,
435 getInventorySlots ()
436 {
437 return inventory?.getInventorySlots?.() ?? [];
438 },
439 getSkillLevel (skillId)
440 {
441 return skills?.skillLevel?.(skillId) ?? 1;
442 }
443 });
351 444 chat = initChat({
352 445 socket: { send (payload) { socket.send(payload); } },
353 446 MessageType,
@@ -404,6 +497,11 @@ async function main ()
404 497 break;
405 498 case MessageType.inventory:
406 499 inventory?.handleInventory(message);
500 crafting?.refresh();
501 break;
502 case MessageType.skills:
503 skills?.render(message.skills);
504 crafting?.refresh();
407 505 break;
408 506 case MessageType.bankSnapshot:
409 507 inventory?.handleBank(message);
@@ -417,6 +515,9 @@ async function main ()
417 515 case MessageType.characterSearchResult:
418 516 inventory?.handleCharacterSearch(message);
419 517 break;
518 case MessageType.craftResult:
519 crafting?.handleCraftResult(message);
520 break;
420 521 case MessageType.worldStatus:
421 522 if (view)
422 523 {
@@ -435,6 +536,8 @@ async function main ()
435 536 view?.spawnCombatSwing(message);
436 537 break;
437 538 case MessageType.combatHit:
539 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
540 view?.flashDamage(message.targetId);
438 541 view?.addDynamicLight({
439 542 worldX: (message.tileX ?? 0) + 0.5,
440 543 worldY: (message.tileY ?? 0) + 0.5,
@@ -451,17 +554,33 @@ async function main ()
451 554 returnToMenu(message.reason);
452 555 break;
453 556 }
557 }, {
558 onClose (event)
559 {
560 if (playing)
561 { returnToMenu(event.reason || "Disconnected from server."); }
562 }
454 563 });
455 564 await socket.connect();
565 if (typeof window !== "undefined")
566 {
567 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
568 {
569 crafting?.openStation(stationId);
570 };
571 }
456 572 }
457 573
458 574 function returnToMenu (reason = "")
459 575 {
460 576 playing = false;
461 577 clearPendingPickup();
578 clearPendingBank();
462 579 social?.reset();
463 580 chat?.reset();
464 581 inventory?.reset();
582 crafting?.reset();
583 skills?.hide();
465 584 contextMenu?.hide();
466 585 if (view)
467 586 {
@@ -6,7 +6,11 @@ import { WorldView } from "../render/worldView.js";
6import { initSocial } from "./social.js";
6import { initSocial } from "./social.js";
7import { initChat } from "./chat.js";
7import { initChat } from "./chat.js";
8import { initInventory } from "./inventory.js";
8import { initInventory } from "./inventory.js";
9import { initSkills } from "./skills.js";
10import { initCrafting } from "./crafting.js";
9import { initContextMenu } from "./contextMenu.js";
11import { initContextMenu } from "./contextMenu.js";
12import { CraftingStationId } from "/shared/definitions/craftingStations.js";
13import { formatQuantity } from "/shared/items/formatQuantity.js";
10
14
11const game = new Game();
15const game = new Game();
12const hud = document.getElementById("hud");
16const hud = document.getElementById("hud");
@@ -25,8 +29,12 @@ let catalog = { grounds: {}, blocks: {} };
25let social;
29let social;
26let chat;
30let chat;
27let inventory;
31let inventory;
32let skills;
33let crafting;
28let contextMenu;
34let contextMenu;
29let pendingPickup = null;
35let pendingPickup = null;
36let pendingBank = null;
37let pendingGetCheques = false;
30
38
31function showError (message)
39function showError (message)
32{
40{
@@ -64,7 +72,8 @@ function renderCharacters (characters)
64
72
65function uiBlocked ()
73function uiBlocked ()
66{
74{
67 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() || contextMenu?.isOpen());
75 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
76 || crafting?.isBlocking() || contextMenu?.isOpen());
68}
77}
69
78
70function clearPendingPickup ()
79function clearPendingPickup ()
@@ -72,6 +81,63 @@ function clearPendingPickup ()
72 pendingPickup = null;
81 pendingPickup = null;
73}
82}
74
83
84function clearPendingBank ()
85{
86 pendingBank = null;
87 pendingGetCheques = false;
88}
89
90function requestOpenBank (tileX, tileY, { getCheques = false } = {})
91{
92 clearPendingPickup();
93 pendingBank = { tileX, tileY };
94 pendingGetCheques = !!getCheques;
95 const local = view.entities.get(view.localEntityId);
96 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
97 {
98 flushPendingBank();
99 return;
100 }
101 let best = null;
102 let bestDist = Infinity;
103 for (let dy = -1; dy <= 1; dy++)
104 {
105 for (let dx = -1; dx <= 1; dx++)
106 {
107 if (dx === 0 && dy === 0)
108 { continue; }
109 const destX = tileX + dx;
110 const destY = tileY + dy;
111 const dist = local
112 ? chebyshev(local.tileX, local.tileY, destX, destY)
113 : 0;
114 if (dist < bestDist)
115 {
116 bestDist = dist;
117 best = { tileX: destX, tileY: destY };
118 }
119 }
120 }
121 if (best)
122 { socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); }
123}
124
125function flushPendingBank ()
126{
127 if (!pendingBank || !view)
128 { return; }
129 const local = view.entities.get(view.localEntityId);
130 if (!local)
131 { return; }
132 if (chebyshev(local.tileX, local.tileY, pendingBank.tileX, pendingBank.tileY) > 1)
133 { return; }
134 const getCheques = pendingGetCheques;
135 socket.send({ type: MessageType.openBank });
136 if (getCheques)
137 { inventory?.getBlankCheques(); }
138 clearPendingBank();
139}
140
75function requestPickup (ground)
141function requestPickup (ground)
76{
142{
77 if (!ground)
143 if (!ground)
@@ -115,6 +181,7 @@ function handleLeftClick (mouseX, mouseY)
115 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
181 if (entity && entity.entityId !== view.localEntityId && !entity.untargetable)
116 {
182 {
117 clearPendingPickup();
183 clearPendingPickup();
184 clearPendingBank();
118 if (entity.characterId)
185 if (entity.characterId)
119 {
186 {
120 social.inspect(entity);
187 social.inspect(entity);
@@ -125,7 +192,7 @@ function handleLeftClick (mouseX, mouseY)
125 socket.send({ type: MessageType.interact, targetEntityId: entity.entityId });
192 socket.send({ type: MessageType.interact, targetEntityId: entity.entityId });
126 return;
193 return;
127 }
194 }
128 if (entity.hostile)
195 if (entity.canFight)
129 {
196 {
130 socket.send({ type: MessageType.attack, targetEntityId: entity.entityId });
197 socket.send({ type: MessageType.attack, targetEntityId: entity.entityId });
131 return;
198 return;
@@ -133,18 +200,18 @@ function handleLeftClick (mouseX, mouseY)
133 }
200 }
134
201
135 const tile = view.screenToTile(mouseX, mouseY);
202 const tile = view.screenToTile(mouseX, mouseY);
136 const local = view.entities.get(view.localEntityId);
137 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
203 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
138 if (ground)
204 if (ground)
139 { requestPickup(ground); }
140 else if (isBankTile(view, tile.tileX, tile.tileY) && local && chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= 1)
141 {
205 {
142 clearPendingPickup();
206 clearPendingBank();
143 socket.send({ type: MessageType.openBank });
207 requestPickup(ground);
144 }
208 }
209 else if (isBankTile(view, tile.tileX, tile.tileY))
210 { requestOpenBank(tile.tileX, tile.tileY); }
145 else
211 else
146 {
212 {
147 clearPendingPickup();
213 clearPendingPickup();
214 clearPendingBank();
148 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
215 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
149 }
216 }
150}
217}
@@ -222,6 +289,18 @@ function handleRightClick (event, mouseX, mouseY)
222 });
289 });
223 }
290 }
224
291
292 if (isBankTile(view, tile.tileX, tile.tileY))
293 {
294 items.push({
295 label: "Bank",
296 onSelect: () => requestOpenBank(tile.tileX, tile.tileY)
297 });
298 items.push({
299 label: "Get Blank Cheques",
300 onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true })
301 });
302 }
303
225 contextMenu.show(event.clientX, event.clientY, items);
304 contextMenu.show(event.clientX, event.clientY, items);
226}
305}
227
306
@@ -237,9 +316,10 @@ function entityLabel (entity)
237function groundLabel (ground)
316function groundLabel (ground)
238{
317{
239 const name = (ground?.displayName ?? "").trim() || "item";
318 const name = (ground?.displayName ?? "").trim() || "item";
240 if ((ground?.quantity ?? 1) > 1)
319 const qty = ground?.quantity ?? 1;
241 { return `${name} (${ground.quantity})`; }
320 if (qty <= 1)
242 return name;
321 { return name; }
322 return `${name} (${formatQuantity(qty)})`;
243}
323}
244
324
245function startPlay (payload)
325function startPlay (payload)
@@ -276,6 +356,7 @@ function startPlay (payload)
276 if (playing)
356 if (playing)
277 {
357 {
278 flushPendingPickup();
358 flushPendingPickup();
359 flushPendingBank();
279 social?.updateNametag(view, scene, view.localEntityId);
360 social?.updateNametag(view, scene, view.localEntityId);
280 chat?.update(view, scene);
361 chat?.update(view, scene);
281 }
362 }
@@ -347,7 +428,19 @@ async function main ()
347 return you.split("(")[0].trim() || "Unknown";
428 return you.split("(")[0].trim() || "Unknown";
348 }
429 }
349 });
430 });
350 document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());
431 skills = initSkills();
432 crafting = initCrafting({
433 socket: { send (payload) { socket.send(payload); } },
434 MessageType,
435 getInventorySlots ()
436 {
437 return inventory?.getInventorySlots?.() ?? [];
438 },
439 getSkillLevel (skillId)
440 {
441 return skills?.skillLevel?.(skillId) ?? 1;
442 }
443 });
351 chat = initChat({
444 chat = initChat({
352 socket: { send (payload) { socket.send(payload); } },
445 socket: { send (payload) { socket.send(payload); } },
353 MessageType,
446 MessageType,
@@ -404,6 +497,11 @@ async function main ()
404 break;
497 break;
405 case MessageType.inventory:
498 case MessageType.inventory:
406 inventory?.handleInventory(message);
499 inventory?.handleInventory(message);
500 crafting?.refresh();
501 break;
502 case MessageType.skills:
503 skills?.render(message.skills);
504 crafting?.refresh();
407 break;
505 break;
408 case MessageType.bankSnapshot:
506 case MessageType.bankSnapshot:
409 inventory?.handleBank(message);
507 inventory?.handleBank(message);
@@ -417,6 +515,9 @@ async function main ()
417 case MessageType.characterSearchResult:
515 case MessageType.characterSearchResult:
418 inventory?.handleCharacterSearch(message);
516 inventory?.handleCharacterSearch(message);
419 break;
517 break;
518 case MessageType.craftResult:
519 crafting?.handleCraftResult(message);
520 break;
420 case MessageType.worldStatus:
521 case MessageType.worldStatus:
421 if (view)
522 if (view)
422 {
523 {
@@ -435,6 +536,8 @@ async function main ()
435 view?.spawnCombatSwing(message);
536 view?.spawnCombatSwing(message);
436 break;
537 break;
437 case MessageType.combatHit:
538 case MessageType.combatHit:
539 view?.updateEntityHealth(message.targetId, message.health, message.maxHealth);
540 view?.flashDamage(message.targetId);
438 view?.addDynamicLight({
541 view?.addDynamicLight({
439 worldX: (message.tileX ?? 0) + 0.5,
542 worldX: (message.tileX ?? 0) + 0.5,
440 worldY: (message.tileY ?? 0) + 0.5,
543 worldY: (message.tileY ?? 0) + 0.5,
@@ -451,17 +554,33 @@ async function main ()
451 returnToMenu(message.reason);
554 returnToMenu(message.reason);
452 break;
555 break;
453 }
556 }
557 }, {
558 onClose (event)
559 {
560 if (playing)
561 { returnToMenu(event.reason || "Disconnected from server."); }
562 }
454 });
563 });
455 await socket.connect();
564 await socket.connect();
565 if (typeof window !== "undefined")
566 {
567 window.__craftDev = (stationId = CraftingStationId.craftingBench) =>
568 {
569 crafting?.openStation(stationId);
570 };
571 }
456}
572}
457
573
458function returnToMenu (reason = "")
574function returnToMenu (reason = "")
459{
575{
460 playing = false;
576 playing = false;
461 clearPendingPickup();
577 clearPendingPickup();
578 clearPendingBank();
462 social?.reset();
579 social?.reset();
463 chat?.reset();
580 chat?.reset();
464 inventory?.reset();
581 inventory?.reset();
582 crafting?.reset();
583 skills?.hide();
465 contextMenu?.hide();
584 contextMenu?.hide();
466 if (view)
585 if (view)
467 {
586 {
client/src/play/skills.js added +64 −0
@@ -0,0 +1,64 @@
1 export function initSkills ()
2 {
3 const panel = document.getElementById("skills-panel");
4 const list = document.getElementById("skills-list");
5 let current = [];
6 document.getElementById("skills-toggle").addEventListener("click", () =>
7 {
8 panel.hidden = !panel.hidden;
9 });
10
11 function render (skills)
12 {
13 current = skills ?? [];
14 list.replaceChildren();
15 for (const skill of current)
16 {
17 list.append(renderSkillRow(skill));
18 }
19 }
20
21 return {
22 render,
23 skillLevel (skillId)
24 {
25 return current.find((entry) => entry.skillId === skillId)?.level ?? 1;
26 },
27 hide ()
28 {
29 panel.hidden = true;
30 }
31 };
32 }
33
34 function renderSkillRow (skill)
35 {
36 const row = document.createElement("div");
37 row.className = "skill-row";
38
39 const icon = document.createElement("img");
40 icon.className = "skill-icon";
41 icon.src = skill.icon;
42 icon.alt = "";
43 icon.loading = "lazy";
44
45 const body = document.createElement("div");
46 body.className = "skill-body";
47
48 const title = document.createElement("div");
49 title.className = "skill-title";
50 title.textContent = `${skill.displayName} — Level ${skill.level}`;
51
52 const track = document.createElement("div");
53 track.className = "skill-xp-track";
54 const fill = document.createElement("div");
55 fill.className = "skill-xp-fill";
56 const pct = skill.xpToNext > 0 ? Math.min(100, (skill.xp / skill.xpToNext) * 100) : 100;
57 fill.style.width = `${pct}%`;
58 track.title = `${skill.xp} / ${skill.xpToNext} XP to next level`;
59 track.append(fill);
60
61 body.append(title, track);
62 row.append(icon, body);
63 return row;
64 }
@@ -0,0 +1,64 @@
1export function initSkills ()
2{
3 const panel = document.getElementById("skills-panel");
4 const list = document.getElementById("skills-list");
5 let current = [];
6 document.getElementById("skills-toggle").addEventListener("click", () =>
7 {
8 panel.hidden = !panel.hidden;
9 });
10
11 function render (skills)
12 {
13 current = skills ?? [];
14 list.replaceChildren();
15 for (const skill of current)
16 {
17 list.append(renderSkillRow(skill));
18 }
19 }
20
21 return {
22 render,
23 skillLevel (skillId)
24 {
25 return current.find((entry) => entry.skillId === skillId)?.level ?? 1;
26 },
27 hide ()
28 {
29 panel.hidden = true;
30 }
31 };
32}
33
34function renderSkillRow (skill)
35{
36 const row = document.createElement("div");
37 row.className = "skill-row";
38
39 const icon = document.createElement("img");
40 icon.className = "skill-icon";
41 icon.src = skill.icon;
42 icon.alt = "";
43 icon.loading = "lazy";
44
45 const body = document.createElement("div");
46 body.className = "skill-body";
47
48 const title = document.createElement("div");
49 title.className = "skill-title";
50 title.textContent = `${skill.displayName} — Level ${skill.level}`;
51
52 const track = document.createElement("div");
53 track.className = "skill-xp-track";
54 const fill = document.createElement("div");
55 fill.className = "skill-xp-fill";
56 const pct = skill.xpToNext > 0 ? Math.min(100, (skill.xp / skill.xpToNext) * 100) : 100;
57 fill.style.width = `${pct}%`;
58 track.title = `${skill.xp} / ${skill.xpToNext} XP to next level`;
59 track.append(fill);
60
61 body.append(title, track);
62 row.append(icon, body);
63 return row;
64}
client/src/render/worldView.js +211 −11
@@ -1,4 +1,4 @@
1 import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
1 import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
2 2 import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
3 3 import { itemSpriteName } from "/shared/definitions/items.js";
4 4 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
@@ -14,8 +14,17 @@ const SORT_BLOCK = 1;
14 14 const SORT_SHADE = 2;
15 15 const SORT_ENTITY = 3;
16 16 const SORT_SPRITE_SHADE = 4;
17 const SORT_HP_BAR = 5;
17 18 const RENDER_LAYER_BLOOM = "bloom";
18 19
20 const HP_BAR_W = 14;
21 const HP_BAR_H = 4;
22 const WALK_TILT_DEG = 6;
23 const RUN_TILT_DEG = 8;
24 const SHOVE_TILE_FRACTION = 0.25;
25 const SHOVE_MS = 280;
26 const DAMAGE_FLASH_MS = 180;
27
19 28 const SPRITE_SHADE_FRAG = [
20 29 "precision mediump float;",
21 30 "varying vec2 v_texCoord;",
@@ -28,7 +37,21 @@ const SPRITE_SHADE_FRAG = [
28 37 "}"
29 38 ].join("\n");
30 39
40 const DAMAGE_FLASH_FRAG = [
41 "precision mediump float;",
42 "varying vec2 v_texCoord;",
43 "uniform sampler2D u_texture;",
44 "uniform float u_strength;",
45 "void main() {",
46 " vec4 color = texture2D(u_texture, v_texCoord);",
47 " if (color.a <= 0.0) { discard; }",
48 " vec3 flash = mix(color.rgb, vec3(1.0, 0.12, 0.12), u_strength);",
49 " gl_FragColor = vec4(flash, color.a);",
50 "}"
51 ].join("\n");
52
31 53 let spriteShadeShader = null;
54 let damageFlashShader = null;
32 55
33 56 function getSpriteShadeShader ()
34 57 {
@@ -37,6 +60,13 @@ function getSpriteShadeShader ()
37 60 return spriteShadeShader;
38 61 }
39 62
63 function getDamageFlashShader ()
64 {
65 if (!damageFlashShader)
66 { damageFlashShader = Shader.fragment(DAMAGE_FLASH_FRAG); }
67 return damageFlashShader;
68 }
69
40 70 export class WorldView
41 71 {
42 72 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
@@ -181,6 +211,7 @@ export class WorldView
181 211 { return; }
182 212 existing.object?.destroy();
183 213 existing.spriteShade?.destroy();
214 existing.hpBar?.destroy();
184 215 for (const shade of existing.overlayShades ?? [])
185 216 { shade.destroy(); }
186 217 for (const overlay of existing.overlays ?? [])
@@ -190,6 +221,24 @@ export class WorldView
190 221 this.entities.delete(entityId);
191 222 }
192 223
224 updateEntityHealth (entityId, health, maxHealth)
225 {
226 const entity = this.entities.get(entityId);
227 if (!entity)
228 { return; }
229 entity.health = health;
230 entity.maxHealth = maxHealth;
231 this.#syncHpBar(entity);
232 }
233
234 flashDamage (entityId)
235 {
236 const entity = this.entities.get(entityId);
237 if (!entity)
238 { return; }
239 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
240 }
241
193 242 setAppearance (payload)
194 243 {
195 244 const existing = this.entities.get(payload.entityId);
@@ -377,7 +426,8 @@ export class WorldView
377 426 entity.visualX = target.x;
378 427 entity.visualY = target.y;
379 428 }
380 this.#placeEntity(entity);
429 this.#updateShove(entity, now, size);
430 this.#placeEntity(entity, now);
381 431 }
382 432
383 433 this.#updateSwipes(now);
@@ -385,12 +435,47 @@ export class WorldView
385 435 this.#updateShade(deltaTime);
386 436 }
387 437
438 #updateShove (entity, now, tileSize)
439 {
440 if (!entity.shove)
441 {
442 entity.shoveOffsetX = 0;
443 entity.shoveOffsetY = 0;
444 return;
445 }
446 const elapsed = now - entity.shove.started;
447 const t = Math.min(1, elapsed / entity.shove.durationMs);
448 const maxDist = tileSize * SHOVE_TILE_FRACTION;
449 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
450 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
451 const dist = Math.hypot(dx, dy) || 1;
452 const ux = dx / dist;
453 const uy = dy / dist;
454 let phase;
455 if (t < 0.45)
456 { phase = t / 0.45; }
457 else
458 { phase = 1 - (t - 0.45) / 0.55; }
459 entity.shoveOffsetX = ux * maxDist * phase;
460 entity.shoveOffsetY = uy * maxDist * phase;
461 if (t >= 1)
462 { entity.shove = null; }
463 }
464
388 465 spawnCombatSwing (payload)
389 466 {
390 467 const attacker = this.entities.get(payload.attackerId);
391 468 const target = this.entities.get(payload.targetId);
392 469 if (!attacker || !target)
393 470 { return; }
471 attacker.shove = {
472 startVisualX: attacker.visualX,
473 startVisualY: attacker.visualY,
474 targetVisualX: target.visualX,
475 targetVisualY: target.visualY,
476 started: performance.now(),
477 durationMs: SHOVE_MS
478 };
394 479 const midX = (attacker.visualX + target.visualX) / 2;
395 480 const midY = (attacker.visualY + target.visualY) / 2;
396 481 const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
@@ -506,9 +591,14 @@ export class WorldView
506 591 entity.characterId = payload.characterId ?? entity.characterId ?? null;
507 592 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
508 593 entity.hostile = !!payload.hostile;
594 entity.canFight = !!payload.canFight;
509 595 entity.talkable = !!payload.talkable;
510 596 entity.untargetable = !!payload.untargetable;
511 597 entity.freeFlight = !!payload.freeFlight;
598 if (payload.health != null)
599 { entity.health = payload.health; }
600 if (payload.maxHealth != null)
601 { entity.maxHealth = payload.maxHealth; }
512 602 if (payload.firstName)
513 603 { entity.firstName = payload.firstName; }
514 604 if (payload.lastName)
@@ -535,7 +625,8 @@ export class WorldView
535 625 entity.fromY = entity.visualY;
536 626 if (payload.layers)
537 627 { this.#applyLayers(entity, payload.layers); }
538 this.#placeEntity(entity);
628 this.#syncHpBar(entity);
629 this.#placeEntity(entity, performance.now());
539 630 }
540 631
541 632 #applyLayers (entity, layers)
@@ -572,27 +663,121 @@ export class WorldView
572 663 }
573 664 }
574 665
575 #placeEntity (entity)
666 #placeEntity (entity, now = performance.now())
576 667 {
577 this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY);
578 for (const overlay of entity.overlays ?? [])
579 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); }
668 const zoom = this.zoom;
669 const offsetX = entity.shoveOffsetX ?? 0;
670 const offsetY = entity.shoveOffsetY ?? 0;
671 const pivotX = entity.visualX + offsetX;
672 const pivotY = entity.visualY + offsetY;
673 let walkTilt = 0;
674 if (entity.lerpStarted != null)
675 {
676 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
677 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
678 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
679 walkTilt = Math.sin(cycles) * tilt;
680 }
681 const flashStrength = (entity.damageFlashUntil ?? 0) > now
682 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
683 : 0;
684
685 entity.object.transform.rotation = walkTilt;
686 this.#applyDamageFlash(entity.object, flashStrength);
687 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
688 for (let index = 0; index < (entity.overlays ?? []).length; index++)
689 {
690 const overlay = entity.overlays[index];
691 overlay.transform.rotation = walkTilt;
692 this.#applyDamageFlash(overlay, flashStrength);
693 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.001, SORT_ENTITY);
694 }
580 695 for (const overlay of entity.bloomOverlays ?? [])
581 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
582 entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY);
696 {
697 overlay.transform.rotation = walkTilt;
698 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
699 }
700 entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, pivotX, pivotY);
583 701 const nextOverlayShades = [];
584 702 for (let index = 0; index < (entity.overlays ?? []).length; index++)
585 703 {
586 704 nextOverlayShades.push(this.#placeSpriteShade(
587 705 entity.overlayShades?.[index] ?? null,
588 706 entity.overlays[index],
589 entity.visualX,
590 entity.visualY + 0.001
707 pivotX,
708 pivotY + 0.001
591 709 ));
592 710 }
593 711 for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)
594 712 { entity.overlayShades[index]?.destroy(); }
595 713 entity.overlayShades = nextOverlayShades;
714 this.#placeHpBar(entity, pivotX, pivotY);
715 }
716
717 #applyDamageFlash (object, strength)
718 {
719 if (!object?.renderer)
720 { return; }
721 if (strength > 0)
722 {
723 object.renderer.shader = getDamageFlashShader();
724 object.renderer.shaderUniforms = { u_strength: strength };
725 return;
726 }
727 if (object.renderer.shader === getDamageFlashShader())
728 {
729 object.renderer.shader = null;
730 object.renderer.shaderUniforms = null;
731 }
732 }
733
734 #syncHpBar (entity)
735 {
736 const current = entity.health;
737 const max = entity.maxHealth;
738 const show = entity.mobTypeId != null
739 && current != null
740 && max != null
741 && max > 0
742 && current < max;
743 if (!show)
744 {
745 entity.hpBar?.destroy();
746 entity.hpBar = null;
747 entity.hpBarCanvas = null;
748 return;
749 }
750 if (!entity.hpBarCanvas)
751 {
752 entity.hpBarCanvas = document.createElement("canvas");
753 entity.hpBarCanvas.width = HP_BAR_W;
754 entity.hpBarCanvas.height = HP_BAR_H;
755 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
756 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
757 this.scene.addObject(entity.hpBar);
758 }
759 drawHpBar(entity.hpBarCanvas, current, max);
760 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
761 }
762
763 #placeHpBar (entity, pivotX, pivotY)
764 {
765 if (!entity.hpBar)
766 { return; }
767 const sprite = entity.object?.renderer?.sprite;
768 if (!sprite)
769 { return; }
770 const zoom = this.zoom;
771 const drawH = sprite.height * zoom;
772 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
773 const spriteTop = centerY - drawH / 2;
774 const barW = HP_BAR_W * zoom;
775 const barH = HP_BAR_H * zoom;
776 entity.hpBar.transform.position.x = pivotX;
777 entity.hpBar.transform.position.y = spriteTop - barH / 2;
778 entity.hpBar.transform.size = new vector(barW, barH);
779 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
780 this.#markSortDirty();
596 781 }
597 782
598 783 #rebuildChunk (snapshot)
@@ -1077,6 +1262,21 @@ function lerp (a, b, t)
1077 1262 return a + (b - a) * Math.min(1, Math.max(0, t));
1078 1263 }
1079 1264
1265 function drawHpBar (canvas, current, max)
1266 {
1267 const ctx = canvas.getContext("2d");
1268 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
1269 ctx.fillStyle = "#000000";
1270 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
1271 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
1272 const fillW = Math.round(12 * ratio);
1273 if (fillW > 0)
1274 {
1275 ctx.fillStyle = "#ff0000";
1276 ctx.fillRect(1, 1, fillW, 2);
1277 }
1278 }
1279
1080 1280 function copyCanvas (source, dest)
1081 1281 {
1082 1282 const ctx = dest.getContext("2d");
@@ -1,4 +1,4 @@
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX } from "/shared/protocol/constants.js";
2import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
2import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
3import { itemSpriteName } from "/shared/definitions/items.js";
3import { itemSpriteName } from "/shared/definitions/items.js";
4import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
4import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
@@ -14,8 +14,17 @@ const SORT_BLOCK = 1;
14const SORT_SHADE = 2;
14const SORT_SHADE = 2;
15const SORT_ENTITY = 3;
15const SORT_ENTITY = 3;
16const SORT_SPRITE_SHADE = 4;
16const SORT_SPRITE_SHADE = 4;
17const SORT_HP_BAR = 5;
17const RENDER_LAYER_BLOOM = "bloom";
18const RENDER_LAYER_BLOOM = "bloom";
18
19
20const HP_BAR_W = 14;
21const HP_BAR_H = 4;
22const WALK_TILT_DEG = 6;
23const RUN_TILT_DEG = 8;
24const SHOVE_TILE_FRACTION = 0.25;
25const SHOVE_MS = 280;
26const DAMAGE_FLASH_MS = 180;
27
19const SPRITE_SHADE_FRAG = [
28const SPRITE_SHADE_FRAG = [
20 "precision mediump float;",
29 "precision mediump float;",
21 "varying vec2 v_texCoord;",
30 "varying vec2 v_texCoord;",
@@ -28,7 +37,21 @@ const SPRITE_SHADE_FRAG = [
28 "}"
37 "}"
29].join("\n");
38].join("\n");
30
39
40const DAMAGE_FLASH_FRAG = [
41 "precision mediump float;",
42 "varying vec2 v_texCoord;",
43 "uniform sampler2D u_texture;",
44 "uniform float u_strength;",
45 "void main() {",
46 " vec4 color = texture2D(u_texture, v_texCoord);",
47 " if (color.a <= 0.0) { discard; }",
48 " vec3 flash = mix(color.rgb, vec3(1.0, 0.12, 0.12), u_strength);",
49 " gl_FragColor = vec4(flash, color.a);",
50 "}"
51].join("\n");
52
31let spriteShadeShader = null;
53let spriteShadeShader = null;
54let damageFlashShader = null;
32
55
33function getSpriteShadeShader ()
56function getSpriteShadeShader ()
34{
57{
@@ -37,6 +60,13 @@ function getSpriteShadeShader ()
37 return spriteShadeShader;
60 return spriteShadeShader;
38}
61}
39
62
63function getDamageFlashShader ()
64{
65 if (!damageFlashShader)
66 { damageFlashShader = Shader.fragment(DAMAGE_FLASH_FRAG); }
67 return damageFlashShader;
68}
69
40export class WorldView
70export class WorldView
41{
71{
42 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
72 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
@@ -181,6 +211,7 @@ export class WorldView
181 { return; }
211 { return; }
182 existing.object?.destroy();
212 existing.object?.destroy();
183 existing.spriteShade?.destroy();
213 existing.spriteShade?.destroy();
214 existing.hpBar?.destroy();
184 for (const shade of existing.overlayShades ?? [])
215 for (const shade of existing.overlayShades ?? [])
185 { shade.destroy(); }
216 { shade.destroy(); }
186 for (const overlay of existing.overlays ?? [])
217 for (const overlay of existing.overlays ?? [])
@@ -190,6 +221,24 @@ export class WorldView
190 this.entities.delete(entityId);
221 this.entities.delete(entityId);
191 }
222 }
192
223
224 updateEntityHealth (entityId, health, maxHealth)
225 {
226 const entity = this.entities.get(entityId);
227 if (!entity)
228 { return; }
229 entity.health = health;
230 entity.maxHealth = maxHealth;
231 this.#syncHpBar(entity);
232 }
233
234 flashDamage (entityId)
235 {
236 const entity = this.entities.get(entityId);
237 if (!entity)
238 { return; }
239 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
240 }
241
193 setAppearance (payload)
242 setAppearance (payload)
194 {
243 {
195 const existing = this.entities.get(payload.entityId);
244 const existing = this.entities.get(payload.entityId);
@@ -377,7 +426,8 @@ export class WorldView
377 entity.visualX = target.x;
426 entity.visualX = target.x;
378 entity.visualY = target.y;
427 entity.visualY = target.y;
379 }
428 }
380 this.#placeEntity(entity);
429 this.#updateShove(entity, now, size);
430 this.#placeEntity(entity, now);
381 }
431 }
382
432
383 this.#updateSwipes(now);
433 this.#updateSwipes(now);
@@ -385,12 +435,47 @@ export class WorldView
385 this.#updateShade(deltaTime);
435 this.#updateShade(deltaTime);
386 }
436 }
387
437
438 #updateShove (entity, now, tileSize)
439 {
440 if (!entity.shove)
441 {
442 entity.shoveOffsetX = 0;
443 entity.shoveOffsetY = 0;
444 return;
445 }
446 const elapsed = now - entity.shove.started;
447 const t = Math.min(1, elapsed / entity.shove.durationMs);
448 const maxDist = tileSize * SHOVE_TILE_FRACTION;
449 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
450 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
451 const dist = Math.hypot(dx, dy) || 1;
452 const ux = dx / dist;
453 const uy = dy / dist;
454 let phase;
455 if (t < 0.45)
456 { phase = t / 0.45; }
457 else
458 { phase = 1 - (t - 0.45) / 0.55; }
459 entity.shoveOffsetX = ux * maxDist * phase;
460 entity.shoveOffsetY = uy * maxDist * phase;
461 if (t >= 1)
462 { entity.shove = null; }
463 }
464
388 spawnCombatSwing (payload)
465 spawnCombatSwing (payload)
389 {
466 {
390 const attacker = this.entities.get(payload.attackerId);
467 const attacker = this.entities.get(payload.attackerId);
391 const target = this.entities.get(payload.targetId);
468 const target = this.entities.get(payload.targetId);
392 if (!attacker || !target)
469 if (!attacker || !target)
393 { return; }
470 { return; }
471 attacker.shove = {
472 startVisualX: attacker.visualX,
473 startVisualY: attacker.visualY,
474 targetVisualX: target.visualX,
475 targetVisualY: target.visualY,
476 started: performance.now(),
477 durationMs: SHOVE_MS
478 };
394 const midX = (attacker.visualX + target.visualX) / 2;
479 const midX = (attacker.visualX + target.visualX) / 2;
395 const midY = (attacker.visualY + target.visualY) / 2;
480 const midY = (attacker.visualY + target.visualY) / 2;
396 const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
481 const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
@@ -506,9 +591,14 @@ export class WorldView
506 entity.characterId = payload.characterId ?? entity.characterId ?? null;
591 entity.characterId = payload.characterId ?? entity.characterId ?? null;
507 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
592 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
508 entity.hostile = !!payload.hostile;
593 entity.hostile = !!payload.hostile;
594 entity.canFight = !!payload.canFight;
509 entity.talkable = !!payload.talkable;
595 entity.talkable = !!payload.talkable;
510 entity.untargetable = !!payload.untargetable;
596 entity.untargetable = !!payload.untargetable;
511 entity.freeFlight = !!payload.freeFlight;
597 entity.freeFlight = !!payload.freeFlight;
598 if (payload.health != null)
599 { entity.health = payload.health; }
600 if (payload.maxHealth != null)
601 { entity.maxHealth = payload.maxHealth; }
512 if (payload.firstName)
602 if (payload.firstName)
513 { entity.firstName = payload.firstName; }
603 { entity.firstName = payload.firstName; }
514 if (payload.lastName)
604 if (payload.lastName)
@@ -535,7 +625,8 @@ export class WorldView
535 entity.fromY = entity.visualY;
625 entity.fromY = entity.visualY;
536 if (payload.layers)
626 if (payload.layers)
537 { this.#applyLayers(entity, payload.layers); }
627 { this.#applyLayers(entity, payload.layers); }
538 this.#placeEntity(entity);
628 this.#syncHpBar(entity);
629 this.#placeEntity(entity, performance.now());
539 }
630 }
540
631
541 #applyLayers (entity, layers)
632 #applyLayers (entity, layers)
@@ -572,27 +663,121 @@ export class WorldView
572 }
663 }
573 }
664 }
574
665
575 #placeEntity (entity)
666 #placeEntity (entity, now = performance.now())
576 {
667 {
577 this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY);
668 const zoom = this.zoom;
578 for (const overlay of entity.overlays ?? [])
669 const offsetX = entity.shoveOffsetX ?? 0;
579 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); }
670 const offsetY = entity.shoveOffsetY ?? 0;
671 const pivotX = entity.visualX + offsetX;
672 const pivotY = entity.visualY + offsetY;
673 let walkTilt = 0;
674 if (entity.lerpStarted != null)
675 {
676 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
677 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
678 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
679 walkTilt = Math.sin(cycles) * tilt;
680 }
681 const flashStrength = (entity.damageFlashUntil ?? 0) > now
682 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
683 : 0;
684
685 entity.object.transform.rotation = walkTilt;
686 this.#applyDamageFlash(entity.object, flashStrength);
687 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
688 for (let index = 0; index < (entity.overlays ?? []).length; index++)
689 {
690 const overlay = entity.overlays[index];
691 overlay.transform.rotation = walkTilt;
692 this.#applyDamageFlash(overlay, flashStrength);
693 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.001, SORT_ENTITY);
694 }
580 for (const overlay of entity.bloomOverlays ?? [])
695 for (const overlay of entity.bloomOverlays ?? [])
581 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
696 {
582 entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, entity.visualX, entity.visualY);
697 overlay.transform.rotation = walkTilt;
698 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
699 }
700 entity.spriteShade = this.#placeSpriteShade(entity.spriteShade, entity.object, pivotX, pivotY);
583 const nextOverlayShades = [];
701 const nextOverlayShades = [];
584 for (let index = 0; index < (entity.overlays ?? []).length; index++)
702 for (let index = 0; index < (entity.overlays ?? []).length; index++)
585 {
703 {
586 nextOverlayShades.push(this.#placeSpriteShade(
704 nextOverlayShades.push(this.#placeSpriteShade(
587 entity.overlayShades?.[index] ?? null,
705 entity.overlayShades?.[index] ?? null,
588 entity.overlays[index],
706 entity.overlays[index],
589 entity.visualX,
707 pivotX,
590 entity.visualY + 0.001
708 pivotY + 0.001
591 ));
709 ));
592 }
710 }
593 for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)
711 for (let index = nextOverlayShades.length; index < (entity.overlayShades ?? []).length; index++)
594 { entity.overlayShades[index]?.destroy(); }
712 { entity.overlayShades[index]?.destroy(); }
595 entity.overlayShades = nextOverlayShades;
713 entity.overlayShades = nextOverlayShades;
714 this.#placeHpBar(entity, pivotX, pivotY);
715 }
716
717 #applyDamageFlash (object, strength)
718 {
719 if (!object?.renderer)
720 { return; }
721 if (strength > 0)
722 {
723 object.renderer.shader = getDamageFlashShader();
724 object.renderer.shaderUniforms = { u_strength: strength };
725 return;
726 }
727 if (object.renderer.shader === getDamageFlashShader())
728 {
729 object.renderer.shader = null;
730 object.renderer.shaderUniforms = null;
731 }
732 }
733
734 #syncHpBar (entity)
735 {
736 const current = entity.health;
737 const max = entity.maxHealth;
738 const show = entity.mobTypeId != null
739 && current != null
740 && max != null
741 && max > 0
742 && current < max;
743 if (!show)
744 {
745 entity.hpBar?.destroy();
746 entity.hpBar = null;
747 entity.hpBarCanvas = null;
748 return;
749 }
750 if (!entity.hpBarCanvas)
751 {
752 entity.hpBarCanvas = document.createElement("canvas");
753 entity.hpBarCanvas.width = HP_BAR_W;
754 entity.hpBarCanvas.height = HP_BAR_H;
755 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
756 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
757 this.scene.addObject(entity.hpBar);
758 }
759 drawHpBar(entity.hpBarCanvas, current, max);
760 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
761 }
762
763 #placeHpBar (entity, pivotX, pivotY)
764 {
765 if (!entity.hpBar)
766 { return; }
767 const sprite = entity.object?.renderer?.sprite;
768 if (!sprite)
769 { return; }
770 const zoom = this.zoom;
771 const drawH = sprite.height * zoom;
772 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
773 const spriteTop = centerY - drawH / 2;
774 const barW = HP_BAR_W * zoom;
775 const barH = HP_BAR_H * zoom;
776 entity.hpBar.transform.position.x = pivotX;
777 entity.hpBar.transform.position.y = spriteTop - barH / 2;
778 entity.hpBar.transform.size = new vector(barW, barH);
779 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
780 this.#markSortDirty();
596 }
781 }
597
782
598 #rebuildChunk (snapshot)
783 #rebuildChunk (snapshot)
@@ -1077,6 +1262,21 @@ function lerp (a, b, t)
1077 return a + (b - a) * Math.min(1, Math.max(0, t));
1262 return a + (b - a) * Math.min(1, Math.max(0, t));
1078}
1263}
1079
1264
1265function drawHpBar (canvas, current, max)
1266{
1267 const ctx = canvas.getContext("2d");
1268 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
1269 ctx.fillStyle = "#000000";
1270 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
1271 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
1272 const fillW = Math.round(12 * ratio);
1273 if (fillW > 0)
1274 {
1275 ctx.fillStyle = "#ff0000";
1276 ctx.fillRect(1, 1, fillW, 2);
1277 }
1278}
1279
1080function copyCanvas (source, dest)
1280function copyCanvas (source, dest)
1081{
1281{
1082 const ctx = dest.getContext("2d");
1282 const ctx = dest.getContext("2d");
client/ui/play.css +245 −2
@@ -155,6 +155,76 @@ a { color: #d4c48a; }
155 155 padding: 0.75rem;
156 156 }
157 157
158 #skills-panel {
159 position: fixed;
160 z-index: 5;
161 top: 50%;
162 left: 50%;
163 transform: translate(-50%, -50%);
164 width: min(520px, 94vw);
165 max-height: calc(100vh - 80px);
166 overflow: auto;
167 background: #1a1e26;
168 border: 1px solid #2c3340;
169 padding: 0.75rem;
170 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
171 }
172
173 .skills-grid {
174 display: grid;
175 grid-template-columns: 1fr 1fr;
176 gap: 0.55rem 0.75rem;
177 margin: 0.5rem 0;
178 }
179
180 .skill-row {
181 display: flex;
182 gap: 0.55rem;
183 align-items: stretch;
184 min-width: 0;
185 }
186
187 .skill-icon {
188 flex: 0 0 36px;
189 width: 36px;
190 height: 36px;
191 border-radius: 6px;
192 background: #101216;
193 border: 1px solid #3a4250;
194 }
195
196 .skill-body {
197 flex: 1;
198 display: flex;
199 flex-direction: column;
200 justify-content: center;
201 gap: 0.25rem;
202 min-width: 0;
203 }
204
205 .skill-title {
206 font-size: 0.85rem;
207 line-height: 1.2;
208 white-space: nowrap;
209 overflow: hidden;
210 text-overflow: ellipsis;
211 }
212
213 .skill-xp-track {
214 height: 8px;
215 background: #101216;
216 border: 1px solid #3a4250;
217 border-radius: 4px;
218 overflow: hidden;
219 }
220
221 .skill-xp-fill {
222 height: 100%;
223 background: linear-gradient(90deg, #6a7a40, #d4c48a);
224 border-radius: 3px;
225 transition: width 0.25s ease-out;
226 }
227
158 228 #bag-panel, #bank-panel {
159 229 position: fixed;
160 230 z-index: 5;
@@ -180,6 +250,22 @@ a { color: #d4c48a; }
180 250 align-items: center;
181 251 }
182 252
253 .bank-tabs {
254 display: flex;
255 gap: 0.25rem;
256 margin: 0.4rem 0;
257 }
258
259 .bank-tab {
260 flex: 1;
261 font-size: 0.8rem;
262 padding: 0.3rem 0.4rem;
263 }
264
265 .bank-tab.active {
266 outline: 1px solid #d4c48a;
267 }
268
183 269 .item-grid {
184 270 display: grid;
185 271 grid-template-columns: repeat(8, 1fr);
@@ -231,7 +317,9 @@ a { color: #d4c48a; }
231 317
232 318 #send-panel,
233 319 #send-target-panel,
234 #letter-panel {
320 #letter-panel,
321 #transfer-panel,
322 #write-cheque-panel {
235 323 position: fixed;
236 324 z-index: 6;
237 325 top: 50%;
@@ -245,13 +333,163 @@ a { color: #d4c48a; }
245 333 padding: 0.85rem 1rem 1rem;
246 334 }
247 335
336 #craft-panel {
337 position: fixed;
338 z-index: 6;
339 top: 50%;
340 left: 50%;
341 transform: translate(-50%, -50%);
342 width: min(560px, 94vw);
343 max-height: min(85vh, 720px);
344 overflow: auto;
345 background: #1a1e26;
346 border: 1px solid #2c3340;
347 padding: 0.85rem 1rem 1rem;
348 }
349
350 #craft-panel header {
351 display: flex;
352 justify-content: space-between;
353 align-items: center;
354 margin-bottom: 0.5rem;
355 }
356
357 .craft-layout {
358 display: grid;
359 grid-template-columns: 1fr 1fr;
360 gap: 0.75rem;
361 align-items: start;
362 }
363
364 @media (max-width: 520px) {
365 .craft-layout {
366 grid-template-columns: 1fr;
367 }
368 }
369
370 .craft-recipe-grid {
371 display: grid;
372 grid-template-columns: repeat(3, 1fr);
373 gap: 0.35rem;
374 }
375
376 .craft-recipe-cell {
377 display: flex;
378 flex-direction: column;
379 align-items: center;
380 gap: 0.2rem;
381 padding: 0.35rem 0.25rem;
382 min-height: 72px;
383 background: #12151c;
384 border: 1px solid #2c3340;
385 cursor: pointer;
386 }
387
388 .craft-recipe-cell.selected {
389 outline: 2px solid #d4c48a;
390 }
391
392 .craft-recipe-cell img {
393 width: 32px;
394 height: 32px;
395 object-fit: contain;
396 image-rendering: pixelated;
397 }
398
399 .craft-recipe-name {
400 font-size: 0.72rem;
401 text-align: center;
402 line-height: 1.15;
403 word-break: break-word;
404 }
405
406 .craft-detail {
407 min-height: 160px;
408 padding: 0.35rem;
409 background: #12151c;
410 border: 1px solid #2c3340;
411 }
412
413 .craft-output {
414 display: flex;
415 flex-direction: column;
416 align-items: center;
417 gap: 0.25rem;
418 margin-bottom: 0.5rem;
419 }
420
421 .craft-output img {
422 width: 48px;
423 height: 48px;
424 object-fit: contain;
425 image-rendering: pixelated;
426 }
427
428 .craft-output h3 {
429 margin: 0;
430 font-size: 0.95rem;
431 text-align: center;
432 }
433
434 .craft-inputs {
435 list-style: none;
436 margin: 0 0 0.5rem;
437 padding: 0;
438 }
439
440 .craft-input-row {
441 display: flex;
442 align-items: center;
443 gap: 0.4rem;
444 margin-bottom: 0.35rem;
445 font-size: 0.85rem;
446 }
447
448 .craft-input-row.short {
449 color: #c07070;
450 }
451
452 .craft-input-row img {
453 width: 24px;
454 height: 24px;
455 object-fit: contain;
456 image-rendering: pixelated;
457 }
458
459 .craft-progress {
460 height: 8px;
461 margin: 0.4rem 0;
462 background: #0e1014;
463 border: 1px solid #2c3340;
464 border-radius: 2px;
465 overflow: hidden;
466 }
467
468 .craft-progress-fill {
469 height: 100%;
470 width: 0%;
471 background: linear-gradient(90deg, #6a7a40, #d4c48a);
472 transition: width 0.05s linear;
473 }
474
475 #craft-button {
476 width: 100%;
477 margin-top: 0.25rem;
478 }
479
480 #craft-button:disabled {
481 opacity: 0.45;
482 }
483
248 484 #send-target-panel {
249 485 z-index: 7;
250 486 }
251 487
252 488 #send-panel header,
253 489 #send-target-panel header,
254 #letter-panel header {
490 #letter-panel header,
491 #transfer-panel header,
492 #write-cheque-panel header {
255 493 display: flex;
256 494 justify-content: space-between;
257 495 align-items: center;
@@ -262,6 +500,8 @@ a { color: #d4c48a; }
262 500 #send-panel[hidden],
263 501 #send-target-panel[hidden],
264 502 #letter-panel[hidden],
503 #transfer-panel[hidden],
504 #write-cheque-panel[hidden],
265 505 .modal-backdrop[hidden] {
266 506 display: none !important;
267 507 }
@@ -396,8 +636,11 @@ a { color: #d4c48a; }
396 636 #inspect-modal[hidden],
397 637 #inspect-backdrop[hidden],
398 638 #friends-panel[hidden],
639 #skills-panel[hidden],
399 640 #bag-panel[hidden],
400 641 #bank-panel[hidden],
642 #craft-panel[hidden],
643 #craft-backdrop[hidden],
401 644 #nametag[hidden],
402 645 #chat-bar[hidden] {
403 646 display: none !important;
@@ -155,6 +155,76 @@ a { color: #d4c48a; }
155 padding: 0.75rem;
155 padding: 0.75rem;
156}
156}
157
157
158#skills-panel {
159 position: fixed;
160 z-index: 5;
161 top: 50%;
162 left: 50%;
163 transform: translate(-50%, -50%);
164 width: min(520px, 94vw);
165 max-height: calc(100vh - 80px);
166 overflow: auto;
167 background: #1a1e26;
168 border: 1px solid #2c3340;
169 padding: 0.75rem;
170 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
171}
172
173.skills-grid {
174 display: grid;
175 grid-template-columns: 1fr 1fr;
176 gap: 0.55rem 0.75rem;
177 margin: 0.5rem 0;
178}
179
180.skill-row {
181 display: flex;
182 gap: 0.55rem;
183 align-items: stretch;
184 min-width: 0;
185}
186
187.skill-icon {
188 flex: 0 0 36px;
189 width: 36px;
190 height: 36px;
191 border-radius: 6px;
192 background: #101216;
193 border: 1px solid #3a4250;
194}
195
196.skill-body {
197 flex: 1;
198 display: flex;
199 flex-direction: column;
200 justify-content: center;
201 gap: 0.25rem;
202 min-width: 0;
203}
204
205.skill-title {
206 font-size: 0.85rem;
207 line-height: 1.2;
208 white-space: nowrap;
209 overflow: hidden;
210 text-overflow: ellipsis;
211}
212
213.skill-xp-track {
214 height: 8px;
215 background: #101216;
216 border: 1px solid #3a4250;
217 border-radius: 4px;
218 overflow: hidden;
219}
220
221.skill-xp-fill {
222 height: 100%;
223 background: linear-gradient(90deg, #6a7a40, #d4c48a);
224 border-radius: 3px;
225 transition: width 0.25s ease-out;
226}
227
158#bag-panel, #bank-panel {
228#bag-panel, #bank-panel {
159 position: fixed;
229 position: fixed;
160 z-index: 5;
230 z-index: 5;
@@ -180,6 +250,22 @@ a { color: #d4c48a; }
180 align-items: center;
250 align-items: center;
181}
251}
182
252
253.bank-tabs {
254 display: flex;
255 gap: 0.25rem;
256 margin: 0.4rem 0;
257}
258
259.bank-tab {
260 flex: 1;
261 font-size: 0.8rem;
262 padding: 0.3rem 0.4rem;
263}
264
265.bank-tab.active {
266 outline: 1px solid #d4c48a;
267}
268
183.item-grid {
269.item-grid {
184 display: grid;
270 display: grid;
185 grid-template-columns: repeat(8, 1fr);
271 grid-template-columns: repeat(8, 1fr);
@@ -231,7 +317,9 @@ a { color: #d4c48a; }
231
317
232#send-panel,
318#send-panel,
233#send-target-panel,
319#send-target-panel,
234#letter-panel {
320#letter-panel,
321#transfer-panel,
322#write-cheque-panel {
235 position: fixed;
323 position: fixed;
236 z-index: 6;
324 z-index: 6;
237 top: 50%;
325 top: 50%;
@@ -245,13 +333,163 @@ a { color: #d4c48a; }
245 padding: 0.85rem 1rem 1rem;
333 padding: 0.85rem 1rem 1rem;
246}
334}
247
335
336#craft-panel {
337 position: fixed;
338 z-index: 6;
339 top: 50%;
340 left: 50%;
341 transform: translate(-50%, -50%);
342 width: min(560px, 94vw);
343 max-height: min(85vh, 720px);
344 overflow: auto;
345 background: #1a1e26;
346 border: 1px solid #2c3340;
347 padding: 0.85rem 1rem 1rem;
348}
349
350#craft-panel header {
351 display: flex;
352 justify-content: space-between;
353 align-items: center;
354 margin-bottom: 0.5rem;
355}
356
357.craft-layout {
358 display: grid;
359 grid-template-columns: 1fr 1fr;
360 gap: 0.75rem;
361 align-items: start;
362}
363
364@media (max-width: 520px) {
365 .craft-layout {
366 grid-template-columns: 1fr;
367 }
368}
369
370.craft-recipe-grid {
371 display: grid;
372 grid-template-columns: repeat(3, 1fr);
373 gap: 0.35rem;
374}
375
376.craft-recipe-cell {
377 display: flex;
378 flex-direction: column;
379 align-items: center;
380 gap: 0.2rem;
381 padding: 0.35rem 0.25rem;
382 min-height: 72px;
383 background: #12151c;
384 border: 1px solid #2c3340;
385 cursor: pointer;
386}
387
388.craft-recipe-cell.selected {
389 outline: 2px solid #d4c48a;
390}
391
392.craft-recipe-cell img {
393 width: 32px;
394 height: 32px;
395 object-fit: contain;
396 image-rendering: pixelated;
397}
398
399.craft-recipe-name {
400 font-size: 0.72rem;
401 text-align: center;
402 line-height: 1.15;
403 word-break: break-word;
404}
405
406.craft-detail {
407 min-height: 160px;
408 padding: 0.35rem;
409 background: #12151c;
410 border: 1px solid #2c3340;
411}
412
413.craft-output {
414 display: flex;
415 flex-direction: column;
416 align-items: center;
417 gap: 0.25rem;
418 margin-bottom: 0.5rem;
419}
420
421.craft-output img {
422 width: 48px;
423 height: 48px;
424 object-fit: contain;
425 image-rendering: pixelated;
426}
427
428.craft-output h3 {
429 margin: 0;
430 font-size: 0.95rem;
431 text-align: center;
432}
433
434.craft-inputs {
435 list-style: none;
436 margin: 0 0 0.5rem;
437 padding: 0;
438}
439
440.craft-input-row {
441 display: flex;
442 align-items: center;
443 gap: 0.4rem;
444 margin-bottom: 0.35rem;
445 font-size: 0.85rem;
446}
447
448.craft-input-row.short {
449 color: #c07070;
450}
451
452.craft-input-row img {
453 width: 24px;
454 height: 24px;
455 object-fit: contain;
456 image-rendering: pixelated;
457}
458
459.craft-progress {
460 height: 8px;
461 margin: 0.4rem 0;
462 background: #0e1014;
463 border: 1px solid #2c3340;
464 border-radius: 2px;
465 overflow: hidden;
466}
467
468.craft-progress-fill {
469 height: 100%;
470 width: 0%;
471 background: linear-gradient(90deg, #6a7a40, #d4c48a);
472 transition: width 0.05s linear;
473}
474
475#craft-button {
476 width: 100%;
477 margin-top: 0.25rem;
478}
479
480#craft-button:disabled {
481 opacity: 0.45;
482}
483
248#send-target-panel {
484#send-target-panel {
249 z-index: 7;
485 z-index: 7;
250}
486}
251
487
252#send-panel header,
488#send-panel header,
253#send-target-panel header,
489#send-target-panel header,
254#letter-panel header {
490#letter-panel header,
491#transfer-panel header,
492#write-cheque-panel header {
255 display: flex;
493 display: flex;
256 justify-content: space-between;
494 justify-content: space-between;
257 align-items: center;
495 align-items: center;
@@ -262,6 +500,8 @@ a { color: #d4c48a; }
262#send-panel[hidden],
500#send-panel[hidden],
263#send-target-panel[hidden],
501#send-target-panel[hidden],
264#letter-panel[hidden],
502#letter-panel[hidden],
503#transfer-panel[hidden],
504#write-cheque-panel[hidden],
265.modal-backdrop[hidden] {
505.modal-backdrop[hidden] {
266 display: none !important;
506 display: none !important;
267}
507}
@@ -396,8 +636,11 @@ a { color: #d4c48a; }
396#inspect-modal[hidden],
636#inspect-modal[hidden],
397#inspect-backdrop[hidden],
637#inspect-backdrop[hidden],
398#friends-panel[hidden],
638#friends-panel[hidden],
639#skills-panel[hidden],
399#bag-panel[hidden],
640#bag-panel[hidden],
400#bank-panel[hidden],
641#bank-panel[hidden],
642#craft-panel[hidden],
643#craft-backdrop[hidden],
401#nametag[hidden],
644#nametag[hidden],
402#chat-bar[hidden] {
645#chat-bar[hidden] {
403 display: none !important;
646 display: none !important;
docs/FEATURES.md +75 −10
@@ -178,8 +178,20 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
178 178 ## Spawners
179 179
180 180 **Status:** full
181 **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.
182 **Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
181 **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.
182 **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/`
183
184 ## Mob definitions (content schema)
185
186 **Status:** partial
187 **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.
188 **Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
189
190 ## Quests
191
192 **Status:** not implemented
193 **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.
194 **Code:** —
183 195
184 196 ## Character logout resume
185 197
@@ -187,17 +199,70 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
187 199 **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.
188 200 **Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
189 201
190 ## Inventory, items, equipment, ground drops
202 ## Combat resolution (rolls)
191 203
192 **Status:** full
193 **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).
194 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
204 **Status:** partial
205 **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.
206 **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`
195 207
196 208 ## Combat, skills, groups, pigeons
197 209
198 210 **Status:** partial
199 **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.
200 **Code:** `shared/courier/flight.js`, `server/src/courier/service.js`, bag pigeon UI, tests in `server/tests/courier.test.js` (+ combat/follow tests)
211 **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.
212 **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)
213
214 ## Equipment tiers and worn stat bonuses
215
216 **Status:** partial
217 **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.
218 **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`
219
220 ## Gathering, crafting, and production skills
221
222 **Status:** not implemented
223 **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**.
224 **Code:** `shared/definitions/skills.js` (skill IDs + panel entries only)
225
226 ## Crafting stations
227
228 **Status:** UI shell + item/recipe scaffolding; server crafting not implemented
229 **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`.
230
231 | Station | Role | Skill |
232 | --- | --- | --- |
233 | **Furnace** | Smelt gathered **ore → bars** | Smithing |
234 | **Spinning wheel** | **Wool → thread** (wool from shorn sheep — sheep/WIP) | Tailoring |
235 | **Loom** | Weave **cloth clothing** | Tailoring |
236 | **Anvil** | Smith **metal items** from bars | Smithing |
237 | **Leatherworking station** | Craft **leather** goods | Leatherworking |
238 | **Crafting bench** | General **Crafting** (e.g. arrows + tips) | Crafting |
239 | **Oven** | Cook **raw meat** | Cooking |
240 | **Fireplace (campfire)** | Same cooking as oven | Cooking |
241
242 **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.
243
244 **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).
245
246 **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.
247
248 **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()`.
249
250 **Dev:** In the browser console, `__craftDev()` opens the crafting bench UI; pass any `CraftingStationId` string for other stations.
251
252 **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.
253 **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)
254
255 ## Stamina and running
256
257 **Status:** not implemented
258 **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.
259 **Code:** `shared/definitions/skills.js` (`playerMaxStamina` helper only)
260
261 ## Inventory, items, equipment, ground drops
262
263 **Status:** full
264 **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).
265 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
201 266
202 267 ## Proximity chat
203 268
@@ -214,8 +279,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
214 279 ## Banking, cheques, shops, player-driven marketplace
215 280
216 281 **Status:** partial
217 **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.
218 **Code:** `server/src/items/bags.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`
282 **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.
283 **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`
219 284
220 285 ## Player scripting hooks
221 286
@@ -178,8 +178,20 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
178## Spawners
178## Spawners
179
179
180**Status:** full
180**Status:** full
181**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.
181**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.
182**Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
182**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/`
183
184## Mob definitions (content schema)
185
186**Status:** partial
187**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.
188**Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
189
190## Quests
191
192**Status:** not implemented
193**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.
194**Code:** —
183
195
184## Character logout resume
196## Character logout resume
185
197
@@ -187,17 +199,70 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
187**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.
199**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.
188**Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
200**Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
189
201
190## Inventory, items, equipment, ground drops
202## Combat resolution (rolls)
191
203
192**Status:** full
204**Status:** partial
193**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).
205**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.
194**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
206**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`
195
207
196## Combat, skills, groups, pigeons
208## Combat, skills, groups, pigeons
197
209
198**Status:** partial
210**Status:** partial
199**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.
211**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.
200**Code:** `shared/courier/flight.js`, `server/src/courier/service.js`, bag pigeon UI, tests in `server/tests/courier.test.js` (+ combat/follow tests)
212**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)
213
214## Equipment tiers and worn stat bonuses
215
216**Status:** partial
217**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.
218**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`
219
220## Gathering, crafting, and production skills
221
222**Status:** not implemented
223**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**.
224**Code:** `shared/definitions/skills.js` (skill IDs + panel entries only)
225
226## Crafting stations
227
228**Status:** UI shell + item/recipe scaffolding; server crafting not implemented
229**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`.
230
231| Station | Role | Skill |
232| --- | --- | --- |
233| **Furnace** | Smelt gathered **ore → bars** | Smithing |
234| **Spinning wheel** | **Wool → thread** (wool from shorn sheep — sheep/WIP) | Tailoring |
235| **Loom** | Weave **cloth clothing** | Tailoring |
236| **Anvil** | Smith **metal items** from bars | Smithing |
237| **Leatherworking station** | Craft **leather** goods | Leatherworking |
238| **Crafting bench** | General **Crafting** (e.g. arrows + tips) | Crafting |
239| **Oven** | Cook **raw meat** | Cooking |
240| **Fireplace (campfire)** | Same cooking as oven | Cooking |
241
242**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.
243
244**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).
245
246**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.
247
248**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()`.
249
250**Dev:** In the browser console, `__craftDev()` opens the crafting bench UI; pass any `CraftingStationId` string for other stations.
251
252**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.
253**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)
254
255## Stamina and running
256
257**Status:** not implemented
258**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.
259**Code:** `shared/definitions/skills.js` (`playerMaxStamina` helper only)
260
261## Inventory, items, equipment, ground drops
262
263**Status:** full
264**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).
265**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
201
266
202## Proximity chat
267## Proximity chat
203
268
@@ -214,8 +279,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
214## Banking, cheques, shops, player-driven marketplace
279## Banking, cheques, shops, player-driven marketplace
215
280
216**Status:** partial
281**Status:** partial
217**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.
282**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.
218**Code:** `server/src/items/bags.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`
283**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`
219
284
220## Player scripting hooks
285## Player scripting hooks
221
286
server/src/combat/service.js +149 −11
@@ -1,7 +1,18 @@
1 1 import { Component } from "../ecs/components.js";
2 2 import { itemDefinition } from "../../../shared/definitions/items.js";
3 3 import { mobDefinition } from "../../../shared/definitions/mobs.js";
4 import { skillLevel, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
4 import {
5 mobCanFightType,
6 mobMeleeAttackProfile,
7 mobSkillLevels
8 } from "../../../shared/definitions/mobCombat.js";
9 import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
10 import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
11 import {
12 effectiveSkillLevel,
13 equipmentBonusesFromSlots
14 } from "../../../shared/equipment/stats.js";
15 import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
5 16 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
6 17 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
7 18
@@ -21,12 +32,57 @@ export function attackProfileOf (ecs, handle)
21 32 { return { ...attack }; }
22 33 }
23 34 const creature = ecs.get(handle, Component.creature);
24 const mobAttack = creature ? mobDefinition(creature.mobTypeId)?.defaultAttack : null;
25 if (mobAttack)
26 { return { ...mobAttack }; }
35 if (creature)
36 {
37 const def = mobDefinition(creature.mobTypeId);
38 if (mobCanFightType(creature.mobTypeId))
39 { return mobMeleeAttackProfile(def); }
40 }
27 41 return { ...UNARMED_ATTACK };
28 42 }
29 43
44 export function ensureMobCombat (ecs, entityId)
45 {
46 const handle = ecs.handleOf(entityId);
47 if (handle == null)
48 { return false; }
49 const creature = ecs.get(handle, Component.creature);
50 if (!creature || !mobCanFightType(creature.mobTypeId))
51 { return false; }
52 const def = mobDefinition(creature.mobTypeId);
53 if (!ecs.get(handle, Component.combat))
54 { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
55 if (!ecs.get(handle, Component.skills))
56 { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); }
57 return true;
58 }
59
60 function attackerSkillLevel (skills, profile, skillId)
61 {
62 if (profile.mobAttackSkill != null)
63 { return profile.mobAttackSkill; }
64 return skillLevel(skills, skillId);
65 }
66
67 function defenderSkillLevel (skills, skillId, equipment = null)
68 {
69 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {};
70 return effectiveSkillLevel(skills, skillId, bonuses);
71 }
72
73 function playerCombatLevels (ecs, handle, profile)
74 {
75 const skills = ecs.get(handle, Component.skills);
76 const equipment = ecs.get(handle, Component.equipment);
77 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
78 return {
79 hitLevel: skillLevel(skills, profile.hitSkillId),
80 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
81 agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses),
82 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
83 };
84 }
85
30 86 export function isUntargetable (ecs, handle)
31 87 {
32 88 const creature = ecs.get(handle, Component.creature);
@@ -180,10 +236,43 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
180 236 fromTileY: from.tileY
181 237 });
182 238
239 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
240 if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
241 { engageTarget(world.ecs, targetId, attackerId, now); }
242
183 243 const skills = world.ecs.get(attackerHandle, Component.skills);
184 const hitChance = Math.min(0.95, 0.45 + skillLevel(skills, profile.hitSkillId) * 0.03);
185 const hit = Math.random() < hitChance;
186 if (!hit)
244 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
245 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
246 const attackerLevels = attackerCharacter
247 ? playerCombatLevels(world.ecs, attackerHandle, profile)
248 : {
249 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
250 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
251 agilityLevel: skillLevel(skills, SkillId.dexterity),
252 defenceLevel: skillLevel(skills, SkillId.defence)
253 };
254 const hitLevel = attackerLevels.hitLevel;
255 const damageLevel = attackerLevels.damageLevel;
256 const agilityLevel = defenderSkillLevel(
257 defenderSkills,
258 SkillId.dexterity,
259 defenderEquipment
260 );
261 const defenceLevel = defenderSkillLevel(
262 defenderSkills,
263 SkillId.defence,
264 defenderEquipment
265 );
266
267 const resolved = resolvePhysicalAttack({
268 hitSkillLevel: hitLevel,
269 agilitySkillLevel: agilityLevel,
270 damageSkillLevel: damageLevel,
271 defenceSkillLevel: defenceLevel,
272 baseDamage: profile.baseDamage ?? 1
273 });
274
275 if (resolved.outcome === "miss")
187 276 {
188 277 events.push({
189 278 type: "combat-miss",
@@ -195,7 +284,22 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
195 284 return events;
196 285 }
197 286
198 const damage = Math.max(1, (profile.baseDamage | 0) + Math.floor(skillLevel(skills, profile.damageSkillId) / 5));
287 if (resolved.outcome === "block")
288 {
289 events.push({
290 type: "combat-block",
291 attackerId,
292 targetId,
293 tileX: to.tileX,
294 tileY: to.tileY
295 });
296 return events;
297 }
298
299 const damage = resolved.damage;
300 const targetCharacter = world.ecs.get(targetHandle, Component.character);
301 if (targetCharacter)
302 { syncPlayerHealth(world.ecs, targetHandle); }
199 303 const health = world.ecs.get(targetHandle, Component.health);
200 304 if (health)
201 305 {
@@ -208,11 +312,45 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
208 312 damage,
209 313 tileX: to.tileX,
210 314 tileY: to.tileY,
211 health: health?.current ?? 0
315 health: health?.current ?? 0,
316 maxHealth: health?.max ?? 0
212 317 });
213 318
214 if (world.ecs.get(targetHandle, Component.combat))
215 { engageTarget(world.ecs, targetId, attackerId, now); }
319 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
320 if (healthXp)
321 {
322 events.push({
323 type: "skills-updated",
324 entityId: targetId,
325 characterId: healthXp.characterId,
326 skills: healthXp.view,
327 stored: healthXp.stored
328 });
329 if (health)
330 {
331 const hitEvent = events[events.length - 2];
332 if (hitEvent?.type === "combat-hit")
333 {
334 hitEvent.health = health.current;
335 hitEvent.maxHealth = health.max;
336 }
337 }
338 }
339
340 if (attackerCharacter)
341 {
342 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
343 if (xpAward)
344 {
345 events.push({
346 type: "skills-updated",
347 entityId: attackerId,
348 characterId: attackerCharacter.characterId,
349 skills: xpAward.view,
350 stored: xpAward.stored
351 });
352 }
353 }
216 354
217 355 if (health && health.current <= 0)
218 356 {
@@ -1,7 +1,18 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
2import { itemDefinition } from "../../../shared/definitions/items.js";
3import { mobDefinition } from "../../../shared/definitions/mobs.js";
3import { mobDefinition } from "../../../shared/definitions/mobs.js";
4import { skillLevel, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
4import {
5 mobCanFightType,
6 mobMeleeAttackProfile,
7 mobSkillLevels
8} from "../../../shared/definitions/mobCombat.js";
9import { resolvePhysicalAttack } from "../../../shared/combat/rolls.js";
10import { skillLevel, SkillId, UNARMED_ATTACK } from "../../../shared/definitions/skills.js";
11import {
12 effectiveSkillLevel,
13 equipmentBonusesFromSlots
14} from "../../../shared/equipment/stats.js";
15import { awardCombatHitXp, awardDamageHealthXp, syncPlayerHealth } from "../skills/service.js";
5import { chunkBoundsAround, findPath } from "../navigation/astar.js";
16import { chunkBoundsAround, findPath } from "../navigation/astar.js";
6import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
17import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
7
18
@@ -21,12 +32,57 @@ export function attackProfileOf (ecs, handle)
21 { return { ...attack }; }
32 { return { ...attack }; }
22 }
33 }
23 const creature = ecs.get(handle, Component.creature);
34 const creature = ecs.get(handle, Component.creature);
24 const mobAttack = creature ? mobDefinition(creature.mobTypeId)?.defaultAttack : null;
35 if (creature)
25 if (mobAttack)
36 {
26 { return { ...mobAttack }; }
37 const def = mobDefinition(creature.mobTypeId);
38 if (mobCanFightType(creature.mobTypeId))
39 { return mobMeleeAttackProfile(def); }
40 }
27 return { ...UNARMED_ATTACK };
41 return { ...UNARMED_ATTACK };
28}
42}
29
43
44export function ensureMobCombat (ecs, entityId)
45{
46 const handle = ecs.handleOf(entityId);
47 if (handle == null)
48 { return false; }
49 const creature = ecs.get(handle, Component.creature);
50 if (!creature || !mobCanFightType(creature.mobTypeId))
51 { return false; }
52 const def = mobDefinition(creature.mobTypeId);
53 if (!ecs.get(handle, Component.combat))
54 { ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
55 if (!ecs.get(handle, Component.skills))
56 { ecs.add(handle, Component.skills, { levels: mobSkillLevels(def) }); }
57 return true;
58}
59
60function attackerSkillLevel (skills, profile, skillId)
61{
62 if (profile.mobAttackSkill != null)
63 { return profile.mobAttackSkill; }
64 return skillLevel(skills, skillId);
65}
66
67function defenderSkillLevel (skills, skillId, equipment = null)
68{
69 const bonuses = equipment ? equipmentBonusesFromSlots(equipment.slots) : {};
70 return effectiveSkillLevel(skills, skillId, bonuses);
71}
72
73function playerCombatLevels (ecs, handle, profile)
74{
75 const skills = ecs.get(handle, Component.skills);
76 const equipment = ecs.get(handle, Component.equipment);
77 const bonuses = equipmentBonusesFromSlots(equipment?.slots);
78 return {
79 hitLevel: skillLevel(skills, profile.hitSkillId),
80 damageLevel: effectiveSkillLevel(skills, profile.damageSkillId, bonuses),
81 agilityLevel: effectiveSkillLevel(skills, SkillId.dexterity, bonuses),
82 defenceLevel: effectiveSkillLevel(skills, SkillId.defence, bonuses)
83 };
84}
85
30export function isUntargetable (ecs, handle)
86export function isUntargetable (ecs, handle)
31{
87{
32 const creature = ecs.get(handle, Component.creature);
88 const creature = ecs.get(handle, Component.creature);
@@ -180,10 +236,43 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
180 fromTileY: from.tileY
236 fromTileY: from.tileY
181 });
237 });
182
238
239 const attackerCharacter = world.ecs.get(attackerHandle, Component.character);
240 if (attackerCharacter && ensureMobCombat(world.ecs, targetId))
241 { engageTarget(world.ecs, targetId, attackerId, now); }
242
183 const skills = world.ecs.get(attackerHandle, Component.skills);
243 const skills = world.ecs.get(attackerHandle, Component.skills);
184 const hitChance = Math.min(0.95, 0.45 + skillLevel(skills, profile.hitSkillId) * 0.03);
244 const defenderSkills = world.ecs.get(targetHandle, Component.skills);
185 const hit = Math.random() < hitChance;
245 const defenderEquipment = world.ecs.get(targetHandle, Component.equipment);
186 if (!hit)
246 const attackerLevels = attackerCharacter
247 ? playerCombatLevels(world.ecs, attackerHandle, profile)
248 : {
249 hitLevel: attackerSkillLevel(skills, profile, profile.hitSkillId),
250 damageLevel: attackerSkillLevel(skills, profile, profile.damageSkillId),
251 agilityLevel: skillLevel(skills, SkillId.dexterity),
252 defenceLevel: skillLevel(skills, SkillId.defence)
253 };
254 const hitLevel = attackerLevels.hitLevel;
255 const damageLevel = attackerLevels.damageLevel;
256 const agilityLevel = defenderSkillLevel(
257 defenderSkills,
258 SkillId.dexterity,
259 defenderEquipment
260 );
261 const defenceLevel = defenderSkillLevel(
262 defenderSkills,
263 SkillId.defence,
264 defenderEquipment
265 );
266
267 const resolved = resolvePhysicalAttack({
268 hitSkillLevel: hitLevel,
269 agilitySkillLevel: agilityLevel,
270 damageSkillLevel: damageLevel,
271 defenceSkillLevel: defenceLevel,
272 baseDamage: profile.baseDamage ?? 1
273 });
274
275 if (resolved.outcome === "miss")
187 {
276 {
188 events.push({
277 events.push({
189 type: "combat-miss",
278 type: "combat-miss",
@@ -195,7 +284,22 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
195 return events;
284 return events;
196 }
285 }
197
286
198 const damage = Math.max(1, (profile.baseDamage | 0) + Math.floor(skillLevel(skills, profile.damageSkillId) / 5));
287 if (resolved.outcome === "block")
288 {
289 events.push({
290 type: "combat-block",
291 attackerId,
292 targetId,
293 tileX: to.tileX,
294 tileY: to.tileY
295 });
296 return events;
297 }
298
299 const damage = resolved.damage;
300 const targetCharacter = world.ecs.get(targetHandle, Component.character);
301 if (targetCharacter)
302 { syncPlayerHealth(world.ecs, targetHandle); }
199 const health = world.ecs.get(targetHandle, Component.health);
303 const health = world.ecs.get(targetHandle, Component.health);
200 if (health)
304 if (health)
201 {
305 {
@@ -208,11 +312,45 @@ export function resolveMeleeSwing (world, attackerId, targetId, profile, now = D
208 damage,
312 damage,
209 tileX: to.tileX,
313 tileX: to.tileX,
210 tileY: to.tileY,
314 tileY: to.tileY,
211 health: health?.current ?? 0
315 health: health?.current ?? 0,
316 maxHealth: health?.max ?? 0
212 });
317 });
213
318
214 if (world.ecs.get(targetHandle, Component.combat))
319 const healthXp = awardDamageHealthXp(world.ecs, targetHandle, damage);
215 { engageTarget(world.ecs, targetId, attackerId, now); }
320 if (healthXp)
321 {
322 events.push({
323 type: "skills-updated",
324 entityId: targetId,
325 characterId: healthXp.characterId,
326 skills: healthXp.view,
327 stored: healthXp.stored
328 });
329 if (health)
330 {
331 const hitEvent = events[events.length - 2];
332 if (hitEvent?.type === "combat-hit")
333 {
334 hitEvent.health = health.current;
335 hitEvent.maxHealth = health.max;
336 }
337 }
338 }
339
340 if (attackerCharacter)
341 {
342 const xpAward = awardCombatHitXp(world.ecs, attackerHandle, profile);
343 if (xpAward)
344 {
345 events.push({
346 type: "skills-updated",
347 entityId: attackerId,
348 characterId: attackerCharacter.characterId,
349 skills: xpAward.view,
350 stored: xpAward.stored
351 });
352 }
353 }
216
354
217 if (health && health.current <= 0)
355 if (health && health.current <= 0)
218 {
356 {
server/src/courier/service.js +28 −29
@@ -2,7 +2,7 @@ import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2 2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 3 import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4 4 import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5 import { insertStack, takeFromSlot, emptySlots } from "../../../shared/items/inventory.js";
5 import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6 6 import { advanceCourierFlight } from "../../../shared/courier/flight.js";
7 7 import { GAIT } from "../../../shared/protocol/constants.js";
8 8 import { decodeChunkBlob } from "../world/chunkData.js";
@@ -81,21 +81,15 @@ export class CourierService
81 81 }
82 82
83 83 let takenCargo;
84 if (cargo?.kind === "money")
84 if (cargo?.kind === "item")
85 85 {
86 const amount = Math.max(0, cargo.amount | 0);
87 if (amount <= 0 || amount > (bag.currency | 0))
86 const slot = bag.inventory?.[cargo.slotIndex | 0];
87 if (slot?.itemId === ItemId.blankCheque)
88 88 {
89 const error = new Error("Not enough coins.");
89 const error = new Error("Blank cheques cannot be sent by pigeon.");
90 90 error.userFacing = true;
91 91 throw error;
92 92 }
93 bag.currency -= amount;
94 takenCargo = { kind: "money", amount };
95 }
96 else if (cargo?.kind === "item")
97 {
98 const slot = bag.inventory?.[cargo.slotIndex | 0];
99 93 if (slot?.itemId === ItemId.letter)
100 94 {
101 95 if (Number(slot.instance?.authorCharacterId) !== Number(characterId))
@@ -379,20 +373,24 @@ export class CourierService
379 373 return events;
380 374 }
381 375
376 #normalizeCargo (cargo)
377 {
378 if (cargo?.kind === "money")
379 {
380 return {
381 kind: "item",
382 stack: { itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) }
383 };
384 }
385 return cargo;
386 }
387
382 388 #tryDeliverToPlayer (characterId, cargo)
383 389 {
390 cargo = this.#normalizeCargo(cargo);
384 391 const onlineId = this.simulation.characterEntities.get(characterId);
385 392 if (onlineId)
386 393 {
387 if (cargo.kind === "money")
388 {
389 const bag = this.simulation.bagOf(onlineId);
390 if (!bag)
391 { return false; }
392 bag.currency = (bag.currency | 0) + (cargo.amount | 0);
393 this.#persistBag(characterId, bag);
394 return true;
395 }
396 394 if (cargo.kind === "item")
397 395 {
398 396 const bag = this.simulation.bagOf(onlineId);
@@ -408,7 +406,7 @@ export class CourierService
408 406 }
409 407 }
410 408
411 if (cargo.kind === "money")
409 if (cargo.kind === "item")
412 410 {
413 411 this.#creditVault(characterId, cargo);
414 412 return true;
@@ -418,23 +416,24 @@ export class CourierService
418 416
419 417 #creditVault (characterId, cargo)
420 418 {
419 cargo = this.#normalizeCargo(cargo);
421 420 const onlineId = this.simulation.characterEntities.get(characterId);
422 421 const bag = onlineId
423 422 ? this.simulation.bagOf(onlineId)
424 423 : this.stateDb.getBag(characterId);
425 424 if (!bag)
426 425 { return; }
427 if (cargo.kind === "money")
428 {
429 bag.vaultCurrency = (bag.vaultCurrency | 0) + (cargo.amount | 0);
430 this.#persistBag(characterId, bag);
431 return;
432 }
433 426 if (cargo.kind === "item")
434 427 {
435 428 const def = itemDefinition(cargo.stack.itemId);
436 const result = insertStack(bag.vault ?? emptySlots(), cargo.stack, def);
437 bag.vault = result.ok ? result.slots : [...(bag.vault ?? []), cargo.stack];
429 const vault = normalizeVault(
430 bag.vaultReserved != null
431 ? { slots: bag.vault, reserved: bag.vaultReserved }
432 : bag.vault
433 );
434 const result = insertStackGrowable(vault.slots, cargo.stack, def);
435 bag.vault = result.slots;
436 bag.vaultReserved = vault.reserved;
438 437 this.#persistBag(characterId, bag);
439 438 }
440 439 }
@@ -2,7 +2,7 @@ import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
3import { MobId, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
4import { ItemId, itemDefinition } from "../../../shared/definitions/items.js";
5import { insertStack, takeFromSlot, emptySlots } from "../../../shared/items/inventory.js";
5import { insertStack, insertStackGrowable, takeFromSlot, emptySlots, normalizeVault } from "../../../shared/items/inventory.js";
6import { advanceCourierFlight } from "../../../shared/courier/flight.js";
6import { advanceCourierFlight } from "../../../shared/courier/flight.js";
7import { GAIT } from "../../../shared/protocol/constants.js";
7import { GAIT } from "../../../shared/protocol/constants.js";
8import { decodeChunkBlob } from "../world/chunkData.js";
8import { decodeChunkBlob } from "../world/chunkData.js";
@@ -81,21 +81,15 @@ export class CourierService
81 }
81 }
82
82
83 let takenCargo;
83 let takenCargo;
84 if (cargo?.kind === "money")
84 if (cargo?.kind === "item")
85 {
85 {
86 const amount = Math.max(0, cargo.amount | 0);
86 const slot = bag.inventory?.[cargo.slotIndex | 0];
87 if (amount <= 0 || amount > (bag.currency | 0))
87 if (slot?.itemId === ItemId.blankCheque)
88 {
88 {
89 const error = new Error("Not enough coins.");
89 const error = new Error("Blank cheques cannot be sent by pigeon.");
90 error.userFacing = true;
90 error.userFacing = true;
91 throw error;
91 throw error;
92 }
92 }
93 bag.currency -= amount;
94 takenCargo = { kind: "money", amount };
95 }
96 else if (cargo?.kind === "item")
97 {
98 const slot = bag.inventory?.[cargo.slotIndex | 0];
99 if (slot?.itemId === ItemId.letter)
93 if (slot?.itemId === ItemId.letter)
100 {
94 {
101 if (Number(slot.instance?.authorCharacterId) !== Number(characterId))
95 if (Number(slot.instance?.authorCharacterId) !== Number(characterId))
@@ -379,20 +373,24 @@ export class CourierService
379 return events;
373 return events;
380 }
374 }
381
375
376 #normalizeCargo (cargo)
377 {
378 if (cargo?.kind === "money")
379 {
380 return {
381 kind: "item",
382 stack: { itemId: ItemId.coins, quantity: Math.max(0, cargo.amount | 0) }
383 };
384 }
385 return cargo;
386 }
387
382 #tryDeliverToPlayer (characterId, cargo)
388 #tryDeliverToPlayer (characterId, cargo)
383 {
389 {
390 cargo = this.#normalizeCargo(cargo);
384 const onlineId = this.simulation.characterEntities.get(characterId);
391 const onlineId = this.simulation.characterEntities.get(characterId);
385 if (onlineId)
392 if (onlineId)
386 {
393 {
387 if (cargo.kind === "money")
388 {
389 const bag = this.simulation.bagOf(onlineId);
390 if (!bag)
391 { return false; }
392 bag.currency = (bag.currency | 0) + (cargo.amount | 0);
393 this.#persistBag(characterId, bag);
394 return true;
395 }
396 if (cargo.kind === "item")
394 if (cargo.kind === "item")
397 {
395 {
398 const bag = this.simulation.bagOf(onlineId);
396 const bag = this.simulation.bagOf(onlineId);
@@ -408,7 +406,7 @@ export class CourierService
408 }
406 }
409 }
407 }
410
408
411 if (cargo.kind === "money")
409 if (cargo.kind === "item")
412 {
410 {
413 this.#creditVault(characterId, cargo);
411 this.#creditVault(characterId, cargo);
414 return true;
412 return true;
@@ -418,23 +416,24 @@ export class CourierService
418
416
419 #creditVault (characterId, cargo)
417 #creditVault (characterId, cargo)
420 {
418 {
419 cargo = this.#normalizeCargo(cargo);
421 const onlineId = this.simulation.characterEntities.get(characterId);
420 const onlineId = this.simulation.characterEntities.get(characterId);
422 const bag = onlineId
421 const bag = onlineId
423 ? this.simulation.bagOf(onlineId)
422 ? this.simulation.bagOf(onlineId)
424 : this.stateDb.getBag(characterId);
423 : this.stateDb.getBag(characterId);
425 if (!bag)
424 if (!bag)
426 { return; }
425 { return; }
427 if (cargo.kind === "money")
428 {
429 bag.vaultCurrency = (bag.vaultCurrency | 0) + (cargo.amount | 0);
430 this.#persistBag(characterId, bag);
431 return;
432 }
433 if (cargo.kind === "item")
426 if (cargo.kind === "item")
434 {
427 {
435 const def = itemDefinition(cargo.stack.itemId);
428 const def = itemDefinition(cargo.stack.itemId);
436 const result = insertStack(bag.vault ?? emptySlots(), cargo.stack, def);
429 const vault = normalizeVault(
437 bag.vault = result.ok ? result.slots : [...(bag.vault ?? []), cargo.stack];
430 bag.vaultReserved != null
431 ? { slots: bag.vault, reserved: bag.vaultReserved }
432 : bag.vault
433 );
434 const result = insertStackGrowable(vault.slots, cargo.stack, def);
435 bag.vault = result.slots;
436 bag.vaultReserved = vault.reserved;
438 this.#persistBag(characterId, bag);
437 this.#persistBag(characterId, bag);
439 }
438 }
440 }
439 }
server/src/ecs/components.js +0 −1
@@ -10,7 +10,6 @@ export const Component = Object.freeze({
10 10 persistent: "persistent",
11 11 inventory: "inventory",
12 12 equipment: "equipment",
13 currency: "currency",
14 13 vault: "vault",
15 14 health: "health",
16 15 creature: "creature",
@@ -10,7 +10,6 @@ export const Component = Object.freeze({
10 persistent: "persistent",
10 persistent: "persistent",
11 inventory: "inventory",
11 inventory: "inventory",
12 equipment: "equipment",
12 equipment: "equipment",
13 currency: "currency",
14 vault: "vault",
13 vault: "vault",
15 health: "health",
14 health: "health",
16 creature: "creature",
15 creature: "creature",
server/src/ecs/serialize.js +10 −1
@@ -2,6 +2,7 @@ import { Component } from "./components.js";
2 2 import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
3 3 import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4 4 import { mobDefinition } from "../../../shared/definitions/mobs.js";
5 import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
5 6
6 7 function bodySprite (sex)
7 8 {
@@ -63,8 +64,10 @@ export function publicEntityView (ecs, entityId)
63 64 const character = ecs.get(handle, Component.character);
64 65 const creature = ecs.get(handle, Component.creature);
65 66 const flight = ecs.get(handle, Component.flight);
67 const health = ecs.get(handle, Component.health);
66 68 const layers = appearanceLayers(ecs, handle, appearance);
67 69 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
70 const isMob = !!creature && !character;
68 71 return {
69 72 entityId,
70 73 tileX: position.tileX,
@@ -77,10 +80,13 @@ export function publicEntityView (ecs, entityId)
77 80 lastName: appearance?.lastName ?? "",
78 81 characterId: character?.characterId ?? null,
79 82 mobTypeId: creature?.mobTypeId ?? null,
83 canFight: mob ? mobCanFight(mob) : false,
80 84 hostile: !!mob?.hostile,
81 85 talkable: !!mob?.talkable,
82 86 untargetable: !!mob?.untargetable,
83 87 freeFlight: !!mob?.freeFlight,
88 health: isMob && health ? health.current : undefined,
89 maxHealth: isMob && health ? health.max : undefined,
84 90 sprite: layers[0]?.sprite ?? null,
85 91 layers
86 92 };
@@ -122,10 +128,13 @@ export function replicationSpawn (view)
122 128 sprite: view.sprite ?? null,
123 129 layers: view.layers ?? [],
124 130 mobTypeId: view.mobTypeId ?? null,
131 canFight: !!view.canFight,
125 132 hostile: !!view.hostile,
126 133 talkable: !!view.talkable,
127 134 untargetable: !!view.untargetable,
128 freeFlight: !!view.freeFlight
135 freeFlight: !!view.freeFlight,
136 health: view.health,
137 maxHealth: view.maxHealth
129 138 };
130 139 }
131 140
@@ -2,6 +2,7 @@ import { Component } from "./components.js";
2import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
2import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
3import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
3import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
4import { mobDefinition } from "../../../shared/definitions/mobs.js";
5import { mobCanFight } from "../../../shared/definitions/mobCombat.js";
5
6
6function bodySprite (sex)
7function bodySprite (sex)
7{
8{
@@ -63,8 +64,10 @@ export function publicEntityView (ecs, entityId)
63 const character = ecs.get(handle, Component.character);
64 const character = ecs.get(handle, Component.character);
64 const creature = ecs.get(handle, Component.creature);
65 const creature = ecs.get(handle, Component.creature);
65 const flight = ecs.get(handle, Component.flight);
66 const flight = ecs.get(handle, Component.flight);
67 const health = ecs.get(handle, Component.health);
66 const layers = appearanceLayers(ecs, handle, appearance);
68 const layers = appearanceLayers(ecs, handle, appearance);
67 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
69 const mob = creature ? mobDefinition(creature.mobTypeId) : null;
70 const isMob = !!creature && !character;
68 return {
71 return {
69 entityId,
72 entityId,
70 tileX: position.tileX,
73 tileX: position.tileX,
@@ -77,10 +80,13 @@ export function publicEntityView (ecs, entityId)
77 lastName: appearance?.lastName ?? "",
80 lastName: appearance?.lastName ?? "",
78 characterId: character?.characterId ?? null,
81 characterId: character?.characterId ?? null,
79 mobTypeId: creature?.mobTypeId ?? null,
82 mobTypeId: creature?.mobTypeId ?? null,
83 canFight: mob ? mobCanFight(mob) : false,
80 hostile: !!mob?.hostile,
84 hostile: !!mob?.hostile,
81 talkable: !!mob?.talkable,
85 talkable: !!mob?.talkable,
82 untargetable: !!mob?.untargetable,
86 untargetable: !!mob?.untargetable,
83 freeFlight: !!mob?.freeFlight,
87 freeFlight: !!mob?.freeFlight,
88 health: isMob && health ? health.current : undefined,
89 maxHealth: isMob && health ? health.max : undefined,
84 sprite: layers[0]?.sprite ?? null,
90 sprite: layers[0]?.sprite ?? null,
85 layers
91 layers
86 };
92 };
@@ -122,10 +128,13 @@ export function replicationSpawn (view)
122 sprite: view.sprite ?? null,
128 sprite: view.sprite ?? null,
123 layers: view.layers ?? [],
129 layers: view.layers ?? [],
124 mobTypeId: view.mobTypeId ?? null,
130 mobTypeId: view.mobTypeId ?? null,
131 canFight: !!view.canFight,
125 hostile: !!view.hostile,
132 hostile: !!view.hostile,
126 talkable: !!view.talkable,
133 talkable: !!view.talkable,
127 untargetable: !!view.untargetable,
134 untargetable: !!view.untargetable,
128 freeFlight: !!view.freeFlight
135 freeFlight: !!view.freeFlight,
136 health: view.health,
137 maxHealth: view.maxHealth
129 };
138 };
130}
139}
131
140
server/src/gateway/websocket.js +105 −23
@@ -3,6 +3,7 @@ import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3 3 import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4 4 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5 5 import { broadcastSpeech } from "../chat/speech.js";
6 import { publicSkillsView } from "../../../shared/skills/state.js";
6 7
7 8 let nextSessionId = 1;
8 9
@@ -160,6 +161,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
160 161 equipSlot: message.equipSlot
161 162 });
162 163 break;
164 case MessageType.eatItem:
165 requirePlaying(session);
166 simulation.enqueue(session.id, {
167 type: "eat-item",
168 characterId: session.characterId,
169 slotIndex: message.slotIndex | 0
170 });
171 break;
163 172 case MessageType.openBank:
164 173 requirePlaying(session);
165 174 simulation.enqueue(session.id, {
@@ -170,21 +179,53 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
170 179 case MessageType.bankDeposit:
171 180 requirePlaying(session);
172 181 simulation.enqueue(session.id, {
173 type: message.money ? "bank-deposit-money" : "bank-deposit",
182 type: "bank-deposit",
174 183 characterId: session.characterId,
175 184 slotIndex: message.slotIndex | 0,
176 quantity: message.quantity ?? null,
177 amount: message.amount | 0
185 quantity: message.quantity ?? null
178 186 });
179 187 break;
180 188 case MessageType.bankWithdraw:
181 189 requirePlaying(session);
182 190 simulation.enqueue(session.id, {
183 type: message.money ? "bank-withdraw-money" : "bank-withdraw",
191 type: "bank-withdraw",
184 192 characterId: session.characterId,
185 193 slotIndex: message.slotIndex | 0,
186 quantity: message.quantity ?? null,
187 amount: message.amount | 0
194 quantity: message.quantity ?? null
195 });
196 break;
197 case MessageType.getBlankCheques:
198 requirePlaying(session);
199 simulation.enqueue(session.id, {
200 type: "get-blank-cheques",
201 characterId: session.characterId
202 });
203 break;
204 case MessageType.returnBlankCheques:
205 requirePlaying(session);
206 simulation.enqueue(session.id, {
207 type: "return-blank-cheques",
208 characterId: session.characterId,
209 slotIndex: message.slotIndex | 0,
210 quantity: message.quantity ?? null
211 });
212 break;
213 case MessageType.writeCheque:
214 requirePlaying(session);
215 simulation.enqueue(session.id, {
216 type: "write-cheque",
217 characterId: session.characterId,
218 slotIndex: message.slotIndex | 0,
219 vaultSlotIndex: message.vaultSlotIndex | 0,
220 quantity: message.quantity ?? 1
221 });
222 break;
223 case MessageType.redeemCheque:
224 requirePlaying(session);
225 simulation.enqueue(session.id, {
226 type: "redeem-cheque",
227 characterId: session.characterId,
228 slotIndex: message.slotIndex | 0
188 229 });
189 230 break;
190 231 case MessageType.claimInheritance:
@@ -194,8 +235,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
194 235 simulation.enqueue(session.id, {
195 236 type: "claim-inheritance",
196 237 characterId: session.characterId,
197 stacks: (inheritance.slots ?? []).filter(Boolean),
198 currency: inheritance.currency | 0
238 stacks: (inheritance.slots ?? []).filter(Boolean)
199 239 });
200 240 }
201 241 break;
@@ -371,6 +411,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
371 411 const bag = simulation.bagOf(session.entityId);
372 412 if (bag)
373 413 { send(session, { type: MessageType.inventory, ...bag }); }
414 const skills = simulation.skillsOf(session.entityId);
415 if (skills)
416 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
374 417 publishReplication(simulation.drainReplication());
375 418 }
376 419
@@ -501,22 +544,28 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
501 544 type: MessageType.inventory,
502 545 inventory: event.inventory,
503 546 equipment: event.equipment,
504 currency: event.currency,
505 547 vault: event.vault,
506 vaultCurrency: event.vaultCurrency
548 vaultReserved: event.vaultReserved
507 549 });
508 550 if (event.bank)
509 551 {
510 552 send(session, {
511 553 type: MessageType.bankSnapshot,
512 554 vault: event.vault,
513 vaultCurrency: event.vaultCurrency,
514 currency: event.currency,
555 vaultReserved: event.vaultReserved,
515 556 inheritance: stateDb.getInheritance(session.account.account_id)
516 557 });
517 558 }
518 559 continue;
519 560 }
561 if (event.type === "skills")
562 {
563 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
564 if (!session)
565 { continue; }
566 send(session, { type: MessageType.skills, skills: event.skills ?? [] });
567 continue;
568 }
520 569 if (event.type === "pigeon-delivered")
521 570 {
522 571 for (const session of sessions.values())
@@ -534,7 +583,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
534 583 }
535 584 continue;
536 585 }
537 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")
586 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")
538 587 { publishEntity(event); }
539 588 }
540 589 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -599,7 +648,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
599 648 send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });
600 649 continue;
601 650 }
602 if (event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")
651 if (event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")
603 652 {
604 653 if (!seesTo && !seesFrom)
605 654 { continue; }
@@ -607,13 +656,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
607 656 ? MessageType.combatSwing
608 657 : event.type === "combat-hit"
609 658 ? MessageType.combatHit
610 : MessageType.combatMiss;
659 : event.type === "combat-block"
660 ? MessageType.combatBlock
661 : MessageType.combatMiss;
611 662 send(session, {
612 663 type,
613 664 attackerId: event.attackerId,
614 665 targetId: event.targetId,
615 666 damage: event.damage,
616 667 health: event.health,
668 maxHealth: event.maxHealth,
617 669 tileX: event.tileX,
618 670 tileY: event.tileY,
619 671 fromTileX: event.fromTileX,
@@ -667,10 +719,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
667 719 sprite: record.sprite ?? event.sprite ?? null,
668 720 layers: record.layers ?? event.layers ?? [],
669 721 mobTypeId: record.mobTypeId ?? event.mobTypeId ?? null,
722 canFight: !!(record.canFight ?? event.canFight),
670 723 hostile: !!(record.hostile ?? event.hostile),
671 724 talkable: !!(record.talkable ?? event.talkable),
672 725 untargetable: !!(record.untargetable ?? event.untargetable),
673 freeFlight: !!(record.freeFlight ?? event.freeFlight)
726 freeFlight: !!(record.freeFlight ?? event.freeFlight),
727 health: record.health ?? event.health,
728 maxHealth: record.maxHealth ?? event.maxHealth
674 729 };
675 730 }
676 731
@@ -680,18 +735,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
680 735 wss,
681 736 async shutdown ()
682 737 {
683 for (const session of [...sessions.values()])
738 await Promise.all([...sessions.values()].map(async (session) =>
684 739 {
685 send(session, {
740 await sendAsync(session, {
686 741 type: MessageType.forceLogout,
687 742 reason: "Server shutting down."
688 743 });
689 744 leaveWorld(session);
690 try
691 { session.socket.close(1001, "Server shutting down"); }
692 catch
693 { /* ignore */ }
694 }
745 await closeAsync(session, 1001, "Server shutting down.");
746 }));
695 747 sessions.clear();
696 748 await simulation.shutdown();
697 749 }
@@ -703,3 +755,33 @@ function send (session, payload)
703 755 if (session.socket.readyState === 1)
704 756 { session.socket.send(JSON.stringify(payload)); }
705 757 }
758
759 function sendAsync (session, payload)
760 {
761 return new Promise((resolve) =>
762 {
763 if (session.socket.readyState !== 1)
764 {
765 resolve();
766 return;
767 }
768 session.socket.send(JSON.stringify(payload), () => resolve());
769 });
770 }
771
772 function closeAsync (session, code, reason)
773 {
774 return new Promise((resolve) =>
775 {
776 if (session.socket.readyState !== 1)
777 {
778 resolve();
779 return;
780 }
781 session.socket.once("close", resolve);
782 try
783 { session.socket.close(code, reason); }
784 catch
785 { resolve(); }
786 });
787 }
@@ -3,6 +3,7 @@ import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
4import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5import { broadcastSpeech } from "../chat/speech.js";
5import { broadcastSpeech } from "../chat/speech.js";
6import { publicSkillsView } from "../../../shared/skills/state.js";
6
7
7let nextSessionId = 1;
8let nextSessionId = 1;
8
9
@@ -160,6 +161,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
160 equipSlot: message.equipSlot
161 equipSlot: message.equipSlot
161 });
162 });
162 break;
163 break;
164 case MessageType.eatItem:
165 requirePlaying(session);
166 simulation.enqueue(session.id, {
167 type: "eat-item",
168 characterId: session.characterId,
169 slotIndex: message.slotIndex | 0
170 });
171 break;
163 case MessageType.openBank:
172 case MessageType.openBank:
164 requirePlaying(session);
173 requirePlaying(session);
165 simulation.enqueue(session.id, {
174 simulation.enqueue(session.id, {
@@ -170,21 +179,53 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
170 case MessageType.bankDeposit:
179 case MessageType.bankDeposit:
171 requirePlaying(session);
180 requirePlaying(session);
172 simulation.enqueue(session.id, {
181 simulation.enqueue(session.id, {
173 type: message.money ? "bank-deposit-money" : "bank-deposit",
182 type: "bank-deposit",
174 characterId: session.characterId,
183 characterId: session.characterId,
175 slotIndex: message.slotIndex | 0,
184 slotIndex: message.slotIndex | 0,
176 quantity: message.quantity ?? null,
185 quantity: message.quantity ?? null
177 amount: message.amount | 0
178 });
186 });
179 break;
187 break;
180 case MessageType.bankWithdraw:
188 case MessageType.bankWithdraw:
181 requirePlaying(session);
189 requirePlaying(session);
182 simulation.enqueue(session.id, {
190 simulation.enqueue(session.id, {
183 type: message.money ? "bank-withdraw-money" : "bank-withdraw",
191 type: "bank-withdraw",
184 characterId: session.characterId,
192 characterId: session.characterId,
185 slotIndex: message.slotIndex | 0,
193 slotIndex: message.slotIndex | 0,
186 quantity: message.quantity ?? null,
194 quantity: message.quantity ?? null
187 amount: message.amount | 0
195 });
196 break;
197 case MessageType.getBlankCheques:
198 requirePlaying(session);
199 simulation.enqueue(session.id, {
200 type: "get-blank-cheques",
201 characterId: session.characterId
202 });
203 break;
204 case MessageType.returnBlankCheques:
205 requirePlaying(session);
206 simulation.enqueue(session.id, {
207 type: "return-blank-cheques",
208 characterId: session.characterId,
209 slotIndex: message.slotIndex | 0,
210 quantity: message.quantity ?? null
211 });
212 break;
213 case MessageType.writeCheque:
214 requirePlaying(session);
215 simulation.enqueue(session.id, {
216 type: "write-cheque",
217 characterId: session.characterId,
218 slotIndex: message.slotIndex | 0,
219 vaultSlotIndex: message.vaultSlotIndex | 0,
220 quantity: message.quantity ?? 1
221 });
222 break;
223 case MessageType.redeemCheque:
224 requirePlaying(session);
225 simulation.enqueue(session.id, {
226 type: "redeem-cheque",
227 characterId: session.characterId,
228 slotIndex: message.slotIndex | 0
188 });
229 });
189 break;
230 break;
190 case MessageType.claimInheritance:
231 case MessageType.claimInheritance:
@@ -194,8 +235,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
194 simulation.enqueue(session.id, {
235 simulation.enqueue(session.id, {
195 type: "claim-inheritance",
236 type: "claim-inheritance",
196 characterId: session.characterId,
237 characterId: session.characterId,
197 stacks: (inheritance.slots ?? []).filter(Boolean),
238 stacks: (inheritance.slots ?? []).filter(Boolean)
198 currency: inheritance.currency | 0
199 });
239 });
200 }
240 }
201 break;
241 break;
@@ -371,6 +411,9 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
371 const bag = simulation.bagOf(session.entityId);
411 const bag = simulation.bagOf(session.entityId);
372 if (bag)
412 if (bag)
373 { send(session, { type: MessageType.inventory, ...bag }); }
413 { send(session, { type: MessageType.inventory, ...bag }); }
414 const skills = simulation.skillsOf(session.entityId);
415 if (skills)
416 { send(session, { type: MessageType.skills, skills: publicSkillsView(skills) }); }
374 publishReplication(simulation.drainReplication());
417 publishReplication(simulation.drainReplication());
375 }
418 }
376
419
@@ -501,22 +544,28 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
501 type: MessageType.inventory,
544 type: MessageType.inventory,
502 inventory: event.inventory,
545 inventory: event.inventory,
503 equipment: event.equipment,
546 equipment: event.equipment,
504 currency: event.currency,
505 vault: event.vault,
547 vault: event.vault,
506 vaultCurrency: event.vaultCurrency
548 vaultReserved: event.vaultReserved
507 });
549 });
508 if (event.bank)
550 if (event.bank)
509 {
551 {
510 send(session, {
552 send(session, {
511 type: MessageType.bankSnapshot,
553 type: MessageType.bankSnapshot,
512 vault: event.vault,
554 vault: event.vault,
513 vaultCurrency: event.vaultCurrency,
555 vaultReserved: event.vaultReserved,
514 currency: event.currency,
515 inheritance: stateDb.getInheritance(session.account.account_id)
556 inheritance: stateDb.getInheritance(session.account.account_id)
516 });
557 });
517 }
558 }
518 continue;
559 continue;
519 }
560 }
561 if (event.type === "skills")
562 {
563 const session = [...sessions.values()].find((entry) => entry.characterId === event.characterId);
564 if (!session)
565 { continue; }
566 send(session, { type: MessageType.skills, skills: event.skills ?? [] });
567 continue;
568 }
520 if (event.type === "pigeon-delivered")
569 if (event.type === "pigeon-delivered")
521 {
570 {
522 for (const session of sessions.values())
571 for (const session of sessions.values())
@@ -534,7 +583,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
534 }
583 }
535 continue;
584 continue;
536 }
585 }
537 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")
586 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")
538 { publishEntity(event); }
587 { publishEntity(event); }
539 }
588 }
540 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
589 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
@@ -599,7 +648,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
599 send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });
648 send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });
600 continue;
649 continue;
601 }
650 }
602 if (event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss")
651 if (event.type === "combat-swing" || event.type === "combat-hit" || event.type === "combat-miss" || event.type === "combat-block")
603 {
652 {
604 if (!seesTo && !seesFrom)
653 if (!seesTo && !seesFrom)
605 { continue; }
654 { continue; }
@@ -607,13 +656,16 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
607 ? MessageType.combatSwing
656 ? MessageType.combatSwing
608 : event.type === "combat-hit"
657 : event.type === "combat-hit"
609 ? MessageType.combatHit
658 ? MessageType.combatHit
610 : MessageType.combatMiss;
659 : event.type === "combat-block"
660 ? MessageType.combatBlock
661 : MessageType.combatMiss;
611 send(session, {
662 send(session, {
612 type,
663 type,
613 attackerId: event.attackerId,
664 attackerId: event.attackerId,
614 targetId: event.targetId,
665 targetId: event.targetId,
615 damage: event.damage,
666 damage: event.damage,
616 health: event.health,
667 health: event.health,
668 maxHealth: event.maxHealth,
617 tileX: event.tileX,
669 tileX: event.tileX,
618 tileY: event.tileY,
670 tileY: event.tileY,
619 fromTileX: event.fromTileX,
671 fromTileX: event.fromTileX,
@@ -667,10 +719,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
667 sprite: record.sprite ?? event.sprite ?? null,
719 sprite: record.sprite ?? event.sprite ?? null,
668 layers: record.layers ?? event.layers ?? [],
720 layers: record.layers ?? event.layers ?? [],
669 mobTypeId: record.mobTypeId ?? event.mobTypeId ?? null,
721 mobTypeId: record.mobTypeId ?? event.mobTypeId ?? null,
722 canFight: !!(record.canFight ?? event.canFight),
670 hostile: !!(record.hostile ?? event.hostile),
723 hostile: !!(record.hostile ?? event.hostile),
671 talkable: !!(record.talkable ?? event.talkable),
724 talkable: !!(record.talkable ?? event.talkable),
672 untargetable: !!(record.untargetable ?? event.untargetable),
725 untargetable: !!(record.untargetable ?? event.untargetable),
673 freeFlight: !!(record.freeFlight ?? event.freeFlight)
726 freeFlight: !!(record.freeFlight ?? event.freeFlight),
727 health: record.health ?? event.health,
728 maxHealth: record.maxHealth ?? event.maxHealth
674 };
729 };
675 }
730 }
676
731
@@ -680,18 +735,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
680 wss,
735 wss,
681 async shutdown ()
736 async shutdown ()
682 {
737 {
683 for (const session of [...sessions.values()])
738 await Promise.all([...sessions.values()].map(async (session) =>
684 {
739 {
685 send(session, {
740 await sendAsync(session, {
686 type: MessageType.forceLogout,
741 type: MessageType.forceLogout,
687 reason: "Server shutting down."
742 reason: "Server shutting down."
688 });
743 });
689 leaveWorld(session);
744 leaveWorld(session);
690 try
745 await closeAsync(session, 1001, "Server shutting down.");
691 { session.socket.close(1001, "Server shutting down"); }
746 }));
692 catch
693 { /* ignore */ }
694 }
695 sessions.clear();
747 sessions.clear();
696 await simulation.shutdown();
748 await simulation.shutdown();
697 }
749 }
@@ -703,3 +755,33 @@ function send (session, payload)
703 if (session.socket.readyState === 1)
755 if (session.socket.readyState === 1)
704 { session.socket.send(JSON.stringify(payload)); }
756 { session.socket.send(JSON.stringify(payload)); }
705}
757}
758
759function sendAsync (session, payload)
760{
761 return new Promise((resolve) =>
762 {
763 if (session.socket.readyState !== 1)
764 {
765 resolve();
766 return;
767 }
768 session.socket.send(JSON.stringify(payload), () => resolve());
769 });
770}
771
772function closeAsync (session, code, reason)
773{
774 return new Promise((resolve) =>
775 {
776 if (session.socket.readyState !== 1)
777 {
778 resolve();
779 return;
780 }
781 session.socket.once("close", resolve);
782 try
783 { session.socket.close(code, reason); }
784 catch
785 { resolve(); }
786 });
787}
server/src/items/bags.js +307 −56
@@ -1,13 +1,23 @@
1 1 import { Component } from "../ecs/components.js";
2 import { syncPlayerHealth } from "../skills/service.js";
3 import { canEquipItem } from "../../../shared/equipment/stats.js";
2 4 import { BlockType } from "../../../shared/definitions/tiles.js";
3 import { ItemId, itemDefinition, itemSpriteName, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
5 import { ItemId, itemDefinition, itemSpriteName, stackDisplayLabel, LETTER_MAX_BODY_CHARS, BLANK_CHEQUE_CARRY_CAP } from "../../../shared/definitions/items.js";
4 6 import {
5 7 emptyEquipment,
6 8 emptySlots,
7 9 insertStack,
10 insertStackGrowable,
11 normalizeVault,
12 normalizeInventorySlots,
8 13 publicEquipment,
9 14 publicSlots,
10 takeFromSlot
15 takeFromSlot,
16 takeMatchingFromSlots,
17 countItemInSlots,
18 cloneStack,
19 singleItemFromStack,
20 stackQuantity
11 21 } from "../../../shared/items/inventory.js";
12 22 import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
13 23 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
@@ -22,7 +32,7 @@ export function publicGroundItem (item)
22 32 tileY: item.tileY,
23 33 itemId: item.stack.itemId,
24 34 quantity: item.stack.quantity,
25 displayName: def?.displayName ?? "Item",
35 displayName: stackDisplayLabel(item.stack),
26 36 sprite: itemSpriteName(item.stack.itemId, item.stack.instance),
27 37 expiresAt: item.expiresAt
28 38 };
@@ -30,29 +40,30 @@ export function publicGroundItem (item)
30 40
31 41 export function bagView (ecs, handle)
32 42 {
43 const vault = normalizeVault(ecs.get(handle, Component.vault));
33 44 return {
34 inventory: publicSlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots()),
45 inventory: publicSlots(normalizeInventorySlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots())),
35 46 equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()),
36 currency: ecs.get(handle, Component.currency)?.amount ?? 0,
37 vault: publicSlots(ecs.get(handle, Component.vault)?.slots ?? emptySlots()),
38 vaultCurrency: ecs.get(handle, Component.vault)?.currency ?? 0
47 vault: publicSlots(vault.slots),
48 vaultReserved: publicSlots(vault.reserved)
39 49 };
40 50 }
41 51
42 52 export function applyBagView (ecs, handle, bag)
43 53 {
44 54 const inventory = ensureInventory(ecs, handle);
45 inventory.slots = publicSlots(bag.inventory ?? emptySlots());
55 inventory.slots = normalizeInventorySlots(publicSlots(bag.inventory ?? emptySlots()));
46 56 const equipment = ensureEquipment(ecs, handle);
47 57 const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment());
48 58 equipment.slots = nextEquip.slots;
49 let currency = ecs.get(handle, Component.currency);
50 if (!currency)
51 { currency = ecs.add(handle, Component.currency, { amount: 0 }); }
52 currency.amount = bag.currency | 0;
53 59 const vault = ensureVault(ecs, handle);
54 vault.slots = publicSlots(bag.vault ?? emptySlots());
55 vault.currency = bag.vaultCurrency | 0;
60 const normalized = normalizeVault(
61 bag.vaultReserved != null || (bag.vault && !Array.isArray(bag.vault))
62 ? { slots: bag.vault, reserved: bag.vaultReserved }
63 : bag.vault
64 );
65 vault.slots = publicSlots(normalized.slots);
66 vault.reserved = publicSlots(normalized.reserved);
56 67 return bagView(ecs, handle);
57 68 }
58 69
@@ -74,10 +85,14 @@ export function handleItemCommand (world, sessionId, command, now)
74 85 return bankMove(world, sessionId, command, "inventory", "vault");
75 86 case "bank-withdraw":
76 87 return bankMove(world, sessionId, command, "vault", "inventory");
77 case "bank-deposit-money":
78 return bankMoney(world, sessionId, command, "currency", "vault");
79 case "bank-withdraw-money":
80 return bankMoney(world, sessionId, command, "vault", "currency");
88 case "get-blank-cheques":
89 return getBlankCheques(world, sessionId, command);
90 case "return-blank-cheques":
91 return returnBlankCheques(world, sessionId, command);
92 case "write-cheque":
93 return writeCheque(world, sessionId, command);
94 case "redeem-cheque":
95 return redeemCheque(world, sessionId, command);
81 96 case "claim-inheritance":
82 97 return claimInheritance(world, sessionId, command);
83 98 case "write-letter":
@@ -86,6 +101,8 @@ export function handleItemCommand (world, sessionId, command, now)
86 101 return editLetter(world, sessionId, command);
87 102 case "open-letter":
88 103 return openLetter(world, sessionId, command);
104 case "eat-item":
105 return eatItem(world, sessionId, command);
89 106 default:
90 107 return null;
91 108 }
@@ -196,13 +213,41 @@ function pickupItem (world, sessionId, command)
196 213 if (!def)
197 214 { throw userError("Unknown item."); }
198 215 const inventory = ensureInventory(world.ecs, handle);
199 const inserted = insertStack(inventory.slots, item.stack, def);
216 let stackToAdd = item.stack;
217 if (item.stack.itemId === ItemId.blankCheque)
218 {
219 const have = countItemInSlots(inventory.slots, ItemId.blankCheque);
220 const room = BLANK_CHEQUE_CARRY_CAP - have;
221 if (room <= 0)
222 { throw userError(`You already carry ${BLANK_CHEQUE_CARRY_CAP} blank cheques.`); }
223 const takeQty = Math.min(item.stack.quantity, room);
224 stackToAdd = { ...item.stack, quantity: takeQty };
225 }
226 const inserted = insertStack(inventory.slots, stackToAdd, def);
200 227 if (!inserted.ok)
201 228 { throw userError("Your inventory cannot hold that."); }
202 229 inventory.slots = inserted.slots;
203 removeGroundItem(world, item.groundItemId);
230 const events = [];
231 if (item.stack.itemId === ItemId.blankCheque && stackToAdd.quantity < item.stack.quantity)
232 {
233 item.stack.quantity -= stackToAdd.quantity;
234 events.push({
235 type: "ground-item-appear",
236 ...publicGroundItem(item),
237 stack: item.stack,
238 droppedAt: item.droppedAt,
239 source: item.source,
240 droppedByCharacterId: item.droppedByCharacterId,
241 expiresAt: item.expiresAt
242 });
243 }
244 else
245 {
246 removeGroundItem(world, item.groundItemId);
247 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
248 }
204 249 return {
205 events: [{ type: "ground-item-despawn", ...publicGroundItem(item) }],
250 events,
206 251 private: bagView(world.ecs, handle)
207 252 };
208 253 }
@@ -212,30 +257,48 @@ function equipItem (world, sessionId, command)
212 257 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
213 258 const inventory = ensureInventory(world.ecs, handle);
214 259 const equipment = ensureEquipment(world.ecs, handle);
215 const taken = takeFromSlot(inventory.slots, command.slotIndex, 1);
216 if (!taken.ok)
260 const slotIndex = command.slotIndex | 0;
261 const source = inventory.slots[slotIndex];
262 if (!source || stackQuantity(source.quantity) <= 0)
217 263 { throw userError("That inventory slot is empty."); }
264 const taken = takeFromSlot(inventory.slots, slotIndex, 1);
265 if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1)
266 { throw userError("That inventory slot is empty."); }
267 if (taken.taken.itemId === ItemId.coins)
268 {
269 inventory.slots = insertStack(taken.slots, taken.taken, itemDefinition(ItemId.coins)).slots;
270 throw userError("Coins cannot be equipped.");
271 }
218 272 const def = itemDefinition(taken.taken.itemId);
219 273 const slot = def?.equipment?.slot;
220 274 if (!slot)
221 275 {
222 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
276 inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
223 277 throw userError("That item cannot be equipped.");
224 278 }
279 const skills = world.ecs.get(handle, Component.skills);
280 const equipCheck = canEquipItem(skills, def);
281 if (!equipCheck.ok)
282 {
283 inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
284 throw userError(equipCheck.reason);
285 }
286 const toEquip = singleItemFromStack(taken.taken);
225 287 const previous = equipment.slots[slot];
226 288 if (previous)
227 289 {
228 const back = insertStack(taken.slots, previous, itemDefinition(previous.itemId));
290 const previousSingle = singleItemFromStack(previous);
291 const back = insertStack(taken.slots, previousSingle, itemDefinition(previous.itemId));
229 292 if (!back.ok)
230 293 {
231 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
294 inventory.slots = insertStack(inventory.slots, toEquip, def).slots;
232 295 throw userError("No inventory space to unequip the current item.");
233 296 }
234 297 inventory.slots = back.slots;
235 298 }
236 299 else
237 300 { inventory.slots = taken.slots; }
238 equipment.slots[slot] = { ...taken.taken, quantity: 1 };
301 equipment.slots[slot] = toEquip;
239 302 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
240 303 }
241 304
@@ -248,7 +311,8 @@ function unequipItem (world, sessionId, command)
248 311 if (!worn)
249 312 { throw userError("Nothing is equipped there."); }
250 313 const def = itemDefinition(worn.itemId);
251 const inserted = insertStack(inventory.slots, worn, def);
314 const single = singleItemFromStack(worn);
315 const inserted = insertStack(inventory.slots, single, def);
252 316 if (!inserted.ok)
253 317 { throw userError("Your inventory cannot hold that."); }
254 318 inventory.slots = inserted.slots;
@@ -256,6 +320,32 @@ function unequipItem (world, sessionId, command)
256 320 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
257 321 }
258 322
323 function eatItem (world, sessionId, command)
324 {
325 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
326 syncPlayerHealth(world.ecs, handle);
327 const inventory = ensureInventory(world.ecs, handle);
328 const health = world.ecs.get(handle, Component.health);
329 if (!health)
330 { throw userError("You cannot eat right now."); }
331 if ((health.current | 0) >= (health.max | 0))
332 { throw userError("You are already at full health."); }
333 const slotIndex = command.slotIndex | 0;
334 const slot = inventory.slots[slotIndex];
335 if (!slot || stackQuantity(slot.quantity) <= 0)
336 { throw userError("That inventory slot is empty."); }
337 const def = itemDefinition(slot.itemId);
338 const healing = def?.healing ?? 0;
339 if (healing <= 0)
340 { throw userError("That cannot be eaten."); }
341 const taken = takeFromSlot(inventory.slots, slotIndex, 1);
342 if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1)
343 { throw userError("That inventory slot is empty."); }
344 inventory.slots = taken.slots;
345 health.current = Math.min(health.max | 0, (health.current | 0) + healing);
346 return { events: [], private: bagView(world.ecs, handle) };
347 }
348
259 349 function openBank (world, sessionId, command)
260 350 {
261 351 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -271,45 +361,196 @@ function bankMove (world, sessionId, command, fromKey, toKey)
271 361 requireBank(world, handle);
272 362 const inventory = ensureInventory(world.ecs, handle);
273 363 const vault = ensureVault(world.ecs, handle);
364 if (fromKey === "inventory" && toKey === "vault")
365 {
366 const slot = inventory.slots[command.slotIndex | 0];
367 if (slot?.itemId === ItemId.filledCheque)
368 { return redeemCheque(world, sessionId, command); }
369 }
274 370 const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots;
275 371 const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null);
276 372 if (!taken.ok)
277 373 { throw userError("That slot is empty."); }
278 374 const def = itemDefinition(taken.taken.itemId);
279 const dest = toKey === "vault" ? vault : inventory;
280 const inserted = insertStack(dest.slots, taken.taken, def);
281 if (!inserted.ok)
282 { throw userError("Not enough space."); }
283 if (fromKey === "vault")
284 { vault.slots = taken.slots; }
375 if (toKey === "vault")
376 {
377 const inserted = insertStackGrowable(vault.slots, taken.taken, def);
378 inventory.slots = taken.slots;
379 vault.slots = inserted.slots;
380 }
285 381 else
286 { inventory.slots = taken.slots; }
287 dest.slots = inserted.slots;
382 {
383 const inserted = insertStack(inventory.slots, taken.taken, def);
384 if (!inserted.ok)
385 { throw userError("Not enough space."); }
386 vault.slots = taken.slots;
387 inventory.slots = inserted.slots;
388 }
389 return { events: [], private: bagView(world.ecs, handle), bank: true };
390 }
391
392 function getBlankCheques (world, sessionId, command)
393 {
394 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
395 requireBank(world, handle);
396 const inventory = ensureInventory(world.ecs, handle);
397 const have = countItemInSlots(inventory.slots, ItemId.blankCheque);
398 const need = Math.max(0, BLANK_CHEQUE_CARRY_CAP - have);
399 if (!need)
400 { return { events: [], private: bagView(world.ecs, handle), bank: true }; }
401 const def = itemDefinition(ItemId.blankCheque);
402 const inserted = insertStack(inventory.slots, { itemId: ItemId.blankCheque, quantity: need }, def);
403 if (!inserted.ok)
404 { throw userError("Need inventory space for blank cheques."); }
405 inventory.slots = inserted.slots;
288 406 return { events: [], private: bagView(world.ecs, handle), bank: true };
289 407 }
290 408
291 function bankMoney (world, sessionId, command, fromKey, toKey)
409 function returnBlankCheques (world, sessionId, command)
292 410 {
293 411 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
294 412 requireBank(world, handle);
295 const amount = Math.max(0, command.amount | 0);
296 if (!amount)
297 { throw userError("Enter an amount."); }
298 const currency = world.ecs.get(handle, Component.currency) ?? world.ecs.add(handle, Component.currency, { amount: 0 });
413 const inventory = ensureInventory(world.ecs, handle);
414 const slot = inventory.slots[command.slotIndex | 0];
415 if (!slot || slot.itemId !== ItemId.blankCheque)
416 { throw userError("Select blank cheques."); }
417 const quantity = command.quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, command.quantity | 0));
418 const taken = takeFromSlot(inventory.slots, command.slotIndex | 0, quantity);
419 if (!taken.ok)
420 { throw userError("Select blank cheques."); }
421 inventory.slots = taken.slots;
422 return { events: [], private: bagView(world.ecs, handle), bank: true };
423 }
424
425 function writeCheque (world, sessionId, command)
426 {
427 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
428 const inventory = ensureInventory(world.ecs, handle);
299 429 const vault = ensureVault(world.ecs, handle);
300 const from = fromKey === "vault" ? vault : currency;
301 const to = toKey === "vault" ? vault : currency;
302 const fromAmount = fromKey === "vault" ? vault.currency : currency.amount;
303 if (fromAmount < amount)
304 { throw userError("Not enough coins."); }
305 if (fromKey === "vault")
306 { vault.currency -= amount; }
430 const slotIndex = command.slotIndex | 0;
431 const blankSlot = inventory.slots[slotIndex];
432 if (!blankSlot || blankSlot.itemId !== ItemId.blankCheque)
433 { throw userError("Select a blank cheque."); }
434 const vaultSlot = vault.slots[command.vaultSlotIndex | 0];
435 if (!vaultSlot)
436 { throw userError("Select vault goods to reserve."); }
437 const def = itemDefinition(vaultSlot.itemId);
438 if (!def)
439 { throw userError("Unknown item."); }
440 const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);
441 const available = countItemInSlots(vault.slots, vaultSlot.itemId);
442 if (available < quantity)
443 { throw userError("Not enough unreserved goods in the vault."); }
444 if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))
445 { throw userError("Need a free inventory slot for the filled cheque."); }
446
447 const pulled = takeMatchingFromSlots(vault.slots, {
448 itemId: vaultSlot.itemId,
449 quantity,
450 instance: def.uniqueInstance ? vaultSlot.instance : null
451 });
452 if (!pulled.ok)
453 { throw userError("Not enough unreserved goods in the vault."); }
454
455 const chequeId = randomUUID();
456 const reservedStack = {
457 itemId: pulled.taken.itemId,
458 quantity: pulled.taken.quantity,
459 origin: pulled.taken.origin ?? null,
460 instance: pulled.taken.instance ?? null,
461 chequeId
462 };
463 vault.slots = pulled.slots;
464 vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack];
465
466 const filled = {
467 itemId: ItemId.filledCheque,
468 quantity: 1,
469 origin: null,
470 instance: {
471 kind: "filled-cheque",
472 chequeId,
473 issuerCharacterId: command.characterId,
474 itemId: pulled.taken.itemId,
475 quantity: pulled.taken.quantity,
476 reservedInstance: pulled.taken.instance ?? null,
477 createdAt: Date.now()
478 }
479 };
480 const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1);
481 inventory.slots = blankTaken.slots;
482 if (!inventory.slots[slotIndex])
483 { inventory.slots[slotIndex] = filled; }
307 484 else
308 { currency.amount -= amount; }
309 if (toKey === "vault")
310 { vault.currency += amount; }
485 {
486 const free = inventory.slots.findIndex((entry) => !entry);
487 inventory.slots[free] = filled;
488 }
489 return { events: [], private: bagView(world.ecs, handle) };
490 }
491
492 function redeemCheque (world, sessionId, command)
493 {
494 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
495 requireBank(world, handle);
496 const inventory = ensureInventory(world.ecs, handle);
497 const vault = ensureVault(world.ecs, handle);
498 const slotIndex = command.slotIndex | 0;
499 const slot = inventory.slots[slotIndex];
500 if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")
501 { throw userError("Select a filled cheque."); }
502
503 const chequeId = slot.instance.chequeId;
504 const issuerId = slot.instance.issuerCharacterId;
505 const goodsDef = itemDefinition(slot.instance.itemId);
506 if (!goodsDef)
507 { throw userError("Unknown reserved goods."); }
508
509 const chequeTaken = takeFromSlot(inventory.slots, slotIndex, 1);
510 if (!chequeTaken.ok)
511 { throw userError("Select a filled cheque."); }
512 inventory.slots = chequeTaken.slots;
513
514 let reservedStack = null;
515 if (Number(issuerId) === Number(command.characterId))
516 {
517 const index = (vault.reserved ?? []).findIndex((entry) => entry?.chequeId === chequeId);
518 if (index < 0)
519 {
520 inventory.slots[slotIndex] = chequeTaken.taken;
521 throw userError("That cheque cannot be redeemed.");
522 }
523 reservedStack = cloneStack(vault.reserved[index]);
524 vault.reserved = vault.reserved.filter((_, i) => i !== index);
525 }
311 526 else
312 { currency.amount += amount; }
527 {
528 const release = world.releaseChequeReservation?.(issuerId, chequeId);
529 if (!release?.ok)
530 {
531 inventory.slots[slotIndex] = chequeTaken.taken;
532 throw userError(release?.error ?? "That cheque cannot be redeemed.");
533 }
534 reservedStack = release.stack;
535 }
536
537 const inserted = insertStackGrowable(vault.slots, {
538 itemId: reservedStack.itemId,
539 quantity: reservedStack.quantity,
540 origin: reservedStack.origin ?? null,
541 origins: reservedStack.origins ?? null,
542 instance: reservedStack.instance ?? null
543 }, goodsDef);
544 if (!inserted.ok)
545 {
546 inventory.slots[slotIndex] = chequeTaken.taken;
547 if (Number(issuerId) === Number(command.characterId))
548 { vault.reserved = [...(vault.reserved ?? []), reservedStack]; }
549 else
550 { world.restoreChequeReservation?.(issuerId, reservedStack); }
551 throw userError("Your vault cannot hold those goods.");
552 }
553 vault.slots = inserted.slots;
313 554 return { events: [], private: bagView(world.ecs, handle), bank: true };
314 555 }
315 556
@@ -327,13 +568,12 @@ function claimInheritance (world, sessionId, command)
327 568 remainder.push(stack);
328 569 continue;
329 570 }
330 const inserted = insertStack(vault.slots, stack, def);
571 const inserted = insertStackGrowable(vault.slots, stack, def);
331 572 if (inserted.ok)
332 573 { vault.slots = inserted.slots; }
333 574 else
334 575 { remainder.push(stack); }
335 576 }
336 vault.currency += command.currency | 0;
337 577 return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
338 578 }
339 579
@@ -443,7 +683,11 @@ function nearBank (world, tileX, tileY)
443 683
444 684 function ensureInventory (ecs, handle)
445 685 {
446 return ecs.get(handle, Component.inventory) ?? ecs.add(handle, Component.inventory, { slots: emptySlots() });
686 let inventory = ecs.get(handle, Component.inventory);
687 if (!inventory)
688 { inventory = ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
689 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
690 return inventory;
447 691 }
448 692
449 693 function ensureEquipment (ecs, handle)
@@ -453,7 +697,14 @@ function ensureEquipment (ecs, handle)
453 697
454 698 function ensureVault (ecs, handle)
455 699 {
456 return ecs.get(handle, Component.vault) ?? ecs.add(handle, Component.vault, { slots: emptySlots(), currency: 0 });
700 let vault = ecs.get(handle, Component.vault);
701 if (!vault)
702 { vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); }
703 if (!Array.isArray(vault.slots))
704 { vault.slots = []; }
705 if (!Array.isArray(vault.reserved))
706 { vault.reserved = []; }
707 return vault;
457 708 }
458 709
459 710 function userError (message)
@@ -1,13 +1,23 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { syncPlayerHealth } from "../skills/service.js";
3import { canEquipItem } from "../../../shared/equipment/stats.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
4import { BlockType } from "../../../shared/definitions/tiles.js";
3import { ItemId, itemDefinition, itemSpriteName, LETTER_MAX_BODY_CHARS } from "../../../shared/definitions/items.js";
5import { ItemId, itemDefinition, itemSpriteName, stackDisplayLabel, LETTER_MAX_BODY_CHARS, BLANK_CHEQUE_CARRY_CAP } from "../../../shared/definitions/items.js";
4import {
6import {
5 emptyEquipment,
7 emptyEquipment,
6 emptySlots,
8 emptySlots,
7 insertStack,
9 insertStack,
10 insertStackGrowable,
11 normalizeVault,
12 normalizeInventorySlots,
8 publicEquipment,
13 publicEquipment,
9 publicSlots,
14 publicSlots,
10 takeFromSlot
15 takeFromSlot,
16 takeMatchingFromSlots,
17 countItemInSlots,
18 cloneStack,
19 singleItemFromStack,
20 stackQuantity
11} from "../../../shared/items/inventory.js";
21} from "../../../shared/items/inventory.js";
12import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
22import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
13import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
23import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
@@ -22,7 +32,7 @@ export function publicGroundItem (item)
22 tileY: item.tileY,
32 tileY: item.tileY,
23 itemId: item.stack.itemId,
33 itemId: item.stack.itemId,
24 quantity: item.stack.quantity,
34 quantity: item.stack.quantity,
25 displayName: def?.displayName ?? "Item",
35 displayName: stackDisplayLabel(item.stack),
26 sprite: itemSpriteName(item.stack.itemId, item.stack.instance),
36 sprite: itemSpriteName(item.stack.itemId, item.stack.instance),
27 expiresAt: item.expiresAt
37 expiresAt: item.expiresAt
28 };
38 };
@@ -30,29 +40,30 @@ export function publicGroundItem (item)
30
40
31export function bagView (ecs, handle)
41export function bagView (ecs, handle)
32{
42{
43 const vault = normalizeVault(ecs.get(handle, Component.vault));
33 return {
44 return {
34 inventory: publicSlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots()),
45 inventory: publicSlots(normalizeInventorySlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots())),
35 equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()),
46 equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()),
36 currency: ecs.get(handle, Component.currency)?.amount ?? 0,
47 vault: publicSlots(vault.slots),
37 vault: publicSlots(ecs.get(handle, Component.vault)?.slots ?? emptySlots()),
48 vaultReserved: publicSlots(vault.reserved)
38 vaultCurrency: ecs.get(handle, Component.vault)?.currency ?? 0
39 };
49 };
40}
50}
41
51
42export function applyBagView (ecs, handle, bag)
52export function applyBagView (ecs, handle, bag)
43{
53{
44 const inventory = ensureInventory(ecs, handle);
54 const inventory = ensureInventory(ecs, handle);
45 inventory.slots = publicSlots(bag.inventory ?? emptySlots());
55 inventory.slots = normalizeInventorySlots(publicSlots(bag.inventory ?? emptySlots()));
46 const equipment = ensureEquipment(ecs, handle);
56 const equipment = ensureEquipment(ecs, handle);
47 const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment());
57 const nextEquip = publicEquipment(bag.equipment ?? emptyEquipment());
48 equipment.slots = nextEquip.slots;
58 equipment.slots = nextEquip.slots;
49 let currency = ecs.get(handle, Component.currency);
50 if (!currency)
51 { currency = ecs.add(handle, Component.currency, { amount: 0 }); }
52 currency.amount = bag.currency | 0;
53 const vault = ensureVault(ecs, handle);
59 const vault = ensureVault(ecs, handle);
54 vault.slots = publicSlots(bag.vault ?? emptySlots());
60 const normalized = normalizeVault(
55 vault.currency = bag.vaultCurrency | 0;
61 bag.vaultReserved != null || (bag.vault && !Array.isArray(bag.vault))
62 ? { slots: bag.vault, reserved: bag.vaultReserved }
63 : bag.vault
64 );
65 vault.slots = publicSlots(normalized.slots);
66 vault.reserved = publicSlots(normalized.reserved);
56 return bagView(ecs, handle);
67 return bagView(ecs, handle);
57}
68}
58
69
@@ -74,10 +85,14 @@ export function handleItemCommand (world, sessionId, command, now)
74 return bankMove(world, sessionId, command, "inventory", "vault");
85 return bankMove(world, sessionId, command, "inventory", "vault");
75 case "bank-withdraw":
86 case "bank-withdraw":
76 return bankMove(world, sessionId, command, "vault", "inventory");
87 return bankMove(world, sessionId, command, "vault", "inventory");
77 case "bank-deposit-money":
88 case "get-blank-cheques":
78 return bankMoney(world, sessionId, command, "currency", "vault");
89 return getBlankCheques(world, sessionId, command);
79 case "bank-withdraw-money":
90 case "return-blank-cheques":
80 return bankMoney(world, sessionId, command, "vault", "currency");
91 return returnBlankCheques(world, sessionId, command);
92 case "write-cheque":
93 return writeCheque(world, sessionId, command);
94 case "redeem-cheque":
95 return redeemCheque(world, sessionId, command);
81 case "claim-inheritance":
96 case "claim-inheritance":
82 return claimInheritance(world, sessionId, command);
97 return claimInheritance(world, sessionId, command);
83 case "write-letter":
98 case "write-letter":
@@ -86,6 +101,8 @@ export function handleItemCommand (world, sessionId, command, now)
86 return editLetter(world, sessionId, command);
101 return editLetter(world, sessionId, command);
87 case "open-letter":
102 case "open-letter":
88 return openLetter(world, sessionId, command);
103 return openLetter(world, sessionId, command);
104 case "eat-item":
105 return eatItem(world, sessionId, command);
89 default:
106 default:
90 return null;
107 return null;
91 }
108 }
@@ -196,13 +213,41 @@ function pickupItem (world, sessionId, command)
196 if (!def)
213 if (!def)
197 { throw userError("Unknown item."); }
214 { throw userError("Unknown item."); }
198 const inventory = ensureInventory(world.ecs, handle);
215 const inventory = ensureInventory(world.ecs, handle);
199 const inserted = insertStack(inventory.slots, item.stack, def);
216 let stackToAdd = item.stack;
217 if (item.stack.itemId === ItemId.blankCheque)
218 {
219 const have = countItemInSlots(inventory.slots, ItemId.blankCheque);
220 const room = BLANK_CHEQUE_CARRY_CAP - have;
221 if (room <= 0)
222 { throw userError(`You already carry ${BLANK_CHEQUE_CARRY_CAP} blank cheques.`); }
223 const takeQty = Math.min(item.stack.quantity, room);
224 stackToAdd = { ...item.stack, quantity: takeQty };
225 }
226 const inserted = insertStack(inventory.slots, stackToAdd, def);
200 if (!inserted.ok)
227 if (!inserted.ok)
201 { throw userError("Your inventory cannot hold that."); }
228 { throw userError("Your inventory cannot hold that."); }
202 inventory.slots = inserted.slots;
229 inventory.slots = inserted.slots;
203 removeGroundItem(world, item.groundItemId);
230 const events = [];
231 if (item.stack.itemId === ItemId.blankCheque && stackToAdd.quantity < item.stack.quantity)
232 {
233 item.stack.quantity -= stackToAdd.quantity;
234 events.push({
235 type: "ground-item-appear",
236 ...publicGroundItem(item),
237 stack: item.stack,
238 droppedAt: item.droppedAt,
239 source: item.source,
240 droppedByCharacterId: item.droppedByCharacterId,
241 expiresAt: item.expiresAt
242 });
243 }
244 else
245 {
246 removeGroundItem(world, item.groundItemId);
247 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
248 }
204 return {
249 return {
205 events: [{ type: "ground-item-despawn", ...publicGroundItem(item) }],
250 events,
206 private: bagView(world.ecs, handle)
251 private: bagView(world.ecs, handle)
207 };
252 };
208}
253}
@@ -212,30 +257,48 @@ function equipItem (world, sessionId, command)
212 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
257 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
213 const inventory = ensureInventory(world.ecs, handle);
258 const inventory = ensureInventory(world.ecs, handle);
214 const equipment = ensureEquipment(world.ecs, handle);
259 const equipment = ensureEquipment(world.ecs, handle);
215 const taken = takeFromSlot(inventory.slots, command.slotIndex, 1);
260 const slotIndex = command.slotIndex | 0;
216 if (!taken.ok)
261 const source = inventory.slots[slotIndex];
262 if (!source || stackQuantity(source.quantity) <= 0)
217 { throw userError("That inventory slot is empty."); }
263 { throw userError("That inventory slot is empty."); }
264 const taken = takeFromSlot(inventory.slots, slotIndex, 1);
265 if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1)
266 { throw userError("That inventory slot is empty."); }
267 if (taken.taken.itemId === ItemId.coins)
268 {
269 inventory.slots = insertStack(taken.slots, taken.taken, itemDefinition(ItemId.coins)).slots;
270 throw userError("Coins cannot be equipped.");
271 }
218 const def = itemDefinition(taken.taken.itemId);
272 const def = itemDefinition(taken.taken.itemId);
219 const slot = def?.equipment?.slot;
273 const slot = def?.equipment?.slot;
220 if (!slot)
274 if (!slot)
221 {
275 {
222 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
276 inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
223 throw userError("That item cannot be equipped.");
277 throw userError("That item cannot be equipped.");
224 }
278 }
279 const skills = world.ecs.get(handle, Component.skills);
280 const equipCheck = canEquipItem(skills, def);
281 if (!equipCheck.ok)
282 {
283 inventory.slots = insertStack(taken.slots, taken.taken, def).slots;
284 throw userError(equipCheck.reason);
285 }
286 const toEquip = singleItemFromStack(taken.taken);
225 const previous = equipment.slots[slot];
287 const previous = equipment.slots[slot];
226 if (previous)
288 if (previous)
227 {
289 {
228 const back = insertStack(taken.slots, previous, itemDefinition(previous.itemId));
290 const previousSingle = singleItemFromStack(previous);
291 const back = insertStack(taken.slots, previousSingle, itemDefinition(previous.itemId));
229 if (!back.ok)
292 if (!back.ok)
230 {
293 {
231 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
294 inventory.slots = insertStack(inventory.slots, toEquip, def).slots;
232 throw userError("No inventory space to unequip the current item.");
295 throw userError("No inventory space to unequip the current item.");
233 }
296 }
234 inventory.slots = back.slots;
297 inventory.slots = back.slots;
235 }
298 }
236 else
299 else
237 { inventory.slots = taken.slots; }
300 { inventory.slots = taken.slots; }
238 equipment.slots[slot] = { ...taken.taken, quantity: 1 };
301 equipment.slots[slot] = toEquip;
239 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
302 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
240}
303}
241
304
@@ -248,7 +311,8 @@ function unequipItem (world, sessionId, command)
248 if (!worn)
311 if (!worn)
249 { throw userError("Nothing is equipped there."); }
312 { throw userError("Nothing is equipped there."); }
250 const def = itemDefinition(worn.itemId);
313 const def = itemDefinition(worn.itemId);
251 const inserted = insertStack(inventory.slots, worn, def);
314 const single = singleItemFromStack(worn);
315 const inserted = insertStack(inventory.slots, single, def);
252 if (!inserted.ok)
316 if (!inserted.ok)
253 { throw userError("Your inventory cannot hold that."); }
317 { throw userError("Your inventory cannot hold that."); }
254 inventory.slots = inserted.slots;
318 inventory.slots = inserted.slots;
@@ -256,6 +320,32 @@ function unequipItem (world, sessionId, command)
256 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
320 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
257}
321}
258
322
323function eatItem (world, sessionId, command)
324{
325 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
326 syncPlayerHealth(world.ecs, handle);
327 const inventory = ensureInventory(world.ecs, handle);
328 const health = world.ecs.get(handle, Component.health);
329 if (!health)
330 { throw userError("You cannot eat right now."); }
331 if ((health.current | 0) >= (health.max | 0))
332 { throw userError("You are already at full health."); }
333 const slotIndex = command.slotIndex | 0;
334 const slot = inventory.slots[slotIndex];
335 if (!slot || stackQuantity(slot.quantity) <= 0)
336 { throw userError("That inventory slot is empty."); }
337 const def = itemDefinition(slot.itemId);
338 const healing = def?.healing ?? 0;
339 if (healing <= 0)
340 { throw userError("That cannot be eaten."); }
341 const taken = takeFromSlot(inventory.slots, slotIndex, 1);
342 if (!taken.ok || stackQuantity(taken.taken?.quantity) !== 1)
343 { throw userError("That inventory slot is empty."); }
344 inventory.slots = taken.slots;
345 health.current = Math.min(health.max | 0, (health.current | 0) + healing);
346 return { events: [], private: bagView(world.ecs, handle) };
347}
348
259function openBank (world, sessionId, command)
349function openBank (world, sessionId, command)
260{
350{
261 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
351 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
@@ -271,45 +361,196 @@ function bankMove (world, sessionId, command, fromKey, toKey)
271 requireBank(world, handle);
361 requireBank(world, handle);
272 const inventory = ensureInventory(world.ecs, handle);
362 const inventory = ensureInventory(world.ecs, handle);
273 const vault = ensureVault(world.ecs, handle);
363 const vault = ensureVault(world.ecs, handle);
364 if (fromKey === "inventory" && toKey === "vault")
365 {
366 const slot = inventory.slots[command.slotIndex | 0];
367 if (slot?.itemId === ItemId.filledCheque)
368 { return redeemCheque(world, sessionId, command); }
369 }
274 const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots;
370 const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots;
275 const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null);
371 const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null);
276 if (!taken.ok)
372 if (!taken.ok)
277 { throw userError("That slot is empty."); }
373 { throw userError("That slot is empty."); }
278 const def = itemDefinition(taken.taken.itemId);
374 const def = itemDefinition(taken.taken.itemId);
279 const dest = toKey === "vault" ? vault : inventory;
375 if (toKey === "vault")
280 const inserted = insertStack(dest.slots, taken.taken, def);
376 {
281 if (!inserted.ok)
377 const inserted = insertStackGrowable(vault.slots, taken.taken, def);
282 { throw userError("Not enough space."); }
378 inventory.slots = taken.slots;
283 if (fromKey === "vault")
379 vault.slots = inserted.slots;
284 { vault.slots = taken.slots; }
380 }
285 else
381 else
286 { inventory.slots = taken.slots; }
382 {
287 dest.slots = inserted.slots;
383 const inserted = insertStack(inventory.slots, taken.taken, def);
384 if (!inserted.ok)
385 { throw userError("Not enough space."); }
386 vault.slots = taken.slots;
387 inventory.slots = inserted.slots;
388 }
389 return { events: [], private: bagView(world.ecs, handle), bank: true };
390}
391
392function getBlankCheques (world, sessionId, command)
393{
394 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
395 requireBank(world, handle);
396 const inventory = ensureInventory(world.ecs, handle);
397 const have = countItemInSlots(inventory.slots, ItemId.blankCheque);
398 const need = Math.max(0, BLANK_CHEQUE_CARRY_CAP - have);
399 if (!need)
400 { return { events: [], private: bagView(world.ecs, handle), bank: true }; }
401 const def = itemDefinition(ItemId.blankCheque);
402 const inserted = insertStack(inventory.slots, { itemId: ItemId.blankCheque, quantity: need }, def);
403 if (!inserted.ok)
404 { throw userError("Need inventory space for blank cheques."); }
405 inventory.slots = inserted.slots;
288 return { events: [], private: bagView(world.ecs, handle), bank: true };
406 return { events: [], private: bagView(world.ecs, handle), bank: true };
289}
407}
290
408
291function bankMoney (world, sessionId, command, fromKey, toKey)
409function returnBlankCheques (world, sessionId, command)
292{
410{
293 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
411 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
294 requireBank(world, handle);
412 requireBank(world, handle);
295 const amount = Math.max(0, command.amount | 0);
413 const inventory = ensureInventory(world.ecs, handle);
296 if (!amount)
414 const slot = inventory.slots[command.slotIndex | 0];
297 { throw userError("Enter an amount."); }
415 if (!slot || slot.itemId !== ItemId.blankCheque)
298 const currency = world.ecs.get(handle, Component.currency) ?? world.ecs.add(handle, Component.currency, { amount: 0 });
416 { throw userError("Select blank cheques."); }
417 const quantity = command.quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, command.quantity | 0));
418 const taken = takeFromSlot(inventory.slots, command.slotIndex | 0, quantity);
419 if (!taken.ok)
420 { throw userError("Select blank cheques."); }
421 inventory.slots = taken.slots;
422 return { events: [], private: bagView(world.ecs, handle), bank: true };
423}
424
425function writeCheque (world, sessionId, command)
426{
427 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
428 const inventory = ensureInventory(world.ecs, handle);
299 const vault = ensureVault(world.ecs, handle);
429 const vault = ensureVault(world.ecs, handle);
300 const from = fromKey === "vault" ? vault : currency;
430 const slotIndex = command.slotIndex | 0;
301 const to = toKey === "vault" ? vault : currency;
431 const blankSlot = inventory.slots[slotIndex];
302 const fromAmount = fromKey === "vault" ? vault.currency : currency.amount;
432 if (!blankSlot || blankSlot.itemId !== ItemId.blankCheque)
303 if (fromAmount < amount)
433 { throw userError("Select a blank cheque."); }
304 { throw userError("Not enough coins."); }
434 const vaultSlot = vault.slots[command.vaultSlotIndex | 0];
305 if (fromKey === "vault")
435 if (!vaultSlot)
306 { vault.currency -= amount; }
436 { throw userError("Select vault goods to reserve."); }
437 const def = itemDefinition(vaultSlot.itemId);
438 if (!def)
439 { throw userError("Unknown item."); }
440 const quantity = def.uniqueInstance ? 1 : Math.max(1, command.quantity | 0);
441 const available = countItemInSlots(vault.slots, vaultSlot.itemId);
442 if (available < quantity)
443 { throw userError("Not enough unreserved goods in the vault."); }
444 if (blankSlot.quantity > 1 && inventory.slots.every((entry) => entry))
445 { throw userError("Need a free inventory slot for the filled cheque."); }
446
447 const pulled = takeMatchingFromSlots(vault.slots, {
448 itemId: vaultSlot.itemId,
449 quantity,
450 instance: def.uniqueInstance ? vaultSlot.instance : null
451 });
452 if (!pulled.ok)
453 { throw userError("Not enough unreserved goods in the vault."); }
454
455 const chequeId = randomUUID();
456 const reservedStack = {
457 itemId: pulled.taken.itemId,
458 quantity: pulled.taken.quantity,
459 origin: pulled.taken.origin ?? null,
460 instance: pulled.taken.instance ?? null,
461 chequeId
462 };
463 vault.slots = pulled.slots;
464 vault.reserved = [...(vault.reserved ?? []).map(cloneStack), reservedStack];
465
466 const filled = {
467 itemId: ItemId.filledCheque,
468 quantity: 1,
469 origin: null,
470 instance: {
471 kind: "filled-cheque",
472 chequeId,
473 issuerCharacterId: command.characterId,
474 itemId: pulled.taken.itemId,
475 quantity: pulled.taken.quantity,
476 reservedInstance: pulled.taken.instance ?? null,
477 createdAt: Date.now()
478 }
479 };
480 const blankTaken = takeFromSlot(inventory.slots, slotIndex, 1);
481 inventory.slots = blankTaken.slots;
482 if (!inventory.slots[slotIndex])
483 { inventory.slots[slotIndex] = filled; }
307 else
484 else
308 { currency.amount -= amount; }
485 {
309 if (toKey === "vault")
486 const free = inventory.slots.findIndex((entry) => !entry);
310 { vault.currency += amount; }
487 inventory.slots[free] = filled;
488 }
489 return { events: [], private: bagView(world.ecs, handle) };
490}
491
492function redeemCheque (world, sessionId, command)
493{
494 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
495 requireBank(world, handle);
496 const inventory = ensureInventory(world.ecs, handle);
497 const vault = ensureVault(world.ecs, handle);
498 const slotIndex = command.slotIndex | 0;
499 const slot = inventory.slots[slotIndex];
500 if (!slot || slot.itemId !== ItemId.filledCheque || slot.instance?.kind !== "filled-cheque")
501 { throw userError("Select a filled cheque."); }
502
503 const chequeId = slot.instance.chequeId;
504 const issuerId = slot.instance.issuerCharacterId;
505 const goodsDef = itemDefinition(slot.instance.itemId);
506 if (!goodsDef)
507 { throw userError("Unknown reserved goods."); }
508
509 const chequeTaken = takeFromSlot(inventory.slots, slotIndex, 1);
510 if (!chequeTaken.ok)
511 { throw userError("Select a filled cheque."); }
512 inventory.slots = chequeTaken.slots;
513
514 let reservedStack = null;
515 if (Number(issuerId) === Number(command.characterId))
516 {
517 const index = (vault.reserved ?? []).findIndex((entry) => entry?.chequeId === chequeId);
518 if (index < 0)
519 {
520 inventory.slots[slotIndex] = chequeTaken.taken;
521 throw userError("That cheque cannot be redeemed.");
522 }
523 reservedStack = cloneStack(vault.reserved[index]);
524 vault.reserved = vault.reserved.filter((_, i) => i !== index);
525 }
311 else
526 else
312 { currency.amount += amount; }
527 {
528 const release = world.releaseChequeReservation?.(issuerId, chequeId);
529 if (!release?.ok)
530 {
531 inventory.slots[slotIndex] = chequeTaken.taken;
532 throw userError(release?.error ?? "That cheque cannot be redeemed.");
533 }
534 reservedStack = release.stack;
535 }
536
537 const inserted = insertStackGrowable(vault.slots, {
538 itemId: reservedStack.itemId,
539 quantity: reservedStack.quantity,
540 origin: reservedStack.origin ?? null,
541 origins: reservedStack.origins ?? null,
542 instance: reservedStack.instance ?? null
543 }, goodsDef);
544 if (!inserted.ok)
545 {
546 inventory.slots[slotIndex] = chequeTaken.taken;
547 if (Number(issuerId) === Number(command.characterId))
548 { vault.reserved = [...(vault.reserved ?? []), reservedStack]; }
549 else
550 { world.restoreChequeReservation?.(issuerId, reservedStack); }
551 throw userError("Your vault cannot hold those goods.");
552 }
553 vault.slots = inserted.slots;
313 return { events: [], private: bagView(world.ecs, handle), bank: true };
554 return { events: [], private: bagView(world.ecs, handle), bank: true };
314}
555}
315
556
@@ -327,13 +568,12 @@ function claimInheritance (world, sessionId, command)
327 remainder.push(stack);
568 remainder.push(stack);
328 continue;
569 continue;
329 }
570 }
330 const inserted = insertStack(vault.slots, stack, def);
571 const inserted = insertStackGrowable(vault.slots, stack, def);
331 if (inserted.ok)
572 if (inserted.ok)
332 { vault.slots = inserted.slots; }
573 { vault.slots = inserted.slots; }
333 else
574 else
334 { remainder.push(stack); }
575 { remainder.push(stack); }
335 }
576 }
336 vault.currency += command.currency | 0;
337 return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
577 return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
338}
578}
339
579
@@ -443,7 +683,11 @@ function nearBank (world, tileX, tileY)
443
683
444function ensureInventory (ecs, handle)
684function ensureInventory (ecs, handle)
445{
685{
446 return ecs.get(handle, Component.inventory) ?? ecs.add(handle, Component.inventory, { slots: emptySlots() });
686 let inventory = ecs.get(handle, Component.inventory);
687 if (!inventory)
688 { inventory = ecs.add(handle, Component.inventory, { slots: emptySlots() }); }
689 inventory.slots = normalizeInventorySlots(inventory.slots ?? emptySlots());
690 return inventory;
447}
691}
448
692
449function ensureEquipment (ecs, handle)
693function ensureEquipment (ecs, handle)
@@ -453,7 +697,14 @@ function ensureEquipment (ecs, handle)
453
697
454function ensureVault (ecs, handle)
698function ensureVault (ecs, handle)
455{
699{
456 return ecs.get(handle, Component.vault) ?? ecs.add(handle, Component.vault, { slots: emptySlots(), currency: 0 });
700 let vault = ecs.get(handle, Component.vault);
701 if (!vault)
702 { vault = ecs.add(handle, Component.vault, { slots: [], reserved: [] }); }
703 if (!Array.isArray(vault.slots))
704 { vault.slots = []; }
705 if (!Array.isArray(vault.reserved))
706 { vault.reserved = []; }
707 return vault;
457}
708}
458
709
459function userError (message)
710function userError (message)
server/src/persistence/stateDb.js +90 −29
@@ -1,6 +1,7 @@
1 1 import { openDatabase } from "./database.js";
2 import { emptyEquipment, emptySlots, insertStack, publicSlots } from "../../../shared/items/inventory.js";
3 import { STARTER_CURRENCY, STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";
2 import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
3 import { STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";
4 import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
4 5
5 6 const STATE_SCHEMA = `
6 7 CREATE TABLE IF NOT EXISTS accounts (
@@ -56,7 +57,8 @@ CREATE TABLE IF NOT EXISTS character_bags (
56 57 equipment_blob TEXT NOT NULL,
57 58 currency INTEGER NOT NULL DEFAULT 0,
58 59 vault_blob TEXT NOT NULL,
59 vault_currency INTEGER NOT NULL DEFAULT 0
60 vault_currency INTEGER NOT NULL DEFAULT 0,
61 skills_blob TEXT NOT NULL DEFAULT '{}'
60 62 );
61 63
62 64 CREATE TABLE IF NOT EXISTS account_inheritance (
@@ -100,6 +102,16 @@ export class StateDatabase
100 102 {
101 103 this.db = openDatabase(filePath);
102 104 this.db.exec(STATE_SCHEMA);
105 this.#migrateSchema();
106 }
107
108 #migrateSchema ()
109 {
110 const columns = this.db.prepare("PRAGMA table_info(character_bags)").all();
111 if (!columns.some((column) => column.name === "skills_blob"))
112 {
113 this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
114 }
103 115 }
104 116
105 117 getAccountBySubject (authSubject)
@@ -390,14 +402,14 @@ export class StateDatabase
390 402 }
391 403 this.db.prepare(`
392 404 INSERT INTO character_bags (
393 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency
394 ) VALUES (?, ?, ?, ?, ?, 0)
405 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
406 ) VALUES (?, ?, ?, 0, ?, 0, ?)
395 407 `).run(
396 408 characterId,
397 409 JSON.stringify(slots),
398 410 JSON.stringify(emptyEquipment()),
399 STARTER_CURRENCY,
400 JSON.stringify(emptySlots())
411 JSON.stringify({ slots: [], reserved: [] }),
412 JSON.stringify(storedSkillXp(defaultPlayerSkills()))
401 413 );
402 414 return this.getBag(characterId);
403 415 }
@@ -415,16 +427,43 @@ export class StateDatabase
415 427 saveBag (characterId, bag)
416 428 {
417 429 this.#ensureBag(characterId);
430 const migrated = migrateBagCoins(bag);
431 const vault = normalizeVault(
432 migrated.vaultReserved != null
433 ? { slots: migrated.vault, reserved: migrated.vaultReserved }
434 : migrated.vault
435 );
418 436 this.db.prepare(`
419 437 UPDATE character_bags
420 SET inventory_blob = ?, equipment_blob = ?, currency = ?, vault_blob = ?, vault_currency = ?
438 SET inventory_blob = ?, equipment_blob = ?, currency = 0, vault_blob = ?, vault_currency = 0
421 439 WHERE character_id = ?
422 440 `).run(
423 JSON.stringify(bag.inventory ?? emptySlots()),
424 JSON.stringify(bag.equipment ?? emptyEquipment()),
425 bag.currency ?? 0,
426 JSON.stringify(bag.vault ?? emptySlots()),
427 bag.vaultCurrency ?? 0,
441 JSON.stringify(normalizeInventorySlots(migrated.inventory ?? emptySlots())),
442 JSON.stringify(migrated.equipment ?? emptyEquipment()),
443 JSON.stringify({ slots: vault.slots, reserved: vault.reserved }),
444 characterId
445 );
446 }
447
448 getSkills (characterId)
449 {
450 const row = this.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?").get(characterId);
451 if (row)
452 { return normalizePlayerSkills(JSON.parse(row.skills_blob || "{}")); }
453 if (this.getCharacter(characterId))
454 {
455 this.#ensureBag(characterId);
456 return this.getSkills(characterId);
457 }
458 return null;
459 }
460
461 saveSkills (characterId, skills)
462 {
463 this.#ensureBag(characterId);
464 const xp = storedSkillXp(skills?.xp ? skills : { xp: skills });
465 this.db.prepare("UPDATE character_bags SET skills_blob = ? WHERE character_id = ?").run(
466 JSON.stringify({ xp }),
428 467 characterId
429 468 );
430 469 }
@@ -433,21 +472,22 @@ export class StateDatabase
433 472 {
434 473 const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
435 474 if (!row)
436 { return { accountId, slots: emptySlots(), currency: 0 }; }
437 return {
475 { return { accountId, slots: emptySlots() }; }
476 return migrateInheritanceCoins({
438 477 accountId,
439 478 slots: JSON.parse(row.slots_blob),
440 479 currency: row.currency
441 };
480 });
442 481 }
443 482
444 483 saveInheritance (accountId, inheritance)
445 484 {
485 const migrated = migrateInheritanceCoins(inheritance);
446 486 this.db.prepare(`
447 487 INSERT INTO account_inheritance (account_id, slots_blob, currency)
448 VALUES (?, ?, ?)
449 ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = excluded.currency
450 `).run(accountId, JSON.stringify(inheritance.slots ?? emptySlots()), inheritance.currency ?? 0);
488 VALUES (?, ?, 0)
489 ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = 0
490 `).run(accountId, JSON.stringify(migrated.slots ?? emptySlots()));
451 491 }
452 492
453 493 #moveGoodsToInheritance (character)
@@ -455,15 +495,35 @@ export class StateDatabase
455 495 const bag = this.getBag(character.character_id) ?? {
456 496 inventory: emptySlots(),
457 497 equipment: emptyEquipment(),
458 currency: 0,
459 vault: emptySlots(),
460 vaultCurrency: 0
498 vault: [],
499 vaultReserved: []
461 500 };
462 501 const inheritance = this.getInheritance(character.account_id);
502 const vault = normalizeVault(
503 bag.vaultReserved != null
504 ? { slots: bag.vault, reserved: bag.vaultReserved }
505 : bag.vault
506 );
507 // Void outstanding cheques issued by this character: reservations return to available vault.
508 for (const reserved of vault.reserved ?? [])
509 {
510 const stack = {
511 itemId: reserved.itemId,
512 quantity: reserved.quantity,
513 origin: reserved.origin ?? null,
514 instance: reserved.instance ?? null
515 };
516 const def = itemDefinition(stack.itemId);
517 if (!def)
518 { continue; }
519 const restored = insertStackGrowable(vault.slots, stack, def);
520 vault.slots = restored.slots;
521 }
522 vault.reserved = [];
463 523 const incoming = [
464 524 ...(bag.inventory ?? []),
465 525 ...Object.values(bag.equipment?.slots ?? {}),
466 ...(bag.vault ?? [])
526 ...(vault.slots ?? [])
467 527 ].filter(Boolean);
468 528 let slots = inheritance.slots ?? emptySlots();
469 529 for (const stack of incoming)
@@ -486,8 +546,7 @@ export class StateDatabase
486 546 }
487 547 }
488 548 this.saveInheritance(character.account_id, {
489 slots: publicSlots(slots),
490 currency: (inheritance.currency ?? 0) + (bag.currency ?? 0) + (bag.vaultCurrency ?? 0)
549 slots: publicSlots(slots)
491 550 });
492 551 }
493 552
@@ -630,14 +689,16 @@ function parseGroundItem (row)
630 689
631 690 function parseBag (row, characterId)
632 691 {
633 return {
692 const vault = normalizeVault(JSON.parse(row.vault_blob));
693 return migrateBagCoins({
634 694 characterId,
635 inventory: JSON.parse(row.inventory_blob),
695 inventory: normalizeInventorySlots(JSON.parse(row.inventory_blob)),
636 696 equipment: JSON.parse(row.equipment_blob),
637 697 currency: row.currency,
638 vault: JSON.parse(row.vault_blob),
698 vault: vault.slots,
699 vaultReserved: vault.reserved,
639 700 vaultCurrency: row.vault_currency
640 };
701 });
641 702 }
642 703
643 704 function parseCourierTransit (row)
@@ -1,6 +1,7 @@
1import { openDatabase } from "./database.js";
1import { openDatabase } from "./database.js";
2import { emptyEquipment, emptySlots, insertStack, publicSlots } from "../../../shared/items/inventory.js";
2import { emptyEquipment, emptySlots, insertStack, insertStackGrowable, normalizeVault, normalizeInventorySlots, publicSlots, migrateBagCoins, migrateInheritanceCoins } from "../../../shared/items/inventory.js";
3import { STARTER_CURRENCY, STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";
3import { STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";
4import { normalizePlayerSkills, defaultPlayerSkills, storedSkillXp } from "../../../shared/skills/state.js";
4
5
5const STATE_SCHEMA = `
6const STATE_SCHEMA = `
6CREATE TABLE IF NOT EXISTS accounts (
7CREATE TABLE IF NOT EXISTS accounts (
@@ -56,7 +57,8 @@ CREATE TABLE IF NOT EXISTS character_bags (
56 equipment_blob TEXT NOT NULL,
57 equipment_blob TEXT NOT NULL,
57 currency INTEGER NOT NULL DEFAULT 0,
58 currency INTEGER NOT NULL DEFAULT 0,
58 vault_blob TEXT NOT NULL,
59 vault_blob TEXT NOT NULL,
59 vault_currency INTEGER NOT NULL DEFAULT 0
60 vault_currency INTEGER NOT NULL DEFAULT 0,
61 skills_blob TEXT NOT NULL DEFAULT '{}'
60);
62);
61
63
62CREATE TABLE IF NOT EXISTS account_inheritance (
64CREATE TABLE IF NOT EXISTS account_inheritance (
@@ -100,6 +102,16 @@ export class StateDatabase
100 {
102 {
101 this.db = openDatabase(filePath);
103 this.db = openDatabase(filePath);
102 this.db.exec(STATE_SCHEMA);
104 this.db.exec(STATE_SCHEMA);
105 this.#migrateSchema();
106 }
107
108 #migrateSchema ()
109 {
110 const columns = this.db.prepare("PRAGMA table_info(character_bags)").all();
111 if (!columns.some((column) => column.name === "skills_blob"))
112 {
113 this.db.exec("ALTER TABLE character_bags ADD COLUMN skills_blob TEXT NOT NULL DEFAULT '{}'");
114 }
103 }
115 }
104
116
105 getAccountBySubject (authSubject)
117 getAccountBySubject (authSubject)
@@ -390,14 +402,14 @@ export class StateDatabase
390 }
402 }
391 this.db.prepare(`
403 this.db.prepare(`
392 INSERT INTO character_bags (
404 INSERT INTO character_bags (
393 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency
405 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency, skills_blob
394 ) VALUES (?, ?, ?, ?, ?, 0)
406 ) VALUES (?, ?, ?, 0, ?, 0, ?)
395 `).run(
407 `).run(
396 characterId,
408 characterId,
397 JSON.stringify(slots),
409 JSON.stringify(slots),
398 JSON.stringify(emptyEquipment()),
410 JSON.stringify(emptyEquipment()),
399 STARTER_CURRENCY,
411 JSON.stringify({ slots: [], reserved: [] }),
400 JSON.stringify(emptySlots())
412 JSON.stringify(storedSkillXp(defaultPlayerSkills()))
401 );
413 );
402 return this.getBag(characterId);
414 return this.getBag(characterId);
403 }
415 }
@@ -415,16 +427,43 @@ export class StateDatabase
415 saveBag (characterId, bag)
427 saveBag (characterId, bag)
416 {
428 {
417 this.#ensureBag(characterId);
429 this.#ensureBag(characterId);
430 const migrated = migrateBagCoins(bag);
431 const vault = normalizeVault(
432 migrated.vaultReserved != null
433 ? { slots: migrated.vault, reserved: migrated.vaultReserved }
434 : migrated.vault
435 );
418 this.db.prepare(`
436 this.db.prepare(`
419 UPDATE character_bags
437 UPDATE character_bags
420 SET inventory_blob = ?, equipment_blob = ?, currency = ?, vault_blob = ?, vault_currency = ?
438 SET inventory_blob = ?, equipment_blob = ?, currency = 0, vault_blob = ?, vault_currency = 0
421 WHERE character_id = ?
439 WHERE character_id = ?
422 `).run(
440 `).run(
423 JSON.stringify(bag.inventory ?? emptySlots()),
441 JSON.stringify(normalizeInventorySlots(migrated.inventory ?? emptySlots())),
424 JSON.stringify(bag.equipment ?? emptyEquipment()),
442 JSON.stringify(migrated.equipment ?? emptyEquipment()),
425 bag.currency ?? 0,
443 JSON.stringify({ slots: vault.slots, reserved: vault.reserved }),
426 JSON.stringify(bag.vault ?? emptySlots()),
444 characterId
427 bag.vaultCurrency ?? 0,
445 );
446 }
447
448 getSkills (characterId)
449 {
450 const row = this.db.prepare("SELECT skills_blob FROM character_bags WHERE character_id = ?").get(characterId);
451 if (row)
452 { return normalizePlayerSkills(JSON.parse(row.skills_blob || "{}")); }
453 if (this.getCharacter(characterId))
454 {
455 this.#ensureBag(characterId);
456 return this.getSkills(characterId);
457 }
458 return null;
459 }
460
461 saveSkills (characterId, skills)
462 {
463 this.#ensureBag(characterId);
464 const xp = storedSkillXp(skills?.xp ? skills : { xp: skills });
465 this.db.prepare("UPDATE character_bags SET skills_blob = ? WHERE character_id = ?").run(
466 JSON.stringify({ xp }),
428 characterId
467 characterId
429 );
468 );
430 }
469 }
@@ -433,21 +472,22 @@ export class StateDatabase
433 {
472 {
434 const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
473 const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
435 if (!row)
474 if (!row)
436 { return { accountId, slots: emptySlots(), currency: 0 }; }
475 { return { accountId, slots: emptySlots() }; }
437 return {
476 return migrateInheritanceCoins({
438 accountId,
477 accountId,
439 slots: JSON.parse(row.slots_blob),
478 slots: JSON.parse(row.slots_blob),
440 currency: row.currency
479 currency: row.currency
441 };
480 });
442 }
481 }
443
482
444 saveInheritance (accountId, inheritance)
483 saveInheritance (accountId, inheritance)
445 {
484 {
485 const migrated = migrateInheritanceCoins(inheritance);
446 this.db.prepare(`
486 this.db.prepare(`
447 INSERT INTO account_inheritance (account_id, slots_blob, currency)
487 INSERT INTO account_inheritance (account_id, slots_blob, currency)
448 VALUES (?, ?, ?)
488 VALUES (?, ?, 0)
449 ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = excluded.currency
489 ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = 0
450 `).run(accountId, JSON.stringify(inheritance.slots ?? emptySlots()), inheritance.currency ?? 0);
490 `).run(accountId, JSON.stringify(migrated.slots ?? emptySlots()));
451 }
491 }
452
492
453 #moveGoodsToInheritance (character)
493 #moveGoodsToInheritance (character)
@@ -455,15 +495,35 @@ export class StateDatabase
455 const bag = this.getBag(character.character_id) ?? {
495 const bag = this.getBag(character.character_id) ?? {
456 inventory: emptySlots(),
496 inventory: emptySlots(),
457 equipment: emptyEquipment(),
497 equipment: emptyEquipment(),
458 currency: 0,
498 vault: [],
459 vault: emptySlots(),
499 vaultReserved: []
460 vaultCurrency: 0
461 };
500 };
462 const inheritance = this.getInheritance(character.account_id);
501 const inheritance = this.getInheritance(character.account_id);
502 const vault = normalizeVault(
503 bag.vaultReserved != null
504 ? { slots: bag.vault, reserved: bag.vaultReserved }
505 : bag.vault
506 );
507 // Void outstanding cheques issued by this character: reservations return to available vault.
508 for (const reserved of vault.reserved ?? [])
509 {
510 const stack = {
511 itemId: reserved.itemId,
512 quantity: reserved.quantity,
513 origin: reserved.origin ?? null,
514 instance: reserved.instance ?? null
515 };
516 const def = itemDefinition(stack.itemId);
517 if (!def)
518 { continue; }
519 const restored = insertStackGrowable(vault.slots, stack, def);
520 vault.slots = restored.slots;
521 }
522 vault.reserved = [];
463 const incoming = [
523 const incoming = [
464 ...(bag.inventory ?? []),
524 ...(bag.inventory ?? []),
465 ...Object.values(bag.equipment?.slots ?? {}),
525 ...Object.values(bag.equipment?.slots ?? {}),
466 ...(bag.vault ?? [])
526 ...(vault.slots ?? [])
467 ].filter(Boolean);
527 ].filter(Boolean);
468 let slots = inheritance.slots ?? emptySlots();
528 let slots = inheritance.slots ?? emptySlots();
469 for (const stack of incoming)
529 for (const stack of incoming)
@@ -486,8 +546,7 @@ export class StateDatabase
486 }
546 }
487 }
547 }
488 this.saveInheritance(character.account_id, {
548 this.saveInheritance(character.account_id, {
489 slots: publicSlots(slots),
549 slots: publicSlots(slots)
490 currency: (inheritance.currency ?? 0) + (bag.currency ?? 0) + (bag.vaultCurrency ?? 0)
491 });
550 });
492 }
551 }
493
552
@@ -630,14 +689,16 @@ function parseGroundItem (row)
630
689
631function parseBag (row, characterId)
690function parseBag (row, characterId)
632{
691{
633 return {
692 const vault = normalizeVault(JSON.parse(row.vault_blob));
693 return migrateBagCoins({
634 characterId,
694 characterId,
635 inventory: JSON.parse(row.inventory_blob),
695 inventory: normalizeInventorySlots(JSON.parse(row.inventory_blob)),
636 equipment: JSON.parse(row.equipment_blob),
696 equipment: JSON.parse(row.equipment_blob),
637 currency: row.currency,
697 currency: row.currency,
638 vault: JSON.parse(row.vault_blob),
698 vault: vault.slots,
699 vaultReserved: vault.reserved,
639 vaultCurrency: row.vault_currency
700 vaultCurrency: row.vault_currency
640 };
701 });
641}
702}
642
703
643function parseCourierTransit (row)
704function parseCourierTransit (row)
server/src/simulation/protocol.js +1 −0
@@ -20,6 +20,7 @@ export const WorkerMessage = Object.freeze({
20 20 entitiesInRegion: "entitiesInRegion",
21 21 inspect: "inspect",
22 22 inspectBag: "inspectBag",
23 inspectSkills: "inspectSkills",
23 24 applyBag: "applyBag",
24 25 updateFlight: "updateFlight",
25 26 chunkIsSimulating: "chunkIsSimulating",
@@ -20,6 +20,7 @@ export const WorkerMessage = Object.freeze({
20 entitiesInRegion: "entitiesInRegion",
20 entitiesInRegion: "entitiesInRegion",
21 inspect: "inspect",
21 inspect: "inspect",
22 inspectBag: "inspectBag",
22 inspectBag: "inspectBag",
23 inspectSkills: "inspectSkills",
23 applyBag: "applyBag",
24 applyBag: "applyBag",
24 updateFlight: "updateFlight",
25 updateFlight: "updateFlight",
25 chunkIsSimulating: "chunkIsSimulating",
26 chunkIsSimulating: "chunkIsSimulating",
server/src/simulation/simulation.js +96 −14
@@ -29,7 +29,8 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29 29 import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30 30 import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31 31 import { mobComponents } from "./spawners.js";
32 import { DEFAULT_PLAYER_SKILL_LEVELS } from "../../../shared/definitions/skills.js";
32 import { defaultPlayerSkills } from "../../../shared/skills/state.js";
33 import { playerMaxHealth } from "../../../shared/definitions/skills.js";
33 34 import { CourierService } from "../courier/service.js";
34 35
35 36 export class Simulation
@@ -72,6 +73,13 @@ export class Simulation
72 73 });
73 74 this.workers.push(worker);
74 75 }
76 for (const worker of this.workers)
77 {
78 if (!worker.world)
79 { continue; }
80 worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId);
81 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
82 }
75 83 this.courier = new CourierService({
76 84 stateDb: this.stateDb,
77 85 worldDb: this.worldDb,
@@ -154,8 +162,11 @@ export class Simulation
154 162 { this.#applyMoveToDirectory(event); }
155 163 if (event.type === "entity-despawn")
156 164 { this.#forget(event.entityId); }
165 if (event.type === "skills-updated")
166 { this.#applySkillsUpdated(event); }
157 167 this.#persistGroundEvent(event);
158 events.push(event);
168 if (event.type !== "skills-updated")
169 { events.push(event); }
159 170 }
160 171 for (const request of result?.transferRequests ?? [])
161 172 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
@@ -244,10 +255,11 @@ export class Simulation
244 255 const bag = this.stateDb.getBag(character.character_id) ?? {
245 256 inventory: emptySlots(),
246 257 equipment: emptyEquipment(),
247 currency: 0,
248 vault: emptySlots(),
249 vaultCurrency: 0
258 vault: [],
259 vaultReserved: []
250 260 };
261 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
262 const maxHealth = playerMaxHealth(skills);
251 263 const entityId = this.nextEntityId++;
252 264 const components = {
253 265 position: { tileX, tileY },
@@ -266,11 +278,13 @@ export class Simulation
266 278 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
267 279 inventory: { slots: bag.inventory ?? emptySlots() },
268 280 equipment: bag.equipment ?? emptyEquipment(),
269 currency: { amount: bag.currency ?? 0 },
270 vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 },
271 health: { current: 20, max: 20 },
281 vault: {
282 slots: bag.vault ?? [],
283 reserved: bag.vaultReserved ?? []
284 },
285 health: { current: maxHealth, max: maxHealth },
272 286 combat: { targetEntityId: null, nextSwingAt: 0 },
273 skills: { levels: { ...DEFAULT_PLAYER_SKILL_LEVELS } }
287 skills,
274 288 };
275 289 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
276 290 const workerId = this.#ownerOfTile(tileX, tileY);
@@ -406,6 +420,26 @@ export class Simulation
406 420 });
407 421 }
408 422
423 pushSkills (characterId, skills)
424 {
425 this.pendingPrivate.push({
426 type: "skills",
427 characterId,
428 skills
429 });
430 }
431
432 skillsOf (entityId)
433 {
434 const record = this.directory.get(entityId);
435 if (!record)
436 { return null; }
437 return this.workers[record.workerId].call({
438 type: WorkerMessage.inspectSkills,
439 entityId
440 });
441 }
442
409 443 pushInventory (characterId, bag)
410 444 {
411 445 this.pendingPrivate.push({
@@ -413,9 +447,8 @@ export class Simulation
413 447 characterId,
414 448 inventory: bag.inventory,
415 449 equipment: bag.equipment,
416 currency: bag.currency,
417 450 vault: bag.vault,
418 vaultCurrency: bag.vaultCurrency
451 vaultReserved: bag.vaultReserved
419 452 });
420 453 }
421 454
@@ -665,7 +698,7 @@ export class Simulation
665 698 {
666 699 this.stateDb.saveInheritance(
667 700 this.stateDb.getCharacter(item.command.characterId).account_id,
668 { slots: result.remainder, currency: 0 }
701 { slots: result.remainder }
669 702 );
670 703 }
671 704 for (const event of result?.events ?? [])
@@ -1128,6 +1161,20 @@ export class Simulation
1128 1161 if (!bag || !record?.characterId)
1129 1162 { return; }
1130 1163 this.#saveBagFromView(record.characterId, bag);
1164 const skills = this.workers[workerId].call({
1165 type: WorkerMessage.inspectSkills,
1166 entityId
1167 });
1168 if (skills)
1169 { this.stateDb.saveSkills(record.characterId, skills); }
1170 }
1171
1172 #applySkillsUpdated (event)
1173 {
1174 if (!event?.characterId || !event.stored)
1175 { return; }
1176 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
1177 this.pushSkills(event.characterId, event.skills ?? []);
1131 1178 }
1132 1179
1133 1180 #saveBagFromView (characterId, bag)
@@ -1135,12 +1182,47 @@ export class Simulation
1135 1182 this.stateDb.saveBag(characterId, {
1136 1183 inventory: bag.inventory,
1137 1184 equipment: bag.equipment,
1138 currency: bag.currency,
1139 1185 vault: bag.vault,
1140 vaultCurrency: bag.vaultCurrency
1186 vaultReserved: bag.vaultReserved
1141 1187 });
1142 1188 }
1143 1189
1190 releaseChequeReservation (issuerCharacterId, chequeId)
1191 {
1192 const onlineId = this.characterEntities.get(issuerCharacterId);
1193 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1194 if (!bag)
1195 { return { ok: false, error: "Issuer vault not found." }; }
1196 const reserved = [...(bag.vaultReserved ?? [])];
1197 const index = reserved.findIndex((entry) => entry?.chequeId === chequeId);
1198 if (index < 0)
1199 { return { ok: false, error: "That cheque cannot be redeemed." }; }
1200 const [stack] = reserved.splice(index, 1);
1201 bag.vaultReserved = reserved;
1202 this.stateDb.saveBag(issuerCharacterId, bag);
1203 if (onlineId)
1204 {
1205 this.applyBag(onlineId, bag);
1206 this.pushInventory(issuerCharacterId, bag);
1207 }
1208 return { ok: true, stack };
1209 }
1210
1211 restoreChequeReservation (issuerCharacterId, stack)
1212 {
1213 const onlineId = this.characterEntities.get(issuerCharacterId);
1214 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1215 if (!bag)
1216 { return; }
1217 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
1218 this.stateDb.saveBag(issuerCharacterId, bag);
1219 if (onlineId)
1220 {
1221 this.applyBag(onlineId, bag);
1222 this.pushInventory(issuerCharacterId, bag);
1223 }
1224 }
1225
1144 1226 #remember (view, workerId)
1145 1227 {
1146 1228 if (!view)
@@ -29,7 +29,8 @@ import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
29import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
30import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31import { mobComponents } from "./spawners.js";
31import { mobComponents } from "./spawners.js";
32import { DEFAULT_PLAYER_SKILL_LEVELS } from "../../../shared/definitions/skills.js";
32import { defaultPlayerSkills } from "../../../shared/skills/state.js";
33import { playerMaxHealth } from "../../../shared/definitions/skills.js";
33import { CourierService } from "../courier/service.js";
34import { CourierService } from "../courier/service.js";
34
35
35export class Simulation
36export class Simulation
@@ -72,6 +73,13 @@ export class Simulation
72 });
73 });
73 this.workers.push(worker);
74 this.workers.push(worker);
74 }
75 }
76 for (const worker of this.workers)
77 {
78 if (!worker.world)
79 { continue; }
80 worker.world.releaseChequeReservation = (issuerId, chequeId) => this.releaseChequeReservation(issuerId, chequeId);
81 worker.world.restoreChequeReservation = (issuerId, stack) => this.restoreChequeReservation(issuerId, stack);
82 }
75 this.courier = new CourierService({
83 this.courier = new CourierService({
76 stateDb: this.stateDb,
84 stateDb: this.stateDb,
77 worldDb: this.worldDb,
85 worldDb: this.worldDb,
@@ -154,8 +162,11 @@ export class Simulation
154 { this.#applyMoveToDirectory(event); }
162 { this.#applyMoveToDirectory(event); }
155 if (event.type === "entity-despawn")
163 if (event.type === "entity-despawn")
156 { this.#forget(event.entityId); }
164 { this.#forget(event.entityId); }
165 if (event.type === "skills-updated")
166 { this.#applySkillsUpdated(event); }
157 this.#persistGroundEvent(event);
167 this.#persistGroundEvent(event);
158 events.push(event);
168 if (event.type !== "skills-updated")
169 { events.push(event); }
159 }
170 }
160 for (const request of result?.transferRequests ?? [])
171 for (const request of result?.transferRequests ?? [])
161 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
172 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
@@ -244,10 +255,11 @@ export class Simulation
244 const bag = this.stateDb.getBag(character.character_id) ?? {
255 const bag = this.stateDb.getBag(character.character_id) ?? {
245 inventory: emptySlots(),
256 inventory: emptySlots(),
246 equipment: emptyEquipment(),
257 equipment: emptyEquipment(),
247 currency: 0,
258 vault: [],
248 vault: emptySlots(),
259 vaultReserved: []
249 vaultCurrency: 0
250 };
260 };
261 const skills = this.stateDb.getSkills(character.character_id) ?? defaultPlayerSkills();
262 const maxHealth = playerMaxHealth(skills);
251 const entityId = this.nextEntityId++;
263 const entityId = this.nextEntityId++;
252 const components = {
264 const components = {
253 position: { tileX, tileY },
265 position: { tileX, tileY },
@@ -266,11 +278,13 @@ export class Simulation
266 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
278 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
267 inventory: { slots: bag.inventory ?? emptySlots() },
279 inventory: { slots: bag.inventory ?? emptySlots() },
268 equipment: bag.equipment ?? emptyEquipment(),
280 equipment: bag.equipment ?? emptyEquipment(),
269 currency: { amount: bag.currency ?? 0 },
281 vault: {
270 vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 },
282 slots: bag.vault ?? [],
271 health: { current: 20, max: 20 },
283 reserved: bag.vaultReserved ?? []
284 },
285 health: { current: maxHealth, max: maxHealth },
272 combat: { targetEntityId: null, nextSwingAt: 0 },
286 combat: { targetEntityId: null, nextSwingAt: 0 },
273 skills: { levels: { ...DEFAULT_PLAYER_SKILL_LEVELS } }
287 skills,
274 };
288 };
275 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
289 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
276 const workerId = this.#ownerOfTile(tileX, tileY);
290 const workerId = this.#ownerOfTile(tileX, tileY);
@@ -406,6 +420,26 @@ export class Simulation
406 });
420 });
407 }
421 }
408
422
423 pushSkills (characterId, skills)
424 {
425 this.pendingPrivate.push({
426 type: "skills",
427 characterId,
428 skills
429 });
430 }
431
432 skillsOf (entityId)
433 {
434 const record = this.directory.get(entityId);
435 if (!record)
436 { return null; }
437 return this.workers[record.workerId].call({
438 type: WorkerMessage.inspectSkills,
439 entityId
440 });
441 }
442
409 pushInventory (characterId, bag)
443 pushInventory (characterId, bag)
410 {
444 {
411 this.pendingPrivate.push({
445 this.pendingPrivate.push({
@@ -413,9 +447,8 @@ export class Simulation
413 characterId,
447 characterId,
414 inventory: bag.inventory,
448 inventory: bag.inventory,
415 equipment: bag.equipment,
449 equipment: bag.equipment,
416 currency: bag.currency,
417 vault: bag.vault,
450 vault: bag.vault,
418 vaultCurrency: bag.vaultCurrency
451 vaultReserved: bag.vaultReserved
419 });
452 });
420 }
453 }
421
454
@@ -665,7 +698,7 @@ export class Simulation
665 {
698 {
666 this.stateDb.saveInheritance(
699 this.stateDb.saveInheritance(
667 this.stateDb.getCharacter(item.command.characterId).account_id,
700 this.stateDb.getCharacter(item.command.characterId).account_id,
668 { slots: result.remainder, currency: 0 }
701 { slots: result.remainder }
669 );
702 );
670 }
703 }
671 for (const event of result?.events ?? [])
704 for (const event of result?.events ?? [])
@@ -1128,6 +1161,20 @@ export class Simulation
1128 if (!bag || !record?.characterId)
1161 if (!bag || !record?.characterId)
1129 { return; }
1162 { return; }
1130 this.#saveBagFromView(record.characterId, bag);
1163 this.#saveBagFromView(record.characterId, bag);
1164 const skills = this.workers[workerId].call({
1165 type: WorkerMessage.inspectSkills,
1166 entityId
1167 });
1168 if (skills)
1169 { this.stateDb.saveSkills(record.characterId, skills); }
1170 }
1171
1172 #applySkillsUpdated (event)
1173 {
1174 if (!event?.characterId || !event.stored)
1175 { return; }
1176 this.stateDb.saveSkills(event.characterId, { xp: event.stored });
1177 this.pushSkills(event.characterId, event.skills ?? []);
1131 }
1178 }
1132
1179
1133 #saveBagFromView (characterId, bag)
1180 #saveBagFromView (characterId, bag)
@@ -1135,12 +1182,47 @@ export class Simulation
1135 this.stateDb.saveBag(characterId, {
1182 this.stateDb.saveBag(characterId, {
1136 inventory: bag.inventory,
1183 inventory: bag.inventory,
1137 equipment: bag.equipment,
1184 equipment: bag.equipment,
1138 currency: bag.currency,
1139 vault: bag.vault,
1185 vault: bag.vault,
1140 vaultCurrency: bag.vaultCurrency
1186 vaultReserved: bag.vaultReserved
1141 });
1187 });
1142 }
1188 }
1143
1189
1190 releaseChequeReservation (issuerCharacterId, chequeId)
1191 {
1192 const onlineId = this.characterEntities.get(issuerCharacterId);
1193 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1194 if (!bag)
1195 { return { ok: false, error: "Issuer vault not found." }; }
1196 const reserved = [...(bag.vaultReserved ?? [])];
1197 const index = reserved.findIndex((entry) => entry?.chequeId === chequeId);
1198 if (index < 0)
1199 { return { ok: false, error: "That cheque cannot be redeemed." }; }
1200 const [stack] = reserved.splice(index, 1);
1201 bag.vaultReserved = reserved;
1202 this.stateDb.saveBag(issuerCharacterId, bag);
1203 if (onlineId)
1204 {
1205 this.applyBag(onlineId, bag);
1206 this.pushInventory(issuerCharacterId, bag);
1207 }
1208 return { ok: true, stack };
1209 }
1210
1211 restoreChequeReservation (issuerCharacterId, stack)
1212 {
1213 const onlineId = this.characterEntities.get(issuerCharacterId);
1214 const bag = onlineId ? this.bagOf(onlineId) : this.stateDb.getBag(issuerCharacterId);
1215 if (!bag)
1216 { return; }
1217 bag.vaultReserved = [...(bag.vaultReserved ?? []), stack];
1218 this.stateDb.saveBag(issuerCharacterId, bag);
1219 if (onlineId)
1220 {
1221 this.applyBag(onlineId, bag);
1222 this.pushInventory(issuerCharacterId, bag);
1223 }
1224 }
1225
1144 #remember (view, workerId)
1226 #remember (view, workerId)
1145 {
1227 {
1146 if (!view)
1228 if (!view)
server/src/simulation/spawners.js +3 −2
@@ -1,5 +1,6 @@
1 1 import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2 2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";
3 4 import {
4 5 defaultSpawnerConfig,
5 6 listAmbientMobTypes,
@@ -80,10 +81,10 @@ export function mobComponents (request)
80 81 lastAt: 0
81 82 };
82 83 }
83 if (!def.untargetable && (def.hostile || def.defaultAttack || def.skillLevels))
84 if (mobCanFight(def))
84 85 {
85 86 components.combat = { targetEntityId: null, nextSwingAt: 0 };
86 components.skills = { levels: { ...(def.skillLevels ?? {}) } };
87 components.skills = { levels: mobSkillLevels(def) };
87 88 }
88 89 return components;
89 90 }
@@ -1,5 +1,6 @@
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { mobCanFight, mobSkillLevels } from "../../../shared/definitions/mobCombat.js";
3import {
4import {
4 defaultSpawnerConfig,
5 defaultSpawnerConfig,
5 listAmbientMobTypes,
6 listAmbientMobTypes,
@@ -80,10 +81,10 @@ export function mobComponents (request)
80 lastAt: 0
81 lastAt: 0
81 };
82 };
82 }
83 }
83 if (!def.untargetable && (def.hostile || def.defaultAttack || def.skillLevels))
84 if (mobCanFight(def))
84 {
85 {
85 components.combat = { targetEntityId: null, nextSwingAt: 0 };
86 components.combat = { targetEntityId: null, nextSwingAt: 0 };
86 components.skills = { levels: { ...(def.skillLevels ?? {}) } };
87 components.skills = { levels: mobSkillLevels(def) };
87 }
88 }
88 return components;
89 return components;
89}
90}
server/src/simulation/workerWorld.js +18 −1
@@ -31,6 +31,7 @@ import {
31 31 import {
32 32 clearEngage,
33 33 engageTarget,
34 ensureMobCombat,
34 35 isUntargetable,
35 36 stepCombat
36 37 } from "../combat/service.js";
@@ -93,6 +94,8 @@ export class WorkerWorld
93 94 return { ok: true };
94 95 case WorkerMessage.inspectBag:
95 96 return this.#inspectBag(message.entityId);
97 case WorkerMessage.inspectSkills:
98 return this.#inspectSkills(message.entityId);
96 99 case WorkerMessage.applyBag:
97 100 return this.#applyBag(message.entityId, message.bag);
98 101 case WorkerMessage.updateFlight:
@@ -183,6 +186,9 @@ export class WorkerWorld
183 186 const dropped = [];
184 187 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
185 188 {
189 const components = record.payload?.components;
190 if (components?.creature && !components?.character && components?.health)
191 { components.health.current = components.health.max; }
186 192 dropped.push(record);
187 193 this.#destroyEntity(record.entityId);
188 194 }
@@ -352,6 +358,17 @@ export class WorkerWorld
352 358 return bagView(this.ecs, handle);
353 359 }
354 360
361 #inspectSkills (entityId)
362 {
363 const handle = this.ecs.handleOf(entityId);
364 if (handle == null)
365 { return null; }
366 const skills = this.ecs.get(handle, Component.skills);
367 if (!skills?.xp)
368 { return null; }
369 return skills;
370 }
371
355 372 #applyBag (entityId, bag)
356 373 {
357 374 const handle = this.ecs.handleOf(entityId);
@@ -476,7 +493,7 @@ export class WorkerWorld
476 493 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
477 494 clearFollow(this.ecs, entityId);
478 495 engageTarget(this.ecs, entityId, targetEntityId, now);
479 if (this.ecs.get(targetHandle, Component.combat))
496 if (ensureMobCombat(this.ecs, targetEntityId))
480 497 { engageTarget(this.ecs, targetEntityId, entityId, now); }
481 498 const path = this.ecs.get(handle, Component.path);
482 499 if (path)
@@ -31,6 +31,7 @@ import {
31import {
31import {
32 clearEngage,
32 clearEngage,
33 engageTarget,
33 engageTarget,
34 ensureMobCombat,
34 isUntargetable,
35 isUntargetable,
35 stepCombat
36 stepCombat
36} from "../combat/service.js";
37} from "../combat/service.js";
@@ -93,6 +94,8 @@ export class WorkerWorld
93 return { ok: true };
94 return { ok: true };
94 case WorkerMessage.inspectBag:
95 case WorkerMessage.inspectBag:
95 return this.#inspectBag(message.entityId);
96 return this.#inspectBag(message.entityId);
97 case WorkerMessage.inspectSkills:
98 return this.#inspectSkills(message.entityId);
96 case WorkerMessage.applyBag:
99 case WorkerMessage.applyBag:
97 return this.#applyBag(message.entityId, message.bag);
100 return this.#applyBag(message.entityId, message.bag);
98 case WorkerMessage.updateFlight:
101 case WorkerMessage.updateFlight:
@@ -183,6 +186,9 @@ export class WorkerWorld
183 const dropped = [];
186 const dropped = [];
184 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
187 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
185 {
188 {
189 const components = record.payload?.components;
190 if (components?.creature && !components?.character && components?.health)
191 { components.health.current = components.health.max; }
186 dropped.push(record);
192 dropped.push(record);
187 this.#destroyEntity(record.entityId);
193 this.#destroyEntity(record.entityId);
188 }
194 }
@@ -352,6 +358,17 @@ export class WorkerWorld
352 return bagView(this.ecs, handle);
358 return bagView(this.ecs, handle);
353 }
359 }
354
360
361 #inspectSkills (entityId)
362 {
363 const handle = this.ecs.handleOf(entityId);
364 if (handle == null)
365 { return null; }
366 const skills = this.ecs.get(handle, Component.skills);
367 if (!skills?.xp)
368 { return null; }
369 return skills;
370 }
371
355 #applyBag (entityId, bag)
372 #applyBag (entityId, bag)
356 {
373 {
357 const handle = this.ecs.handleOf(entityId);
374 const handle = this.ecs.handleOf(entityId);
@@ -476,7 +493,7 @@ export class WorkerWorld
476 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
493 { this.ecs.add(handle, Component.combat, { targetEntityId: null, nextSwingAt: 0 }); }
477 clearFollow(this.ecs, entityId);
494 clearFollow(this.ecs, entityId);
478 engageTarget(this.ecs, entityId, targetEntityId, now);
495 engageTarget(this.ecs, entityId, targetEntityId, now);
479 if (this.ecs.get(targetHandle, Component.combat))
496 if (ensureMobCombat(this.ecs, targetEntityId))
480 { engageTarget(this.ecs, targetEntityId, entityId, now); }
497 { engageTarget(this.ecs, targetEntityId, entityId, now); }
481 const path = this.ecs.get(handle, Component.path);
498 const path = this.ecs.get(handle, Component.path);
482 if (path)
499 if (path)
server/src/skills/service.js added +55 −0
@@ -0,0 +1,55 @@
1 import { Component } from "../ecs/components.js";
2 import { SkillId, playerMaxHealth } from "../../../shared/definitions/skills.js";
3 import { combatHitXpPerSkill } from "../../../shared/skills/progression.js";
4 import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
5
6 export function syncPlayerHealth (ecs, handle)
7 {
8 const character = ecs.get(handle, Component.character);
9 if (!character)
10 { return; }
11 const skills = ecs.get(handle, Component.skills);
12 const health = ecs.get(handle, Component.health);
13 if (!skills || !health)
14 { return; }
15 const max = playerMaxHealth(skills);
16 health.max = max;
17 health.current = Math.min(health.current | 0, max);
18 }
19
20 export function awardCombatHitXp (ecs, attackerHandle, profile)
21 {
22 const skills = ecs.get(attackerHandle, Component.skills);
23 if (!skills?.xp)
24 { return null; }
25 const perSkill = combatHitXpPerSkill();
26 const hit = addSkillXp(skills, profile.hitSkillId, perSkill);
27 const damage = addSkillXp(skills, profile.damageSkillId, perSkill);
28 if (!hit && !damage)
29 { return null; }
30 return {
31 view: publicSkillsView(skills),
32 stored: storedSkillXp(skills)
33 };
34 }
35
36 export function awardDamageHealthXp (ecs, targetHandle, damage)
37 {
38 const amount = Math.max(0, Math.floor(Number(damage) || 0));
39 if (!amount)
40 { return null; }
41 const character = ecs.get(targetHandle, Component.character);
42 if (!character)
43 { return null; }
44 const skills = ecs.get(targetHandle, Component.skills);
45 if (!skills?.xp)
46 { return null; }
47 if (!addSkillXp(skills, SkillId.health, amount))
48 { return null; }
49 syncPlayerHealth(ecs, targetHandle);
50 return {
51 characterId: character.characterId,
52 view: publicSkillsView(skills),
53 stored: storedSkillXp(skills)
54 };
55 }
@@ -0,0 +1,55 @@
1import { Component } from "../ecs/components.js";
2import { SkillId, playerMaxHealth } from "../../../shared/definitions/skills.js";
3import { combatHitXpPerSkill } from "../../../shared/skills/progression.js";
4import { addSkillXp, publicSkillsView, storedSkillXp } from "../../../shared/skills/state.js";
5
6export function syncPlayerHealth (ecs, handle)
7{
8 const character = ecs.get(handle, Component.character);
9 if (!character)
10 { return; }
11 const skills = ecs.get(handle, Component.skills);
12 const health = ecs.get(handle, Component.health);
13 if (!skills || !health)
14 { return; }
15 const max = playerMaxHealth(skills);
16 health.max = max;
17 health.current = Math.min(health.current | 0, max);
18}
19
20export function awardCombatHitXp (ecs, attackerHandle, profile)
21{
22 const skills = ecs.get(attackerHandle, Component.skills);
23 if (!skills?.xp)
24 { return null; }
25 const perSkill = combatHitXpPerSkill();
26 const hit = addSkillXp(skills, profile.hitSkillId, perSkill);
27 const damage = addSkillXp(skills, profile.damageSkillId, perSkill);
28 if (!hit && !damage)
29 { return null; }
30 return {
31 view: publicSkillsView(skills),
32 stored: storedSkillXp(skills)
33 };
34}
35
36export function awardDamageHealthXp (ecs, targetHandle, damage)
37{
38 const amount = Math.max(0, Math.floor(Number(damage) || 0));
39 if (!amount)
40 { return null; }
41 const character = ecs.get(targetHandle, Component.character);
42 if (!character)
43 { return null; }
44 const skills = ecs.get(targetHandle, Component.skills);
45 if (!skills?.xp)
46 { return null; }
47 if (!addSkillXp(skills, SkillId.health, amount))
48 { return null; }
49 syncPlayerHealth(ecs, targetHandle);
50 return {
51 characterId: character.characterId,
52 view: publicSkillsView(skills),
53 stored: storedSkillXp(skills)
54 };
55}
server/tests/bank.test.js added +291 −0
@@ -0,0 +1,291 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { BlockType } from "../../shared/definitions/tiles.js";
4 import { ItemId } from "../../shared/definitions/items.js";
5 import { emptyEquipment } from "../../shared/items/inventory.js";
6 import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
7 import {
8 makeCharacter,
9 makeSimulation
10 } from "./helpers/simulationHarness.js";
11
12 function placeBank (worldDb, tileX, tileY)
13 {
14 const chunkX = Math.floor(tileX / 16);
15 const chunkY = Math.floor(tileY / 16);
16 const data = createEmptyChunkData();
17 data.open = true;
18 const localX = tileX - chunkX * 16;
19 const localY = tileY - chunkY * 16;
20 data.blocks[localY * 16 + localX] = { typeId: BlockType.bank, state: 0 };
21 worldDb.saveChunkVersion(
22 chunkX,
23 chunkY,
24 worldDb.getActiveRevisionId(),
25 true,
26 encodeChunkBlob(data)
27 );
28 }
29
30 function countItem (slots, itemId)
31 {
32 return (slots ?? [])
33 .filter((slot) => slot?.itemId === itemId)
34 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
35 }
36
37 test("blank cheques top up inventory to 99 at a bank", () =>
38 {
39 const harness = makeSimulation({ workerCount: 1 });
40 try
41 {
42 placeBank(harness.worldDb, 8, 8);
43 harness.simulation.reloadWorld();
44 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
45 const entityId = harness.simulation.spawnCharacter(1, character);
46 harness.simulation.enqueue(1, {
47 type: "get-blank-cheques",
48 characterId: character.character_id
49 });
50 harness.simulation.step();
51 const bag = harness.simulation.bagOf(entityId);
52 assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99);
53 }
54 finally
55 { harness.close(); }
56 });
57
58 test("bank deposit and withdraw move stacks with quantity", () =>
59 {
60 const harness = makeSimulation({ workerCount: 1 });
61 try
62 {
63 placeBank(harness.worldDb, 8, 8);
64 harness.simulation.reloadWorld();
65 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
66 const entityId = harness.simulation.spawnCharacter(1, character);
67 const before = harness.simulation.bagOf(entityId);
68 const appleIndex = before.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
69 assert.ok(appleIndex >= 0);
70 const qty = before.inventory[appleIndex].quantity;
71 harness.simulation.enqueue(1, {
72 type: "bank-deposit",
73 characterId: character.character_id,
74 slotIndex: appleIndex,
75 quantity: 1
76 });
77 harness.simulation.step();
78 let bag = harness.simulation.bagOf(entityId);
79 assert.equal(countItem(bag.vault, ItemId.apple), 1);
80 assert.equal(bag.inventory[appleIndex]?.quantity ?? 0, qty - 1);
81 const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple);
82 harness.simulation.enqueue(1, {
83 type: "bank-withdraw",
84 characterId: character.character_id,
85 slotIndex: vaultIndex,
86 quantity: 1
87 });
88 harness.simulation.step();
89 bag = harness.simulation.bagOf(entityId);
90 assert.equal(countItem(bag.vault, ItemId.apple), 0);
91 }
92 finally
93 { harness.close(); }
94 });
95
96 test("write cheque reserves vault goods and redeem returns them", () =>
97 {
98 const harness = makeSimulation({ workerCount: 1 });
99 try
100 {
101 placeBank(harness.worldDb, 8, 8);
102 harness.simulation.reloadWorld();
103 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
104 const entityId = harness.simulation.spawnCharacter(1, character);
105 harness.simulation.enqueue(1, {
106 type: "get-blank-cheques",
107 characterId: character.character_id
108 });
109 harness.simulation.step();
110 let bag = harness.simulation.bagOf(entityId);
111 const appleIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
112 harness.simulation.enqueue(1, {
113 type: "bank-deposit",
114 characterId: character.character_id,
115 slotIndex: appleIndex,
116 quantity: null
117 });
118 harness.simulation.step();
119 bag = harness.simulation.bagOf(entityId);
120 const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
121 const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple);
122 harness.simulation.enqueue(1, {
123 type: "write-cheque",
124 characterId: character.character_id,
125 slotIndex: blankIndex,
126 vaultSlotIndex: vaultIndex,
127 quantity: 2
128 });
129 harness.simulation.step();
130 bag = harness.simulation.bagOf(entityId);
131 assert.equal((bag.vaultReserved ?? []).length, 1);
132 assert.equal(bag.vaultReserved[0].quantity, 2);
133 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
134 assert.ok(chequeIndex >= 0);
135 harness.simulation.enqueue(1, {
136 type: "redeem-cheque",
137 characterId: character.character_id,
138 slotIndex: chequeIndex
139 });
140 harness.simulation.step();
141 bag = harness.simulation.bagOf(entityId);
142 assert.equal((bag.vaultReserved ?? []).length, 0);
143 assert.ok(countItem(bag.vault, ItemId.apple) >= 2);
144 }
145 finally
146 { harness.close(); }
147 });
148
149 test("bank deposit of a filled cheque redeems reserved goods", () =>
150 {
151 const harness = makeSimulation({ workerCount: 1 });
152 try
153 {
154 placeBank(harness.worldDb, 8, 8);
155 harness.simulation.reloadWorld();
156 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
157 const entityId = harness.simulation.spawnCharacter(1, character);
158 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
159 harness.simulation.step();
160 let bag = harness.simulation.bagOf(entityId);
161 const appleIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
162 harness.simulation.enqueue(1, {
163 type: "bank-deposit",
164 characterId: character.character_id,
165 slotIndex: appleIndex,
166 quantity: null
167 });
168 harness.simulation.step();
169 bag = harness.simulation.bagOf(entityId);
170 const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
171 const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple);
172 harness.simulation.enqueue(1, {
173 type: "write-cheque",
174 characterId: character.character_id,
175 slotIndex: blankIndex,
176 vaultSlotIndex: vaultIndex,
177 quantity: 2
178 });
179 harness.simulation.step();
180 bag = harness.simulation.bagOf(entityId);
181 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
182 assert.ok(chequeIndex >= 0);
183 harness.simulation.enqueue(1, {
184 type: "bank-deposit",
185 characterId: character.character_id,
186 slotIndex: chequeIndex,
187 quantity: null
188 });
189 harness.simulation.step();
190 bag = harness.simulation.bagOf(entityId);
191 assert.equal(bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque), -1);
192 assert.equal((bag.vaultReserved ?? []).length, 0);
193 assert.ok(countItem(bag.vault, ItemId.apple) >= 2);
194 }
195 finally
196 { harness.close(); }
197 });
198
199 test("new characters start with coin stacks in inventory", () =>
200 {
201 const harness = makeSimulation({ workerCount: 1 });
202 try
203 {
204 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
205 const bag = harness.stateDb.getBag(character.character_id);
206 assert.equal(countItem(bag.inventory, ItemId.coins), 25);
207 }
208 finally
209 { harness.close(); }
210 });
211
212 test("legacy currency counters migrate into coin stacks", () =>
213 {
214 const harness = makeSimulation({ workerCount: 1 });
215 try
216 {
217 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
218 harness.stateDb.saveBag(character.character_id, {
219 inventory: [],
220 equipment: emptyEquipment(),
221 currency: 100,
222 vault: [],
223 vaultReserved: [],
224 vaultCurrency: 50
225 });
226 const bag = harness.stateDb.getBag(character.character_id);
227 assert.equal(countItem(bag.inventory, ItemId.coins), 100);
228 assert.equal(countItem(bag.vault, ItemId.coins), 50);
229 }
230 finally
231 { harness.close(); }
232 });
233
234 test("stored inventory with excess blank cheques is capped on load", () =>
235 {
236 const harness = makeSimulation({ workerCount: 1 });
237 try
238 {
239 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
240 harness.stateDb.saveBag(character.character_id, {
241 inventory: [{ itemId: ItemId.blankCheque, quantity: 120 }],
242 equipment: emptyEquipment(),
243 vault: [],
244 vaultReserved: []
245 });
246 const bag = harness.stateDb.getBag(character.character_id);
247 assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99);
248 }
249 finally
250 { harness.close(); }
251 });
252 test("blank cheque ground pickup stops at 99 carried", () =>
253 {
254 const harness = makeSimulation({ workerCount: 1 });
255 try
256 {
257 placeBank(harness.worldDb, 8, 8);
258 harness.simulation.reloadWorld();
259 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
260 const entityId = harness.simulation.spawnCharacter(1, character);
261 harness.simulation.enqueue(1, {
262 type: "get-blank-cheques",
263 characterId: character.character_id
264 });
265 harness.simulation.step();
266 let bag = harness.simulation.bagOf(entityId);
267 const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
268 assert.ok(blankIndex >= 0);
269 harness.simulation.enqueue(1, {
270 type: "drop-item",
271 characterId: character.character_id,
272 slotIndex: blankIndex,
273 quantity: 10
274 });
275 const dropEvents = harness.simulation.step().events;
276 const appear = dropEvents.find((event) => event.type === "ground-item-appear");
277 assert.ok(appear);
278 harness.simulation.enqueue(1, {
279 type: "pickup-item",
280 characterId: character.character_id,
281 groundItemId: appear.groundItemId
282 });
283 harness.simulation.step();
284 bag = harness.simulation.bagOf(entityId);
285 assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99);
286 const snapshot = harness.simulation.snapshotChunk(0, 0);
287 assert.equal((snapshot.groundItems ?? []).length, 0);
288 }
289 finally
290 { harness.close(); }
291 });
@@ -0,0 +1,291 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { BlockType } from "../../shared/definitions/tiles.js";
4import { ItemId } from "../../shared/definitions/items.js";
5import { emptyEquipment } from "../../shared/items/inventory.js";
6import { createEmptyChunkData, encodeChunkBlob } from "../src/world/chunkData.js";
7import {
8 makeCharacter,
9 makeSimulation
10} from "./helpers/simulationHarness.js";
11
12function placeBank (worldDb, tileX, tileY)
13{
14 const chunkX = Math.floor(tileX / 16);
15 const chunkY = Math.floor(tileY / 16);
16 const data = createEmptyChunkData();
17 data.open = true;
18 const localX = tileX - chunkX * 16;
19 const localY = tileY - chunkY * 16;
20 data.blocks[localY * 16 + localX] = { typeId: BlockType.bank, state: 0 };
21 worldDb.saveChunkVersion(
22 chunkX,
23 chunkY,
24 worldDb.getActiveRevisionId(),
25 true,
26 encodeChunkBlob(data)
27 );
28}
29
30function countItem (slots, itemId)
31{
32 return (slots ?? [])
33 .filter((slot) => slot?.itemId === itemId)
34 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
35}
36
37test("blank cheques top up inventory to 99 at a bank", () =>
38{
39 const harness = makeSimulation({ workerCount: 1 });
40 try
41 {
42 placeBank(harness.worldDb, 8, 8);
43 harness.simulation.reloadWorld();
44 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
45 const entityId = harness.simulation.spawnCharacter(1, character);
46 harness.simulation.enqueue(1, {
47 type: "get-blank-cheques",
48 characterId: character.character_id
49 });
50 harness.simulation.step();
51 const bag = harness.simulation.bagOf(entityId);
52 assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99);
53 }
54 finally
55 { harness.close(); }
56});
57
58test("bank deposit and withdraw move stacks with quantity", () =>
59{
60 const harness = makeSimulation({ workerCount: 1 });
61 try
62 {
63 placeBank(harness.worldDb, 8, 8);
64 harness.simulation.reloadWorld();
65 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
66 const entityId = harness.simulation.spawnCharacter(1, character);
67 const before = harness.simulation.bagOf(entityId);
68 const appleIndex = before.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
69 assert.ok(appleIndex >= 0);
70 const qty = before.inventory[appleIndex].quantity;
71 harness.simulation.enqueue(1, {
72 type: "bank-deposit",
73 characterId: character.character_id,
74 slotIndex: appleIndex,
75 quantity: 1
76 });
77 harness.simulation.step();
78 let bag = harness.simulation.bagOf(entityId);
79 assert.equal(countItem(bag.vault, ItemId.apple), 1);
80 assert.equal(bag.inventory[appleIndex]?.quantity ?? 0, qty - 1);
81 const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple);
82 harness.simulation.enqueue(1, {
83 type: "bank-withdraw",
84 characterId: character.character_id,
85 slotIndex: vaultIndex,
86 quantity: 1
87 });
88 harness.simulation.step();
89 bag = harness.simulation.bagOf(entityId);
90 assert.equal(countItem(bag.vault, ItemId.apple), 0);
91 }
92 finally
93 { harness.close(); }
94});
95
96test("write cheque reserves vault goods and redeem returns them", () =>
97{
98 const harness = makeSimulation({ workerCount: 1 });
99 try
100 {
101 placeBank(harness.worldDb, 8, 8);
102 harness.simulation.reloadWorld();
103 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
104 const entityId = harness.simulation.spawnCharacter(1, character);
105 harness.simulation.enqueue(1, {
106 type: "get-blank-cheques",
107 characterId: character.character_id
108 });
109 harness.simulation.step();
110 let bag = harness.simulation.bagOf(entityId);
111 const appleIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
112 harness.simulation.enqueue(1, {
113 type: "bank-deposit",
114 characterId: character.character_id,
115 slotIndex: appleIndex,
116 quantity: null
117 });
118 harness.simulation.step();
119 bag = harness.simulation.bagOf(entityId);
120 const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
121 const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple);
122 harness.simulation.enqueue(1, {
123 type: "write-cheque",
124 characterId: character.character_id,
125 slotIndex: blankIndex,
126 vaultSlotIndex: vaultIndex,
127 quantity: 2
128 });
129 harness.simulation.step();
130 bag = harness.simulation.bagOf(entityId);
131 assert.equal((bag.vaultReserved ?? []).length, 1);
132 assert.equal(bag.vaultReserved[0].quantity, 2);
133 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
134 assert.ok(chequeIndex >= 0);
135 harness.simulation.enqueue(1, {
136 type: "redeem-cheque",
137 characterId: character.character_id,
138 slotIndex: chequeIndex
139 });
140 harness.simulation.step();
141 bag = harness.simulation.bagOf(entityId);
142 assert.equal((bag.vaultReserved ?? []).length, 0);
143 assert.ok(countItem(bag.vault, ItemId.apple) >= 2);
144 }
145 finally
146 { harness.close(); }
147});
148
149test("bank deposit of a filled cheque redeems reserved goods", () =>
150{
151 const harness = makeSimulation({ workerCount: 1 });
152 try
153 {
154 placeBank(harness.worldDb, 8, 8);
155 harness.simulation.reloadWorld();
156 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
157 const entityId = harness.simulation.spawnCharacter(1, character);
158 harness.simulation.enqueue(1, { type: "get-blank-cheques", characterId: character.character_id });
159 harness.simulation.step();
160 let bag = harness.simulation.bagOf(entityId);
161 const appleIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
162 harness.simulation.enqueue(1, {
163 type: "bank-deposit",
164 characterId: character.character_id,
165 slotIndex: appleIndex,
166 quantity: null
167 });
168 harness.simulation.step();
169 bag = harness.simulation.bagOf(entityId);
170 const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
171 const vaultIndex = bag.vault.findIndex((slot) => slot?.itemId === ItemId.apple);
172 harness.simulation.enqueue(1, {
173 type: "write-cheque",
174 characterId: character.character_id,
175 slotIndex: blankIndex,
176 vaultSlotIndex: vaultIndex,
177 quantity: 2
178 });
179 harness.simulation.step();
180 bag = harness.simulation.bagOf(entityId);
181 const chequeIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque);
182 assert.ok(chequeIndex >= 0);
183 harness.simulation.enqueue(1, {
184 type: "bank-deposit",
185 characterId: character.character_id,
186 slotIndex: chequeIndex,
187 quantity: null
188 });
189 harness.simulation.step();
190 bag = harness.simulation.bagOf(entityId);
191 assert.equal(bag.inventory.findIndex((slot) => slot?.itemId === ItemId.filledCheque), -1);
192 assert.equal((bag.vaultReserved ?? []).length, 0);
193 assert.ok(countItem(bag.vault, ItemId.apple) >= 2);
194 }
195 finally
196 { harness.close(); }
197});
198
199test("new characters start with coin stacks in inventory", () =>
200{
201 const harness = makeSimulation({ workerCount: 1 });
202 try
203 {
204 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
205 const bag = harness.stateDb.getBag(character.character_id);
206 assert.equal(countItem(bag.inventory, ItemId.coins), 25);
207 }
208 finally
209 { harness.close(); }
210});
211
212test("legacy currency counters migrate into coin stacks", () =>
213{
214 const harness = makeSimulation({ workerCount: 1 });
215 try
216 {
217 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
218 harness.stateDb.saveBag(character.character_id, {
219 inventory: [],
220 equipment: emptyEquipment(),
221 currency: 100,
222 vault: [],
223 vaultReserved: [],
224 vaultCurrency: 50
225 });
226 const bag = harness.stateDb.getBag(character.character_id);
227 assert.equal(countItem(bag.inventory, ItemId.coins), 100);
228 assert.equal(countItem(bag.vault, ItemId.coins), 50);
229 }
230 finally
231 { harness.close(); }
232});
233
234test("stored inventory with excess blank cheques is capped on load", () =>
235{
236 const harness = makeSimulation({ workerCount: 1 });
237 try
238 {
239 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
240 harness.stateDb.saveBag(character.character_id, {
241 inventory: [{ itemId: ItemId.blankCheque, quantity: 120 }],
242 equipment: emptyEquipment(),
243 vault: [],
244 vaultReserved: []
245 });
246 const bag = harness.stateDb.getBag(character.character_id);
247 assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99);
248 }
249 finally
250 { harness.close(); }
251});
252test("blank cheque ground pickup stops at 99 carried", () =>
253{
254 const harness = makeSimulation({ workerCount: 1 });
255 try
256 {
257 placeBank(harness.worldDb, 8, 8);
258 harness.simulation.reloadWorld();
259 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
260 const entityId = harness.simulation.spawnCharacter(1, character);
261 harness.simulation.enqueue(1, {
262 type: "get-blank-cheques",
263 characterId: character.character_id
264 });
265 harness.simulation.step();
266 let bag = harness.simulation.bagOf(entityId);
267 const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
268 assert.ok(blankIndex >= 0);
269 harness.simulation.enqueue(1, {
270 type: "drop-item",
271 characterId: character.character_id,
272 slotIndex: blankIndex,
273 quantity: 10
274 });
275 const dropEvents = harness.simulation.step().events;
276 const appear = dropEvents.find((event) => event.type === "ground-item-appear");
277 assert.ok(appear);
278 harness.simulation.enqueue(1, {
279 type: "pickup-item",
280 characterId: character.character_id,
281 groundItemId: appear.groundItemId
282 });
283 harness.simulation.step();
284 bag = harness.simulation.bagOf(entityId);
285 assert.equal(countItem(bag.inventory, ItemId.blankCheque), 99);
286 const snapshot = harness.simulation.snapshotChunk(0, 0);
287 assert.equal((snapshot.groundItems ?? []).length, 0);
288 }
289 finally
290 { harness.close(); }
291});
server/tests/coins.test.js added +39 −0
@@ -0,0 +1,39 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { formatQuantity } from "../../shared/items/formatQuantity.js";
4 import { ItemId, coinSpriteTierForQuantity, COIN_MAX_STACK } from "../../shared/definitions/items.js";
5 import { addCoinsToSlots, emptySlots, countCoinsInSlots } from "../../shared/items/inventory.js";
6
7 test("formatQuantity uses compact notation", () =>
8 {
9 assert.equal(formatQuantity(1), "1");
10 assert.equal(formatQuantity(500), "500");
11 assert.equal(formatQuantity(1000), "1k");
12 assert.equal(formatQuantity(1500), "1.5k");
13 assert.equal(formatQuantity(2000), "2k");
14 assert.equal(formatQuantity(50000), "50k");
15 assert.equal(formatQuantity(100000), "100k");
16 assert.equal(formatQuantity(1000000), "1M");
17 assert.equal(formatQuantity(1500000), "1.5M");
18 });
19
20 test("coin stacks split above max stack size", () =>
21 {
22 const amount = COIN_MAX_STACK + 1;
23 const result = addCoinsToSlots(emptySlots(), amount, { growable: false });
24 assert.equal(result.ok, true);
25 assert.equal(countCoinsInSlots(result.slots), amount);
26 const stacks = result.slots.filter((slot) => slot?.itemId === ItemId.coins);
27 assert.equal(stacks.length, 2);
28 assert.equal(stacks[0].quantity, COIN_MAX_STACK);
29 assert.equal(stacks[1].quantity, 1);
30 });
31
32 test("coin sprite tier picks the largest denomination not exceeding stack size", () =>
33 {
34 assert.equal(coinSpriteTierForQuantity(1), 1);
35 assert.equal(coinSpriteTierForQuantity(500), 500);
36 assert.equal(coinSpriteTierForQuantity(1500), 1500);
37 assert.equal(coinSpriteTierForQuantity(999), 500);
38 assert.equal(coinSpriteTierForQuantity(50_000_000), 50_000_000);
39 });
@@ -0,0 +1,39 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { formatQuantity } from "../../shared/items/formatQuantity.js";
4import { ItemId, coinSpriteTierForQuantity, COIN_MAX_STACK } from "../../shared/definitions/items.js";
5import { addCoinsToSlots, emptySlots, countCoinsInSlots } from "../../shared/items/inventory.js";
6
7test("formatQuantity uses compact notation", () =>
8{
9 assert.equal(formatQuantity(1), "1");
10 assert.equal(formatQuantity(500), "500");
11 assert.equal(formatQuantity(1000), "1k");
12 assert.equal(formatQuantity(1500), "1.5k");
13 assert.equal(formatQuantity(2000), "2k");
14 assert.equal(formatQuantity(50000), "50k");
15 assert.equal(formatQuantity(100000), "100k");
16 assert.equal(formatQuantity(1000000), "1M");
17 assert.equal(formatQuantity(1500000), "1.5M");
18});
19
20test("coin stacks split above max stack size", () =>
21{
22 const amount = COIN_MAX_STACK + 1;
23 const result = addCoinsToSlots(emptySlots(), amount, { growable: false });
24 assert.equal(result.ok, true);
25 assert.equal(countCoinsInSlots(result.slots), amount);
26 const stacks = result.slots.filter((slot) => slot?.itemId === ItemId.coins);
27 assert.equal(stacks.length, 2);
28 assert.equal(stacks[0].quantity, COIN_MAX_STACK);
29 assert.equal(stacks[1].quantity, 1);
30});
31
32test("coin sprite tier picks the largest denomination not exceeding stack size", () =>
33{
34 assert.equal(coinSpriteTierForQuantity(1), 1);
35 assert.equal(coinSpriteTierForQuantity(500), 500);
36 assert.equal(coinSpriteTierForQuantity(1500), 1500);
37 assert.equal(coinSpriteTierForQuantity(999), 500);
38 assert.equal(coinSpriteTierForQuantity(50_000_000), 50_000_000);
39});
server/tests/combat.test.js +136 −2
@@ -3,6 +3,11 @@ import assert from "node:assert/strict";
3 3 import { mobComponents } from "../src/simulation/spawners.js";
4 4 import { MobId } from "../../shared/definitions/mobs.js";
5 5 import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6 import { Component } from "../src/ecs/components.js";
7 import { WorkerMessage } from "../src/simulation/protocol.js";
8 import { tileToRegion } from "../src/world/coordinates.js";
9 import { SkillId } from "../../shared/definitions/skills.js";
10 import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
6 11 import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
7 12
8 13 function workerOf (simulation, entityId)
@@ -96,7 +101,10 @@ test("melee swing only resolves at Chebyshev distance 1", () =>
96 101 });
97 102 const nearEvents = harness.simulation.step().events;
98 103 assert.ok(nearEvents.some((event) => event.type === "combat-swing"));
99 assert.ok(nearEvents.some((event) => event.type === "combat-hit" || event.type === "combat-miss"));
104 assert.ok(nearEvents.some((event) =>
105 event.type === "combat-hit"
106 || event.type === "combat-miss"
107 || event.type === "combat-block"));
100 108 }
101 109 finally
102 110 { harness.close(); }
@@ -139,6 +147,71 @@ test("pigeons are untargetable free-flight and never get path tiles", () =>
139 147 { harness.close(); }
140 148 });
141 149
150 test("deer retaliate when attacked", () =>
151 {
152 const harness = makeSimulation({ workerCount: 1 });
153 try
154 {
155 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
156 const playerId = harness.simulation.spawnCharacter(1, character);
157 const deerId = harness.simulation.spawnEntity(mobComponents({
158 tileX: 9,
159 tileY: 8,
160 mobTypeId: MobId.deer,
161 spawnerId: null
162 }));
163
164 harness.simulation.enqueue(1, {
165 type: "attack",
166 characterId: character.character_id,
167 targetEntityId: deerId
168 });
169 harness.simulation.step();
170
171 const deer = componentsOf(harness.simulation, deerId);
172 assert.equal(deer.combat?.targetEntityId, playerId);
173 assert.ok(deer.skills?.levels?.unarmed >= 1);
174 }
175 finally
176 { harness.close(); }
177 });
178
179 test("cancel attack stops the player but the mob keeps pursuing", () =>
180 {
181 const harness = makeSimulation({ workerCount: 1 });
182 try
183 {
184 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
185 const playerId = harness.simulation.spawnCharacter(1, character);
186 const ratId = harness.simulation.spawnEntity(mobComponents({
187 tileX: 9,
188 tileY: 8,
189 mobTypeId: MobId.rat,
190 spawnerId: null
191 }));
192
193 harness.simulation.enqueue(1, {
194 type: "attack",
195 characterId: character.character_id,
196 targetEntityId: ratId
197 });
198 harness.simulation.step();
199
200 harness.simulation.enqueue(1, {
201 type: "cancel-attack",
202 characterId: character.character_id
203 });
204 harness.simulation.step();
205
206 const player = componentsOf(harness.simulation, playerId);
207 const rat = componentsOf(harness.simulation, ratId);
208 assert.equal(player.combat?.targetEntityId, null);
209 assert.equal(rat.combat?.targetEntityId, playerId);
210 }
211 finally
212 { harness.close(); }
213 });
214
142 215 test("player combat and skills components are present on spawn", () =>
143 216 {
144 217 const harness = makeSimulation({ workerCount: 1 });
@@ -148,9 +221,70 @@ test("player combat and skills components are present on spawn", () =>
148 221 const playerId = harness.simulation.spawnCharacter(1, character);
149 222 const comps = componentsOf(harness.simulation, playerId);
150 223 assert.ok(comps.combat);
151 assert.ok(comps.skills?.levels?.clubfighting);
224 assert.equal(comps.skills?.xp?.clubfighting, 0);
152 225 assert.ok(comps.health);
153 226 }
154 227 finally
155 228 { harness.close(); }
156 229 });
230
231 test("mobs heal to full when their region unloads", () =>
232 {
233 const harness = makeSimulation({ workerCount: 1 });
234 try
235 {
236 const ratId = harness.simulation.spawnEntity(mobComponents({
237 tileX: 8,
238 tileY: 8,
239 mobTypeId: MobId.rat
240 }));
241 const worker = workerOf(harness.simulation, ratId);
242 const handle = worker.world.ecs.handleOf(ratId);
243 worker.world.ecs.get(handle, Component.health).current = 2;
244 const result = worker.call({
245 type: WorkerMessage.dropRegion,
246 regionX: tileToRegion(8),
247 regionY: tileToRegion(8)
248 });
249 const record = result.dropped.find((entry) => entry.entityId === ratId);
250 assert.ok(record);
251 assert.equal(
252 record.payload.components.health.current,
253 record.payload.components.health.max
254 );
255 }
256 finally
257 { harness.close(); }
258 });
259
260 test("taking damage awards Health XP equal to damage dealt", () =>
261 {
262 const harness = makeSimulation({ workerCount: 1 });
263 const random = Math.random;
264 Math.random = () => 0;
265 try
266 {
267 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
268 const playerId = harness.simulation.spawnCharacter(1, character);
269 const ratId = harness.simulation.spawnEntity(mobComponents({
270 mobTypeId: MobId.rat,
271 tileX: 9,
272 tileY: 8
273 }));
274 const worker = harness.simulation.workers[0];
275 const playerHandle = worker.world.ecs.handleOf(playerId);
276 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
277 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
278 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
279 const hit = events.find((event) => event.type === "combat-hit");
280 assert.ok(hit);
281 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
282 assert.ok(updated);
283 assert.equal(updated.stored[SkillId.health] - before, hit.damage);
284 }
285 finally
286 {
287 Math.random = random;
288 harness.close();
289 }
290 });
@@ -3,6 +3,11 @@ import assert from "node:assert/strict";
3import { mobComponents } from "../src/simulation/spawners.js";
3import { mobComponents } from "../src/simulation/spawners.js";
4import { MobId } from "../../shared/definitions/mobs.js";
4import { MobId } from "../../shared/definitions/mobs.js";
5import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
5import { ItemId, EQUIPMENT_SLOT } from "../../shared/definitions/items.js";
6import { Component } from "../src/ecs/components.js";
7import { WorkerMessage } from "../src/simulation/protocol.js";
8import { tileToRegion } from "../src/world/coordinates.js";
9import { SkillId } from "../../shared/definitions/skills.js";
10import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
6import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
11import { makeCharacter, makeSimulation, stepTimes } from "./helpers/simulationHarness.js";
7
12
8function workerOf (simulation, entityId)
13function workerOf (simulation, entityId)
@@ -96,7 +101,10 @@ test("melee swing only resolves at Chebyshev distance 1", () =>
96 });
101 });
97 const nearEvents = harness.simulation.step().events;
102 const nearEvents = harness.simulation.step().events;
98 assert.ok(nearEvents.some((event) => event.type === "combat-swing"));
103 assert.ok(nearEvents.some((event) => event.type === "combat-swing"));
99 assert.ok(nearEvents.some((event) => event.type === "combat-hit" || event.type === "combat-miss"));
104 assert.ok(nearEvents.some((event) =>
105 event.type === "combat-hit"
106 || event.type === "combat-miss"
107 || event.type === "combat-block"));
100 }
108 }
101 finally
109 finally
102 { harness.close(); }
110 { harness.close(); }
@@ -139,6 +147,71 @@ test("pigeons are untargetable free-flight and never get path tiles", () =>
139 { harness.close(); }
147 { harness.close(); }
140});
148});
141
149
150test("deer retaliate when attacked", () =>
151{
152 const harness = makeSimulation({ workerCount: 1 });
153 try
154 {
155 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
156 const playerId = harness.simulation.spawnCharacter(1, character);
157 const deerId = harness.simulation.spawnEntity(mobComponents({
158 tileX: 9,
159 tileY: 8,
160 mobTypeId: MobId.deer,
161 spawnerId: null
162 }));
163
164 harness.simulation.enqueue(1, {
165 type: "attack",
166 characterId: character.character_id,
167 targetEntityId: deerId
168 });
169 harness.simulation.step();
170
171 const deer = componentsOf(harness.simulation, deerId);
172 assert.equal(deer.combat?.targetEntityId, playerId);
173 assert.ok(deer.skills?.levels?.unarmed >= 1);
174 }
175 finally
176 { harness.close(); }
177});
178
179test("cancel attack stops the player but the mob keeps pursuing", () =>
180{
181 const harness = makeSimulation({ workerCount: 1 });
182 try
183 {
184 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
185 const playerId = harness.simulation.spawnCharacter(1, character);
186 const ratId = harness.simulation.spawnEntity(mobComponents({
187 tileX: 9,
188 tileY: 8,
189 mobTypeId: MobId.rat,
190 spawnerId: null
191 }));
192
193 harness.simulation.enqueue(1, {
194 type: "attack",
195 characterId: character.character_id,
196 targetEntityId: ratId
197 });
198 harness.simulation.step();
199
200 harness.simulation.enqueue(1, {
201 type: "cancel-attack",
202 characterId: character.character_id
203 });
204 harness.simulation.step();
205
206 const player = componentsOf(harness.simulation, playerId);
207 const rat = componentsOf(harness.simulation, ratId);
208 assert.equal(player.combat?.targetEntityId, null);
209 assert.equal(rat.combat?.targetEntityId, playerId);
210 }
211 finally
212 { harness.close(); }
213});
214
142test("player combat and skills components are present on spawn", () =>
215test("player combat and skills components are present on spawn", () =>
143{
216{
144 const harness = makeSimulation({ workerCount: 1 });
217 const harness = makeSimulation({ workerCount: 1 });
@@ -148,9 +221,70 @@ test("player combat and skills components are present on spawn", () =>
148 const playerId = harness.simulation.spawnCharacter(1, character);
221 const playerId = harness.simulation.spawnCharacter(1, character);
149 const comps = componentsOf(harness.simulation, playerId);
222 const comps = componentsOf(harness.simulation, playerId);
150 assert.ok(comps.combat);
223 assert.ok(comps.combat);
151 assert.ok(comps.skills?.levels?.clubfighting);
224 assert.equal(comps.skills?.xp?.clubfighting, 0);
152 assert.ok(comps.health);
225 assert.ok(comps.health);
153 }
226 }
154 finally
227 finally
155 { harness.close(); }
228 { harness.close(); }
156});
229});
230
231test("mobs heal to full when their region unloads", () =>
232{
233 const harness = makeSimulation({ workerCount: 1 });
234 try
235 {
236 const ratId = harness.simulation.spawnEntity(mobComponents({
237 tileX: 8,
238 tileY: 8,
239 mobTypeId: MobId.rat
240 }));
241 const worker = workerOf(harness.simulation, ratId);
242 const handle = worker.world.ecs.handleOf(ratId);
243 worker.world.ecs.get(handle, Component.health).current = 2;
244 const result = worker.call({
245 type: WorkerMessage.dropRegion,
246 regionX: tileToRegion(8),
247 regionY: tileToRegion(8)
248 });
249 const record = result.dropped.find((entry) => entry.entityId === ratId);
250 assert.ok(record);
251 assert.equal(
252 record.payload.components.health.current,
253 record.payload.components.health.max
254 );
255 }
256 finally
257 { harness.close(); }
258});
259
260test("taking damage awards Health XP equal to damage dealt", () =>
261{
262 const harness = makeSimulation({ workerCount: 1 });
263 const random = Math.random;
264 Math.random = () => 0;
265 try
266 {
267 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
268 const playerId = harness.simulation.spawnCharacter(1, character);
269 const ratId = harness.simulation.spawnEntity(mobComponents({
270 mobTypeId: MobId.rat,
271 tileX: 9,
272 tileY: 8
273 }));
274 const worker = harness.simulation.workers[0];
275 const playerHandle = worker.world.ecs.handleOf(playerId);
276 const before = worker.world.ecs.get(playerHandle, Component.skills).xp[SkillId.health];
277 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(ratId));
278 const events = resolveMeleeSwing(worker.world, ratId, playerId, profile, Date.now());
279 const hit = events.find((event) => event.type === "combat-hit");
280 assert.ok(hit);
281 const updated = events.find((event) => event.type === "skills-updated" && event.entityId === playerId);
282 assert.ok(updated);
283 assert.equal(updated.stored[SkillId.health] - before, hit.damage);
284 }
285 finally
286 {
287 Math.random = random;
288 harness.close();
289 }
290});
server/tests/combatRolls.test.js added +108 −0
@@ -0,0 +1,108 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { resolvePhysicalAttack, rollSkill } from "../../shared/combat/rolls.js";
4
5 test("rollSkill returns values within 1..skillLevel", () =>
6 {
7 const seen = new Set();
8 for (let i = 0; i < 200; i++)
9 { seen.add(rollSkill(5, () => Math.random())); }
10 for (const value of seen)
11 {
12 assert.ok(value >= 1 && value <= 5);
13 }
14 });
15
16 test("deterministic rng produces stable rolls", () =>
17 {
18 let i = 0;
19 const seq = [0, 0.99, 0.5];
20 const rng = () => seq[i++ % seq.length];
21 assert.equal(rollSkill(4, rng), 1);
22 assert.equal(rollSkill(4, rng), 4);
23 assert.equal(rollSkill(4, rng), 3);
24 });
25
26 test("physical attack miss when agility roll beats hit roll", () =>
27 {
28 let i = 0;
29 const rng = () => [0.25, 0.45][i++];
30 const result = resolvePhysicalAttack({
31 hitSkillLevel: 5,
32 agilitySkillLevel: 10,
33 damageSkillLevel: 10,
34 defenceSkillLevel: 1,
35 baseDamage: 2,
36 rng
37 });
38 assert.equal(result.outcome, "miss");
39 assert.equal(result.toHitRoll, 2);
40 assert.equal(result.agilityRoll, 5);
41 assert.equal(result.damage, 0);
42 });
43
44 test("equal hit and agility rolls count as a hit", () =>
45 {
46 let i = 0;
47 const rng = () => [0.4, 0.4, 0, 0][i++];
48 const result = resolvePhysicalAttack({
49 hitSkillLevel: 5,
50 agilitySkillLevel: 5,
51 damageSkillLevel: 5,
52 defenceSkillLevel: 1,
53 baseDamage: 1,
54 rng
55 });
56 assert.equal(result.toHitRoll, result.agilityRoll);
57 assert.equal(result.outcome, "hit");
58 });
59
60 test("physical attack block prevents damage after winning the hit contest", () =>
61 {
62 let i = 0;
63 const rolls = [0.4, 0, 0, 0.95];
64 const rng = () => rolls[i++];
65 const result = resolvePhysicalAttack({
66 hitSkillLevel: 10,
67 agilitySkillLevel: 3,
68 damageSkillLevel: 8,
69 defenceSkillLevel: 10,
70 baseDamage: 1,
71 rng
72 });
73 assert.equal(result.outcome, "block");
74 assert.equal(result.damage, 0);
75 assert.ok(result.defenceRoll > result.toHitRoll);
76 });
77
78 test("physical attack hit applies rolled damage when not blocked", () =>
79 {
80 let i = 0;
81 const rolls = [0.9, 0, 0, 0];
82 const rng = () => rolls[i++];
83 const result = resolvePhysicalAttack({
84 hitSkillLevel: 10,
85 agilitySkillLevel: 1,
86 damageSkillLevel: 5,
87 defenceSkillLevel: 1,
88 baseDamage: 2,
89 rng
90 });
91 assert.equal(result.outcome, "hit");
92 assert.equal(result.damage, 2);
93 });
94
95 test("skill level 1 contest can still land a hit on equal agility", () =>
96 {
97 const result = resolvePhysicalAttack({
98 hitSkillLevel: 1,
99 agilitySkillLevel: 1,
100 damageSkillLevel: 1,
101 defenceSkillLevel: 1,
102 baseDamage: 1,
103 rng: () => 0
104 });
105 assert.equal(result.outcome, "hit");
106 assert.equal(result.toHitRoll, 1);
107 assert.equal(result.agilityRoll, 1);
108 });
@@ -0,0 +1,108 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { resolvePhysicalAttack, rollSkill } from "../../shared/combat/rolls.js";
4
5test("rollSkill returns values within 1..skillLevel", () =>
6{
7 const seen = new Set();
8 for (let i = 0; i < 200; i++)
9 { seen.add(rollSkill(5, () => Math.random())); }
10 for (const value of seen)
11 {
12 assert.ok(value >= 1 && value <= 5);
13 }
14});
15
16test("deterministic rng produces stable rolls", () =>
17{
18 let i = 0;
19 const seq = [0, 0.99, 0.5];
20 const rng = () => seq[i++ % seq.length];
21 assert.equal(rollSkill(4, rng), 1);
22 assert.equal(rollSkill(4, rng), 4);
23 assert.equal(rollSkill(4, rng), 3);
24});
25
26test("physical attack miss when agility roll beats hit roll", () =>
27{
28 let i = 0;
29 const rng = () => [0.25, 0.45][i++];
30 const result = resolvePhysicalAttack({
31 hitSkillLevel: 5,
32 agilitySkillLevel: 10,
33 damageSkillLevel: 10,
34 defenceSkillLevel: 1,
35 baseDamage: 2,
36 rng
37 });
38 assert.equal(result.outcome, "miss");
39 assert.equal(result.toHitRoll, 2);
40 assert.equal(result.agilityRoll, 5);
41 assert.equal(result.damage, 0);
42});
43
44test("equal hit and agility rolls count as a hit", () =>
45{
46 let i = 0;
47 const rng = () => [0.4, 0.4, 0, 0][i++];
48 const result = resolvePhysicalAttack({
49 hitSkillLevel: 5,
50 agilitySkillLevel: 5,
51 damageSkillLevel: 5,
52 defenceSkillLevel: 1,
53 baseDamage: 1,
54 rng
55 });
56 assert.equal(result.toHitRoll, result.agilityRoll);
57 assert.equal(result.outcome, "hit");
58});
59
60test("physical attack block prevents damage after winning the hit contest", () =>
61{
62 let i = 0;
63 const rolls = [0.4, 0, 0, 0.95];
64 const rng = () => rolls[i++];
65 const result = resolvePhysicalAttack({
66 hitSkillLevel: 10,
67 agilitySkillLevel: 3,
68 damageSkillLevel: 8,
69 defenceSkillLevel: 10,
70 baseDamage: 1,
71 rng
72 });
73 assert.equal(result.outcome, "block");
74 assert.equal(result.damage, 0);
75 assert.ok(result.defenceRoll > result.toHitRoll);
76});
77
78test("physical attack hit applies rolled damage when not blocked", () =>
79{
80 let i = 0;
81 const rolls = [0.9, 0, 0, 0];
82 const rng = () => rolls[i++];
83 const result = resolvePhysicalAttack({
84 hitSkillLevel: 10,
85 agilitySkillLevel: 1,
86 damageSkillLevel: 5,
87 defenceSkillLevel: 1,
88 baseDamage: 2,
89 rng
90 });
91 assert.equal(result.outcome, "hit");
92 assert.equal(result.damage, 2);
93});
94
95test("skill level 1 contest can still land a hit on equal agility", () =>
96{
97 const result = resolvePhysicalAttack({
98 hitSkillLevel: 1,
99 agilitySkillLevel: 1,
100 damageSkillLevel: 1,
101 defenceSkillLevel: 1,
102 baseDamage: 1,
103 rng: () => 0
104 });
105 assert.equal(result.outcome, "hit");
106 assert.equal(result.toHitRoll, 1);
107 assert.equal(result.agilityRoll, 1);
108});
server/tests/courier.test.js +45 −5
@@ -54,7 +54,7 @@ function placeBank (worldDb, tileX, tileY)
54 54 );
55 55 }
56 56
57 test("pigeon to bank deposits money into the sender vault", () =>
57 test("pigeon to bank deposits coin stacks into the sender vault", () =>
58 58 {
59 59 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
60 60 try
@@ -71,24 +71,34 @@ test("pigeon to bank deposits money into the sender vault", () =>
71 71 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
72 72 const entityId = harness.simulation.spawnCharacter(1, character);
73 73 const before = harness.simulation.bagOf(entityId);
74 assert.ok((before.currency | 0) >= 5);
74 const coinSlot = before.inventory.findIndex((slot) => slot?.itemId === ItemId.coins);
75 assert.ok(coinSlot >= 0);
76 assert.ok(before.inventory[coinSlot].quantity >= 5);
77 const beforeCoins = before.inventory[coinSlot].quantity;
75 78 const result = harness.simulation.dispatchPigeon({
76 79 characterId: character.character_id,
77 80 destination: { kind: "bank" },
78 cargo: { kind: "money", amount: 5 }
81 cargo: { kind: "item", slotIndex: coinSlot, quantity: 5 }
79 82 });
80 83 assert.equal(result.transit.destinationKind, "bank");
81 assert.equal(harness.simulation.bagOf(entityId).currency, before.currency - 5);
84 assert.equal(harness.simulation.bagOf(entityId).inventory[coinSlot].quantity, beforeCoins - 5);
82 85
83 86 stepTimes(harness.simulation, 80);
84 87 const after = harness.stateDb.getBag(character.character_id);
85 assert.equal(after.vaultCurrency, (before.vaultCurrency | 0) + 5);
88 assert.equal(countItem(after.vault, ItemId.coins), 5);
86 89 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
87 90 }
88 91 finally
89 92 { harness.close(); }
90 93 });
91 94
95 function countItem (slots, itemId)
96 {
97 return (slots ?? [])
98 .filter((slot) => slot?.itemId === itemId)
99 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
100 }
101
92 102 test("pigeon delivers an item to an online player inventory", () =>
93 103 {
94 104 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
@@ -131,3 +141,33 @@ test("pigeon delivers an item to an online player inventory", () =>
131 141 finally
132 142 { harness.close(); }
133 143 });
144
145 test("pigeon rejects blank cheques", () =>
146 {
147 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
148 try
149 {
150 placeBank(harness.worldDb, 8, 8);
151 harness.simulation.reloadWorld();
152 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
153 const entityId = harness.simulation.spawnCharacter(1, character);
154 harness.simulation.enqueue(1, {
155 type: "get-blank-cheques",
156 characterId: character.character_id
157 });
158 harness.simulation.step();
159 const bag = harness.simulation.bagOf(entityId);
160 const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
161 assert.ok(blankIndex >= 0);
162 assert.throws(
163 () => harness.simulation.dispatchPigeon({
164 characterId: character.character_id,
165 destination: { kind: "bank" },
166 cargo: { kind: "item", slotIndex: blankIndex, quantity: 1 }
167 }),
168 (err) => err.message === "Blank cheques cannot be sent by pigeon."
169 );
170 }
171 finally
172 { harness.close(); }
173 });
@@ -54,7 +54,7 @@ function placeBank (worldDb, tileX, tileY)
54 );
54 );
55}
55}
56
56
57test("pigeon to bank deposits money into the sender vault", () =>
57test("pigeon to bank deposits coin stacks into the sender vault", () =>
58{
58{
59 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
59 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
60 try
60 try
@@ -71,24 +71,34 @@ test("pigeon to bank deposits money into the sender vault", () =>
71 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
71 const character = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
72 const entityId = harness.simulation.spawnCharacter(1, character);
72 const entityId = harness.simulation.spawnCharacter(1, character);
73 const before = harness.simulation.bagOf(entityId);
73 const before = harness.simulation.bagOf(entityId);
74 assert.ok((before.currency | 0) >= 5);
74 const coinSlot = before.inventory.findIndex((slot) => slot?.itemId === ItemId.coins);
75 assert.ok(coinSlot >= 0);
76 assert.ok(before.inventory[coinSlot].quantity >= 5);
77 const beforeCoins = before.inventory[coinSlot].quantity;
75 const result = harness.simulation.dispatchPigeon({
78 const result = harness.simulation.dispatchPigeon({
76 characterId: character.character_id,
79 characterId: character.character_id,
77 destination: { kind: "bank" },
80 destination: { kind: "bank" },
78 cargo: { kind: "money", amount: 5 }
81 cargo: { kind: "item", slotIndex: coinSlot, quantity: 5 }
79 });
82 });
80 assert.equal(result.transit.destinationKind, "bank");
83 assert.equal(result.transit.destinationKind, "bank");
81 assert.equal(harness.simulation.bagOf(entityId).currency, before.currency - 5);
84 assert.equal(harness.simulation.bagOf(entityId).inventory[coinSlot].quantity, beforeCoins - 5);
82
85
83 stepTimes(harness.simulation, 80);
86 stepTimes(harness.simulation, 80);
84 const after = harness.stateDb.getBag(character.character_id);
87 const after = harness.stateDb.getBag(character.character_id);
85 assert.equal(after.vaultCurrency, (before.vaultCurrency | 0) + 5);
88 assert.equal(countItem(after.vault, ItemId.coins), 5);
86 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
89 assert.equal(harness.stateDb.listActiveCourierTransits().length, 0);
87 }
90 }
88 finally
91 finally
89 { harness.close(); }
92 { harness.close(); }
90});
93});
91
94
95function countItem (slots, itemId)
96{
97 return (slots ?? [])
98 .filter((slot) => slot?.itemId === itemId)
99 .reduce((sum, slot) => sum + (slot.quantity | 0), 0);
100}
101
92test("pigeon delivers an item to an online player inventory", () =>
102test("pigeon delivers an item to an online player inventory", () =>
93{
103{
94 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
104 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
@@ -131,3 +141,33 @@ test("pigeon delivers an item to an online player inventory", () =>
131 finally
141 finally
132 { harness.close(); }
142 { harness.close(); }
133});
143});
144
145test("pigeon rejects blank cheques", () =>
146{
147 const harness = makeSimulation({ workerCount: 1, maxChunkX: 2 });
148 try
149 {
150 placeBank(harness.worldDb, 8, 8);
151 harness.simulation.reloadWorld();
152 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 9 });
153 const entityId = harness.simulation.spawnCharacter(1, character);
154 harness.simulation.enqueue(1, {
155 type: "get-blank-cheques",
156 characterId: character.character_id
157 });
158 harness.simulation.step();
159 const bag = harness.simulation.bagOf(entityId);
160 const blankIndex = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.blankCheque);
161 assert.ok(blankIndex >= 0);
162 assert.throws(
163 () => harness.simulation.dispatchPigeon({
164 characterId: character.character_id,
165 destination: { kind: "bank" },
166 cargo: { kind: "item", slotIndex: blankIndex, quantity: 1 }
167 }),
168 (err) => err.message === "Blank cheques cannot be sent by pigeon."
169 );
170 }
171 finally
172 { harness.close(); }
173});
server/tests/craftingStations.test.js added +86 −0
@@ -0,0 +1,86 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 CraftingStationId,
5 FIREPLACE_DURATION_MS,
6 CRAFT_DURATION_MS,
7 craftingStationDefinition
8 } from "../../shared/definitions/craftingStations.js";
9 import { SkillId } from "../../shared/definitions/skills.js";
10 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11 import { emptySlots } from "../../shared/items/inventory.js";
12 import { canCraftFitInventory, CRAFT_DURATION_MS as RECIPE_CRAFT_MS, canStartCraft } from "../../shared/crafting/recipes.js";
13 import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
14 import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
15
16 test("crafting stations map to the expected skills", () =>
17 {
18 assert.equal(craftingStationDefinition(CraftingStationId.furnace).skillId, SkillId.smithing);
19 assert.equal(craftingStationDefinition(CraftingStationId.anvil).skillId, SkillId.smithing);
20 assert.equal(craftingStationDefinition(CraftingStationId.loom).skillId, SkillId.tailoring);
21 assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);
22 assert.equal(craftingStationDefinition(CraftingStationId.oven).skillId, SkillId.cooking);
23 assert.equal(craftingStationDefinition(CraftingStationId.fireplace).skillId, SkillId.cooking);
24 });
25
26 test("fireplace is portable with a ten minute lifetime", () =>
27 {
28 const def = craftingStationDefinition(CraftingStationId.fireplace);
29 assert.equal(def.portable, true);
30 assert.equal(def.maxPerTile, 1);
31 assert.equal(def.durationMs, FIREPLACE_DURATION_MS);
32 assert.equal(FIREPLACE_DURATION_MS, 10 * 60 * 1000);
33 });
34
35 test("every craft takes two seconds", () =>
36 {
37 assert.equal(CRAFT_DURATION_MS, 2000);
38 assert.equal(RECIPE_CRAFT_MS, CRAFT_DURATION_MS);
39 });
40
41 test("canCraftFitInventory accounts for space freed by consumed materials", () =>
42 {
43 const recipe = {
44 output: { itemId: ItemId.stick, quantity: 1 },
45 inputs: [{ itemId: ItemId.paper, quantity: 2 }]
46 };
47 const slots = emptySlots();
48 slots[0] = { itemId: ItemId.paper, quantity: 10 };
49 for (let i = 1; i < 32; i++)
50 { slots[i] = { itemId: ItemId.coins, quantity: 1 }; }
51 assert.equal(canCraftFitInventory(slots, recipe), false);
52 slots[31] = null;
53 assert.equal(canCraftFitInventory(slots, recipe), true);
54 });
55
56 test("canCraftFitInventory rejects missing inputs", () =>
57 {
58 const slots = emptySlots();
59 slots[0] = { itemId: ItemId.paper, quantity: 1 };
60 assert.equal(canCraftFitInventory(slots, {
61 output: { itemId: ItemId.stick, quantity: 1 },
62 inputs: [{ itemId: ItemId.paper, quantity: 2 }]
63 }), false);
64 });
65
66 test("recipesForStation lists bench recipes", () =>
67 {
68 const bench = recipesForStation(CraftingStationId.craftingBench);
69 assert.ok(bench.length >= 1);
70 assert.equal(bench[0].recipeId, "dev-stick-from-paper");
71 });
72
73 test("canStartCraft enforces minimum skill level", () =>
74 {
75 const slots = emptySlots();
76 slots[0] = { itemId: ItemId.paper, quantity: 5 };
77 const recipe = recipeDefinition("dev-stick-from-paper");
78 assert.equal(canStartCraft(slots, recipe, 1), true);
79 assert.equal(canStartCraft(slots, recipe, 0), false);
80 });
81
82 test("crafting item stubs are registered", () =>
83 {
84 assert.equal(itemDefinition(CraftingItemId.log)?.stub, true);
85 assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");
86 });
@@ -0,0 +1,86 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 CraftingStationId,
5 FIREPLACE_DURATION_MS,
6 CRAFT_DURATION_MS,
7 craftingStationDefinition
8} from "../../shared/definitions/craftingStations.js";
9import { SkillId } from "../../shared/definitions/skills.js";
10import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
11import { emptySlots } from "../../shared/items/inventory.js";
12import { canCraftFitInventory, CRAFT_DURATION_MS as RECIPE_CRAFT_MS, canStartCraft } from "../../shared/crafting/recipes.js";
13import { recipesForStation, recipeDefinition } from "../../shared/crafting/stationRecipes.js";
14import { CraftingItemId } from "../../shared/definitions/craftingItems.js";
15
16test("crafting stations map to the expected skills", () =>
17{
18 assert.equal(craftingStationDefinition(CraftingStationId.furnace).skillId, SkillId.smithing);
19 assert.equal(craftingStationDefinition(CraftingStationId.anvil).skillId, SkillId.smithing);
20 assert.equal(craftingStationDefinition(CraftingStationId.loom).skillId, SkillId.tailoring);
21 assert.equal(craftingStationDefinition(CraftingStationId.craftingBench).skillId, SkillId.crafting);
22 assert.equal(craftingStationDefinition(CraftingStationId.oven).skillId, SkillId.cooking);
23 assert.equal(craftingStationDefinition(CraftingStationId.fireplace).skillId, SkillId.cooking);
24});
25
26test("fireplace is portable with a ten minute lifetime", () =>
27{
28 const def = craftingStationDefinition(CraftingStationId.fireplace);
29 assert.equal(def.portable, true);
30 assert.equal(def.maxPerTile, 1);
31 assert.equal(def.durationMs, FIREPLACE_DURATION_MS);
32 assert.equal(FIREPLACE_DURATION_MS, 10 * 60 * 1000);
33});
34
35test("every craft takes two seconds", () =>
36{
37 assert.equal(CRAFT_DURATION_MS, 2000);
38 assert.equal(RECIPE_CRAFT_MS, CRAFT_DURATION_MS);
39});
40
41test("canCraftFitInventory accounts for space freed by consumed materials", () =>
42{
43 const recipe = {
44 output: { itemId: ItemId.stick, quantity: 1 },
45 inputs: [{ itemId: ItemId.paper, quantity: 2 }]
46 };
47 const slots = emptySlots();
48 slots[0] = { itemId: ItemId.paper, quantity: 10 };
49 for (let i = 1; i < 32; i++)
50 { slots[i] = { itemId: ItemId.coins, quantity: 1 }; }
51 assert.equal(canCraftFitInventory(slots, recipe), false);
52 slots[31] = null;
53 assert.equal(canCraftFitInventory(slots, recipe), true);
54});
55
56test("canCraftFitInventory rejects missing inputs", () =>
57{
58 const slots = emptySlots();
59 slots[0] = { itemId: ItemId.paper, quantity: 1 };
60 assert.equal(canCraftFitInventory(slots, {
61 output: { itemId: ItemId.stick, quantity: 1 },
62 inputs: [{ itemId: ItemId.paper, quantity: 2 }]
63 }), false);
64});
65
66test("recipesForStation lists bench recipes", () =>
67{
68 const bench = recipesForStation(CraftingStationId.craftingBench);
69 assert.ok(bench.length >= 1);
70 assert.equal(bench[0].recipeId, "dev-stick-from-paper");
71});
72
73test("canStartCraft enforces minimum skill level", () =>
74{
75 const slots = emptySlots();
76 slots[0] = { itemId: ItemId.paper, quantity: 5 };
77 const recipe = recipeDefinition("dev-stick-from-paper");
78 assert.equal(canStartCraft(slots, recipe, 1), true);
79 assert.equal(canStartCraft(slots, recipe, 0), false);
80});
81
82test("crafting item stubs are registered", () =>
83{
84 assert.equal(itemDefinition(CraftingItemId.log)?.stub, true);
85 assert.equal(itemDefinition(CraftingItemId.bronzeBar)?.key, "bronze-bar");
86});
server/tests/equipment.test.js added +60 −0
@@ -0,0 +1,60 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
4 import { MaterialTier, tierStatBonus } from "../../shared/definitions/materialTiers.js";
5 import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
6 import { SkillId } from "../../shared/definitions/skills.js";
7 import { normalizePlayerSkills } from "../../shared/skills/state.js";
8 import {
9 canEquipItem,
10 effectiveSkillLevel,
11 equipmentBonusesFromSlots
12 } from "../../shared/equipment/stats.js";
13 import { emptyEquipment } from "../../shared/items/inventory.js";
14
15 test("tier stat bonuses scale by material", () =>
16 {
17 assert.equal(tierStatBonus(MaterialTier.bronze), 1);
18 assert.equal(tierStatBonus(MaterialTier.iron), 2);
19 assert.ok(tierStatBonus(MaterialTier.orichalcum) > tierStatBonus(MaterialTier.mithril));
20 });
21
22 test("equipped weapons and armour add effective combat stats", () =>
23 {
24 const skills = normalizePlayerSkills(null);
25 const slots = {
26 ...emptyEquipment().slots,
27 weapon: { itemId: ItemId.stick, quantity: 1 },
28 chest: { itemId: ItemId.clothShirt, quantity: 1 }
29 };
30 const bonuses = equipmentBonusesFromSlots(slots);
31 assert.equal(bonuses[SkillId.strength], tierStatBonus(MaterialTier.bronze));
32 assert.equal(bonuses[SkillId.defence], tierStatBonus(MaterialTier.bronze));
33 assert.equal(
34 effectiveSkillLevel(skills, SkillId.strength, bonuses),
35 1 + tierStatBonus(MaterialTier.bronze)
36 );
37 });
38
39 test("bronze gear equips at level 1", () =>
40 {
41 const skills = normalizePlayerSkills(null);
42 assert.equal(canEquipItem(skills, itemDefinition(ItemId.stick)).ok, true);
43 assert.equal(canEquipItem(skills, itemDefinition(ItemId.clothShirt)).ok, true);
44 });
45
46 test("higher tiers require the relevant skill level", () =>
47 {
48 const ironSword = {
49 equipment: {
50 slot: "weapon",
51 tier: MaterialTier.iron,
52 kind: EquipmentKind.metalWeapon,
53 attack: { hitSkillId: SkillId.swordfighting }
54 }
55 };
56 const skills = normalizePlayerSkills(null);
57 assert.equal(canEquipItem(skills, ironSword).ok, false);
58 skills.xp[SkillId.swordfighting] = 999999;
59 assert.equal(canEquipItem(skills, ironSword).ok, true);
60 });
@@ -0,0 +1,60 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
4import { MaterialTier, tierStatBonus } from "../../shared/definitions/materialTiers.js";
5import { EquipmentKind } from "../../shared/definitions/equipmentKinds.js";
6import { SkillId } from "../../shared/definitions/skills.js";
7import { normalizePlayerSkills } from "../../shared/skills/state.js";
8import {
9 canEquipItem,
10 effectiveSkillLevel,
11 equipmentBonusesFromSlots
12} from "../../shared/equipment/stats.js";
13import { emptyEquipment } from "../../shared/items/inventory.js";
14
15test("tier stat bonuses scale by material", () =>
16{
17 assert.equal(tierStatBonus(MaterialTier.bronze), 1);
18 assert.equal(tierStatBonus(MaterialTier.iron), 2);
19 assert.ok(tierStatBonus(MaterialTier.orichalcum) > tierStatBonus(MaterialTier.mithril));
20});
21
22test("equipped weapons and armour add effective combat stats", () =>
23{
24 const skills = normalizePlayerSkills(null);
25 const slots = {
26 ...emptyEquipment().slots,
27 weapon: { itemId: ItemId.stick, quantity: 1 },
28 chest: { itemId: ItemId.clothShirt, quantity: 1 }
29 };
30 const bonuses = equipmentBonusesFromSlots(slots);
31 assert.equal(bonuses[SkillId.strength], tierStatBonus(MaterialTier.bronze));
32 assert.equal(bonuses[SkillId.defence], tierStatBonus(MaterialTier.bronze));
33 assert.equal(
34 effectiveSkillLevel(skills, SkillId.strength, bonuses),
35 1 + tierStatBonus(MaterialTier.bronze)
36 );
37});
38
39test("bronze gear equips at level 1", () =>
40{
41 const skills = normalizePlayerSkills(null);
42 assert.equal(canEquipItem(skills, itemDefinition(ItemId.stick)).ok, true);
43 assert.equal(canEquipItem(skills, itemDefinition(ItemId.clothShirt)).ok, true);
44});
45
46test("higher tiers require the relevant skill level", () =>
47{
48 const ironSword = {
49 equipment: {
50 slot: "weapon",
51 tier: MaterialTier.iron,
52 kind: EquipmentKind.metalWeapon,
53 attack: { hitSkillId: SkillId.swordfighting }
54 }
55 };
56 const skills = normalizePlayerSkills(null);
57 assert.equal(canEquipItem(skills, ironSword).ok, false);
58 skills.xp[SkillId.swordfighting] = 999999;
59 assert.equal(canEquipItem(skills, ironSword).ok, true);
60});
server/tests/inventory.test.js +163 −1
@@ -1,8 +1,10 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 import { emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
3 import { emptyEquipment, emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
4 import { ItemOriginKind } from "../../shared/items/origin.js";
4 5 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5 6 import { BlockType } from "../../shared/definitions/tiles.js";
7 import { Component } from "../src/ecs/components.js";
6 8 import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
7 9 import {
8 10 makeCharacter,
@@ -10,6 +12,13 @@ import {
10 12 stepTimes
11 13 } from "./helpers/simulationHarness.js";
12 14
15 function workerOf (simulation, entityId)
16 {
17 const record = simulation.entityRecord(entityId);
18 assert.ok(record, "entity must be remembered");
19 return simulation.workers[record.workerId];
20 }
21
13 22 test("stackable items merge until max stack then need a new slot", () =>
14 23 {
15 24 const slots = emptySlots();
@@ -106,6 +115,129 @@ test("equip uses the item key-equip sprite for appearance layers", () =>
106 115 { harness.close(); }
107 116 });
108 117
118 test("equipping from a stack takes one item and leaves the remainder", () =>
119 {
120 const harness = makeSimulation({ workerCount: 1 });
121 try
122 {
123 const character = makeCharacter(harness.stateDb);
124 harness.stateDb.saveBag(character.character_id, {
125 inventory: (() =>
126 {
127 const slots = emptySlots();
128 slots[0] = {
129 itemId: ItemId.stick,
130 quantity: 3,
131 origins: [{ origin: { kind: ItemOriginKind.crafted, displayName: "Ada" }, quantity: 3 }]
132 };
133 return slots;
134 })(),
135 equipment: emptyEquipment(),
136 vault: [],
137 vaultReserved: []
138 });
139 const entityId = harness.simulation.spawnCharacter(1, character);
140 harness.simulation.enqueue(1, {
141 type: "equip-item",
142 characterId: character.character_id,
143 slotIndex: 0
144 });
145 harness.simulation.step();
146 const bag = harness.simulation.bagOf(entityId);
147 assert.equal(bag.inventory[0].quantity, 2);
148 assert.equal(bag.equipment.slots.weapon.quantity, 1);
149 assert.deepEqual(bag.equipment.slots.weapon.origins, [{
150 origin: { kind: ItemOriginKind.crafted, displayName: "Ada" },
151 quantity: 1
152 }]);
153 }
154 finally
155 { harness.close(); }
156 });
157
158 test("unequipping returns one item to inventory", () =>
159 {
160 const harness = makeSimulation({ workerCount: 1 });
161 try
162 {
163 const character = makeCharacter(harness.stateDb);
164 const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" };
165 harness.stateDb.saveBag(character.character_id, {
166 inventory: emptySlots(),
167 equipment: {
168 slots: {
169 weapon: {
170 itemId: ItemId.stick,
171 quantity: 1,
172 origins: [{ origin, quantity: 1 }]
173 }
174 }
175 },
176 vault: [],
177 vaultReserved: []
178 });
179 const entityId = harness.simulation.spawnCharacter(1, character);
180 harness.simulation.enqueue(1, {
181 type: "unequip-item",
182 characterId: character.character_id,
183 equipSlot: "weapon"
184 });
185 harness.simulation.step();
186 const bag = harness.simulation.bagOf(entityId);
187 assert.equal(bag.equipment.slots.weapon, null);
188 assert.equal(bag.inventory[0].quantity, 1);
189 assert.deepEqual(bag.inventory[0].origins, [{ origin, quantity: 1 }]);
190 }
191 finally
192 { harness.close(); }
193 });
194
195 test("unequipping uses a second slot when the item cannot stack in inventory", () =>
196 {
197 const harness = makeSimulation({ workerCount: 1 });
198 try
199 {
200 const character = makeCharacter(harness.stateDb);
201 const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" };
202 harness.stateDb.saveBag(character.character_id, {
203 inventory: (() =>
204 {
205 const slots = emptySlots();
206 slots[0] = {
207 itemId: ItemId.stick,
208 quantity: 1,
209 origins: [{ origin, quantity: 1 }]
210 };
211 return slots;
212 })(),
213 equipment: {
214 slots: {
215 weapon: {
216 itemId: ItemId.stick,
217 quantity: 1,
218 origins: [{ origin, quantity: 1 }]
219 }
220 }
221 },
222 vault: [],
223 vaultReserved: []
224 });
225 const entityId = harness.simulation.spawnCharacter(1, character);
226 harness.simulation.enqueue(1, {
227 type: "unequip-item",
228 characterId: character.character_id,
229 equipSlot: "weapon"
230 });
231 harness.simulation.step();
232 const bag = harness.simulation.bagOf(entityId);
233 assert.equal(bag.inventory[0].quantity, 1);
234 assert.equal(bag.inventory[1].quantity, 1);
235 assert.equal(bag.inventory.filter(Boolean).length, 2);
236 }
237 finally
238 { harness.close(); }
239 });
240
109 241 test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
110 242 {
111 243 const harness = makeSimulation({ workerCount: 1 });
@@ -133,3 +265,33 @@ test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
133 265 finally
134 266 { harness.close(); }
135 267 });
268
269 test("eating food restores player health", () =>
270 {
271 const harness = makeSimulation({ workerCount: 1 });
272 try
273 {
274 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
275 const playerId = harness.simulation.spawnCharacter(1, character);
276 const worker = workerOf(harness.simulation, playerId);
277 const handle = worker.world.ecs.handleOf(playerId);
278 const health = worker.world.ecs.get(handle, Component.health);
279 health.current = 6;
280 const bag = harness.simulation.bagOf(playerId);
281 const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
282 assert.ok(appleSlot >= 0);
283 harness.simulation.enqueue(1, {
284 type: "eat-item",
285 characterId: character.character_id,
286 slotIndex: appleSlot
287 });
288 harness.simulation.step();
289 const after = worker.world.ecs.get(handle, Component.health);
290 assert.equal(after.current, 10);
291 assert.equal(after.max, 10);
292 const afterBag = harness.simulation.bagOf(playerId);
293 assert.equal(afterBag.inventory[appleSlot].quantity, 2);
294 }
295 finally
296 { harness.close(); }
297 });
@@ -1,8 +1,10 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
3import { emptyEquipment, emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
4import { ItemOriginKind } from "../../shared/items/origin.js";
4import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5import { BlockType } from "../../shared/definitions/tiles.js";
6import { BlockType } from "../../shared/definitions/tiles.js";
7import { Component } from "../src/ecs/components.js";
6import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
8import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
7import {
9import {
8 makeCharacter,
10 makeCharacter,
@@ -10,6 +12,13 @@ import {
10 stepTimes
12 stepTimes
11} from "./helpers/simulationHarness.js";
13} from "./helpers/simulationHarness.js";
12
14
15function workerOf (simulation, entityId)
16{
17 const record = simulation.entityRecord(entityId);
18 assert.ok(record, "entity must be remembered");
19 return simulation.workers[record.workerId];
20}
21
13test("stackable items merge until max stack then need a new slot", () =>
22test("stackable items merge until max stack then need a new slot", () =>
14{
23{
15 const slots = emptySlots();
24 const slots = emptySlots();
@@ -106,6 +115,129 @@ test("equip uses the item key-equip sprite for appearance layers", () =>
106 { harness.close(); }
115 { harness.close(); }
107});
116});
108
117
118test("equipping from a stack takes one item and leaves the remainder", () =>
119{
120 const harness = makeSimulation({ workerCount: 1 });
121 try
122 {
123 const character = makeCharacter(harness.stateDb);
124 harness.stateDb.saveBag(character.character_id, {
125 inventory: (() =>
126 {
127 const slots = emptySlots();
128 slots[0] = {
129 itemId: ItemId.stick,
130 quantity: 3,
131 origins: [{ origin: { kind: ItemOriginKind.crafted, displayName: "Ada" }, quantity: 3 }]
132 };
133 return slots;
134 })(),
135 equipment: emptyEquipment(),
136 vault: [],
137 vaultReserved: []
138 });
139 const entityId = harness.simulation.spawnCharacter(1, character);
140 harness.simulation.enqueue(1, {
141 type: "equip-item",
142 characterId: character.character_id,
143 slotIndex: 0
144 });
145 harness.simulation.step();
146 const bag = harness.simulation.bagOf(entityId);
147 assert.equal(bag.inventory[0].quantity, 2);
148 assert.equal(bag.equipment.slots.weapon.quantity, 1);
149 assert.deepEqual(bag.equipment.slots.weapon.origins, [{
150 origin: { kind: ItemOriginKind.crafted, displayName: "Ada" },
151 quantity: 1
152 }]);
153 }
154 finally
155 { harness.close(); }
156});
157
158test("unequipping returns one item to inventory", () =>
159{
160 const harness = makeSimulation({ workerCount: 1 });
161 try
162 {
163 const character = makeCharacter(harness.stateDb);
164 const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" };
165 harness.stateDb.saveBag(character.character_id, {
166 inventory: emptySlots(),
167 equipment: {
168 slots: {
169 weapon: {
170 itemId: ItemId.stick,
171 quantity: 1,
172 origins: [{ origin, quantity: 1 }]
173 }
174 }
175 },
176 vault: [],
177 vaultReserved: []
178 });
179 const entityId = harness.simulation.spawnCharacter(1, character);
180 harness.simulation.enqueue(1, {
181 type: "unequip-item",
182 characterId: character.character_id,
183 equipSlot: "weapon"
184 });
185 harness.simulation.step();
186 const bag = harness.simulation.bagOf(entityId);
187 assert.equal(bag.equipment.slots.weapon, null);
188 assert.equal(bag.inventory[0].quantity, 1);
189 assert.deepEqual(bag.inventory[0].origins, [{ origin, quantity: 1 }]);
190 }
191 finally
192 { harness.close(); }
193});
194
195test("unequipping uses a second slot when the item cannot stack in inventory", () =>
196{
197 const harness = makeSimulation({ workerCount: 1 });
198 try
199 {
200 const character = makeCharacter(harness.stateDb);
201 const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" };
202 harness.stateDb.saveBag(character.character_id, {
203 inventory: (() =>
204 {
205 const slots = emptySlots();
206 slots[0] = {
207 itemId: ItemId.stick,
208 quantity: 1,
209 origins: [{ origin, quantity: 1 }]
210 };
211 return slots;
212 })(),
213 equipment: {
214 slots: {
215 weapon: {
216 itemId: ItemId.stick,
217 quantity: 1,
218 origins: [{ origin, quantity: 1 }]
219 }
220 }
221 },
222 vault: [],
223 vaultReserved: []
224 });
225 const entityId = harness.simulation.spawnCharacter(1, character);
226 harness.simulation.enqueue(1, {
227 type: "unequip-item",
228 characterId: character.character_id,
229 equipSlot: "weapon"
230 });
231 harness.simulation.step();
232 const bag = harness.simulation.bagOf(entityId);
233 assert.equal(bag.inventory[0].quantity, 1);
234 assert.equal(bag.inventory[1].quantity, 1);
235 assert.equal(bag.inventory.filter(Boolean).length, 2);
236 }
237 finally
238 { harness.close(); }
239});
240
109test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
241test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
110{
242{
111 const harness = makeSimulation({ workerCount: 1 });
243 const harness = makeSimulation({ workerCount: 1 });
@@ -133,3 +265,33 @@ test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
133 finally
265 finally
134 { harness.close(); }
266 { harness.close(); }
135});
267});
268
269test("eating food restores player health", () =>
270{
271 const harness = makeSimulation({ workerCount: 1 });
272 try
273 {
274 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
275 const playerId = harness.simulation.spawnCharacter(1, character);
276 const worker = workerOf(harness.simulation, playerId);
277 const handle = worker.world.ecs.handleOf(playerId);
278 const health = worker.world.ecs.get(handle, Component.health);
279 health.current = 6;
280 const bag = harness.simulation.bagOf(playerId);
281 const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
282 assert.ok(appleSlot >= 0);
283 harness.simulation.enqueue(1, {
284 type: "eat-item",
285 characterId: character.character_id,
286 slotIndex: appleSlot
287 });
288 harness.simulation.step();
289 const after = worker.world.ecs.get(handle, Component.health);
290 assert.equal(after.current, 10);
291 assert.equal(after.max, 10);
292 const afterBag = harness.simulation.bagOf(playerId);
293 assert.equal(afterBag.inventory[appleSlot].quantity, 2);
294 }
295 finally
296 { harness.close(); }
297});
server/tests/magic.test.js added +91 −0
@@ -0,0 +1,91 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { resolveMagicAttack, resolveMagicEffect, resolveSpellCast } from "../../shared/combat/magic.js";
4 import { spellDefinition, SpellId } from "../../shared/definitions/spells.js";
5
6 test("spell cast fails when difficulty roll beats magic roll", () =>
7 {
8 let i = 0;
9 const rng = () => [0.25, 0.45][i++];
10 const cast = resolveSpellCast({ magicSkillLevel: 5, spellDifficulty: 10, rng });
11 assert.equal(cast.success, false);
12 assert.equal(cast.magicRoll, 2);
13 assert.equal(cast.difficultyRoll, 5);
14 });
15
16 test("spell cast succeeds on equal magic and difficulty rolls", () =>
17 {
18 let i = 0;
19 const rng = () => [0.4, 0.4][i++];
20 const cast = resolveSpellCast({ magicSkillLevel: 5, spellDifficulty: 5, rng });
21 assert.equal(cast.magicRoll, cast.difficultyRoll);
22 assert.equal(cast.success, true);
23 });
24
25 test("fizzled magic attack deals no damage", () =>
26 {
27 let i = 0;
28 const rng = () => [0, 0.99][i++];
29 const result = resolveMagicAttack({
30 magicSkillLevel: 3,
31 spellDifficulty: 10,
32 mindSkillLevel: 10,
33 baseDamage: 5,
34 element: "fire",
35 rng
36 });
37 assert.equal(result.outcome, "fizzle");
38 assert.equal(result.damage, 0);
39 });
40
41 test("successful magic attack rolls mind damage and elemental multiplier", () =>
42 {
43 let i = 0;
44 const rng = () => [0.9, 0, 0, 0][i++];
45 const neutral = resolveMagicAttack({
46 magicSkillLevel: 10,
47 spellDifficulty: 1,
48 mindSkillLevel: 5,
49 baseDamage: 2,
50 element: "fire",
51 targetAffinities: {},
52 rng
53 });
54 assert.equal(neutral.outcome, "hit");
55 assert.equal(neutral.multiplier, 1);
56
57 let j = 0;
58 const rngWeak = () => [0.9, 0, 0, 0][j++];
59 const weak = resolveMagicAttack({
60 magicSkillLevel: 10,
61 spellDifficulty: 1,
62 mindSkillLevel: 5,
63 baseDamage: 2,
64 element: "fire",
65 targetAffinities: { fire: "weak" },
66 rng: rngWeak
67 });
68 assert.equal(weak.multiplier, 2);
69 assert.equal(weak.damage, neutral.damage * 2);
70 });
71
72 test("non-damage spell applies effect only after a successful cast roll", () =>
73 {
74 let i = 0;
75 const rng = () => [0.9, 0][i++];
76 const result = resolveMagicEffect({
77 magicSkillLevel: 10,
78 spellDifficulty: 3,
79 effectId: "slow",
80 rng
81 });
82 assert.equal(result.outcome, "effect");
83 assert.equal(result.effectId, "slow");
84 });
85
86 test("spell definitions expose per-spell difficulty", () =>
87 {
88 const spark = spellDefinition(SpellId.spark);
89 assert.equal(spark.difficulty, 4);
90 assert.equal(spark.element, "fire");
91 });
@@ -0,0 +1,91 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { resolveMagicAttack, resolveMagicEffect, resolveSpellCast } from "../../shared/combat/magic.js";
4import { spellDefinition, SpellId } from "../../shared/definitions/spells.js";
5
6test("spell cast fails when difficulty roll beats magic roll", () =>
7{
8 let i = 0;
9 const rng = () => [0.25, 0.45][i++];
10 const cast = resolveSpellCast({ magicSkillLevel: 5, spellDifficulty: 10, rng });
11 assert.equal(cast.success, false);
12 assert.equal(cast.magicRoll, 2);
13 assert.equal(cast.difficultyRoll, 5);
14});
15
16test("spell cast succeeds on equal magic and difficulty rolls", () =>
17{
18 let i = 0;
19 const rng = () => [0.4, 0.4][i++];
20 const cast = resolveSpellCast({ magicSkillLevel: 5, spellDifficulty: 5, rng });
21 assert.equal(cast.magicRoll, cast.difficultyRoll);
22 assert.equal(cast.success, true);
23});
24
25test("fizzled magic attack deals no damage", () =>
26{
27 let i = 0;
28 const rng = () => [0, 0.99][i++];
29 const result = resolveMagicAttack({
30 magicSkillLevel: 3,
31 spellDifficulty: 10,
32 mindSkillLevel: 10,
33 baseDamage: 5,
34 element: "fire",
35 rng
36 });
37 assert.equal(result.outcome, "fizzle");
38 assert.equal(result.damage, 0);
39});
40
41test("successful magic attack rolls mind damage and elemental multiplier", () =>
42{
43 let i = 0;
44 const rng = () => [0.9, 0, 0, 0][i++];
45 const neutral = resolveMagicAttack({
46 magicSkillLevel: 10,
47 spellDifficulty: 1,
48 mindSkillLevel: 5,
49 baseDamage: 2,
50 element: "fire",
51 targetAffinities: {},
52 rng
53 });
54 assert.equal(neutral.outcome, "hit");
55 assert.equal(neutral.multiplier, 1);
56
57 let j = 0;
58 const rngWeak = () => [0.9, 0, 0, 0][j++];
59 const weak = resolveMagicAttack({
60 magicSkillLevel: 10,
61 spellDifficulty: 1,
62 mindSkillLevel: 5,
63 baseDamage: 2,
64 element: "fire",
65 targetAffinities: { fire: "weak" },
66 rng: rngWeak
67 });
68 assert.equal(weak.multiplier, 2);
69 assert.equal(weak.damage, neutral.damage * 2);
70});
71
72test("non-damage spell applies effect only after a successful cast roll", () =>
73{
74 let i = 0;
75 const rng = () => [0.9, 0][i++];
76 const result = resolveMagicEffect({
77 magicSkillLevel: 10,
78 spellDifficulty: 3,
79 effectId: "slow",
80 rng
81 });
82 assert.equal(result.outcome, "effect");
83 assert.equal(result.effectId, "slow");
84});
85
86test("spell definitions expose per-spell difficulty", () =>
87{
88 const spark = spellDefinition(SpellId.spark);
89 assert.equal(spark.difficulty, 4);
90 assert.equal(spark.element, "fire");
91});
server/tests/marketplace.test.js added +30 −0
@@ -0,0 +1,30 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { ItemId } from "../../shared/definitions/items.js";
4 import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
5
6 test("blank cheques cannot be listed on the marketplace", () =>
7 {
8 const stack = { itemId: ItemId.blankCheque, quantity: 1 };
9 assert.equal(canSellOnMarketplace(stack), false);
10 assert.throws(
11 () => assertMarketplaceSellable(stack),
12 (err) => err.message === "Blank cheques cannot be sold on the marketplace."
13 );
14 });
15
16 test("written cheques can be listed on the marketplace", () =>
17 {
18 const stack = {
19 itemId: ItemId.filledCheque,
20 quantity: 1,
21 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 2 }
22 };
23 assert.equal(canSellOnMarketplace(stack), true);
24 assert.doesNotThrow(() => assertMarketplaceSellable(stack));
25 });
26
27 test("normal items are marketplace sellable by default", () =>
28 {
29 assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);
30 });
@@ -0,0 +1,30 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { ItemId } from "../../shared/definitions/items.js";
4import { canSellOnMarketplace, assertMarketplaceSellable } from "../../shared/items/marketplace.js";
5
6test("blank cheques cannot be listed on the marketplace", () =>
7{
8 const stack = { itemId: ItemId.blankCheque, quantity: 1 };
9 assert.equal(canSellOnMarketplace(stack), false);
10 assert.throws(
11 () => assertMarketplaceSellable(stack),
12 (err) => err.message === "Blank cheques cannot be sold on the marketplace."
13 );
14});
15
16test("written cheques can be listed on the marketplace", () =>
17{
18 const stack = {
19 itemId: ItemId.filledCheque,
20 quantity: 1,
21 instance: { kind: "filled-cheque", chequeId: "x", issuerCharacterId: 1, itemId: ItemId.apple, quantity: 2 }
22 };
23 assert.equal(canSellOnMarketplace(stack), true);
24 assert.doesNotThrow(() => assertMarketplaceSellable(stack));
25});
26
27test("normal items are marketplace sellable by default", () =>
28{
29 assert.equal(canSellOnMarketplace({ itemId: ItemId.apple, quantity: 3 }), true);
30});
server/tests/mobCombat.test.js added +18 −0
@@ -0,0 +1,18 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { mobCanFight, mobMeleeAttackProfile } from "../../shared/definitions/mobCombat.js";
4 import { MobId, mobDefinition } from "../../shared/definitions/mobs.js";
5
6 test("living targetable mobs can fight except pigeons", () =>
7 {
8 assert.equal(mobCanFight(mobDefinition(MobId.deer)), true);
9 assert.equal(mobCanFight(mobDefinition(MobId.rat)), true);
10 assert.equal(mobCanFight(mobDefinition(MobId.pigeon)), false);
11 });
12
13 test("mob attack profile uses one attackSkill for hit and damage rolls", () =>
14 {
15 const profile = mobMeleeAttackProfile(mobDefinition(MobId.rat));
16 assert.equal(profile.mobAttackSkill, 3);
17 assert.equal(profile.baseDamage, 2);
18 });
@@ -0,0 +1,18 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mobCanFight, mobMeleeAttackProfile } from "../../shared/definitions/mobCombat.js";
4import { MobId, mobDefinition } from "../../shared/definitions/mobs.js";
5
6test("living targetable mobs can fight except pigeons", () =>
7{
8 assert.equal(mobCanFight(mobDefinition(MobId.deer)), true);
9 assert.equal(mobCanFight(mobDefinition(MobId.rat)), true);
10 assert.equal(mobCanFight(mobDefinition(MobId.pigeon)), false);
11});
12
13test("mob attack profile uses one attackSkill for hit and damage rolls", () =>
14{
15 const profile = mobMeleeAttackProfile(mobDefinition(MobId.rat));
16 assert.equal(profile.mobAttackSkill, 3);
17 assert.equal(profile.baseDamage, 2);
18});
server/tests/origins.test.js added +125 −0
@@ -0,0 +1,125 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { ItemOriginKind, formatOriginBreakdown, mergeOriginLists, splitOrigins } from "../../shared/items/origin.js";
4 import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";
5 import { stackRulesFor } from "../../shared/items/stackRules.js";
6 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
7
8 const crafterA = { kind: ItemOriginKind.crafted, displayName: "Ada" };
9 const crafterB = { kind: ItemOriginKind.crafted, displayName: "Bob" };
10
11 test("mixed-origin stacks merge and show a breakdown label", () =>
12 {
13 const slots = emptySlots();
14 const def = itemDefinition(ItemId.apple);
15 const first = insertStack(slots, {
16 itemId: ItemId.apple,
17 quantity: 5,
18 origins: [{ origin: crafterA, quantity: 5 }]
19 }, def);
20 const second = insertStack(first.slots, {
21 itemId: ItemId.apple,
22 quantity: 3,
23 origins: [{ origin: crafterB, quantity: 3 }]
24 }, def);
25 assert.equal(second.ok, true);
26 assert.equal(second.slots[0].quantity, 8);
27 assert.equal(formatOriginBreakdown(second.slots[0]), "5 made by Ada, 3 made by Bob");
28 });
29
30 test("splitting a stack distributes origins FIFO", () =>
31 {
32 const slots = emptySlots();
33 const def = itemDefinition(ItemId.apple);
34 const inserted = insertStack(slots, {
35 itemId: ItemId.apple,
36 quantity: 8,
37 origins: [
38 { origin: crafterA, quantity: 5 },
39 { origin: crafterB, quantity: 3 }
40 ]
41 }, def);
42 const taken = takeFromSlot(inserted.slots, 0, 6);
43 assert.equal(taken.taken.quantity, 6);
44 assert.deepEqual(taken.taken.origins, [
45 { origin: crafterA, quantity: 5 },
46 { origin: crafterB, quantity: 1 }
47 ]);
48 assert.deepEqual(taken.slots[0].origins, [
49 { origin: crafterB, quantity: 2 }
50 ]);
51 });
52
53 test("equipment stacks only in inventory, but can stack in the vault", () =>
54 {
55 const shirt = itemDefinition(ItemId.clothShirt);
56 const invRules = stackRulesFor(shirt, { inVault: false });
57 const vaultRules = stackRulesFor(shirt, { inVault: true });
58 assert.equal(invRules.maxStackSize, 1);
59 assert.equal(invRules.stackable, false);
60 assert.equal(vaultRules.stackable, true);
61 assert.equal(vaultRules.maxStackSize, Number.POSITIVE_INFINITY);
62
63 const inv = insertStack(emptySlots(), { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
64 const invSecond = insertStack(inv.slots, { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
65 assert.equal(invSecond.slots.filter(Boolean).length, 2);
66
67 const vault = insertStackGrowable([], { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
68 const vaultSecond = insertStackGrowable(vault.slots, { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
69 assert.equal(vaultSecond.slots.length, 1);
70 assert.equal(vaultSecond.slots[0].quantity, 2);
71 });
72
73 test("unique items never stack, even in the vault", () =>
74 {
75 const letter = itemDefinition(ItemId.letter);
76 const vaultRules = stackRulesFor(letter, { inVault: true });
77 assert.equal(vaultRules.uniqueInstance, true);
78 assert.equal(vaultRules.stackable, false);
79
80 const first = insertStackGrowable([], {
81 itemId: ItemId.letter,
82 quantity: 1,
83 instance: { kind: "letter", letterId: "a", body: "Hi" }
84 }, letter);
85 const second = insertStackGrowable(first.slots, {
86 itemId: ItemId.letter,
87 quantity: 1,
88 instance: { kind: "letter", letterId: "b", body: "Bye" }
89 }, letter);
90 assert.equal(second.slots.length, 2);
91 });
92
93 test("mergeOriginLists combines matching crafters", () =>
94 {
95 const merged = mergeOriginLists(
96 [{ origin: crafterA, quantity: 2 }],
97 [{ origin: crafterA, quantity: 3 }, { origin: crafterB, quantity: 1 }]
98 );
99 assert.deepEqual(merged, [
100 { origin: crafterA, quantity: 5 },
101 { origin: crafterB, quantity: 1 }
102 ]);
103 const split = splitOrigins(merged, 6);
104 assert.deepEqual(split.taken, [
105 { origin: crafterA, quantity: 5 },
106 { origin: crafterB, quantity: 1 }
107 ]);
108 });
109
110 test("unequip-style insert merges stackable items within max stack size", () =>
111 {
112 const def = itemDefinition(ItemId.apple);
113 const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" };
114 let slots = emptySlots();
115 slots[0] = { itemId: ItemId.apple, quantity: 5, origins: [{ origin, quantity: 5 }] };
116 const worn = singleItemFromStack({
117 itemId: ItemId.apple,
118 quantity: 1,
119 origins: [{ origin, quantity: 1 }]
120 });
121 const inserted = insertStack(slots, worn, def);
122 assert.equal(inserted.ok, true);
123 assert.equal(inserted.slots[0].quantity, 6);
124 assert.equal(inserted.slots.filter(Boolean).length, 1);
125 });
@@ -0,0 +1,125 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { ItemOriginKind, formatOriginBreakdown, mergeOriginLists, splitOrigins } from "../../shared/items/origin.js";
4import { emptySlots, insertStack, takeFromSlot, insertStackGrowable, singleItemFromStack } from "../../shared/items/inventory.js";
5import { stackRulesFor } from "../../shared/items/stackRules.js";
6import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
7
8const crafterA = { kind: ItemOriginKind.crafted, displayName: "Ada" };
9const crafterB = { kind: ItemOriginKind.crafted, displayName: "Bob" };
10
11test("mixed-origin stacks merge and show a breakdown label", () =>
12{
13 const slots = emptySlots();
14 const def = itemDefinition(ItemId.apple);
15 const first = insertStack(slots, {
16 itemId: ItemId.apple,
17 quantity: 5,
18 origins: [{ origin: crafterA, quantity: 5 }]
19 }, def);
20 const second = insertStack(first.slots, {
21 itemId: ItemId.apple,
22 quantity: 3,
23 origins: [{ origin: crafterB, quantity: 3 }]
24 }, def);
25 assert.equal(second.ok, true);
26 assert.equal(second.slots[0].quantity, 8);
27 assert.equal(formatOriginBreakdown(second.slots[0]), "5 made by Ada, 3 made by Bob");
28});
29
30test("splitting a stack distributes origins FIFO", () =>
31{
32 const slots = emptySlots();
33 const def = itemDefinition(ItemId.apple);
34 const inserted = insertStack(slots, {
35 itemId: ItemId.apple,
36 quantity: 8,
37 origins: [
38 { origin: crafterA, quantity: 5 },
39 { origin: crafterB, quantity: 3 }
40 ]
41 }, def);
42 const taken = takeFromSlot(inserted.slots, 0, 6);
43 assert.equal(taken.taken.quantity, 6);
44 assert.deepEqual(taken.taken.origins, [
45 { origin: crafterA, quantity: 5 },
46 { origin: crafterB, quantity: 1 }
47 ]);
48 assert.deepEqual(taken.slots[0].origins, [
49 { origin: crafterB, quantity: 2 }
50 ]);
51});
52
53test("equipment stacks only in inventory, but can stack in the vault", () =>
54{
55 const shirt = itemDefinition(ItemId.clothShirt);
56 const invRules = stackRulesFor(shirt, { inVault: false });
57 const vaultRules = stackRulesFor(shirt, { inVault: true });
58 assert.equal(invRules.maxStackSize, 1);
59 assert.equal(invRules.stackable, false);
60 assert.equal(vaultRules.stackable, true);
61 assert.equal(vaultRules.maxStackSize, Number.POSITIVE_INFINITY);
62
63 const inv = insertStack(emptySlots(), { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
64 const invSecond = insertStack(inv.slots, { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
65 assert.equal(invSecond.slots.filter(Boolean).length, 2);
66
67 const vault = insertStackGrowable([], { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
68 const vaultSecond = insertStackGrowable(vault.slots, { itemId: ItemId.clothShirt, quantity: 1 }, shirt);
69 assert.equal(vaultSecond.slots.length, 1);
70 assert.equal(vaultSecond.slots[0].quantity, 2);
71});
72
73test("unique items never stack, even in the vault", () =>
74{
75 const letter = itemDefinition(ItemId.letter);
76 const vaultRules = stackRulesFor(letter, { inVault: true });
77 assert.equal(vaultRules.uniqueInstance, true);
78 assert.equal(vaultRules.stackable, false);
79
80 const first = insertStackGrowable([], {
81 itemId: ItemId.letter,
82 quantity: 1,
83 instance: { kind: "letter", letterId: "a", body: "Hi" }
84 }, letter);
85 const second = insertStackGrowable(first.slots, {
86 itemId: ItemId.letter,
87 quantity: 1,
88 instance: { kind: "letter", letterId: "b", body: "Bye" }
89 }, letter);
90 assert.equal(second.slots.length, 2);
91});
92
93test("mergeOriginLists combines matching crafters", () =>
94{
95 const merged = mergeOriginLists(
96 [{ origin: crafterA, quantity: 2 }],
97 [{ origin: crafterA, quantity: 3 }, { origin: crafterB, quantity: 1 }]
98 );
99 assert.deepEqual(merged, [
100 { origin: crafterA, quantity: 5 },
101 { origin: crafterB, quantity: 1 }
102 ]);
103 const split = splitOrigins(merged, 6);
104 assert.deepEqual(split.taken, [
105 { origin: crafterA, quantity: 5 },
106 { origin: crafterB, quantity: 1 }
107 ]);
108});
109
110test("unequip-style insert merges stackable items within max stack size", () =>
111{
112 const def = itemDefinition(ItemId.apple);
113 const origin = { kind: ItemOriginKind.crafted, displayName: "Ada" };
114 let slots = emptySlots();
115 slots[0] = { itemId: ItemId.apple, quantity: 5, origins: [{ origin, quantity: 5 }] };
116 const worn = singleItemFromStack({
117 itemId: ItemId.apple,
118 quantity: 1,
119 origins: [{ origin, quantity: 1 }]
120 });
121 const inserted = insertStack(slots, worn, def);
122 assert.equal(inserted.ok, true);
123 assert.equal(inserted.slots[0].quantity, 6);
124 assert.equal(inserted.slots.filter(Boolean).length, 1);
125});
server/tests/skills.test.js added +146 −0
@@ -0,0 +1,146 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 SKILL_XP_BASE,
5 xpToAdvanceFromLevel,
6 totalXpForLevel,
7 xpProgress,
8 levelFromTotalXp,
9 combatHitXpPerSkill
10 } from "../../shared/skills/progression.js";
11 import {
12 normalizeSkillXp,
13 normalizePlayerSkills,
14 defaultPlayerSkills,
15 addSkillXp,
16 publicSkillsView
17 } from "../../shared/skills/state.js";
18 import { skillLevel, SkillId, playerMaxHealth } from "../../shared/definitions/skills.js";
19 import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
20 import { mobComponents } from "../src/simulation/spawners.js";
21 import { MobId } from "../../shared/definitions/mobs.js";
22 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
23
24 test("xp to advance doubles each level starting at 50", () =>
25 {
26 assert.equal(xpToAdvanceFromLevel(1), 50);
27 assert.equal(xpToAdvanceFromLevel(2), 100);
28 assert.equal(xpToAdvanceFromLevel(3), 200);
29 assert.equal(xpToAdvanceFromLevel(99), 0);
30 });
31
32 test("level is derived from total xp", () =>
33 {
34 assert.equal(levelFromTotalXp(0), 1);
35 assert.equal(levelFromTotalXp(SKILL_XP_BASE - 1), 1);
36 assert.equal(levelFromTotalXp(SKILL_XP_BASE), 2);
37 assert.equal(totalXpForLevel(2), SKILL_XP_BASE);
38 assert.equal(totalXpForLevel(3), SKILL_XP_BASE + xpToAdvanceFromLevel(2));
39 });
40
41 test("skills cap at level 99", () =>
42 {
43 const capped = totalXpForLevel(100) - 1;
44 assert.equal(levelFromTotalXp(capped), 99);
45 const progress = xpProgress(capped);
46 assert.equal(progress.level, 99);
47 assert.equal(progress.xpToNext, 0);
48 });
49
50 test("xp progress reports in-level remainder", () =>
51 {
52 const progress = xpProgress(SKILL_XP_BASE + 25);
53 assert.equal(progress.level, 2);
54 assert.equal(progress.xpInLevel, 25);
55 assert.equal(progress.xpToNext, xpToAdvanceFromLevel(2));
56 });
57
58 test("normalizeSkillXp fills every skill id", () =>
59 {
60 const xp = normalizeSkillXp({ [SkillId.strength]: 42 });
61 assert.equal(xp[SkillId.strength], 42);
62 assert.equal(xp[SkillId.magic], 0);
63 });
64
65 test("skillLevel reads player xp and mob levels", () =>
66 {
67 assert.equal(skillLevel(normalizePlayerSkills(null), SkillId.clubfighting), 1);
68 assert.equal(skillLevel({ xp: { [SkillId.strength]: SKILL_XP_BASE } }, SkillId.strength), 2);
69 assert.equal(skillLevel({ levels: { [SkillId.unarmed]: 5 } }, SkillId.unarmed), 5);
70 });
71
72 test("new characters start with Health level 10", () =>
73 {
74 const skills = defaultPlayerSkills();
75 assert.equal(skillLevel(skills, SkillId.health), 10);
76 assert.equal(skillLevel(skills, SkillId.strength), 1);
77 assert.equal(playerMaxHealth(skills), 10);
78 });
79
80 test("publicSkillsView exposes progress fields for the client", () =>
81 {
82 const view = publicSkillsView(normalizePlayerSkills({ [SkillId.clubfighting]: 50 }));
83 const club = view.find((entry) => entry.skillId === SkillId.clubfighting);
84 assert.equal(club.level, 2);
85 assert.equal(club.xp, 0);
86 assert.equal(club.xpToNext, xpToAdvanceFromLevel(2));
87 assert.match(club.icon, /clubfighting\.svg$/);
88 });
89
90 test("addSkillXp mutates the player skills component", () =>
91 {
92 const skills = normalizePlayerSkills(null);
93 addSkillXp(skills, SkillId.strength, 10);
94 assert.equal(skills.xp[SkillId.strength], 10);
95 });
96
97 test("combat hit xp is split equally", () =>
98 {
99 assert.equal(combatHitXpPerSkill(), 5);
100 });
101
102 test("successful player melee hits award split xp", () =>
103 {
104 const harness = makeSimulation({ workerCount: 1 });
105 const random = Math.random;
106 Math.random = () => 0;
107 try
108 {
109 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
110 const playerId = harness.simulation.spawnCharacter(1, character);
111 const ratId = harness.simulation.spawnEntity(mobComponents({
112 mobTypeId: MobId.rat,
113 position: { tileX: 9, tileY: 8 }
114 }));
115 const worker = harness.simulation.workers[0];
116 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(playerId));
117 const events = resolveMeleeSwing(worker.world, playerId, ratId, profile, Date.now());
118 const updated = events.find((event) => event.type === "skills-updated");
119 assert.ok(updated);
120 assert.equal(updated.stored[profile.hitSkillId], combatHitXpPerSkill());
121 assert.equal(updated.stored[profile.damageSkillId], combatHitXpPerSkill());
122 }
123 finally
124 {
125 Math.random = random;
126 harness.close();
127 }
128 });
129
130 test("skills persist when a character despawns", () =>
131 {
132 const harness = makeSimulation({ workerCount: 1 });
133 try
134 {
135 const character = makeCharacter(harness.stateDb);
136 const playerId = harness.simulation.spawnCharacter(1, character);
137 const worker = harness.simulation.workers[0];
138 const skills = worker.world.ecs.get(worker.world.ecs.handleOf(playerId), "skills");
139 skills.xp[SkillId.strength] = SKILL_XP_BASE + 10;
140 harness.simulation.despawnCharacter(character.character_id);
141 const stored = harness.stateDb.getSkills(character.character_id);
142 assert.equal(stored.xp[SkillId.strength], SKILL_XP_BASE + 10);
143 }
144 finally
145 { harness.close(); }
146 });
@@ -0,0 +1,146 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 SKILL_XP_BASE,
5 xpToAdvanceFromLevel,
6 totalXpForLevel,
7 xpProgress,
8 levelFromTotalXp,
9 combatHitXpPerSkill
10} from "../../shared/skills/progression.js";
11import {
12 normalizeSkillXp,
13 normalizePlayerSkills,
14 defaultPlayerSkills,
15 addSkillXp,
16 publicSkillsView
17} from "../../shared/skills/state.js";
18import { skillLevel, SkillId, playerMaxHealth } from "../../shared/definitions/skills.js";
19import { resolveMeleeSwing, attackProfileOf } from "../src/combat/service.js";
20import { mobComponents } from "../src/simulation/spawners.js";
21import { MobId } from "../../shared/definitions/mobs.js";
22import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
23
24test("xp to advance doubles each level starting at 50", () =>
25{
26 assert.equal(xpToAdvanceFromLevel(1), 50);
27 assert.equal(xpToAdvanceFromLevel(2), 100);
28 assert.equal(xpToAdvanceFromLevel(3), 200);
29 assert.equal(xpToAdvanceFromLevel(99), 0);
30});
31
32test("level is derived from total xp", () =>
33{
34 assert.equal(levelFromTotalXp(0), 1);
35 assert.equal(levelFromTotalXp(SKILL_XP_BASE - 1), 1);
36 assert.equal(levelFromTotalXp(SKILL_XP_BASE), 2);
37 assert.equal(totalXpForLevel(2), SKILL_XP_BASE);
38 assert.equal(totalXpForLevel(3), SKILL_XP_BASE + xpToAdvanceFromLevel(2));
39});
40
41test("skills cap at level 99", () =>
42{
43 const capped = totalXpForLevel(100) - 1;
44 assert.equal(levelFromTotalXp(capped), 99);
45 const progress = xpProgress(capped);
46 assert.equal(progress.level, 99);
47 assert.equal(progress.xpToNext, 0);
48});
49
50test("xp progress reports in-level remainder", () =>
51{
52 const progress = xpProgress(SKILL_XP_BASE + 25);
53 assert.equal(progress.level, 2);
54 assert.equal(progress.xpInLevel, 25);
55 assert.equal(progress.xpToNext, xpToAdvanceFromLevel(2));
56});
57
58test("normalizeSkillXp fills every skill id", () =>
59{
60 const xp = normalizeSkillXp({ [SkillId.strength]: 42 });
61 assert.equal(xp[SkillId.strength], 42);
62 assert.equal(xp[SkillId.magic], 0);
63});
64
65test("skillLevel reads player xp and mob levels", () =>
66{
67 assert.equal(skillLevel(normalizePlayerSkills(null), SkillId.clubfighting), 1);
68 assert.equal(skillLevel({ xp: { [SkillId.strength]: SKILL_XP_BASE } }, SkillId.strength), 2);
69 assert.equal(skillLevel({ levels: { [SkillId.unarmed]: 5 } }, SkillId.unarmed), 5);
70});
71
72test("new characters start with Health level 10", () =>
73{
74 const skills = defaultPlayerSkills();
75 assert.equal(skillLevel(skills, SkillId.health), 10);
76 assert.equal(skillLevel(skills, SkillId.strength), 1);
77 assert.equal(playerMaxHealth(skills), 10);
78});
79
80test("publicSkillsView exposes progress fields for the client", () =>
81{
82 const view = publicSkillsView(normalizePlayerSkills({ [SkillId.clubfighting]: 50 }));
83 const club = view.find((entry) => entry.skillId === SkillId.clubfighting);
84 assert.equal(club.level, 2);
85 assert.equal(club.xp, 0);
86 assert.equal(club.xpToNext, xpToAdvanceFromLevel(2));
87 assert.match(club.icon, /clubfighting\.svg$/);
88});
89
90test("addSkillXp mutates the player skills component", () =>
91{
92 const skills = normalizePlayerSkills(null);
93 addSkillXp(skills, SkillId.strength, 10);
94 assert.equal(skills.xp[SkillId.strength], 10);
95});
96
97test("combat hit xp is split equally", () =>
98{
99 assert.equal(combatHitXpPerSkill(), 5);
100});
101
102test("successful player melee hits award split xp", () =>
103{
104 const harness = makeSimulation({ workerCount: 1 });
105 const random = Math.random;
106 Math.random = () => 0;
107 try
108 {
109 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
110 const playerId = harness.simulation.spawnCharacter(1, character);
111 const ratId = harness.simulation.spawnEntity(mobComponents({
112 mobTypeId: MobId.rat,
113 position: { tileX: 9, tileY: 8 }
114 }));
115 const worker = harness.simulation.workers[0];
116 const profile = attackProfileOf(worker.world.ecs, worker.world.ecs.handleOf(playerId));
117 const events = resolveMeleeSwing(worker.world, playerId, ratId, profile, Date.now());
118 const updated = events.find((event) => event.type === "skills-updated");
119 assert.ok(updated);
120 assert.equal(updated.stored[profile.hitSkillId], combatHitXpPerSkill());
121 assert.equal(updated.stored[profile.damageSkillId], combatHitXpPerSkill());
122 }
123 finally
124 {
125 Math.random = random;
126 harness.close();
127 }
128});
129
130test("skills persist when a character despawns", () =>
131{
132 const harness = makeSimulation({ workerCount: 1 });
133 try
134 {
135 const character = makeCharacter(harness.stateDb);
136 const playerId = harness.simulation.spawnCharacter(1, character);
137 const worker = harness.simulation.workers[0];
138 const skills = worker.world.ecs.get(worker.world.ecs.handleOf(playerId), "skills");
139 skills.xp[SkillId.strength] = SKILL_XP_BASE + 10;
140 harness.simulation.despawnCharacter(character.character_id);
141 const stored = harness.stateDb.getSkills(character.character_id);
142 assert.equal(stored.xp[SkillId.strength], SKILL_XP_BASE + 10);
143 }
144 finally
145 { harness.close(); }
146});
shared/combat/magic.js added +126 −0
@@ -0,0 +1,126 @@
1 import { rollSkill } from "./rolls.js";
2
3 /**
4 * Magic attack resolution — cast step is implemented; full combat wiring is later.
5 *
6 * Flow:
7 * 1. Roll Magic vs per-spell difficulty (contest) — fizzle if magicRoll < difficultyRoll
8 * 2. On success with damage: roll Mind for spell damage
9 * 3. Compare spell element to target weaknesses/resistances (×2 / ×0.5 / ×1)
10 * 4. Apply damage, or apply a non-damage effect when the spell defines one
11 */
12
13 export const ElementMultiplier = Object.freeze({
14 weak: 2,
15 neutral: 1,
16 resistant: 0.5
17 });
18
19 /** @typedef {"fire"|"water"|"earth"|"air"|"holy"|"dark"|"none"} SpellElement */
20
21 /**
22 * Whether the caster successfully channels the spell.
23 * Magic roll vs a difficulty roll sized by spell.difficulty.
24 * Succeeds on tie or higher (same rule as physical hit vs agility).
25 */
26 export function resolveSpellCast ({
27 magicSkillLevel,
28 spellDifficulty,
29 rng = Math.random
30 })
31 {
32 const magicRoll = rollSkill(magicSkillLevel, rng);
33 const difficultyRoll = rollSkill(spellDifficulty, rng);
34 const success = magicRoll >= difficultyRoll;
35 return {
36 success,
37 magicRoll,
38 difficultyRoll
39 };
40 }
41
42 function elementalMultiplier (element, targetAffinities = {})
43 {
44 const affinity = targetAffinities[element];
45 if (affinity === "weak")
46 { return ElementMultiplier.weak; }
47 if (affinity === "resistant")
48 { return ElementMultiplier.resistant; }
49 return ElementMultiplier.neutral;
50 }
51
52 /**
53 * Full magic attack resolution (shared rules, not wired to server combat yet).
54 * @param {object} params
55 * @param {number} params.magicSkillLevel
56 * @param {number} params.spellDifficulty
57 * @param {number} params.mindSkillLevel
58 * @param {number} [params.baseDamage]
59 * @param {SpellElement} [params.element]
60 * @param {Partial<Record<SpellElement, "weak"|"resistant"|"neutral">>} [params.targetAffinities]
61 * @param {() => number} [params.rng]
62 */
63 export function resolveMagicAttack ({
64 magicSkillLevel,
65 spellDifficulty,
66 mindSkillLevel,
67 baseDamage = 1,
68 element = "none",
69 targetAffinities = {},
70 rng = Math.random
71 })
72 {
73 const cast = resolveSpellCast({ magicSkillLevel, spellDifficulty, rng });
74 if (!cast.success)
75 {
76 return {
77 outcome: "fizzle",
78 magicRoll: cast.magicRoll,
79 difficultyRoll: cast.difficultyRoll,
80 damage: 0,
81 multiplier: 1
82 };
83 }
84
85 const mindRoll = rollSkill(mindSkillLevel, rng);
86 const rawDamage = Math.max(1, (baseDamage | 0) + mindRoll - 1);
87 const multiplier = elementalMultiplier(element, targetAffinities);
88 const damage = Math.max(1, Math.floor(rawDamage * multiplier));
89
90 return {
91 outcome: "hit",
92 magicRoll: cast.magicRoll,
93 difficultyRoll: cast.difficultyRoll,
94 mindRoll,
95 damage,
96 multiplier
97 };
98 }
99
100 /**
101 * Non-damage spells: Magic vs spell difficulty, then apply effectId.
102 */
103 export function resolveMagicEffect ({
104 magicSkillLevel,
105 spellDifficulty,
106 effectId,
107 rng = Math.random
108 })
109 {
110 const cast = resolveSpellCast({ magicSkillLevel, spellDifficulty, rng });
111 if (!cast.success)
112 {
113 return {
114 outcome: "fizzle",
115 magicRoll: cast.magicRoll,
116 difficultyRoll: cast.difficultyRoll,
117 effectId: null
118 };
119 }
120 return {
121 outcome: "effect",
122 magicRoll: cast.magicRoll,
123 difficultyRoll: cast.difficultyRoll,
124 effectId: effectId ?? null
125 };
126 }
@@ -0,0 +1,126 @@
1import { rollSkill } from "./rolls.js";
2
3/**
4 * Magic attack resolution — cast step is implemented; full combat wiring is later.
5 *
6 * Flow:
7 * 1. Roll Magic vs per-spell difficulty (contest) — fizzle if magicRoll < difficultyRoll
8 * 2. On success with damage: roll Mind for spell damage
9 * 3. Compare spell element to target weaknesses/resistances (×2 / ×0.5 / ×1)
10 * 4. Apply damage, or apply a non-damage effect when the spell defines one
11 */
12
13export const ElementMultiplier = Object.freeze({
14 weak: 2,
15 neutral: 1,
16 resistant: 0.5
17});
18
19/** @typedef {"fire"|"water"|"earth"|"air"|"holy"|"dark"|"none"} SpellElement */
20
21/**
22 * Whether the caster successfully channels the spell.
23 * Magic roll vs a difficulty roll sized by spell.difficulty.
24 * Succeeds on tie or higher (same rule as physical hit vs agility).
25 */
26export function resolveSpellCast ({
27 magicSkillLevel,
28 spellDifficulty,
29 rng = Math.random
30})
31{
32 const magicRoll = rollSkill(magicSkillLevel, rng);
33 const difficultyRoll = rollSkill(spellDifficulty, rng);
34 const success = magicRoll >= difficultyRoll;
35 return {
36 success,
37 magicRoll,
38 difficultyRoll
39 };
40}
41
42function elementalMultiplier (element, targetAffinities = {})
43{
44 const affinity = targetAffinities[element];
45 if (affinity === "weak")
46 { return ElementMultiplier.weak; }
47 if (affinity === "resistant")
48 { return ElementMultiplier.resistant; }
49 return ElementMultiplier.neutral;
50}
51
52/**
53 * Full magic attack resolution (shared rules, not wired to server combat yet).
54 * @param {object} params
55 * @param {number} params.magicSkillLevel
56 * @param {number} params.spellDifficulty
57 * @param {number} params.mindSkillLevel
58 * @param {number} [params.baseDamage]
59 * @param {SpellElement} [params.element]
60 * @param {Partial<Record<SpellElement, "weak"|"resistant"|"neutral">>} [params.targetAffinities]
61 * @param {() => number} [params.rng]
62 */
63export function resolveMagicAttack ({
64 magicSkillLevel,
65 spellDifficulty,
66 mindSkillLevel,
67 baseDamage = 1,
68 element = "none",
69 targetAffinities = {},
70 rng = Math.random
71})
72{
73 const cast = resolveSpellCast({ magicSkillLevel, spellDifficulty, rng });
74 if (!cast.success)
75 {
76 return {
77 outcome: "fizzle",
78 magicRoll: cast.magicRoll,
79 difficultyRoll: cast.difficultyRoll,
80 damage: 0,
81 multiplier: 1
82 };
83 }
84
85 const mindRoll = rollSkill(mindSkillLevel, rng);
86 const rawDamage = Math.max(1, (baseDamage | 0) + mindRoll - 1);
87 const multiplier = elementalMultiplier(element, targetAffinities);
88 const damage = Math.max(1, Math.floor(rawDamage * multiplier));
89
90 return {
91 outcome: "hit",
92 magicRoll: cast.magicRoll,
93 difficultyRoll: cast.difficultyRoll,
94 mindRoll,
95 damage,
96 multiplier
97 };
98}
99
100/**
101 * Non-damage spells: Magic vs spell difficulty, then apply effectId.
102 */
103export function resolveMagicEffect ({
104 magicSkillLevel,
105 spellDifficulty,
106 effectId,
107 rng = Math.random
108})
109{
110 const cast = resolveSpellCast({ magicSkillLevel, spellDifficulty, rng });
111 if (!cast.success)
112 {
113 return {
114 outcome: "fizzle",
115 magicRoll: cast.magicRoll,
116 difficultyRoll: cast.difficultyRoll,
117 effectId: null
118 };
119 }
120 return {
121 outcome: "effect",
122 magicRoll: cast.magicRoll,
123 difficultyRoll: cast.difficultyRoll,
124 effectId: effectId ?? null
125 };
126}
shared/combat/rolls.js added +62 −0
@@ -0,0 +1,62 @@
1 /** Uniform integer roll in [1, skillLevel]. */
2 export function rollSkill (skillLevel, rng = Math.random)
3 {
4 const max = Math.max(1, Math.floor(Number(skillLevel)) || 1);
5 return 1 + Math.floor(rng() * max);
6 }
7
8 /**
9 * Melee and ranged physical attack resolution (shared rules).
10 * 1. Roll hit skill vs defender agility (Dexterity) — miss if toHitRoll < agilityRoll
11 * 2. On hit: roll damage skill (Strength/Dexterity) for damage
12 * 3. On hit: defender rolls Defence — block if defenceRoll > toHitRoll
13 * 4. On hit and not blocked: apply rolled damage
14 */
15 export function resolvePhysicalAttack ({
16 hitSkillLevel,
17 agilitySkillLevel,
18 damageSkillLevel,
19 defenceSkillLevel,
20 baseDamage = 1,
21 rng = Math.random
22 })
23 {
24 const toHitRoll = rollSkill(hitSkillLevel, rng);
25 const agilityRoll = rollSkill(agilitySkillLevel, rng);
26 if (toHitRoll < agilityRoll)
27 {
28 return {
29 outcome: "miss",
30 toHitRoll,
31 agilityRoll,
32 damage: 0,
33 blocked: false
34 };
35 }
36
37 const damageRoll = rollSkill(damageSkillLevel, rng);
38 const damage = Math.max(1, (baseDamage | 0) + damageRoll - 1);
39 const defenceRoll = rollSkill(defenceSkillLevel, rng);
40 if (defenceRoll > toHitRoll)
41 {
42 return {
43 outcome: "block",
44 toHitRoll,
45 agilityRoll,
46 damageRoll,
47 defenceRoll,
48 damage: 0,
49 blocked: true
50 };
51 }
52
53 return {
54 outcome: "hit",
55 toHitRoll,
56 agilityRoll,
57 damageRoll,
58 defenceRoll,
59 damage,
60 blocked: false
61 };
62 }
@@ -0,0 +1,62 @@
1/** Uniform integer roll in [1, skillLevel]. */
2export function rollSkill (skillLevel, rng = Math.random)
3{
4 const max = Math.max(1, Math.floor(Number(skillLevel)) || 1);
5 return 1 + Math.floor(rng() * max);
6}
7
8/**
9 * Melee and ranged physical attack resolution (shared rules).
10 * 1. Roll hit skill vs defender agility (Dexterity) — miss if toHitRoll < agilityRoll
11 * 2. On hit: roll damage skill (Strength/Dexterity) for damage
12 * 3. On hit: defender rolls Defence — block if defenceRoll > toHitRoll
13 * 4. On hit and not blocked: apply rolled damage
14 */
15export function resolvePhysicalAttack ({
16 hitSkillLevel,
17 agilitySkillLevel,
18 damageSkillLevel,
19 defenceSkillLevel,
20 baseDamage = 1,
21 rng = Math.random
22})
23{
24 const toHitRoll = rollSkill(hitSkillLevel, rng);
25 const agilityRoll = rollSkill(agilitySkillLevel, rng);
26 if (toHitRoll < agilityRoll)
27 {
28 return {
29 outcome: "miss",
30 toHitRoll,
31 agilityRoll,
32 damage: 0,
33 blocked: false
34 };
35 }
36
37 const damageRoll = rollSkill(damageSkillLevel, rng);
38 const damage = Math.max(1, (baseDamage | 0) + damageRoll - 1);
39 const defenceRoll = rollSkill(defenceSkillLevel, rng);
40 if (defenceRoll > toHitRoll)
41 {
42 return {
43 outcome: "block",
44 toHitRoll,
45 agilityRoll,
46 damageRoll,
47 defenceRoll,
48 damage: 0,
49 blocked: true
50 };
51 }
52
53 return {
54 outcome: "hit",
55 toHitRoll,
56 agilityRoll,
57 damageRoll,
58 defenceRoll,
59 damage,
60 blocked: false
61 };
62}
shared/crafting/recipes.js added +95 −0
@@ -0,0 +1,95 @@
1 import { itemDefinition } from "../definitions/items.js";
2 import { insertStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
3
4 export { recipesForStation, recipeDefinition, recipeStationIds } from "./stationRecipes.js";
5
6 /** Fixed craft time for every station recipe (ms). */
7 export const CRAFT_DURATION_MS = 2000;
8
9 function takeItemPreservingSlots (slots, itemId, quantity)
10 {
11 let remaining = Math.max(0, stackQuantity(quantity));
12 if (!remaining)
13 { return { ok: false, slots }; }
14 let next = slots.map((slot) => slot ? structuredClone(slot) : null);
15 for (let i = 0; i < next.length && remaining > 0; i++)
16 {
17 if (!next[i] || next[i].itemId !== itemId)
18 { continue; }
19 const taken = takeFromSlot(next, i, remaining);
20 if (!taken.ok || !taken.taken)
21 { continue; }
22 next = taken.slots;
23 remaining -= stackQuantity(taken.taken.quantity);
24 }
25 return { ok: remaining === 0, slots: next };
26 }
27
28 /**
29 * Recipe shape: `{ output: { itemId, quantity }, inputs: [{ itemId, quantity }] }`.
30 * Returns whether the player has the inputs and, after consuming them, room for the output.
31 * Freed slots from consumed stacks count toward output space.
32 */
33 export function canCraftFitInventory (slots, recipe)
34 {
35 if (!recipe?.output?.itemId || !Array.isArray(recipe.inputs))
36 { return false; }
37 let next = slots;
38 for (const input of recipe.inputs)
39 {
40 const qty = input.quantity | 0;
41 if (qty <= 0)
42 { continue; }
43 const taken = takeItemPreservingSlots(next, input.itemId, qty);
44 if (!taken.ok)
45 { return false; }
46 next = taken.slots;
47 }
48 const def = itemDefinition(recipe.output.itemId);
49 if (!def)
50 { return false; }
51 const added = insertStack(next, {
52 itemId: recipe.output.itemId,
53 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
54 }, def);
55 return added.ok && added.remainder === 0;
56 }
57
58 export function countItemInSlots (slots, itemId)
59 {
60 let total = 0;
61 for (const slot of slots ?? [])
62 {
63 if (slot?.itemId === itemId)
64 { total += stackQuantity(slot.quantity); }
65 }
66 return total;
67 }
68
69 export function hasRecipeInputs (slots, recipe)
70 {
71 if (!recipe?.inputs?.length)
72 { return false; }
73 for (const input of recipe.inputs)
74 {
75 const need = input.quantity | 0;
76 if (need <= 0)
77 { continue; }
78 if (countItemInSlots(slots, input.itemId) < need)
79 { return false; }
80 }
81 return true;
82 }
83
84 /** Whether the player meets skill, has inputs, and bag space after consumption. */
85 export function canStartCraft (slots, recipe, skillLevel = 1)
86 {
87 if (!recipe?.output?.itemId)
88 { return false; }
89 const minLevel = recipe.minSkillLevel | 0 || 1;
90 if ((skillLevel | 0) < minLevel)
91 { return false; }
92 if (!hasRecipeInputs(slots, recipe))
93 { return false; }
94 return canCraftFitInventory(slots, recipe);
95 }
@@ -0,0 +1,95 @@
1import { itemDefinition } from "../definitions/items.js";
2import { insertStack, stackQuantity, takeFromSlot } from "../items/inventory.js";
3
4export { recipesForStation, recipeDefinition, recipeStationIds } from "./stationRecipes.js";
5
6/** Fixed craft time for every station recipe (ms). */
7export const CRAFT_DURATION_MS = 2000;
8
9function takeItemPreservingSlots (slots, itemId, quantity)
10{
11 let remaining = Math.max(0, stackQuantity(quantity));
12 if (!remaining)
13 { return { ok: false, slots }; }
14 let next = slots.map((slot) => slot ? structuredClone(slot) : null);
15 for (let i = 0; i < next.length && remaining > 0; i++)
16 {
17 if (!next[i] || next[i].itemId !== itemId)
18 { continue; }
19 const taken = takeFromSlot(next, i, remaining);
20 if (!taken.ok || !taken.taken)
21 { continue; }
22 next = taken.slots;
23 remaining -= stackQuantity(taken.taken.quantity);
24 }
25 return { ok: remaining === 0, slots: next };
26}
27
28/**
29 * Recipe shape: `{ output: { itemId, quantity }, inputs: [{ itemId, quantity }] }`.
30 * Returns whether the player has the inputs and, after consuming them, room for the output.
31 * Freed slots from consumed stacks count toward output space.
32 */
33export function canCraftFitInventory (slots, recipe)
34{
35 if (!recipe?.output?.itemId || !Array.isArray(recipe.inputs))
36 { return false; }
37 let next = slots;
38 for (const input of recipe.inputs)
39 {
40 const qty = input.quantity | 0;
41 if (qty <= 0)
42 { continue; }
43 const taken = takeItemPreservingSlots(next, input.itemId, qty);
44 if (!taken.ok)
45 { return false; }
46 next = taken.slots;
47 }
48 const def = itemDefinition(recipe.output.itemId);
49 if (!def)
50 { return false; }
51 const added = insertStack(next, {
52 itemId: recipe.output.itemId,
53 quantity: Math.max(1, recipe.output.quantity | 0 || 1)
54 }, def);
55 return added.ok && added.remainder === 0;
56}
57
58export function countItemInSlots (slots, itemId)
59{
60 let total = 0;
61 for (const slot of slots ?? [])
62 {
63 if (slot?.itemId === itemId)
64 { total += stackQuantity(slot.quantity); }
65 }
66 return total;
67}
68
69export function hasRecipeInputs (slots, recipe)
70{
71 if (!recipe?.inputs?.length)
72 { return false; }
73 for (const input of recipe.inputs)
74 {
75 const need = input.quantity | 0;
76 if (need <= 0)
77 { continue; }
78 if (countItemInSlots(slots, input.itemId) < need)
79 { return false; }
80 }
81 return true;
82}
83
84/** Whether the player meets skill, has inputs, and bag space after consumption. */
85export function canStartCraft (slots, recipe, skillLevel = 1)
86{
87 if (!recipe?.output?.itemId)
88 { return false; }
89 const minLevel = recipe.minSkillLevel | 0 || 1;
90 if ((skillLevel | 0) < minLevel)
91 { return false; }
92 if (!hasRecipeInputs(slots, recipe))
93 { return false; }
94 return canCraftFitInventory(slots, recipe);
95}
shared/crafting/stationRecipes.js added +74 −0
@@ -0,0 +1,74 @@
1 import { CraftingStationId } from "../definitions/craftingStations.js";
2 import { ItemId } from "../definitions/items.js";
3
4 /**
5 * Craft recipe schema (shared client + server):
6 *
7 * - recipeId: stable string id
8 * - stationId | stationIds: where the recipe appears (use stationIds for oven + campfire)
9 * - output: { itemId, quantity }
10 * - inputs: [{ itemId, quantity }, ...]
11 * - minSkillLevel: minimum linked station skill (default 1)
12 * - burnChanceOven / burnChanceFireplace: cooking-only, 0–1 when skill is below min (TBD)
13 */
14
15 /** @type {ReadonlyArray<object>} */
16 export const CRAFT_RECIPES = Object.freeze([
17 // UI/dev placeholder — replace with real bench recipes.
18 Object.freeze({
19 recipeId: "dev-stick-from-paper",
20 stationId: CraftingStationId.craftingBench,
21 output: { itemId: ItemId.stick, quantity: 1 },
22 inputs: [{ itemId: ItemId.paper, quantity: 2 }],
23 minSkillLevel: 1
24 }),
25
26 // --- Furnace (smelt ore → bars) ---
27 // { recipeId: "smelt-bronze", stationId: CraftingStationId.furnace, ... },
28
29 // --- Spinning wheel (wool → thread) ---
30 // { recipeId: "spin-thread", stationId: CraftingStationId.spinningWheel, ... },
31
32 // --- Loom (cloth garments) ---
33 // { recipeId: "weave-cloth-shirt", stationId: CraftingStationId.loom, ... },
34
35 // --- Anvil (bars → metal items) ---
36 // { recipeId: "smith-bronze-sword", stationId: CraftingStationId.anvil, ... },
37
38 // --- Leatherworking station ---
39 // { recipeId: "craft-leather-body", stationId: CraftingStationId.leatherworkingStation, ... },
40
41 // --- Crafting bench (arrows, etc.) ---
42 // { recipeId: "fletch-arrow", stationId: CraftingStationId.craftingBench,
43 // output: { itemId: CraftingItemId.arrow, quantity: 1 },
44 // inputs: [{ itemId: CraftingItemId.arrowTip, quantity: 1 }, ...] },
45
46 // --- Cooking (oven + campfire share recipes via stationIds) ---
47 // { recipeId: "cook-meat", stationIds: [CraftingStationId.oven, CraftingStationId.fireplace],
48 // output: { itemId: CraftingItemId.cookedMeat, quantity: 1 },
49 // inputs: [{ itemId: CraftingItemId.rawMeat, quantity: 1 }],
50 // minSkillLevel: 1, burnChanceOven: 0.1, burnChanceFireplace: 0.25 }
51 ]);
52
53 const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
54
55 export function recipeDefinition (recipeId)
56 {
57 return RECIPE_BY_ID.get(recipeId) ?? null;
58 }
59
60 export function recipeStationIds (recipe)
61 {
62 if (!recipe)
63 { return []; }
64 if (Array.isArray(recipe.stationIds))
65 { return recipe.stationIds; }
66 if (recipe.stationId)
67 { return [recipe.stationId]; }
68 return [];
69 }
70
71 export function recipesForStation (stationId)
72 {
73 return CRAFT_RECIPES.filter((recipe) => recipeStationIds(recipe).includes(stationId));
74 }
@@ -0,0 +1,74 @@
1import { CraftingStationId } from "../definitions/craftingStations.js";
2import { ItemId } from "../definitions/items.js";
3
4/**
5 * Craft recipe schema (shared client + server):
6 *
7 * - recipeId: stable string id
8 * - stationId | stationIds: where the recipe appears (use stationIds for oven + campfire)
9 * - output: { itemId, quantity }
10 * - inputs: [{ itemId, quantity }, ...]
11 * - minSkillLevel: minimum linked station skill (default 1)
12 * - burnChanceOven / burnChanceFireplace: cooking-only, 0–1 when skill is below min (TBD)
13 */
14
15/** @type {ReadonlyArray<object>} */
16export const CRAFT_RECIPES = Object.freeze([
17 // UI/dev placeholder — replace with real bench recipes.
18 Object.freeze({
19 recipeId: "dev-stick-from-paper",
20 stationId: CraftingStationId.craftingBench,
21 output: { itemId: ItemId.stick, quantity: 1 },
22 inputs: [{ itemId: ItemId.paper, quantity: 2 }],
23 minSkillLevel: 1
24 }),
25
26 // --- Furnace (smelt ore → bars) ---
27 // { recipeId: "smelt-bronze", stationId: CraftingStationId.furnace, ... },
28
29 // --- Spinning wheel (wool → thread) ---
30 // { recipeId: "spin-thread", stationId: CraftingStationId.spinningWheel, ... },
31
32 // --- Loom (cloth garments) ---
33 // { recipeId: "weave-cloth-shirt", stationId: CraftingStationId.loom, ... },
34
35 // --- Anvil (bars → metal items) ---
36 // { recipeId: "smith-bronze-sword", stationId: CraftingStationId.anvil, ... },
37
38 // --- Leatherworking station ---
39 // { recipeId: "craft-leather-body", stationId: CraftingStationId.leatherworkingStation, ... },
40
41 // --- Crafting bench (arrows, etc.) ---
42 // { recipeId: "fletch-arrow", stationId: CraftingStationId.craftingBench,
43 // output: { itemId: CraftingItemId.arrow, quantity: 1 },
44 // inputs: [{ itemId: CraftingItemId.arrowTip, quantity: 1 }, ...] },
45
46 // --- Cooking (oven + campfire share recipes via stationIds) ---
47 // { recipeId: "cook-meat", stationIds: [CraftingStationId.oven, CraftingStationId.fireplace],
48 // output: { itemId: CraftingItemId.cookedMeat, quantity: 1 },
49 // inputs: [{ itemId: CraftingItemId.rawMeat, quantity: 1 }],
50 // minSkillLevel: 1, burnChanceOven: 0.1, burnChanceFireplace: 0.25 }
51]);
52
53const RECIPE_BY_ID = new Map(CRAFT_RECIPES.map((recipe) => [recipe.recipeId, recipe]));
54
55export function recipeDefinition (recipeId)
56{
57 return RECIPE_BY_ID.get(recipeId) ?? null;
58}
59
60export function recipeStationIds (recipe)
61{
62 if (!recipe)
63 { return []; }
64 if (Array.isArray(recipe.stationIds))
65 { return recipe.stationIds; }
66 if (recipe.stationId)
67 { return [recipe.stationId]; }
68 return [];
69}
70
71export function recipesForStation (stationId)
72{
73 return CRAFT_RECIPES.filter((recipe) => recipeStationIds(recipe).includes(stationId));
74}
shared/definitions/attackTypes.js added +6 −0
@@ -0,0 +1,6 @@
1 /** Physical weapon damage style; mobs may be weak or resistant (later). */
2 export const AttackType = Object.freeze({
3 slashing: "slashing",
4 piercing: "piercing",
5 blunt: "blunt"
6 });
@@ -0,0 +1,6 @@
1/** Physical weapon damage style; mobs may be weak or resistant (later). */
2export const AttackType = Object.freeze({
3 slashing: "slashing",
4 piercing: "piercing",
5 blunt: "blunt"
6});
shared/definitions/craftingItems.js added +114 −0
@@ -0,0 +1,114 @@
1 import { ItemCategory } from "./itemCategories.js";
2
3 const DEFAULT_STACK = 99;
4
5 /**
6 * Reserved numeric IDs for gathering, crafting, and cooking content.
7 * Fill in full definitions in ITEM_DEFINITIONS (or replace these stubs) once
8 * tier rules, stack caps, equipment stats, and sprites are final.
9 *
10 * Tiered families (ore, bars, metal gear, leather, cloth, wizard cloth) should
11 * follow `{tier}-{kind}` keys — e.g. `iron-ore`, `steel-bar`, `mithril-sword`.
12 */
13 export const CraftingItemId = Object.freeze({
14 log: 9,
15 tinderbox: 10,
16 wool: 11,
17 thread: 12,
18 bronzeOre: 13,
19 bronzeBar: 14,
20 rawMeat: 15,
21 cookedMeat: 16,
22 leather: 17,
23 arrowTip: 18,
24 arrow: 19,
25 bronzeAxe: 20,
26 bronzePickaxe: 21,
27 fishingRod: 22,
28 fishingNet: 23,
29 rawFish: 24,
30 cloth: 25
31 });
32
33 function stub (itemId, key, displayName, category, extra = {})
34 {
35 return Object.freeze({
36 itemId,
37 key,
38 displayName,
39 description: extra.description ?? "Placeholder — complete this definition when content rules are set.",
40 seedValue: extra.seedValue ?? 1,
41 stackable: extra.stackable ?? true,
42 maxStackSize: extra.maxStackSize ?? DEFAULT_STACK,
43 uniqueInstance: false,
44 category,
45 stub: true,
46 iconKey: extra.iconKey ?? "paper",
47 ...extra
48 });
49 }
50
51 /** Minimal defs so recipes and the craft UI can resolve names/icons before art exists. */
52 export const CRAFTING_ITEM_STUBS = Object.freeze({
53 [CraftingItemId.log]: stub(CraftingItemId.log, "log", "Log", ItemCategory.ingredient, {
54 description: "Firewood. Drop on the ground and light with a tinderbox (see Crafting stations)."
55 }),
56 [CraftingItemId.tinderbox]: stub(CraftingItemId.tinderbox, "tinderbox", "Tinderbox", ItemCategory.tool, {
57 stackable: false,
58 maxStackSize: 1,
59 description: "Lights campfires from dropped logs."
60 }),
61 [CraftingItemId.wool]: stub(CraftingItemId.wool, "wool", "Wool", ItemCategory.ingredient, {
62 description: "Shorn from sheep. Spin into thread at a spinning wheel."
63 }),
64 [CraftingItemId.thread]: stub(CraftingItemId.thread, "thread", "Thread", ItemCategory.intermediate, {
65 description: "Spun wool. Used at a loom."
66 }),
67 [CraftingItemId.bronzeOre]: stub(CraftingItemId.bronzeOre, "bronze-ore", "Bronze ore", ItemCategory.ingredient, {
68 description: "Mined ore. Smelt at a furnace into bars."
69 }),
70 [CraftingItemId.bronzeBar]: stub(CraftingItemId.bronzeBar, "bronze-bar", "Bronze bar", ItemCategory.intermediate, {
71 description: "Smelted metal. Smith at an anvil."
72 }),
73 [CraftingItemId.rawMeat]: stub(CraftingItemId.rawMeat, "raw-meat", "Raw meat", ItemCategory.ingredient, {
74 description: "Cook at an oven or campfire."
75 }),
76 [CraftingItemId.cookedMeat]: stub(CraftingItemId.cookedMeat, "cooked-meat", "Cooked meat", ItemCategory.food, {
77 description: "Cooked food. Eating rules TBD."
78 }),
79 [CraftingItemId.leather]: stub(CraftingItemId.leather, "leather", "Leather", ItemCategory.ingredient, {
80 description: "Dropped from certain mobs. Craft leather goods at a leatherworking station."
81 }),
82 [CraftingItemId.arrowTip]: stub(CraftingItemId.arrowTip, "arrow-tip", "Arrow tip", ItemCategory.intermediate, {
83 description: "Smithed tip. Fletch into arrows at a crafting bench."
84 }),
85 [CraftingItemId.arrow]: stub(CraftingItemId.arrow, "arrow", "Arrow", ItemCategory.finished, {
86 description: "Ammunition for bows."
87 }),
88 [CraftingItemId.bronzeAxe]: stub(CraftingItemId.bronzeAxe, "bronze-axe", "Bronze axe", ItemCategory.tool, {
89 stackable: false,
90 maxStackSize: 1,
91 description: "Woodcutting tool. Tier and min Woodcutting TBD."
92 }),
93 [CraftingItemId.bronzePickaxe]: stub(CraftingItemId.bronzePickaxe, "bronze-pickaxe", "Bronze pickaxe", ItemCategory.tool, {
94 stackable: false,
95 maxStackSize: 1,
96 description: "Mining tool. Tier and min Mining TBD."
97 }),
98 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
99 stackable: false,
100 maxStackSize: 1,
101 description: "Fishing tool."
102 }),
103 [CraftingItemId.fishingNet]: stub(CraftingItemId.fishingNet, "fishing-net", "Fishing net", ItemCategory.tool, {
104 stackable: false,
105 maxStackSize: 1,
106 description: "Fishing tool."
107 }),
108 [CraftingItemId.rawFish]: stub(CraftingItemId.rawFish, "raw-fish", "Raw fish", ItemCategory.ingredient, {
109 description: "Caught fish. Cook like raw meat."
110 }),
111 [CraftingItemId.cloth]: stub(CraftingItemId.cloth, "cloth", "Cloth", ItemCategory.intermediate, {
112 description: "Woven fabric. Tailor into clothing at a loom."
113 })
114 });
@@ -0,0 +1,114 @@
1import { ItemCategory } from "./itemCategories.js";
2
3const DEFAULT_STACK = 99;
4
5/**
6 * Reserved numeric IDs for gathering, crafting, and cooking content.
7 * Fill in full definitions in ITEM_DEFINITIONS (or replace these stubs) once
8 * tier rules, stack caps, equipment stats, and sprites are final.
9 *
10 * Tiered families (ore, bars, metal gear, leather, cloth, wizard cloth) should
11 * follow `{tier}-{kind}` keys — e.g. `iron-ore`, `steel-bar`, `mithril-sword`.
12 */
13export const CraftingItemId = Object.freeze({
14 log: 9,
15 tinderbox: 10,
16 wool: 11,
17 thread: 12,
18 bronzeOre: 13,
19 bronzeBar: 14,
20 rawMeat: 15,
21 cookedMeat: 16,
22 leather: 17,
23 arrowTip: 18,
24 arrow: 19,
25 bronzeAxe: 20,
26 bronzePickaxe: 21,
27 fishingRod: 22,
28 fishingNet: 23,
29 rawFish: 24,
30 cloth: 25
31});
32
33function stub (itemId, key, displayName, category, extra = {})
34{
35 return Object.freeze({
36 itemId,
37 key,
38 displayName,
39 description: extra.description ?? "Placeholder — complete this definition when content rules are set.",
40 seedValue: extra.seedValue ?? 1,
41 stackable: extra.stackable ?? true,
42 maxStackSize: extra.maxStackSize ?? DEFAULT_STACK,
43 uniqueInstance: false,
44 category,
45 stub: true,
46 iconKey: extra.iconKey ?? "paper",
47 ...extra
48 });
49}
50
51/** Minimal defs so recipes and the craft UI can resolve names/icons before art exists. */
52export const CRAFTING_ITEM_STUBS = Object.freeze({
53 [CraftingItemId.log]: stub(CraftingItemId.log, "log", "Log", ItemCategory.ingredient, {
54 description: "Firewood. Drop on the ground and light with a tinderbox (see Crafting stations)."
55 }),
56 [CraftingItemId.tinderbox]: stub(CraftingItemId.tinderbox, "tinderbox", "Tinderbox", ItemCategory.tool, {
57 stackable: false,
58 maxStackSize: 1,
59 description: "Lights campfires from dropped logs."
60 }),
61 [CraftingItemId.wool]: stub(CraftingItemId.wool, "wool", "Wool", ItemCategory.ingredient, {
62 description: "Shorn from sheep. Spin into thread at a spinning wheel."
63 }),
64 [CraftingItemId.thread]: stub(CraftingItemId.thread, "thread", "Thread", ItemCategory.intermediate, {
65 description: "Spun wool. Used at a loom."
66 }),
67 [CraftingItemId.bronzeOre]: stub(CraftingItemId.bronzeOre, "bronze-ore", "Bronze ore", ItemCategory.ingredient, {
68 description: "Mined ore. Smelt at a furnace into bars."
69 }),
70 [CraftingItemId.bronzeBar]: stub(CraftingItemId.bronzeBar, "bronze-bar", "Bronze bar", ItemCategory.intermediate, {
71 description: "Smelted metal. Smith at an anvil."
72 }),
73 [CraftingItemId.rawMeat]: stub(CraftingItemId.rawMeat, "raw-meat", "Raw meat", ItemCategory.ingredient, {
74 description: "Cook at an oven or campfire."
75 }),
76 [CraftingItemId.cookedMeat]: stub(CraftingItemId.cookedMeat, "cooked-meat", "Cooked meat", ItemCategory.food, {
77 description: "Cooked food. Eating rules TBD."
78 }),
79 [CraftingItemId.leather]: stub(CraftingItemId.leather, "leather", "Leather", ItemCategory.ingredient, {
80 description: "Dropped from certain mobs. Craft leather goods at a leatherworking station."
81 }),
82 [CraftingItemId.arrowTip]: stub(CraftingItemId.arrowTip, "arrow-tip", "Arrow tip", ItemCategory.intermediate, {
83 description: "Smithed tip. Fletch into arrows at a crafting bench."
84 }),
85 [CraftingItemId.arrow]: stub(CraftingItemId.arrow, "arrow", "Arrow", ItemCategory.finished, {
86 description: "Ammunition for bows."
87 }),
88 [CraftingItemId.bronzeAxe]: stub(CraftingItemId.bronzeAxe, "bronze-axe", "Bronze axe", ItemCategory.tool, {
89 stackable: false,
90 maxStackSize: 1,
91 description: "Woodcutting tool. Tier and min Woodcutting TBD."
92 }),
93 [CraftingItemId.bronzePickaxe]: stub(CraftingItemId.bronzePickaxe, "bronze-pickaxe", "Bronze pickaxe", ItemCategory.tool, {
94 stackable: false,
95 maxStackSize: 1,
96 description: "Mining tool. Tier and min Mining TBD."
97 }),
98 [CraftingItemId.fishingRod]: stub(CraftingItemId.fishingRod, "fishing-rod", "Fishing rod", ItemCategory.tool, {
99 stackable: false,
100 maxStackSize: 1,
101 description: "Fishing tool."
102 }),
103 [CraftingItemId.fishingNet]: stub(CraftingItemId.fishingNet, "fishing-net", "Fishing net", ItemCategory.tool, {
104 stackable: false,
105 maxStackSize: 1,
106 description: "Fishing tool."
107 }),
108 [CraftingItemId.rawFish]: stub(CraftingItemId.rawFish, "raw-fish", "Raw fish", ItemCategory.ingredient, {
109 description: "Caught fish. Cook like raw meat."
110 }),
111 [CraftingItemId.cloth]: stub(CraftingItemId.cloth, "cloth", "Cloth", ItemCategory.intermediate, {
112 description: "Woven fabric. Tailor into clothing at a loom."
113 })
114});
shared/definitions/craftingStations.js added +78 −0
@@ -0,0 +1,78 @@
1 import { SkillId } from "./skills.js";
2
3 /** Placeable or fixed world stations that gate recipes (blocks / ground objects later). */
4 export const CraftingStationId = Object.freeze({
5 furnace: "furnace",
6 spinningWheel: "spinning-wheel",
7 loom: "loom",
8 anvil: "anvil",
9 leatherworkingStation: "leatherworking-station",
10 craftingBench: "crafting-bench",
11 oven: "oven",
12 fireplace: "fireplace"
13 });
14
15 /** How long a player-lit campfire stays usable (ms). */
16 export const FIREPLACE_DURATION_MS = 10 * 60 * 1000;
17
18 /** Fixed craft action duration at any station (ms). */
19 export const CRAFT_DURATION_MS = 2000;
20
21 export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
22 [CraftingStationId.furnace]: Object.freeze({
23 stationId: CraftingStationId.furnace,
24 displayName: "Furnace",
25 skillId: SkillId.smithing,
26 description: "Smelt gathered ore into metal bars."
27 }),
28 [CraftingStationId.spinningWheel]: Object.freeze({
29 stationId: CraftingStationId.spinningWheel,
30 displayName: "Spinning wheel",
31 skillId: SkillId.tailoring,
32 description: "Spin wool (from shorn sheep) into thread."
33 }),
34 [CraftingStationId.loom]: Object.freeze({
35 stationId: CraftingStationId.loom,
36 displayName: "Loom",
37 skillId: SkillId.tailoring,
38 description: "Weave cloth garments."
39 }),
40 [CraftingStationId.anvil]: Object.freeze({
41 stationId: CraftingStationId.anvil,
42 displayName: "Anvil",
43 skillId: SkillId.smithing,
44 description: "Smith metal items from bars."
45 }),
46 [CraftingStationId.leatherworkingStation]: Object.freeze({
47 stationId: CraftingStationId.leatherworkingStation,
48 displayName: "Leatherworking station",
49 skillId: SkillId.leatherworking,
50 description: "Craft leather armour and goods."
51 }),
52 [CraftingStationId.craftingBench]: Object.freeze({
53 stationId: CraftingStationId.craftingBench,
54 displayName: "Crafting bench",
55 skillId: SkillId.crafting,
56 description: "General crafting (e.g. fletching arrows from smithed tips)."
57 }),
58 [CraftingStationId.oven]: Object.freeze({
59 stationId: CraftingStationId.oven,
60 displayName: "Oven",
61 skillId: SkillId.cooking,
62 description: "Cook raw meat; low Cooking risks burning the food."
63 }),
64 [CraftingStationId.fireplace]: Object.freeze({
65 stationId: CraftingStationId.fireplace,
66 displayName: "Campfire",
67 skillId: SkillId.cooking,
68 description: "Portable cooking like an oven but a higher burn chance.",
69 portable: true,
70 maxPerTile: 1,
71 durationMs: FIREPLACE_DURATION_MS
72 })
73 });
74
75 export function craftingStationDefinition (stationId)
76 {
77 return CRAFTING_STATION_DEFINITIONS[stationId] ?? null;
78 }
@@ -0,0 +1,78 @@
1import { SkillId } from "./skills.js";
2
3/** Placeable or fixed world stations that gate recipes (blocks / ground objects later). */
4export const CraftingStationId = Object.freeze({
5 furnace: "furnace",
6 spinningWheel: "spinning-wheel",
7 loom: "loom",
8 anvil: "anvil",
9 leatherworkingStation: "leatherworking-station",
10 craftingBench: "crafting-bench",
11 oven: "oven",
12 fireplace: "fireplace"
13});
14
15/** How long a player-lit campfire stays usable (ms). */
16export const FIREPLACE_DURATION_MS = 10 * 60 * 1000;
17
18/** Fixed craft action duration at any station (ms). */
19export const CRAFT_DURATION_MS = 2000;
20
21export const CRAFTING_STATION_DEFINITIONS = Object.freeze({
22 [CraftingStationId.furnace]: Object.freeze({
23 stationId: CraftingStationId.furnace,
24 displayName: "Furnace",
25 skillId: SkillId.smithing,
26 description: "Smelt gathered ore into metal bars."
27 }),
28 [CraftingStationId.spinningWheel]: Object.freeze({
29 stationId: CraftingStationId.spinningWheel,
30 displayName: "Spinning wheel",
31 skillId: SkillId.tailoring,
32 description: "Spin wool (from shorn sheep) into thread."
33 }),
34 [CraftingStationId.loom]: Object.freeze({
35 stationId: CraftingStationId.loom,
36 displayName: "Loom",
37 skillId: SkillId.tailoring,
38 description: "Weave cloth garments."
39 }),
40 [CraftingStationId.anvil]: Object.freeze({
41 stationId: CraftingStationId.anvil,
42 displayName: "Anvil",
43 skillId: SkillId.smithing,
44 description: "Smith metal items from bars."
45 }),
46 [CraftingStationId.leatherworkingStation]: Object.freeze({
47 stationId: CraftingStationId.leatherworkingStation,
48 displayName: "Leatherworking station",
49 skillId: SkillId.leatherworking,
50 description: "Craft leather armour and goods."
51 }),
52 [CraftingStationId.craftingBench]: Object.freeze({
53 stationId: CraftingStationId.craftingBench,
54 displayName: "Crafting bench",
55 skillId: SkillId.crafting,
56 description: "General crafting (e.g. fletching arrows from smithed tips)."
57 }),
58 [CraftingStationId.oven]: Object.freeze({
59 stationId: CraftingStationId.oven,
60 displayName: "Oven",
61 skillId: SkillId.cooking,
62 description: "Cook raw meat; low Cooking risks burning the food."
63 }),
64 [CraftingStationId.fireplace]: Object.freeze({
65 stationId: CraftingStationId.fireplace,
66 displayName: "Campfire",
67 skillId: SkillId.cooking,
68 description: "Portable cooking like an oven but a higher burn chance.",
69 portable: true,
70 maxPerTile: 1,
71 durationMs: FIREPLACE_DURATION_MS
72 })
73});
74
75export function craftingStationDefinition (stationId)
76{
77 return CRAFTING_STATION_DEFINITIONS[stationId] ?? null;
78}
shared/definitions/equipmentKinds.js added +16 −0
@@ -0,0 +1,16 @@
1 /** How an equippable item maps to min-level skill and worn stat bonus. */
2 export const EquipmentKind = Object.freeze({
3 metalWeapon: "metalWeapon",
4 clubWeapon: "clubWeapon",
5 bow: "bow",
6 metalArmour: "metalArmour",
7 leatherArmour: "leatherArmour",
8 clothArmour: "clothArmour",
9 wizardCloth: "wizardCloth",
10 shield: "shield",
11 staff: "staff",
12 axeTool: "axeTool",
13 pickaxeTool: "pickaxeTool",
14 fishingRod: "fishingRod",
15 fishingNet: "fishingNet"
16 });
@@ -0,0 +1,16 @@
1/** How an equippable item maps to min-level skill and worn stat bonus. */
2export const EquipmentKind = Object.freeze({
3 metalWeapon: "metalWeapon",
4 clubWeapon: "clubWeapon",
5 bow: "bow",
6 metalArmour: "metalArmour",
7 leatherArmour: "leatherArmour",
8 clothArmour: "clothArmour",
9 wizardCloth: "wizardCloth",
10 shield: "shield",
11 staff: "staff",
12 axeTool: "axeTool",
13 pickaxeTool: "pickaxeTool",
14 fishingRod: "fishingRod",
15 fishingNet: "fishingNet"
16});
shared/definitions/itemCategories.js added +11 −0
@@ -0,0 +1,11 @@
1 /** Item taxonomy used by definitions, recipes, and marketplace rules. */
2 export const ItemCategory = Object.freeze({
3 ingredient: "ingredient",
4 intermediate: "intermediate",
5 finished: "finished",
6 tool: "tool",
7 food: "food",
8 document: "document",
9 currency: "currency",
10 other: "other"
11 });
@@ -0,0 +1,11 @@
1/** Item taxonomy used by definitions, recipes, and marketplace rules. */
2export const ItemCategory = Object.freeze({
3 ingredient: "ingredient",
4 intermediate: "intermediate",
5 finished: "finished",
6 tool: "tool",
7 food: "food",
8 document: "document",
9 currency: "currency",
10 other: "other"
11});
shared/definitions/items.js +117 −11
@@ -1,5 +1,11 @@
1 1 import { equipImageName, spriteImageName } from "./tileSprites.js";
2 2 import { SkillId } from "./skills.js";
3 import { MaterialTier } from "./materialTiers.js";
4 import { AttackType } from "./attackTypes.js";
5 import { EquipmentKind } from "./equipmentKinds.js";
6 import { formatQuantity } from "../items/formatQuantity.js";
7 import { formatOriginBreakdown } from "../items/origin.js";
8 import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
3 9
4 10 export const ItemId = Object.freeze({
5 11 paper: 1,
@@ -7,7 +13,10 @@ export const ItemId = Object.freeze({
7 13 stick: 3,
8 14 blankCheque: 4,
9 15 clothShirt: 5,
10 letter: 6
16 letter: 6,
17 filledCheque: 7,
18 coins: 8,
19 ...CraftingItemId
11 20 });
12 21
13 22 export const EQUIPMENT_SLOT = Object.freeze({
@@ -29,6 +38,17 @@ export const EQUIPMENT_DRAW_ORDER = Object.freeze([
29 38 ]);
30 39
31 40 export const DEFAULT_MAX_STACK = 99;
41 export const BLANK_CHEQUE_CARRY_CAP = 99;
42 export const COIN_MAX_STACK = 999_000_000_000;
43
44 /** Coin sprite tiers (coins-<n>.png); pick the largest n where stack quantity >= n. */
45 export const COIN_SPRITE_TIERS = Object.freeze([
46 1, 5, 15, 50, 150, 500, 1000, 1500, 2000, 5000, 10000, 20000, 50000,
47 1_000_000, 10_000_000, 50_000_000, 100_000_000, 500_000_000,
48 1_000_000_000, 10_000_000_000, 100_000_000_000, 1_000_000_000_000,
49 10_000_000_000_000, 100_000_000_000_000, 500_000_000_000_000,
50 999_999_999_999_999
51 ]);
32 52
33 53 export const ITEM_DEFINITIONS = Object.freeze({
34 54 [ItemId.paper]: Object.freeze({
@@ -58,12 +78,13 @@ export const ITEM_DEFINITIONS = Object.freeze({
58 78 itemId: ItemId.apple,
59 79 key: "apple",
60 80 displayName: "Apple",
61 description: "A placeholder fruit.",
81 description: "Restores a little health when eaten.",
62 82 seedValue: 1,
63 83 stackable: true,
64 84 maxStackSize: DEFAULT_MAX_STACK,
65 85 uniqueInstance: false,
66 category: "other"
86 category: "food",
87 healing: 4
67 88 }),
68 89 [ItemId.stick]: Object.freeze({
69 90 itemId: ItemId.stick,
@@ -71,17 +92,20 @@ export const ITEM_DEFINITIONS = Object.freeze({
71 92 displayName: "Stick",
72 93 description: "A wooden stick. Can be wielded.",
73 94 seedValue: 3,
74 stackable: true,
75 maxStackSize: DEFAULT_MAX_STACK,
95 stackable: false,
96 maxStackSize: 1,
76 97 uniqueInstance: false,
77 98 category: "finished",
78 99 equipment: Object.freeze({
79 100 slot: EQUIPMENT_SLOT.weapon,
101 tier: MaterialTier.bronze,
102 kind: EquipmentKind.clubWeapon,
80 103 attack: Object.freeze({
81 104 mode: "melee",
82 105 rangeTiles: 1,
83 106 hitSkillId: SkillId.clubfighting,
84 107 damageSkillId: SkillId.strength,
108 attackType: AttackType.blunt,
85 109 cooldownMs: 700,
86 110 baseDamage: 2
87 111 })
@@ -91,12 +115,27 @@ export const ITEM_DEFINITIONS = Object.freeze({
91 115 itemId: ItemId.blankCheque,
92 116 key: "blank-cheque",
93 117 displayName: "Blank cheque",
94 description: "Placeholder bank paper. Filling comes with the bank.",
118 description: "Free bank paper. Write a cheque at a bank to reserve vault goods.",
95 119 seedValue: 5,
96 120 stackable: true,
97 121 maxStackSize: DEFAULT_MAX_STACK,
98 122 uniqueInstance: false,
99 category: "document"
123 category: "document",
124 marketplaceSellable: false,
125 marketplaceSellBlockedReason: "Blank cheques cannot be sold on the marketplace."
126 }),
127 [ItemId.filledCheque]: Object.freeze({
128 itemId: ItemId.filledCheque,
129 key: "filled-cheque",
130 displayName: "Cheque",
131 description: "A bearer cheque linked to reserved goods in the issuer's bank.",
132 seedValue: 5,
133 stackable: false,
134 maxStackSize: 1,
135 uniqueInstance: true,
136 category: "document",
137 defaultState: "filled-cheque",
138 marketplaceSellable: true
100 139 }),
101 140 [ItemId.clothShirt]: Object.freeze({
102 141 itemId: ItemId.clothShirt,
@@ -109,9 +148,24 @@ export const ITEM_DEFINITIONS = Object.freeze({
109 148 uniqueInstance: false,
110 149 category: "finished",
111 150 equipment: Object.freeze({
112 slot: EQUIPMENT_SLOT.chest
151 slot: EQUIPMENT_SLOT.chest,
152 tier: MaterialTier.bronze,
153 kind: EquipmentKind.clothArmour
113 154 })
114 })
155 }),
156 [ItemId.coins]: Object.freeze({
157 itemId: ItemId.coins,
158 key: "coins",
159 displayName: "Coin",
160 displayNamePlural: "Coins",
161 description: "Currency carried in your bag.",
162 seedValue: 1,
163 stackable: true,
164 maxStackSize: COIN_MAX_STACK,
165 uniqueInstance: false,
166 category: "currency"
167 }),
168 ...CRAFTING_ITEM_STUBS
115 169 });
116 170
117 171 export function itemDefinition (itemId)
@@ -119,6 +173,41 @@ export function itemDefinition (itemId)
119 173 return ITEM_DEFINITIONS[itemId] ?? null;
120 174 }
121 175
176 export { formatQuantity };
177
178 export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
179 {
180 if (!def)
181 { return "Item"; }
182 const qty = stack?.quantity ?? 1;
183 if (stack?.itemId === ItemId.coins)
184 { return qty === 1 ? (def.displayName ?? "Coin") : (def.displayNamePlural ?? "Coins"); }
185 return def.displayName ?? "Item";
186 }
187
188 export function stackDisplayLabel (stack)
189 {
190 const name = itemDisplayName(stack);
191 const qty = stack?.quantity ?? 1;
192 if (qty <= 1)
193 { return name; }
194 return `${name} (${formatQuantity(qty)})`;
195 }
196
197 export function coinSpriteTierForQuantity (quantity)
198 {
199 const qty = Math.max(0, Math.floor(Number(quantity) || 0));
200 let tier = COIN_SPRITE_TIERS[0];
201 for (const candidate of COIN_SPRITE_TIERS)
202 {
203 if (qty >= candidate)
204 { tier = candidate; }
205 else
206 { break; }
207 }
208 return tier;
209 }
210
122 211 /** Stack-aware description (letters include open state and author). */
123 212 export function itemDescription (stack, { localCharacterId } = {})
124 213 {
@@ -135,9 +224,21 @@ export function itemDescription (stack, { localCharacterId } = {})
135 224 : (stack.instance.authorDisplayName?.trim() || "someone");
136 225 return `An ${state} letter, written by ${author}.`;
137 226 }
227 if (stack.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
228 {
229 const reserved = itemDefinition(stack.instance.itemId);
230 const qty = stack.instance.quantity | 0;
231 const name = reserved?.displayName ?? "goods";
232 return `Bearer cheque for ${qty}× ${name}.`;
233 }
138 234 return def.description ?? "";
139 235 }
140 236
237 export function itemOriginSummary (stack)
238 {
239 return formatOriginBreakdown(stack);
240 }
241
141 242 export function itemDefaultState (def)
142 243 {
143 244 return def?.defaultState ?? def?.key ?? "paper";
@@ -184,15 +285,20 @@ export function itemAssetPathForStack (stack)
184 285 {
185 286 if (!stack)
186 287 { return itemAssetPath(null); }
288 if (stack.itemId === ItemId.coins)
289 {
290 const tier = coinSpriteTierForQuantity(stack.quantity);
291 return `/assets/items/coins/coins-${tier}.png`;
292 }
187 293 return itemAssetPath(stack.itemId, null, stack.instance);
188 294 }
189 295
190 296 export const LETTER_MAX_BODY_CHARS = 2000;
191 297
192 export const STARTER_CURRENCY = 25;
193 298 export const STARTER_ITEMS = Object.freeze([
194 299 Object.freeze({ itemId: ItemId.paper, quantity: 5 }),
195 300 Object.freeze({ itemId: ItemId.apple, quantity: 3 }),
196 301 Object.freeze({ itemId: ItemId.stick, quantity: 1 }),
197 Object.freeze({ itemId: ItemId.clothShirt, quantity: 1 })
302 Object.freeze({ itemId: ItemId.clothShirt, quantity: 1 }),
303 Object.freeze({ itemId: ItemId.coins, quantity: 25 })
198 304 ]);
@@ -1,5 +1,11 @@
1import { equipImageName, spriteImageName } from "./tileSprites.js";
1import { equipImageName, spriteImageName } from "./tileSprites.js";
2import { SkillId } from "./skills.js";
2import { SkillId } from "./skills.js";
3import { MaterialTier } from "./materialTiers.js";
4import { AttackType } from "./attackTypes.js";
5import { EquipmentKind } from "./equipmentKinds.js";
6import { formatQuantity } from "../items/formatQuantity.js";
7import { formatOriginBreakdown } from "../items/origin.js";
8import { CraftingItemId, CRAFTING_ITEM_STUBS } from "./craftingItems.js";
3
9
4export const ItemId = Object.freeze({
10export const ItemId = Object.freeze({
5 paper: 1,
11 paper: 1,
@@ -7,7 +13,10 @@ export const ItemId = Object.freeze({
7 stick: 3,
13 stick: 3,
8 blankCheque: 4,
14 blankCheque: 4,
9 clothShirt: 5,
15 clothShirt: 5,
10 letter: 6
16 letter: 6,
17 filledCheque: 7,
18 coins: 8,
19 ...CraftingItemId
11});
20});
12
21
13export const EQUIPMENT_SLOT = Object.freeze({
22export const EQUIPMENT_SLOT = Object.freeze({
@@ -29,6 +38,17 @@ export const EQUIPMENT_DRAW_ORDER = Object.freeze([
29]);
38]);
30
39
31export const DEFAULT_MAX_STACK = 99;
40export const DEFAULT_MAX_STACK = 99;
41export const BLANK_CHEQUE_CARRY_CAP = 99;
42export const COIN_MAX_STACK = 999_000_000_000;
43
44/** Coin sprite tiers (coins-<n>.png); pick the largest n where stack quantity >= n. */
45export const COIN_SPRITE_TIERS = Object.freeze([
46 1, 5, 15, 50, 150, 500, 1000, 1500, 2000, 5000, 10000, 20000, 50000,
47 1_000_000, 10_000_000, 50_000_000, 100_000_000, 500_000_000,
48 1_000_000_000, 10_000_000_000, 100_000_000_000, 1_000_000_000_000,
49 10_000_000_000_000, 100_000_000_000_000, 500_000_000_000_000,
50 999_999_999_999_999
51]);
32
52
33export const ITEM_DEFINITIONS = Object.freeze({
53export const ITEM_DEFINITIONS = Object.freeze({
34 [ItemId.paper]: Object.freeze({
54 [ItemId.paper]: Object.freeze({
@@ -58,12 +78,13 @@ export const ITEM_DEFINITIONS = Object.freeze({
58 itemId: ItemId.apple,
78 itemId: ItemId.apple,
59 key: "apple",
79 key: "apple",
60 displayName: "Apple",
80 displayName: "Apple",
61 description: "A placeholder fruit.",
81 description: "Restores a little health when eaten.",
62 seedValue: 1,
82 seedValue: 1,
63 stackable: true,
83 stackable: true,
64 maxStackSize: DEFAULT_MAX_STACK,
84 maxStackSize: DEFAULT_MAX_STACK,
65 uniqueInstance: false,
85 uniqueInstance: false,
66 category: "other"
86 category: "food",
87 healing: 4
67 }),
88 }),
68 [ItemId.stick]: Object.freeze({
89 [ItemId.stick]: Object.freeze({
69 itemId: ItemId.stick,
90 itemId: ItemId.stick,
@@ -71,17 +92,20 @@ export const ITEM_DEFINITIONS = Object.freeze({
71 displayName: "Stick",
92 displayName: "Stick",
72 description: "A wooden stick. Can be wielded.",
93 description: "A wooden stick. Can be wielded.",
73 seedValue: 3,
94 seedValue: 3,
74 stackable: true,
95 stackable: false,
75 maxStackSize: DEFAULT_MAX_STACK,
96 maxStackSize: 1,
76 uniqueInstance: false,
97 uniqueInstance: false,
77 category: "finished",
98 category: "finished",
78 equipment: Object.freeze({
99 equipment: Object.freeze({
79 slot: EQUIPMENT_SLOT.weapon,
100 slot: EQUIPMENT_SLOT.weapon,
101 tier: MaterialTier.bronze,
102 kind: EquipmentKind.clubWeapon,
80 attack: Object.freeze({
103 attack: Object.freeze({
81 mode: "melee",
104 mode: "melee",
82 rangeTiles: 1,
105 rangeTiles: 1,
83 hitSkillId: SkillId.clubfighting,
106 hitSkillId: SkillId.clubfighting,
84 damageSkillId: SkillId.strength,
107 damageSkillId: SkillId.strength,
108 attackType: AttackType.blunt,
85 cooldownMs: 700,
109 cooldownMs: 700,
86 baseDamage: 2
110 baseDamage: 2
87 })
111 })
@@ -91,12 +115,27 @@ export const ITEM_DEFINITIONS = Object.freeze({
91 itemId: ItemId.blankCheque,
115 itemId: ItemId.blankCheque,
92 key: "blank-cheque",
116 key: "blank-cheque",
93 displayName: "Blank cheque",
117 displayName: "Blank cheque",
94 description: "Placeholder bank paper. Filling comes with the bank.",
118 description: "Free bank paper. Write a cheque at a bank to reserve vault goods.",
95 seedValue: 5,
119 seedValue: 5,
96 stackable: true,
120 stackable: true,
97 maxStackSize: DEFAULT_MAX_STACK,
121 maxStackSize: DEFAULT_MAX_STACK,
98 uniqueInstance: false,
122 uniqueInstance: false,
99 category: "document"
123 category: "document",
124 marketplaceSellable: false,
125 marketplaceSellBlockedReason: "Blank cheques cannot be sold on the marketplace."
126 }),
127 [ItemId.filledCheque]: Object.freeze({
128 itemId: ItemId.filledCheque,
129 key: "filled-cheque",
130 displayName: "Cheque",
131 description: "A bearer cheque linked to reserved goods in the issuer's bank.",
132 seedValue: 5,
133 stackable: false,
134 maxStackSize: 1,
135 uniqueInstance: true,
136 category: "document",
137 defaultState: "filled-cheque",
138 marketplaceSellable: true
100 }),
139 }),
101 [ItemId.clothShirt]: Object.freeze({
140 [ItemId.clothShirt]: Object.freeze({
102 itemId: ItemId.clothShirt,
141 itemId: ItemId.clothShirt,
@@ -109,9 +148,24 @@ export const ITEM_DEFINITIONS = Object.freeze({
109 uniqueInstance: false,
148 uniqueInstance: false,
110 category: "finished",
149 category: "finished",
111 equipment: Object.freeze({
150 equipment: Object.freeze({
112 slot: EQUIPMENT_SLOT.chest
151 slot: EQUIPMENT_SLOT.chest,
152 tier: MaterialTier.bronze,
153 kind: EquipmentKind.clothArmour
113 })
154 })
114 })
155 }),
156 [ItemId.coins]: Object.freeze({
157 itemId: ItemId.coins,
158 key: "coins",
159 displayName: "Coin",
160 displayNamePlural: "Coins",
161 description: "Currency carried in your bag.",
162 seedValue: 1,
163 stackable: true,
164 maxStackSize: COIN_MAX_STACK,
165 uniqueInstance: false,
166 category: "currency"
167 }),
168 ...CRAFTING_ITEM_STUBS
115});
169});
116
170
117export function itemDefinition (itemId)
171export function itemDefinition (itemId)
@@ -119,6 +173,41 @@ export function itemDefinition (itemId)
119 return ITEM_DEFINITIONS[itemId] ?? null;
173 return ITEM_DEFINITIONS[itemId] ?? null;
120}
174}
121
175
176export { formatQuantity };
177
178export function itemDisplayName (stack, def = itemDefinition(stack?.itemId))
179{
180 if (!def)
181 { return "Item"; }
182 const qty = stack?.quantity ?? 1;
183 if (stack?.itemId === ItemId.coins)
184 { return qty === 1 ? (def.displayName ?? "Coin") : (def.displayNamePlural ?? "Coins"); }
185 return def.displayName ?? "Item";
186}
187
188export function stackDisplayLabel (stack)
189{
190 const name = itemDisplayName(stack);
191 const qty = stack?.quantity ?? 1;
192 if (qty <= 1)
193 { return name; }
194 return `${name} (${formatQuantity(qty)})`;
195}
196
197export function coinSpriteTierForQuantity (quantity)
198{
199 const qty = Math.max(0, Math.floor(Number(quantity) || 0));
200 let tier = COIN_SPRITE_TIERS[0];
201 for (const candidate of COIN_SPRITE_TIERS)
202 {
203 if (qty >= candidate)
204 { tier = candidate; }
205 else
206 { break; }
207 }
208 return tier;
209}
210
122/** Stack-aware description (letters include open state and author). */
211/** Stack-aware description (letters include open state and author). */
123export function itemDescription (stack, { localCharacterId } = {})
212export function itemDescription (stack, { localCharacterId } = {})
124{
213{
@@ -135,9 +224,21 @@ export function itemDescription (stack, { localCharacterId } = {})
135 : (stack.instance.authorDisplayName?.trim() || "someone");
224 : (stack.instance.authorDisplayName?.trim() || "someone");
136 return `An ${state} letter, written by ${author}.`;
225 return `An ${state} letter, written by ${author}.`;
137 }
226 }
227 if (stack.itemId === ItemId.filledCheque && stack.instance?.kind === "filled-cheque")
228 {
229 const reserved = itemDefinition(stack.instance.itemId);
230 const qty = stack.instance.quantity | 0;
231 const name = reserved?.displayName ?? "goods";
232 return `Bearer cheque for ${qty}× ${name}.`;
233 }
138 return def.description ?? "";
234 return def.description ?? "";
139}
235}
140
236
237export function itemOriginSummary (stack)
238{
239 return formatOriginBreakdown(stack);
240}
241
141export function itemDefaultState (def)
242export function itemDefaultState (def)
142{
243{
143 return def?.defaultState ?? def?.key ?? "paper";
244 return def?.defaultState ?? def?.key ?? "paper";
@@ -184,15 +285,20 @@ export function itemAssetPathForStack (stack)
184{
285{
185 if (!stack)
286 if (!stack)
186 { return itemAssetPath(null); }
287 { return itemAssetPath(null); }
288 if (stack.itemId === ItemId.coins)
289 {
290 const tier = coinSpriteTierForQuantity(stack.quantity);
291 return `/assets/items/coins/coins-${tier}.png`;
292 }
187 return itemAssetPath(stack.itemId, null, stack.instance);
293 return itemAssetPath(stack.itemId, null, stack.instance);
188}
294}
189
295
190export const LETTER_MAX_BODY_CHARS = 2000;
296export const LETTER_MAX_BODY_CHARS = 2000;
191
297
192export const STARTER_CURRENCY = 25;
193export const STARTER_ITEMS = Object.freeze([
298export const STARTER_ITEMS = Object.freeze([
194 Object.freeze({ itemId: ItemId.paper, quantity: 5 }),
299 Object.freeze({ itemId: ItemId.paper, quantity: 5 }),
195 Object.freeze({ itemId: ItemId.apple, quantity: 3 }),
300 Object.freeze({ itemId: ItemId.apple, quantity: 3 }),
196 Object.freeze({ itemId: ItemId.stick, quantity: 1 }),
301 Object.freeze({ itemId: ItemId.stick, quantity: 1 }),
197 Object.freeze({ itemId: ItemId.clothShirt, quantity: 1 })
302 Object.freeze({ itemId: ItemId.clothShirt, quantity: 1 }),
303 Object.freeze({ itemId: ItemId.coins, quantity: 25 })
198]);
304]);
shared/definitions/materialTiers.js added +48 −0
@@ -0,0 +1,48 @@
1 /** Material tiers from lowest to highest. Bronze has no skill gate beyond level 1. */
2 export const MaterialTier = Object.freeze({
3 bronze: "bronze",
4 iron: "iron",
5 steel: "steel",
6 mithril: "mithril",
7 adamantium: "adamantium",
8 orichalcum: "orichalcum"
9 });
10
11 export const MATERIAL_TIER_ORDER = Object.freeze([
12 MaterialTier.bronze,
13 MaterialTier.iron,
14 MaterialTier.steel,
15 MaterialTier.mithril,
16 MaterialTier.adamantium,
17 MaterialTier.orichalcum
18 ]);
19
20 /** Minimum relevant skill level required to equip (bronze always 1). */
21 export const TIER_MIN_SKILL_LEVEL = Object.freeze({
22 [MaterialTier.bronze]: 1,
23 [MaterialTier.iron]: 10,
24 [MaterialTier.steel]: 20,
25 [MaterialTier.mithril]: 30,
26 [MaterialTier.adamantium]: 40,
27 [MaterialTier.orichalcum]: 50
28 });
29
30 /** Stat bonus granted by tier for the equipment's bonus category. */
31 export const TIER_STAT_BONUS = Object.freeze({
32 [MaterialTier.bronze]: 1,
33 [MaterialTier.iron]: 2,
34 [MaterialTier.steel]: 4,
35 [MaterialTier.mithril]: 6,
36 [MaterialTier.adamantium]: 8,
37 [MaterialTier.orichalcum]: 10
38 });
39
40 export function tierStatBonus (tier)
41 {
42 return TIER_STAT_BONUS[tier] ?? TIER_STAT_BONUS[MaterialTier.bronze];
43 }
44
45 export function tierMinSkillLevel (tier)
46 {
47 return TIER_MIN_SKILL_LEVEL[tier] ?? TIER_MIN_SKILL_LEVEL[MaterialTier.bronze];
48 }
@@ -0,0 +1,48 @@
1/** Material tiers from lowest to highest. Bronze has no skill gate beyond level 1. */
2export const MaterialTier = Object.freeze({
3 bronze: "bronze",
4 iron: "iron",
5 steel: "steel",
6 mithril: "mithril",
7 adamantium: "adamantium",
8 orichalcum: "orichalcum"
9});
10
11export const MATERIAL_TIER_ORDER = Object.freeze([
12 MaterialTier.bronze,
13 MaterialTier.iron,
14 MaterialTier.steel,
15 MaterialTier.mithril,
16 MaterialTier.adamantium,
17 MaterialTier.orichalcum
18]);
19
20/** Minimum relevant skill level required to equip (bronze always 1). */
21export const TIER_MIN_SKILL_LEVEL = Object.freeze({
22 [MaterialTier.bronze]: 1,
23 [MaterialTier.iron]: 10,
24 [MaterialTier.steel]: 20,
25 [MaterialTier.mithril]: 30,
26 [MaterialTier.adamantium]: 40,
27 [MaterialTier.orichalcum]: 50
28});
29
30/** Stat bonus granted by tier for the equipment's bonus category. */
31export const TIER_STAT_BONUS = Object.freeze({
32 [MaterialTier.bronze]: 1,
33 [MaterialTier.iron]: 2,
34 [MaterialTier.steel]: 4,
35 [MaterialTier.mithril]: 6,
36 [MaterialTier.adamantium]: 8,
37 [MaterialTier.orichalcum]: 10
38});
39
40export function tierStatBonus (tier)
41{
42 return TIER_STAT_BONUS[tier] ?? TIER_STAT_BONUS[MaterialTier.bronze];
43}
44
45export function tierMinSkillLevel (tier)
46{
47 return TIER_MIN_SKILL_LEVEL[tier] ?? TIER_MIN_SKILL_LEVEL[MaterialTier.bronze];
48}
shared/definitions/mobCombat.js added +62 −0
@@ -0,0 +1,62 @@
1 import { mobDefinition } from "./mobs.js";
2 import { SkillId, UNARMED_ATTACK } from "./skills.js";
3
4 /** Living mobs with health can fight unless explicitly non-combat (pigeon, etc.). */
5 export function mobCanFight (def)
6 {
7 if (!def || def.untargetable || def.freeFlight)
8 { return false; }
9 if (def.canFight === false)
10 { return false; }
11 return Number(def.health ?? def.maxHealth ?? 0) > 0;
12 }
13
14 export function mobCanFightType (mobTypeId)
15 {
16 return mobCanFight(mobDefinition(mobTypeId));
17 }
18
19 /** Melee profile for a mob: one attackSkill drives hit chance and damage. */
20 export function mobMeleeAttackProfile (def)
21 {
22 const attackSkill = Math.max(1, def?.attackSkill | 0 || 1);
23 return {
24 mode: "melee",
25 hitSkillId: SkillId.unarmed,
26 damageSkillId: SkillId.unarmed,
27 cooldownMs: def?.attackCooldownMs ?? 900,
28 baseDamage: def?.baseDamage ?? 1,
29 mobAttackSkill: attackSkill
30 };
31 }
32
33 /** @deprecated Use shared/combat/rolls.js — kept for reference tests only. */
34 export function mobHitChance (attackSkill)
35 {
36 const skill = Math.max(1, attackSkill | 0 || 1);
37 return Math.min(0.95, 0.45 + skill * 0.03);
38 }
39
40 /** @deprecated Use shared/combat/rolls.js */
41 export function mobDamage (attackSkill, baseDamage = 1)
42 {
43 const skill = Math.max(1, attackSkill | 0 || 1);
44 return Math.max(1, (baseDamage | 0) + Math.floor(skill / 5));
45 }
46
47 export function mobSkillLevels (def)
48 {
49 const attackSkill = Math.max(1, def?.attackSkill | 0 || 1);
50 const agilitySkill = Math.max(1, def?.agilitySkill ?? attackSkill);
51 const defenceSkill = Math.max(1, def?.defenceSkill ?? attackSkill);
52 return {
53 [SkillId.unarmed]: attackSkill,
54 [SkillId.dexterity]: agilitySkill,
55 [SkillId.defence]: defenceSkill
56 };
57 }
58
59 export function fallbackMobAttackProfile ()
60 {
61 return { ...UNARMED_ATTACK, mobAttackSkill: 1 };
62 }
@@ -0,0 +1,62 @@
1import { mobDefinition } from "./mobs.js";
2import { SkillId, UNARMED_ATTACK } from "./skills.js";
3
4/** Living mobs with health can fight unless explicitly non-combat (pigeon, etc.). */
5export function mobCanFight (def)
6{
7 if (!def || def.untargetable || def.freeFlight)
8 { return false; }
9 if (def.canFight === false)
10 { return false; }
11 return Number(def.health ?? def.maxHealth ?? 0) > 0;
12}
13
14export function mobCanFightType (mobTypeId)
15{
16 return mobCanFight(mobDefinition(mobTypeId));
17}
18
19/** Melee profile for a mob: one attackSkill drives hit chance and damage. */
20export function mobMeleeAttackProfile (def)
21{
22 const attackSkill = Math.max(1, def?.attackSkill | 0 || 1);
23 return {
24 mode: "melee",
25 hitSkillId: SkillId.unarmed,
26 damageSkillId: SkillId.unarmed,
27 cooldownMs: def?.attackCooldownMs ?? 900,
28 baseDamage: def?.baseDamage ?? 1,
29 mobAttackSkill: attackSkill
30 };
31}
32
33/** @deprecated Use shared/combat/rolls.js — kept for reference tests only. */
34export function mobHitChance (attackSkill)
35{
36 const skill = Math.max(1, attackSkill | 0 || 1);
37 return Math.min(0.95, 0.45 + skill * 0.03);
38}
39
40/** @deprecated Use shared/combat/rolls.js */
41export function mobDamage (attackSkill, baseDamage = 1)
42{
43 const skill = Math.max(1, attackSkill | 0 || 1);
44 return Math.max(1, (baseDamage | 0) + Math.floor(skill / 5));
45}
46
47export function mobSkillLevels (def)
48{
49 const attackSkill = Math.max(1, def?.attackSkill | 0 || 1);
50 const agilitySkill = Math.max(1, def?.agilitySkill ?? attackSkill);
51 const defenceSkill = Math.max(1, def?.defenceSkill ?? attackSkill);
52 return {
53 [SkillId.unarmed]: attackSkill,
54 [SkillId.dexterity]: agilitySkill,
55 [SkillId.defence]: defenceSkill
56 };
57}
58
59export function fallbackMobAttackProfile ()
60{
61 return { ...UNARMED_ATTACK, mobAttackSkill: 1 };
62}
shared/definitions/mobs.js +36 −14
@@ -1,5 +1,4 @@
1 1 import { spriteImageName } from "./tileSprites.js";
2 import { SkillId, UNARMED_ATTACK } from "./skills.js";
3 2
4 3 export const MobId = Object.freeze({
5 4 deer: "deer",
@@ -7,22 +6,41 @@ export const MobId = Object.freeze({
7 6 rat: "rat"
8 7 });
9 8
9 /** @typedef {{ itemId: number, chance: number }} MobDrop */
10 /** @typedef {{ isPlayer: boolean, text: string }} DialogueLine */
11 /** @typedef {{ trigger: string, text: string, available?: (ctx: object) => boolean }} DialogueResponse */
12
13 /**
14 * Target mob content schema (rendering fields stay alongside gameplay fields for now).
15 * - displayName: shown name
16 * - health / maxHealth: hit points
17 * - attackSkill: one skill level for hit chance and damage
18 * - drops: { itemId, chance } roll on death
19 * - sells: item IDs the mob shop stock (later)
20 * - dialogue: branching trees with triggers, lines, responses, and action hooks (later)
21 */
10 22 export const MOB_DEFINITIONS = Object.freeze({
11 23 [MobId.deer]: Object.freeze({
12 24 mobTypeId: MobId.deer,
13 25 key: "deer",
14 26 assetFolder: "mobs",
15 27 displayName: "Deer",
28 health: 8,
29 maxHealth: 8,
30 attackSkill: 2,
31 attackCooldownMs: 1000,
32 baseDamage: 1,
33 drops: Object.freeze([]),
34 sells: Object.freeze([]),
35 dialogue: Object.freeze([]),
16 36 persistent: false,
17 37 flying: false,
18 38 freeFlight: false,
19 39 ambient: false,
20 hostile: false,
21 40 talkable: false,
22 41 untargetable: false,
23 42 gait: "walk",
24 43 sex: "male",
25 health: 8,
26 44 frames: 1,
27 45 framesPerRow: 1,
28 46 animationSpeed: 0
@@ -32,16 +50,20 @@ export const MOB_DEFINITIONS = Object.freeze({
32 50 key: "pigeon",
33 51 assetFolder: "pigeons",
34 52 displayName: "Pigeon",
53 health: 1,
54 maxHealth: 1,
55 canFight: false,
56 drops: Object.freeze([]),
57 sells: Object.freeze([]),
58 dialogue: Object.freeze([]),
35 59 persistent: false,
36 60 flying: true,
37 61 freeFlight: true,
38 62 ambient: false,
39 hostile: false,
40 63 talkable: false,
41 64 untargetable: true,
42 65 gait: "walk",
43 66 sex: "male",
44 health: 1,
45 67 frames: 2,
46 68 framesPerRow: 2,
47 69 animationSpeed: 0.18,
@@ -53,25 +75,25 @@ export const MOB_DEFINITIONS = Object.freeze({
53 75 key: "rat",
54 76 assetFolder: "mobs",
55 77 displayName: "Rat",
78 health: 12,
79 maxHealth: 12,
80 attackSkill: 3,
81 attackCooldownMs: 900,
82 baseDamage: 2,
83 drops: Object.freeze([]),
84 sells: Object.freeze([]),
85 dialogue: Object.freeze([]),
56 86 persistent: false,
57 87 flying: false,
58 88 freeFlight: false,
59 89 ambient: false,
60 hostile: true,
61 90 talkable: false,
62 91 untargetable: false,
63 92 gait: "walk",
64 93 sex: "male",
65 health: 12,
66 94 frames: 1,
67 95 framesPerRow: 1,
68 animationSpeed: 0,
69 skillLevels: Object.freeze({
70 [SkillId.unarmed]: 3,
71 [SkillId.strength]: 3,
72 [SkillId.defence]: 1
73 }),
74 defaultAttack: Object.freeze({ ...UNARMED_ATTACK, baseDamage: 2, cooldownMs: 900 })
96 animationSpeed: 0
75 97 })
76 98 });
77 99
@@ -1,5 +1,4 @@
1import { spriteImageName } from "./tileSprites.js";
1import { spriteImageName } from "./tileSprites.js";
2import { SkillId, UNARMED_ATTACK } from "./skills.js";
3
2
4export const MobId = Object.freeze({
3export const MobId = Object.freeze({
5 deer: "deer",
4 deer: "deer",
@@ -7,22 +6,41 @@ export const MobId = Object.freeze({
7 rat: "rat"
6 rat: "rat"
8});
7});
9
8
9/** @typedef {{ itemId: number, chance: number }} MobDrop */
10/** @typedef {{ isPlayer: boolean, text: string }} DialogueLine */
11/** @typedef {{ trigger: string, text: string, available?: (ctx: object) => boolean }} DialogueResponse */
12
13/**
14 * Target mob content schema (rendering fields stay alongside gameplay fields for now).
15 * - displayName: shown name
16 * - health / maxHealth: hit points
17 * - attackSkill: one skill level for hit chance and damage
18 * - drops: { itemId, chance } roll on death
19 * - sells: item IDs the mob shop stock (later)
20 * - dialogue: branching trees with triggers, lines, responses, and action hooks (later)
21 */
10export const MOB_DEFINITIONS = Object.freeze({
22export const MOB_DEFINITIONS = Object.freeze({
11 [MobId.deer]: Object.freeze({
23 [MobId.deer]: Object.freeze({
12 mobTypeId: MobId.deer,
24 mobTypeId: MobId.deer,
13 key: "deer",
25 key: "deer",
14 assetFolder: "mobs",
26 assetFolder: "mobs",
15 displayName: "Deer",
27 displayName: "Deer",
28 health: 8,
29 maxHealth: 8,
30 attackSkill: 2,
31 attackCooldownMs: 1000,
32 baseDamage: 1,
33 drops: Object.freeze([]),
34 sells: Object.freeze([]),
35 dialogue: Object.freeze([]),
16 persistent: false,
36 persistent: false,
17 flying: false,
37 flying: false,
18 freeFlight: false,
38 freeFlight: false,
19 ambient: false,
39 ambient: false,
20 hostile: false,
21 talkable: false,
40 talkable: false,
22 untargetable: false,
41 untargetable: false,
23 gait: "walk",
42 gait: "walk",
24 sex: "male",
43 sex: "male",
25 health: 8,
26 frames: 1,
44 frames: 1,
27 framesPerRow: 1,
45 framesPerRow: 1,
28 animationSpeed: 0
46 animationSpeed: 0
@@ -32,16 +50,20 @@ export const MOB_DEFINITIONS = Object.freeze({
32 key: "pigeon",
50 key: "pigeon",
33 assetFolder: "pigeons",
51 assetFolder: "pigeons",
34 displayName: "Pigeon",
52 displayName: "Pigeon",
53 health: 1,
54 maxHealth: 1,
55 canFight: false,
56 drops: Object.freeze([]),
57 sells: Object.freeze([]),
58 dialogue: Object.freeze([]),
35 persistent: false,
59 persistent: false,
36 flying: true,
60 flying: true,
37 freeFlight: true,
61 freeFlight: true,
38 ambient: false,
62 ambient: false,
39 hostile: false,
40 talkable: false,
63 talkable: false,
41 untargetable: true,
64 untargetable: true,
42 gait: "walk",
65 gait: "walk",
43 sex: "male",
66 sex: "male",
44 health: 1,
45 frames: 2,
67 frames: 2,
46 framesPerRow: 2,
68 framesPerRow: 2,
47 animationSpeed: 0.18,
69 animationSpeed: 0.18,
@@ -53,25 +75,25 @@ export const MOB_DEFINITIONS = Object.freeze({
53 key: "rat",
75 key: "rat",
54 assetFolder: "mobs",
76 assetFolder: "mobs",
55 displayName: "Rat",
77 displayName: "Rat",
78 health: 12,
79 maxHealth: 12,
80 attackSkill: 3,
81 attackCooldownMs: 900,
82 baseDamage: 2,
83 drops: Object.freeze([]),
84 sells: Object.freeze([]),
85 dialogue: Object.freeze([]),
56 persistent: false,
86 persistent: false,
57 flying: false,
87 flying: false,
58 freeFlight: false,
88 freeFlight: false,
59 ambient: false,
89 ambient: false,
60 hostile: true,
61 talkable: false,
90 talkable: false,
62 untargetable: false,
91 untargetable: false,
63 gait: "walk",
92 gait: "walk",
64 sex: "male",
93 sex: "male",
65 health: 12,
66 frames: 1,
94 frames: 1,
67 framesPerRow: 1,
95 framesPerRow: 1,
68 animationSpeed: 0,
96 animationSpeed: 0
69 skillLevels: Object.freeze({
70 [SkillId.unarmed]: 3,
71 [SkillId.strength]: 3,
72 [SkillId.defence]: 1
73 }),
74 defaultAttack: Object.freeze({ ...UNARMED_ATTACK, baseDamage: 2, cooldownMs: 900 })
75 })
97 })
76});
98});
77
99
shared/definitions/skills.js +64 −15
@@ -8,9 +8,43 @@ export const SkillId = Object.freeze({
8 8 strength: "strength",
9 9 dexterity: "dexterity",
10 10 mind: "mind",
11 defence: "defence"
11 defence: "defence",
12 health: "health",
13 stamina: "stamina",
14 woodcutting: "woodcutting",
15 mining: "mining",
16 fishing: "fishing",
17 smithing: "smithing",
18 crafting: "crafting",
19 leatherworking: "leatherworking",
20 tailoring: "tailoring",
21 cooking: "cooking"
12 22 });
13 23
24 /** Display order for the skills panel (two columns, top to bottom). */
25 export const ALL_SKILL_IDS = Object.freeze([
26 SkillId.clubfighting,
27 SkillId.swordfighting,
28 SkillId.axefighting,
29 SkillId.archery,
30 SkillId.unarmed,
31 SkillId.magic,
32 SkillId.strength,
33 SkillId.dexterity,
34 SkillId.mind,
35 SkillId.defence,
36 SkillId.health,
37 SkillId.stamina,
38 SkillId.woodcutting,
39 SkillId.mining,
40 SkillId.fishing,
41 SkillId.smithing,
42 SkillId.crafting,
43 SkillId.leatherworking,
44 SkillId.tailoring,
45 SkillId.cooking
46 ]);
47
14 48 export const SKILL_DEFINITIONS = Object.freeze({
15 49 [SkillId.clubfighting]: Object.freeze({ skillId: SkillId.clubfighting, displayName: "Club fighting" }),
16 50 [SkillId.swordfighting]: Object.freeze({ skillId: SkillId.swordfighting, displayName: "Sword fighting" }),
@@ -21,21 +55,22 @@ export const SKILL_DEFINITIONS = Object.freeze({
21 55 [SkillId.strength]: Object.freeze({ skillId: SkillId.strength, displayName: "Strength" }),
22 56 [SkillId.dexterity]: Object.freeze({ skillId: SkillId.dexterity, displayName: "Dexterity" }),
23 57 [SkillId.mind]: Object.freeze({ skillId: SkillId.mind, displayName: "Mind" }),
24 [SkillId.defence]: Object.freeze({ skillId: SkillId.defence, displayName: "Defence" })
58 [SkillId.defence]: Object.freeze({ skillId: SkillId.defence, displayName: "Defence" }),
59 [SkillId.health]: Object.freeze({ skillId: SkillId.health, displayName: "Health" }),
60 [SkillId.stamina]: Object.freeze({ skillId: SkillId.stamina, displayName: "Stamina" }),
61 [SkillId.woodcutting]: Object.freeze({ skillId: SkillId.woodcutting, displayName: "Woodcutting" }),
62 [SkillId.mining]: Object.freeze({ skillId: SkillId.mining, displayName: "Mining" }),
63 [SkillId.fishing]: Object.freeze({ skillId: SkillId.fishing, displayName: "Fishing" }),
64 [SkillId.smithing]: Object.freeze({ skillId: SkillId.smithing, displayName: "Smithing" }),
65 [SkillId.crafting]: Object.freeze({ skillId: SkillId.crafting, displayName: "Crafting" }),
66 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
67 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
68 [SkillId.cooking]: Object.freeze({ skillId: SkillId.cooking, displayName: "Cooking" })
25 69 });
26 70
27 export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze({
28 [SkillId.clubfighting]: 1,
29 [SkillId.swordfighting]: 1,
30 [SkillId.axefighting]: 1,
31 [SkillId.archery]: 1,
32 [SkillId.unarmed]: 1,
33 [SkillId.magic]: 1,
34 [SkillId.strength]: 1,
35 [SkillId.dexterity]: 1,
36 [SkillId.mind]: 1,
37 [SkillId.defence]: 1
38 });
71 export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze(Object.fromEntries(
72 ALL_SKILL_IDS.map((skillId) => [skillId, skillId === SkillId.health ? 10 : 1])
73 ));
39 74
40 75 export const UNARMED_ATTACK = Object.freeze({
41 76 mode: "melee",
@@ -46,8 +81,22 @@ export const UNARMED_ATTACK = Object.freeze({
46 81 baseDamage: 1
47 82 });
48 83
84 import { levelFromTotalXp, MAX_SKILL_LEVEL } from "../skills/progression.js";
85
49 86 export function skillLevel (skills, skillId)
50 87 {
88 if (skills?.xp)
89 { return Math.min(MAX_SKILL_LEVEL, levelFromTotalXp(skills.xp[skillId] ?? 0)); }
51 90 const levels = skills?.levels ?? skills ?? {};
52 return Math.max(1, levels[skillId] | 0 || 1);
91 return Math.min(MAX_SKILL_LEVEL, Math.max(1, levels[skillId] | 0 || 1));
92 }
93
94 export function playerMaxHealth (skills)
95 {
96 return skillLevel(skills, SkillId.health);
97 }
98
99 export function playerMaxStamina (skills)
100 {
101 return skillLevel(skills, SkillId.stamina);
53 102 }
@@ -8,9 +8,43 @@ export const SkillId = Object.freeze({
8 strength: "strength",
8 strength: "strength",
9 dexterity: "dexterity",
9 dexterity: "dexterity",
10 mind: "mind",
10 mind: "mind",
11 defence: "defence"
11 defence: "defence",
12 health: "health",
13 stamina: "stamina",
14 woodcutting: "woodcutting",
15 mining: "mining",
16 fishing: "fishing",
17 smithing: "smithing",
18 crafting: "crafting",
19 leatherworking: "leatherworking",
20 tailoring: "tailoring",
21 cooking: "cooking"
12});
22});
13
23
24/** Display order for the skills panel (two columns, top to bottom). */
25export const ALL_SKILL_IDS = Object.freeze([
26 SkillId.clubfighting,
27 SkillId.swordfighting,
28 SkillId.axefighting,
29 SkillId.archery,
30 SkillId.unarmed,
31 SkillId.magic,
32 SkillId.strength,
33 SkillId.dexterity,
34 SkillId.mind,
35 SkillId.defence,
36 SkillId.health,
37 SkillId.stamina,
38 SkillId.woodcutting,
39 SkillId.mining,
40 SkillId.fishing,
41 SkillId.smithing,
42 SkillId.crafting,
43 SkillId.leatherworking,
44 SkillId.tailoring,
45 SkillId.cooking
46]);
47
14export const SKILL_DEFINITIONS = Object.freeze({
48export const SKILL_DEFINITIONS = Object.freeze({
15 [SkillId.clubfighting]: Object.freeze({ skillId: SkillId.clubfighting, displayName: "Club fighting" }),
49 [SkillId.clubfighting]: Object.freeze({ skillId: SkillId.clubfighting, displayName: "Club fighting" }),
16 [SkillId.swordfighting]: Object.freeze({ skillId: SkillId.swordfighting, displayName: "Sword fighting" }),
50 [SkillId.swordfighting]: Object.freeze({ skillId: SkillId.swordfighting, displayName: "Sword fighting" }),
@@ -21,21 +55,22 @@ export const SKILL_DEFINITIONS = Object.freeze({
21 [SkillId.strength]: Object.freeze({ skillId: SkillId.strength, displayName: "Strength" }),
55 [SkillId.strength]: Object.freeze({ skillId: SkillId.strength, displayName: "Strength" }),
22 [SkillId.dexterity]: Object.freeze({ skillId: SkillId.dexterity, displayName: "Dexterity" }),
56 [SkillId.dexterity]: Object.freeze({ skillId: SkillId.dexterity, displayName: "Dexterity" }),
23 [SkillId.mind]: Object.freeze({ skillId: SkillId.mind, displayName: "Mind" }),
57 [SkillId.mind]: Object.freeze({ skillId: SkillId.mind, displayName: "Mind" }),
24 [SkillId.defence]: Object.freeze({ skillId: SkillId.defence, displayName: "Defence" })
58 [SkillId.defence]: Object.freeze({ skillId: SkillId.defence, displayName: "Defence" }),
59 [SkillId.health]: Object.freeze({ skillId: SkillId.health, displayName: "Health" }),
60 [SkillId.stamina]: Object.freeze({ skillId: SkillId.stamina, displayName: "Stamina" }),
61 [SkillId.woodcutting]: Object.freeze({ skillId: SkillId.woodcutting, displayName: "Woodcutting" }),
62 [SkillId.mining]: Object.freeze({ skillId: SkillId.mining, displayName: "Mining" }),
63 [SkillId.fishing]: Object.freeze({ skillId: SkillId.fishing, displayName: "Fishing" }),
64 [SkillId.smithing]: Object.freeze({ skillId: SkillId.smithing, displayName: "Smithing" }),
65 [SkillId.crafting]: Object.freeze({ skillId: SkillId.crafting, displayName: "Crafting" }),
66 [SkillId.leatherworking]: Object.freeze({ skillId: SkillId.leatherworking, displayName: "Leatherworking" }),
67 [SkillId.tailoring]: Object.freeze({ skillId: SkillId.tailoring, displayName: "Tailoring" }),
68 [SkillId.cooking]: Object.freeze({ skillId: SkillId.cooking, displayName: "Cooking" })
25});
69});
26
70
27export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze({
71export const DEFAULT_PLAYER_SKILL_LEVELS = Object.freeze(Object.fromEntries(
28 [SkillId.clubfighting]: 1,
72 ALL_SKILL_IDS.map((skillId) => [skillId, skillId === SkillId.health ? 10 : 1])
29 [SkillId.swordfighting]: 1,
73));
30 [SkillId.axefighting]: 1,
31 [SkillId.archery]: 1,
32 [SkillId.unarmed]: 1,
33 [SkillId.magic]: 1,
34 [SkillId.strength]: 1,
35 [SkillId.dexterity]: 1,
36 [SkillId.mind]: 1,
37 [SkillId.defence]: 1
38});
39
74
40export const UNARMED_ATTACK = Object.freeze({
75export const UNARMED_ATTACK = Object.freeze({
41 mode: "melee",
76 mode: "melee",
@@ -46,8 +81,22 @@ export const UNARMED_ATTACK = Object.freeze({
46 baseDamage: 1
81 baseDamage: 1
47});
82});
48
83
84import { levelFromTotalXp, MAX_SKILL_LEVEL } from "../skills/progression.js";
85
49export function skillLevel (skills, skillId)
86export function skillLevel (skills, skillId)
50{
87{
88 if (skills?.xp)
89 { return Math.min(MAX_SKILL_LEVEL, levelFromTotalXp(skills.xp[skillId] ?? 0)); }
51 const levels = skills?.levels ?? skills ?? {};
90 const levels = skills?.levels ?? skills ?? {};
52 return Math.max(1, levels[skillId] | 0 || 1);
91 return Math.min(MAX_SKILL_LEVEL, Math.max(1, levels[skillId] | 0 || 1));
92}
93
94export function playerMaxHealth (skills)
95{
96 return skillLevel(skills, SkillId.health);
97}
98
99export function playerMaxStamina (skills)
100{
101 return skillLevel(skills, SkillId.stamina);
53}
102}
shared/definitions/spells.js added +36 −0
@@ -0,0 +1,36 @@
1 /**
2 * Minimal spell content definitions. Gameplay wiring (casting UI, ECS) comes later.
3 *
4 * @typedef {object} SpellDefinition
5 * @property {string} spellId
6 * @property {string} displayName
7 * @property {number} difficulty Roll contest die size (1..difficulty) rolled against Magic
8 * @property {number} [baseDamage]
9 * @property {import("../combat/magic.js").SpellElement} [element]
10 * @property {string|null} [effectId] Non-damage spells apply this when cast succeeds
11 * @property {number} [rangeTiles]
12 * @property {number} [minMagicLevel]
13 */
14
15 export const SpellId = Object.freeze({
16 spark: "spark"
17 });
18
19 /** @type {Record<string, SpellDefinition>} */
20 export const SPELL_DEFINITIONS = Object.freeze({
21 [SpellId.spark]: Object.freeze({
22 spellId: SpellId.spark,
23 displayName: "Spark",
24 difficulty: 4,
25 baseDamage: 2,
26 element: "fire",
27 effectId: null,
28 rangeTiles: 4,
29 minMagicLevel: 1
30 })
31 });
32
33 export function spellDefinition (spellId)
34 {
35 return SPELL_DEFINITIONS[spellId] ?? null;
36 }
@@ -0,0 +1,36 @@
1/**
2 * Minimal spell content definitions. Gameplay wiring (casting UI, ECS) comes later.
3 *
4 * @typedef {object} SpellDefinition
5 * @property {string} spellId
6 * @property {string} displayName
7 * @property {number} difficulty Roll contest die size (1..difficulty) rolled against Magic
8 * @property {number} [baseDamage]
9 * @property {import("../combat/magic.js").SpellElement} [element]
10 * @property {string|null} [effectId] Non-damage spells apply this when cast succeeds
11 * @property {number} [rangeTiles]
12 * @property {number} [minMagicLevel]
13 */
14
15export const SpellId = Object.freeze({
16 spark: "spark"
17});
18
19/** @type {Record<string, SpellDefinition>} */
20export const SPELL_DEFINITIONS = Object.freeze({
21 [SpellId.spark]: Object.freeze({
22 spellId: SpellId.spark,
23 displayName: "Spark",
24 difficulty: 4,
25 baseDamage: 2,
26 element: "fire",
27 effectId: null,
28 rangeTiles: 4,
29 minMagicLevel: 1
30 })
31});
32
33export function spellDefinition (spellId)
34{
35 return SPELL_DEFINITIONS[spellId] ?? null;
36}
shared/equipment/stats.js added +106 −0
@@ -0,0 +1,106 @@
1 import { SkillId, skillLevel } from "../definitions/skills.js";
2 import { tierMinSkillLevel, tierStatBonus } from "../definitions/materialTiers.js";
3 import { EquipmentKind } from "../definitions/equipmentKinds.js";
4 import { itemDefinition } from "../definitions/items.js";
5
6 /** How an equippable item maps to min-level skill and worn stat bonus. */
7 export { EquipmentKind } from "../definitions/equipmentKinds.js";
8
9 const BONUS_STAT_BY_KIND = Object.freeze({
10 [EquipmentKind.metalWeapon]: SkillId.strength,
11 [EquipmentKind.clubWeapon]: SkillId.strength,
12 [EquipmentKind.bow]: SkillId.dexterity,
13 [EquipmentKind.metalArmour]: SkillId.defence,
14 [EquipmentKind.leatherArmour]: SkillId.dexterity,
15 [EquipmentKind.clothArmour]: SkillId.defence,
16 [EquipmentKind.wizardCloth]: SkillId.magic,
17 [EquipmentKind.shield]: SkillId.defence,
18 [EquipmentKind.staff]: SkillId.mind
19 });
20
21 export function equipMinSkillId (equipmentDef)
22 {
23 const kind = equipmentDef?.kind;
24 const attack = equipmentDef?.attack;
25 switch (kind)
26 {
27 case EquipmentKind.metalWeapon:
28 case EquipmentKind.clubWeapon:
29 return attack?.hitSkillId ?? SkillId.swordfighting;
30 case EquipmentKind.bow:
31 return SkillId.archery;
32 case EquipmentKind.metalArmour:
33 case EquipmentKind.leatherArmour:
34 case EquipmentKind.clothArmour:
35 case EquipmentKind.shield:
36 return SkillId.defence;
37 case EquipmentKind.wizardCloth:
38 case EquipmentKind.staff:
39 return SkillId.magic;
40 case EquipmentKind.axeTool:
41 return SkillId.woodcutting;
42 case EquipmentKind.pickaxeTool:
43 return SkillId.mining;
44 case EquipmentKind.fishingRod:
45 case EquipmentKind.fishingNet:
46 return SkillId.fishing;
47 default:
48 return null;
49 }
50 }
51
52 export function equipmentBonusesFromSlots (slots)
53 {
54 const bonuses = emptyBonuses();
55 for (const stack of Object.values(slots ?? {}))
56 {
57 if (!stack?.itemId)
58 { continue; }
59 const def = itemDefinition(stack.itemId);
60 const equipment = def?.equipment;
61 if (!equipment)
62 { continue; }
63 const statId = BONUS_STAT_BY_KIND[equipment.kind];
64 if (!statId)
65 { continue; }
66 const tier = equipment.tier;
67 const extra = equipment.bonus ?? tierStatBonus(tier);
68 bonuses[statId] = (bonuses[statId] ?? 0) + extra;
69 }
70 return bonuses;
71 }
72
73 export function effectiveSkillLevel (skills, skillId, bonuses = {})
74 {
75 return skillLevel(skills, skillId) + (bonuses[skillId] ?? 0);
76 }
77
78 export function canEquipItem (skills, itemDef)
79 {
80 const equipment = itemDef?.equipment;
81 if (!equipment)
82 { return { ok: false, reason: "That item cannot be equipped." }; }
83 const minSkillId = equipMinSkillId(equipment);
84 if (!minSkillId)
85 { return { ok: true }; }
86 const required = equipment.minSkillLevel ?? tierMinSkillLevel(equipment.tier);
87 if (skillLevel(skills, minSkillId) < required)
88 {
89 return {
90 ok: false,
91 reason: `Requires ${required} ${minSkillId}.`
92 };
93 }
94 return { ok: true };
95 }
96
97 function emptyBonuses ()
98 {
99 return {
100 [SkillId.strength]: 0,
101 [SkillId.defence]: 0,
102 [SkillId.dexterity]: 0,
103 [SkillId.magic]: 0,
104 [SkillId.mind]: 0
105 };
106 }
@@ -0,0 +1,106 @@
1import { SkillId, skillLevel } from "../definitions/skills.js";
2import { tierMinSkillLevel, tierStatBonus } from "../definitions/materialTiers.js";
3import { EquipmentKind } from "../definitions/equipmentKinds.js";
4import { itemDefinition } from "../definitions/items.js";
5
6/** How an equippable item maps to min-level skill and worn stat bonus. */
7export { EquipmentKind } from "../definitions/equipmentKinds.js";
8
9const BONUS_STAT_BY_KIND = Object.freeze({
10 [EquipmentKind.metalWeapon]: SkillId.strength,
11 [EquipmentKind.clubWeapon]: SkillId.strength,
12 [EquipmentKind.bow]: SkillId.dexterity,
13 [EquipmentKind.metalArmour]: SkillId.defence,
14 [EquipmentKind.leatherArmour]: SkillId.dexterity,
15 [EquipmentKind.clothArmour]: SkillId.defence,
16 [EquipmentKind.wizardCloth]: SkillId.magic,
17 [EquipmentKind.shield]: SkillId.defence,
18 [EquipmentKind.staff]: SkillId.mind
19});
20
21export function equipMinSkillId (equipmentDef)
22{
23 const kind = equipmentDef?.kind;
24 const attack = equipmentDef?.attack;
25 switch (kind)
26 {
27 case EquipmentKind.metalWeapon:
28 case EquipmentKind.clubWeapon:
29 return attack?.hitSkillId ?? SkillId.swordfighting;
30 case EquipmentKind.bow:
31 return SkillId.archery;
32 case EquipmentKind.metalArmour:
33 case EquipmentKind.leatherArmour:
34 case EquipmentKind.clothArmour:
35 case EquipmentKind.shield:
36 return SkillId.defence;
37 case EquipmentKind.wizardCloth:
38 case EquipmentKind.staff:
39 return SkillId.magic;
40 case EquipmentKind.axeTool:
41 return SkillId.woodcutting;
42 case EquipmentKind.pickaxeTool:
43 return SkillId.mining;
44 case EquipmentKind.fishingRod:
45 case EquipmentKind.fishingNet:
46 return SkillId.fishing;
47 default:
48 return null;
49 }
50}
51
52export function equipmentBonusesFromSlots (slots)
53{
54 const bonuses = emptyBonuses();
55 for (const stack of Object.values(slots ?? {}))
56 {
57 if (!stack?.itemId)
58 { continue; }
59 const def = itemDefinition(stack.itemId);
60 const equipment = def?.equipment;
61 if (!equipment)
62 { continue; }
63 const statId = BONUS_STAT_BY_KIND[equipment.kind];
64 if (!statId)
65 { continue; }
66 const tier = equipment.tier;
67 const extra = equipment.bonus ?? tierStatBonus(tier);
68 bonuses[statId] = (bonuses[statId] ?? 0) + extra;
69 }
70 return bonuses;
71}
72
73export function effectiveSkillLevel (skills, skillId, bonuses = {})
74{
75 return skillLevel(skills, skillId) + (bonuses[skillId] ?? 0);
76}
77
78export function canEquipItem (skills, itemDef)
79{
80 const equipment = itemDef?.equipment;
81 if (!equipment)
82 { return { ok: false, reason: "That item cannot be equipped." }; }
83 const minSkillId = equipMinSkillId(equipment);
84 if (!minSkillId)
85 { return { ok: true }; }
86 const required = equipment.minSkillLevel ?? tierMinSkillLevel(equipment.tier);
87 if (skillLevel(skills, minSkillId) < required)
88 {
89 return {
90 ok: false,
91 reason: `Requires ${required} ${minSkillId}.`
92 };
93 }
94 return { ok: true };
95}
96
97function emptyBonuses ()
98{
99 return {
100 [SkillId.strength]: 0,
101 [SkillId.defence]: 0,
102 [SkillId.dexterity]: 0,
103 [SkillId.magic]: 0,
104 [SkillId.mind]: 0
105 };
106}
shared/items/formatQuantity.js added +23 −0
@@ -0,0 +1,23 @@
1 /** Compact stack counts: 1500 → 1.5k, 1000000 → 1M, etc. */
2 export function formatQuantity (value)
3 {
4 const n = Math.max(0, Math.floor(Number(value) || 0));
5 if (n < 1000)
6 { return String(n); }
7 const units = [
8 [1_000_000_000_000, "T"],
9 [1_000_000_000, "B"],
10 [1_000_000, "M"],
11 [1_000, "k"]
12 ];
13 for (const [divisor, suffix] of units)
14 {
15 if (n < divisor)
16 { continue; }
17 const scaled = n / divisor;
18 if (Number.isInteger(scaled))
19 { return `${scaled}${suffix}`; }
20 return `${Math.round(scaled * 10) / 10}${suffix}`;
21 }
22 return String(n);
23 }
@@ -0,0 +1,23 @@
1/** Compact stack counts: 1500 → 1.5k, 1000000 → 1M, etc. */
2export function formatQuantity (value)
3{
4 const n = Math.max(0, Math.floor(Number(value) || 0));
5 if (n < 1000)
6 { return String(n); }
7 const units = [
8 [1_000_000_000_000, "T"],
9 [1_000_000_000, "B"],
10 [1_000_000, "M"],
11 [1_000, "k"]
12 ];
13 for (const [divisor, suffix] of units)
14 {
15 if (n < divisor)
16 { continue; }
17 const scaled = n / divisor;
18 if (Number.isInteger(scaled))
19 { return `${scaled}${suffix}`; }
20 return `${Math.round(scaled * 10) / 10}${suffix}`;
21 }
22 return String(n);
23}
shared/items/inventory.js +320 −31
@@ -1,6 +1,20 @@
1 1 export const INVENTORY_SLOTS = 32;
2 2 export const EQUIPMENT_SLOTS = Object.freeze(["head", "chest", "legs", "boots", "weapon", "offhand"]);
3 3
4 import { attachOrigins, mergeOriginLists, normalizeOrigins, splitOrigins } from "./origin.js";
5 import { stackRulesFor } from "./stackRules.js";
6 import { BLANK_CHEQUE_CARRY_CAP, ItemId, itemDefinition } from "../definitions/items.js";
7
8 /** Stack counts can exceed 32-bit range (coin stacks up to 999B). */
9 export function stackQuantity (value)
10 {
11 const n = Number(value);
12 if (!Number.isFinite(n) || n <= 0)
13 { return 0; }
14 const q = Math.floor(n);
15 return Number.isSafeInteger(q) ? q : 0;
16 }
17
4 18 export function emptySlots (count = INVENTORY_SLOTS)
5 19 {
6 20 return Array.from({ length: count }, () => null);
@@ -19,55 +33,92 @@ export function cloneStack (stack)
19 33 return stack ? structuredClone(stack) : null;
20 34 }
21 35
22 export function stacksMatch (left, right)
36 /** One item from a stack, preserving a single origin slice (for equip). */
37 export function singleItemFromStack (stack)
23 38 {
24 if (!left || !right)
25 { return false; }
26 if (left.itemId !== right.itemId)
39 if (!stack)
40 { return null; }
41 const split = splitOrigins(normalizeOrigins(stack), 1);
42 return {
43 itemId: stack.itemId,
44 quantity: 1,
45 instance: stack.instance ? cloneStack(stack.instance) : null,
46 origins: split.taken
47 };
48 }
49
50 export function stacksMatch (left, right, definition, { inVault = false } = {})
51 {
52 if (!left || !right || left.itemId !== right.itemId)
27 53 { return false; }
28 return JSON.stringify(left.origin ?? null) === JSON.stringify(right.origin ?? null)
29 && JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
54 const rules = stackRulesFor(definition, { inVault });
55 if (rules.uniqueInstance)
56 {
57 return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
58 }
59 return rules.stackable;
60 }
61
62 function stackPayload (stack, quantity, origins)
63 {
64 return {
65 itemId: stack.itemId,
66 quantity,
67 instance: stack.instance ?? null,
68 origins: origins.map((entry) => ({
69 origin: entry.origin ?? null,
70 quantity: stackQuantity(entry.quantity)
71 })).filter((entry) => entry.quantity > 0)
72 };
30 73 }
31 74
32 export function insertStack (slots, stack, definition)
75 export function insertStack (slots, stack, definition, options = {})
33 76 {
34 77 if (!stack || stack.quantity <= 0)
35 78 { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; }
79 const rules = stackRulesFor(definition, options);
36 80 const next = slots.map(cloneStack);
37 let remaining = stack.quantity;
38 if (definition.stackable && !definition.uniqueInstance)
81 let remaining = stackQuantity(stack.quantity);
82 let pendingOrigins = normalizeOrigins(stack);
83
84 if (rules.stackable && !rules.uniqueInstance)
39 85 {
40 86 for (const slot of next)
41 87 {
42 if (!stacksMatch(slot, stack))
88 if (!slot || slot.itemId !== stack.itemId)
89 { continue; }
90 if (slot.instance != null || stack.instance != null)
43 91 { continue; }
44 const space = (definition.maxStackSize ?? 99) - slot.quantity;
92 const space = rules.maxStackSize - stackQuantity(slot.quantity);
45 93 if (space <= 0)
46 94 { continue; }
47 95 const add = Math.min(space, remaining);
48 slot.quantity += add;
96 const split = splitOrigins(pendingOrigins, add);
97 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
98 slot.quantity = stackQuantity(slot.quantity) + add;
99 delete slot.origin;
100 pendingOrigins = split.remain;
49 101 remaining -= add;
50 102 if (remaining === 0)
51 103 { return { ok: true, slots: next, remainder: 0 }; }
52 104 }
53 105 }
106
54 107 for (let i = 0; i < next.length; i++)
55 108 {
56 109 if (next[i])
57 110 { continue; }
58 const amount = definition.stackable && !definition.uniqueInstance
59 ? Math.min(remaining, definition.maxStackSize ?? 99)
111 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
112 const amount = rules.stackable && !rules.uniqueInstance
113 ? Math.min(remaining, cap)
60 114 : 1;
61 next[i] = {
62 itemId: stack.itemId,
63 quantity: amount,
64 origin: stack.origin ?? null,
65 instance: stack.instance ?? null
66 };
115 const split = splitOrigins(pendingOrigins, amount);
116 next[i] = stackPayload(stack, amount, split.taken);
117 pendingOrigins = split.remain;
67 118 remaining -= amount;
68 119 if (remaining === 0)
69 120 { return { ok: true, slots: next, remainder: 0 }; }
70 if (!definition.stackable || definition.uniqueInstance)
121 if (!rules.stackable || rules.uniqueInstance)
71 122 { break; }
72 123 }
73 124 return { ok: false, slots, remainder: remaining };
@@ -79,25 +130,263 @@ export function takeFromSlot (slots, slotIndex, quantity = null)
79 130 const slot = next[slotIndex];
80 131 if (!slot)
81 132 { return { ok: false, slots, taken: null }; }
82 const amount = quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, quantity | 0));
133 const maxQty = stackQuantity(slot.quantity);
134 const amount = quantity == null
135 ? maxQty
136 : Math.min(maxQty, Math.max(1, stackQuantity(quantity)));
83 137 if (amount <= 0)
84 138 { return { ok: false, slots, taken: null }; }
85 const taken = { ...cloneStack(slot), quantity: amount };
86 if (amount >= slot.quantity)
139 const split = splitOrigins(normalizeOrigins(slot), amount);
140 const taken = stackPayload(slot, amount, split.taken);
141 if (amount >= maxQty)
87 142 { next[slotIndex] = null; }
88 143 else
89 { slot.quantity -= amount; }
144 {
145 slot.quantity = maxQty - amount;
146 slot.origins = split.remain;
147 delete slot.origin;
148 }
90 149 return { ok: true, slots: next, taken };
91 150 }
92 151
152 /** Like insertStack, but grows the slot array when capacity runs out (vault). */
153 export function insertStackGrowable (slots, stack, definition)
154 {
155 if (!stack || stack.quantity <= 0)
156 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
157 let next = (slots ?? []).map(cloneStack);
158 let remaining = stackQuantity(stack.quantity);
159 let pendingOrigins = normalizeOrigins(stack);
160 const rules = stackRulesFor(definition, { inVault: true });
161
162 if (rules.stackable && !rules.uniqueInstance)
163 {
164 for (const slot of next)
165 {
166 if (!slot || slot.itemId !== stack.itemId || slot.instance != null || stack.instance != null)
167 { continue; }
168 const space = rules.maxStackSize - stackQuantity(slot.quantity);
169 if (space <= 0)
170 { continue; }
171 const add = Math.min(space, remaining);
172 const split = splitOrigins(pendingOrigins, add);
173 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
174 slot.quantity = stackQuantity(slot.quantity) + add;
175 delete slot.origin;
176 pendingOrigins = split.remain;
177 remaining -= add;
178 if (remaining === 0)
179 { return { ok: true, slots: next, remainder: 0 }; }
180 }
181 }
182
183 while (remaining > 0)
184 {
185 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
186 const amount = rules.stackable && !rules.uniqueInstance
187 ? Math.min(remaining, cap)
188 : 1;
189 const split = splitOrigins(pendingOrigins, amount);
190 next.push(stackPayload(stack, amount, split.taken));
191 pendingOrigins = split.remain;
192 remaining -= amount;
193 if (!rules.stackable || rules.uniqueInstance)
194 { break; }
195 }
196 return { ok: remaining === 0, slots: next, remainder: remaining };
197 }
198
199 /** Take `quantity` of matching goods from vault slots (any slots). */
200 export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null })
201 {
202 let remaining = Math.max(0, stackQuantity(quantity));
203 if (!remaining)
204 { return { ok: false, slots, taken: null }; }
205 const next = (slots ?? []).map(cloneStack);
206 const takenOrigins = [];
207 for (let i = 0; i < next.length && remaining > 0; i++)
208 {
209 const slot = next[i];
210 if (!slot || slot.itemId !== itemId)
211 { continue; }
212 if (instance != null)
213 {
214 if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance))
215 { continue; }
216 }
217 const amount = Math.min(stackQuantity(slot.quantity), remaining);
218 const split = splitOrigins(normalizeOrigins(slot), amount);
219 takenOrigins.push(...split.taken);
220 if (amount >= stackQuantity(slot.quantity))
221 { next[i] = null; }
222 else
223 {
224 slot.quantity = stackQuantity(slot.quantity) - amount;
225 slot.origins = split.remain;
226 delete slot.origin;
227 }
228 remaining -= amount;
229 }
230 const compact = next.filter((slot) => slot);
231 if (remaining > 0)
232 { return { ok: false, slots, taken: null }; }
233 return {
234 ok: true,
235 slots: compact,
236 taken: attachOrigins({
237 itemId,
238 quantity: stackQuantity(quantity),
239 instance: instance ?? null,
240 origins: mergeOriginLists([], takenOrigins)
241 })
242 };
243 }
244
245 export function countItemInSlots (slots, itemId)
246 {
247 let total = 0;
248 for (const slot of slots ?? [])
249 {
250 if (slot?.itemId === itemId)
251 { total += stackQuantity(slot.quantity); }
252 }
253 return total;
254 }
255
256 export function countCoinsInSlots (slots)
257 {
258 return countItemInSlots(slots, ItemId.coins);
259 }
260
261 /** Add coin stacks, splitting at max stack size (999B). */
262 export function addCoinsToSlots (slots, amount, { growable = false } = {})
263 {
264 const def = itemDefinition(ItemId.coins);
265 if (!def || amount <= 0)
266 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
267 let next = (slots ?? []).map(cloneStack);
268 if (!growable && next.length < INVENTORY_SLOTS)
269 {
270 const padded = emptySlots();
271 for (let i = 0; i < next.length; i++)
272 { padded[i] = next[i]; }
273 next = padded;
274 }
275 let remaining = stackQuantity(amount);
276 const insert = growable ? insertStackGrowable : insertStack;
277 while (remaining > 0)
278 {
279 const chunk = Math.min(remaining, def.maxStackSize ?? 99);
280 const result = insert(next, { itemId: ItemId.coins, quantity: chunk }, def);
281 next = result.slots;
282 const placed = chunk - (result.remainder ?? 0);
283 remaining -= placed;
284 if (!result.ok || result.remainder > 0)
285 { return { ok: false, slots: next, remainder: remaining }; }
286 }
287 return { ok: true, slots: next, remainder: 0 };
288 }
289
290 /** Convert legacy currency counters into coin stacks. */
291 export function migrateBagCoins (bag)
292 {
293 let inventory = bag.inventory ?? emptySlots();
294 let vault = bag.vault ?? [];
295 if (bag.currency > 0)
296 {
297 const added = addCoinsToSlots(inventory, stackQuantity(bag.currency), { growable: false });
298 inventory = added.slots;
299 }
300 if (bag.vaultCurrency > 0)
301 {
302 const added = addCoinsToSlots(vault, stackQuantity(bag.vaultCurrency), { growable: true });
303 vault = added.slots;
304 }
305 return {
306 ...bag,
307 inventory,
308 vault,
309 currency: 0,
310 vaultCurrency: 0
311 };
312 }
313
314 export function migrateInheritanceCoins (inheritance)
315 {
316 if (!inheritance?.currency)
317 { return inheritance; }
318 const added = addCoinsToSlots(inheritance.slots ?? emptySlots(), stackQuantity(inheritance.currency), { growable: true });
319 return {
320 ...inheritance,
321 slots: added.slots,
322 currency: 0
323 };
324 }
325
326 /** Trim excess blank cheques in inventory (e.g. after legacy saves or bugs). */
327 export function normalizeInventorySlots (slots)
328 {
329 return capItemTotalInSlots(slots ?? emptySlots(), ItemId.blankCheque, BLANK_CHEQUE_CARRY_CAP);
330 }
331
332 export function capItemTotalInSlots (slots, itemId, cap)
333 {
334 const next = (slots ?? []).map(cloneStack);
335 let total = countItemInSlots(next, itemId);
336 if (total <= cap)
337 { return next; }
338 let toRemove = total - cap;
339 for (let i = next.length - 1; i >= 0 && toRemove > 0; i--)
340 {
341 const slot = next[i];
342 if (!slot || slot.itemId !== itemId)
343 { continue; }
344 const beforeQty = stackQuantity(slot.quantity);
345 const drop = Math.min(beforeQty, toRemove);
346 const { remain } = splitOrigins(normalizeOrigins({ ...slot, quantity: beforeQty }), drop);
347 slot.quantity = beforeQty - drop;
348 slot.origins = remain;
349 delete slot.origin;
350 toRemove -= drop;
351 if (slot.quantity <= 0)
352 { next[i] = null; }
353 }
354 return next;
355 }
356
357 export function normalizeVault (raw)
358 {
359 if (Array.isArray(raw))
360 { return { slots: raw.map(cloneStack), reserved: [] }; }
361 return {
362 slots: (raw?.slots ?? []).map(cloneStack),
363 reserved: (raw?.reserved ?? []).map(cloneStack)
364 };
365 }
366
367 export function serializeVault (vault)
368 {
369 const normalized = normalizeVault(vault);
370 return {
371 slots: publicSlots(normalized.slots),
372 reserved: publicSlots(normalized.reserved)
373 };
374 }
375
93 376 export function publicSlots (slots)
94 377 {
95 return (slots ?? emptySlots()).map((slot) => slot ? {
96 itemId: slot.itemId,
97 quantity: slot.quantity,
98 origin: slot.origin ?? null,
99 instance: slot.instance ?? null
100 } : null);
378 return (slots ?? emptySlots()).map((slot) =>
379 {
380 if (!slot)
381 { return null; }
382 const payload = attachOrigins(cloneStack(slot));
383 return {
384 itemId: payload.itemId,
385 quantity: payload.quantity,
386 origins: payload.origins,
387 instance: payload.instance ?? null
388 };
389 });
101 390 }
102 391
103 392 export function publicEquipment (equipment)
@@ -1,6 +1,20 @@
1export const INVENTORY_SLOTS = 32;
1export const INVENTORY_SLOTS = 32;
2export const EQUIPMENT_SLOTS = Object.freeze(["head", "chest", "legs", "boots", "weapon", "offhand"]);
2export const EQUIPMENT_SLOTS = Object.freeze(["head", "chest", "legs", "boots", "weapon", "offhand"]);
3
3
4import { attachOrigins, mergeOriginLists, normalizeOrigins, splitOrigins } from "./origin.js";
5import { stackRulesFor } from "./stackRules.js";
6import { BLANK_CHEQUE_CARRY_CAP, ItemId, itemDefinition } from "../definitions/items.js";
7
8/** Stack counts can exceed 32-bit range (coin stacks up to 999B). */
9export function stackQuantity (value)
10{
11 const n = Number(value);
12 if (!Number.isFinite(n) || n <= 0)
13 { return 0; }
14 const q = Math.floor(n);
15 return Number.isSafeInteger(q) ? q : 0;
16}
17
4export function emptySlots (count = INVENTORY_SLOTS)
18export function emptySlots (count = INVENTORY_SLOTS)
5{
19{
6 return Array.from({ length: count }, () => null);
20 return Array.from({ length: count }, () => null);
@@ -19,55 +33,92 @@ export function cloneStack (stack)
19 return stack ? structuredClone(stack) : null;
33 return stack ? structuredClone(stack) : null;
20}
34}
21
35
22export function stacksMatch (left, right)
36/** One item from a stack, preserving a single origin slice (for equip). */
37export function singleItemFromStack (stack)
23{
38{
24 if (!left || !right)
39 if (!stack)
25 { return false; }
40 { return null; }
26 if (left.itemId !== right.itemId)
41 const split = splitOrigins(normalizeOrigins(stack), 1);
42 return {
43 itemId: stack.itemId,
44 quantity: 1,
45 instance: stack.instance ? cloneStack(stack.instance) : null,
46 origins: split.taken
47 };
48}
49
50export function stacksMatch (left, right, definition, { inVault = false } = {})
51{
52 if (!left || !right || left.itemId !== right.itemId)
27 { return false; }
53 { return false; }
28 return JSON.stringify(left.origin ?? null) === JSON.stringify(right.origin ?? null)
54 const rules = stackRulesFor(definition, { inVault });
29 && JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
55 if (rules.uniqueInstance)
56 {
57 return JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
58 }
59 return rules.stackable;
60}
61
62function stackPayload (stack, quantity, origins)
63{
64 return {
65 itemId: stack.itemId,
66 quantity,
67 instance: stack.instance ?? null,
68 origins: origins.map((entry) => ({
69 origin: entry.origin ?? null,
70 quantity: stackQuantity(entry.quantity)
71 })).filter((entry) => entry.quantity > 0)
72 };
30}
73}
31
74
32export function insertStack (slots, stack, definition)
75export function insertStack (slots, stack, definition, options = {})
33{
76{
34 if (!stack || stack.quantity <= 0)
77 if (!stack || stack.quantity <= 0)
35 { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; }
78 { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; }
79 const rules = stackRulesFor(definition, options);
36 const next = slots.map(cloneStack);
80 const next = slots.map(cloneStack);
37 let remaining = stack.quantity;
81 let remaining = stackQuantity(stack.quantity);
38 if (definition.stackable && !definition.uniqueInstance)
82 let pendingOrigins = normalizeOrigins(stack);
83
84 if (rules.stackable && !rules.uniqueInstance)
39 {
85 {
40 for (const slot of next)
86 for (const slot of next)
41 {
87 {
42 if (!stacksMatch(slot, stack))
88 if (!slot || slot.itemId !== stack.itemId)
89 { continue; }
90 if (slot.instance != null || stack.instance != null)
43 { continue; }
91 { continue; }
44 const space = (definition.maxStackSize ?? 99) - slot.quantity;
92 const space = rules.maxStackSize - stackQuantity(slot.quantity);
45 if (space <= 0)
93 if (space <= 0)
46 { continue; }
94 { continue; }
47 const add = Math.min(space, remaining);
95 const add = Math.min(space, remaining);
48 slot.quantity += add;
96 const split = splitOrigins(pendingOrigins, add);
97 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
98 slot.quantity = stackQuantity(slot.quantity) + add;
99 delete slot.origin;
100 pendingOrigins = split.remain;
49 remaining -= add;
101 remaining -= add;
50 if (remaining === 0)
102 if (remaining === 0)
51 { return { ok: true, slots: next, remainder: 0 }; }
103 { return { ok: true, slots: next, remainder: 0 }; }
52 }
104 }
53 }
105 }
106
54 for (let i = 0; i < next.length; i++)
107 for (let i = 0; i < next.length; i++)
55 {
108 {
56 if (next[i])
109 if (next[i])
57 { continue; }
110 { continue; }
58 const amount = definition.stackable && !definition.uniqueInstance
111 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
59 ? Math.min(remaining, definition.maxStackSize ?? 99)
112 const amount = rules.stackable && !rules.uniqueInstance
113 ? Math.min(remaining, cap)
60 : 1;
114 : 1;
61 next[i] = {
115 const split = splitOrigins(pendingOrigins, amount);
62 itemId: stack.itemId,
116 next[i] = stackPayload(stack, amount, split.taken);
63 quantity: amount,
117 pendingOrigins = split.remain;
64 origin: stack.origin ?? null,
65 instance: stack.instance ?? null
66 };
67 remaining -= amount;
118 remaining -= amount;
68 if (remaining === 0)
119 if (remaining === 0)
69 { return { ok: true, slots: next, remainder: 0 }; }
120 { return { ok: true, slots: next, remainder: 0 }; }
70 if (!definition.stackable || definition.uniqueInstance)
121 if (!rules.stackable || rules.uniqueInstance)
71 { break; }
122 { break; }
72 }
123 }
73 return { ok: false, slots, remainder: remaining };
124 return { ok: false, slots, remainder: remaining };
@@ -79,25 +130,263 @@ export function takeFromSlot (slots, slotIndex, quantity = null)
79 const slot = next[slotIndex];
130 const slot = next[slotIndex];
80 if (!slot)
131 if (!slot)
81 { return { ok: false, slots, taken: null }; }
132 { return { ok: false, slots, taken: null }; }
82 const amount = quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, quantity | 0));
133 const maxQty = stackQuantity(slot.quantity);
134 const amount = quantity == null
135 ? maxQty
136 : Math.min(maxQty, Math.max(1, stackQuantity(quantity)));
83 if (amount <= 0)
137 if (amount <= 0)
84 { return { ok: false, slots, taken: null }; }
138 { return { ok: false, slots, taken: null }; }
85 const taken = { ...cloneStack(slot), quantity: amount };
139 const split = splitOrigins(normalizeOrigins(slot), amount);
86 if (amount >= slot.quantity)
140 const taken = stackPayload(slot, amount, split.taken);
141 if (amount >= maxQty)
87 { next[slotIndex] = null; }
142 { next[slotIndex] = null; }
88 else
143 else
89 { slot.quantity -= amount; }
144 {
145 slot.quantity = maxQty - amount;
146 slot.origins = split.remain;
147 delete slot.origin;
148 }
90 return { ok: true, slots: next, taken };
149 return { ok: true, slots: next, taken };
91}
150}
92
151
152/** Like insertStack, but grows the slot array when capacity runs out (vault). */
153export function insertStackGrowable (slots, stack, definition)
154{
155 if (!stack || stack.quantity <= 0)
156 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
157 let next = (slots ?? []).map(cloneStack);
158 let remaining = stackQuantity(stack.quantity);
159 let pendingOrigins = normalizeOrigins(stack);
160 const rules = stackRulesFor(definition, { inVault: true });
161
162 if (rules.stackable && !rules.uniqueInstance)
163 {
164 for (const slot of next)
165 {
166 if (!slot || slot.itemId !== stack.itemId || slot.instance != null || stack.instance != null)
167 { continue; }
168 const space = rules.maxStackSize - stackQuantity(slot.quantity);
169 if (space <= 0)
170 { continue; }
171 const add = Math.min(space, remaining);
172 const split = splitOrigins(pendingOrigins, add);
173 slot.origins = mergeOriginLists(normalizeOrigins(slot), split.taken);
174 slot.quantity = stackQuantity(slot.quantity) + add;
175 delete slot.origin;
176 pendingOrigins = split.remain;
177 remaining -= add;
178 if (remaining === 0)
179 { return { ok: true, slots: next, remainder: 0 }; }
180 }
181 }
182
183 while (remaining > 0)
184 {
185 const cap = rules.maxStackSize === Number.POSITIVE_INFINITY ? remaining : rules.maxStackSize;
186 const amount = rules.stackable && !rules.uniqueInstance
187 ? Math.min(remaining, cap)
188 : 1;
189 const split = splitOrigins(pendingOrigins, amount);
190 next.push(stackPayload(stack, amount, split.taken));
191 pendingOrigins = split.remain;
192 remaining -= amount;
193 if (!rules.stackable || rules.uniqueInstance)
194 { break; }
195 }
196 return { ok: remaining === 0, slots: next, remainder: remaining };
197}
198
199/** Take `quantity` of matching goods from vault slots (any slots). */
200export function takeMatchingFromSlots (slots, { itemId, quantity, instance = null })
201{
202 let remaining = Math.max(0, stackQuantity(quantity));
203 if (!remaining)
204 { return { ok: false, slots, taken: null }; }
205 const next = (slots ?? []).map(cloneStack);
206 const takenOrigins = [];
207 for (let i = 0; i < next.length && remaining > 0; i++)
208 {
209 const slot = next[i];
210 if (!slot || slot.itemId !== itemId)
211 { continue; }
212 if (instance != null)
213 {
214 if (JSON.stringify(slot.instance ?? null) !== JSON.stringify(instance))
215 { continue; }
216 }
217 const amount = Math.min(stackQuantity(slot.quantity), remaining);
218 const split = splitOrigins(normalizeOrigins(slot), amount);
219 takenOrigins.push(...split.taken);
220 if (amount >= stackQuantity(slot.quantity))
221 { next[i] = null; }
222 else
223 {
224 slot.quantity = stackQuantity(slot.quantity) - amount;
225 slot.origins = split.remain;
226 delete slot.origin;
227 }
228 remaining -= amount;
229 }
230 const compact = next.filter((slot) => slot);
231 if (remaining > 0)
232 { return { ok: false, slots, taken: null }; }
233 return {
234 ok: true,
235 slots: compact,
236 taken: attachOrigins({
237 itemId,
238 quantity: stackQuantity(quantity),
239 instance: instance ?? null,
240 origins: mergeOriginLists([], takenOrigins)
241 })
242 };
243}
244
245export function countItemInSlots (slots, itemId)
246{
247 let total = 0;
248 for (const slot of slots ?? [])
249 {
250 if (slot?.itemId === itemId)
251 { total += stackQuantity(slot.quantity); }
252 }
253 return total;
254}
255
256export function countCoinsInSlots (slots)
257{
258 return countItemInSlots(slots, ItemId.coins);
259}
260
261/** Add coin stacks, splitting at max stack size (999B). */
262export function addCoinsToSlots (slots, amount, { growable = false } = {})
263{
264 const def = itemDefinition(ItemId.coins);
265 if (!def || amount <= 0)
266 { return { ok: true, slots: (slots ?? []).map(cloneStack), remainder: 0 }; }
267 let next = (slots ?? []).map(cloneStack);
268 if (!growable && next.length < INVENTORY_SLOTS)
269 {
270 const padded = emptySlots();
271 for (let i = 0; i < next.length; i++)
272 { padded[i] = next[i]; }
273 next = padded;
274 }
275 let remaining = stackQuantity(amount);
276 const insert = growable ? insertStackGrowable : insertStack;
277 while (remaining > 0)
278 {
279 const chunk = Math.min(remaining, def.maxStackSize ?? 99);
280 const result = insert(next, { itemId: ItemId.coins, quantity: chunk }, def);
281 next = result.slots;
282 const placed = chunk - (result.remainder ?? 0);
283 remaining -= placed;
284 if (!result.ok || result.remainder > 0)
285 { return { ok: false, slots: next, remainder: remaining }; }
286 }
287 return { ok: true, slots: next, remainder: 0 };
288}
289
290/** Convert legacy currency counters into coin stacks. */
291export function migrateBagCoins (bag)
292{
293 let inventory = bag.inventory ?? emptySlots();
294 let vault = bag.vault ?? [];
295 if (bag.currency > 0)
296 {
297 const added = addCoinsToSlots(inventory, stackQuantity(bag.currency), { growable: false });
298 inventory = added.slots;
299 }
300 if (bag.vaultCurrency > 0)
301 {
302 const added = addCoinsToSlots(vault, stackQuantity(bag.vaultCurrency), { growable: true });
303 vault = added.slots;
304 }
305 return {
306 ...bag,
307 inventory,
308 vault,
309 currency: 0,
310 vaultCurrency: 0
311 };
312}
313
314export function migrateInheritanceCoins (inheritance)
315{
316 if (!inheritance?.currency)
317 { return inheritance; }
318 const added = addCoinsToSlots(inheritance.slots ?? emptySlots(), stackQuantity(inheritance.currency), { growable: true });
319 return {
320 ...inheritance,
321 slots: added.slots,
322 currency: 0
323 };
324}
325
326/** Trim excess blank cheques in inventory (e.g. after legacy saves or bugs). */
327export function normalizeInventorySlots (slots)
328{
329 return capItemTotalInSlots(slots ?? emptySlots(), ItemId.blankCheque, BLANK_CHEQUE_CARRY_CAP);
330}
331
332export function capItemTotalInSlots (slots, itemId, cap)
333{
334 const next = (slots ?? []).map(cloneStack);
335 let total = countItemInSlots(next, itemId);
336 if (total <= cap)
337 { return next; }
338 let toRemove = total - cap;
339 for (let i = next.length - 1; i >= 0 && toRemove > 0; i--)
340 {
341 const slot = next[i];
342 if (!slot || slot.itemId !== itemId)
343 { continue; }
344 const beforeQty = stackQuantity(slot.quantity);
345 const drop = Math.min(beforeQty, toRemove);
346 const { remain } = splitOrigins(normalizeOrigins({ ...slot, quantity: beforeQty }), drop);
347 slot.quantity = beforeQty - drop;
348 slot.origins = remain;
349 delete slot.origin;
350 toRemove -= drop;
351 if (slot.quantity <= 0)
352 { next[i] = null; }
353 }
354 return next;
355}
356
357export function normalizeVault (raw)
358{
359 if (Array.isArray(raw))
360 { return { slots: raw.map(cloneStack), reserved: [] }; }
361 return {
362 slots: (raw?.slots ?? []).map(cloneStack),
363 reserved: (raw?.reserved ?? []).map(cloneStack)
364 };
365}
366
367export function serializeVault (vault)
368{
369 const normalized = normalizeVault(vault);
370 return {
371 slots: publicSlots(normalized.slots),
372 reserved: publicSlots(normalized.reserved)
373 };
374}
375
93export function publicSlots (slots)
376export function publicSlots (slots)
94{
377{
95 return (slots ?? emptySlots()).map((slot) => slot ? {
378 return (slots ?? emptySlots()).map((slot) =>
96 itemId: slot.itemId,
379 {
97 quantity: slot.quantity,
380 if (!slot)
98 origin: slot.origin ?? null,
381 { return null; }
99 instance: slot.instance ?? null
382 const payload = attachOrigins(cloneStack(slot));
100 } : null);
383 return {
384 itemId: payload.itemId,
385 quantity: payload.quantity,
386 origins: payload.origins,
387 instance: payload.instance ?? null
388 };
389 });
101}
390}
102
391
103export function publicEquipment (equipment)
392export function publicEquipment (equipment)
shared/items/marketplace.js added +24 −0
@@ -0,0 +1,24 @@
1 import { itemDefinition } from "../definitions/items.js";
2
3 /** Whether this stack may be listed as a marketplace sell order. */
4 export function canSellOnMarketplace (stack)
5 {
6 const def = itemDefinition(stack?.itemId);
7 if (!def || !stack)
8 { return false; }
9 return def.marketplaceSellable !== false;
10 }
11
12 /** @throws {Error & { userFacing?: boolean }} */
13 export function assertMarketplaceSellable (stack)
14 {
15 if (canSellOnMarketplace(stack))
16 { return; }
17 const def = itemDefinition(stack?.itemId);
18 const error = new Error(
19 def?.marketplaceSellBlockedReason
20 ?? "That item cannot be sold on the marketplace."
21 );
22 error.userFacing = true;
23 throw error;
24 }
@@ -0,0 +1,24 @@
1import { itemDefinition } from "../definitions/items.js";
2
3/** Whether this stack may be listed as a marketplace sell order. */
4export function canSellOnMarketplace (stack)
5{
6 const def = itemDefinition(stack?.itemId);
7 if (!def || !stack)
8 { return false; }
9 return def.marketplaceSellable !== false;
10}
11
12/** @throws {Error & { userFacing?: boolean }} */
13export function assertMarketplaceSellable (stack)
14{
15 if (canSellOnMarketplace(stack))
16 { return; }
17 const def = itemDefinition(stack?.itemId);
18 const error = new Error(
19 def?.marketplaceSellBlockedReason
20 ?? "That item cannot be sold on the marketplace."
21 );
22 error.userFacing = true;
23 throw error;
24}
shared/items/origin.js added +116 −0
@@ -0,0 +1,116 @@
1 export const ItemOriginKind = Object.freeze({
2 crafted: "crafted",
3 shop: "shop",
4 unknown: "unknown"
5 });
6
7 export function originKey (origin)
8 {
9 if (!origin)
10 { return "none"; }
11 return JSON.stringify(origin);
12 }
13
14 export function originLabel (origin)
15 {
16 if (!origin)
17 { return "unknown origin"; }
18 if (origin.kind === ItemOriginKind.crafted)
19 {
20 const name = origin.displayName?.trim() || "someone";
21 return `made by ${name}`;
22 }
23 if (origin.kind === ItemOriginKind.shop)
24 {
25 const name = origin.displayName?.trim() || "a shop";
26 return `bought from ${name}`;
27 }
28 return "unknown origin";
29 }
30
31 /** @returns {{ origin: object|null, quantity: number }[]} */
32 export function normalizeOrigins (stack)
33 {
34 if (!stack)
35 { return []; }
36 const qty = Math.max(0, Math.floor(Number(stack.quantity) || 0));
37 if (Array.isArray(stack.origins) && stack.origins.length)
38 {
39 return stack.origins.map((entry) => ({
40 origin: entry.origin ?? null,
41 quantity: Math.max(0, Math.floor(Number(entry.quantity) || 0))
42 })).filter((entry) => entry.quantity > 0);
43 }
44 if (qty <= 0)
45 { return []; }
46 return [{ origin: stack.origin ?? null, quantity: qty }];
47 }
48
49 export function mergeOriginLists (left, right)
50 {
51 const map = new Map();
52 for (const entry of [...normalizeOriginsList(left), ...normalizeOriginsList(right)])
53 {
54 const key = originKey(entry.origin);
55 const prev = map.get(key) ?? { origin: entry.origin ?? null, quantity: 0 };
56 prev.quantity += entry.quantity;
57 map.set(key, prev);
58 }
59 return [...map.values()].filter((entry) => entry.quantity > 0);
60 }
61
62 function normalizeOriginsList (list)
63 {
64 if (!Array.isArray(list))
65 { return []; }
66 return list.map((entry) => ({
67 origin: entry?.origin ?? null,
68 quantity: Math.max(0, Math.floor(Number(entry?.quantity) || 0))
69 })).filter((entry) => entry.quantity > 0);
70 }
71
72 /** FIFO split of origin quantities when taking from a stack. */
73 export function splitOrigins (origins, takeQuantity)
74 {
75 const take = Math.max(0, Math.floor(Number(takeQuantity) || 0));
76 const source = normalizeOriginsList(origins);
77 const taken = [];
78 const remain = [];
79 let left = take;
80 for (const entry of source)
81 {
82 if (left <= 0)
83 {
84 remain.push({ ...entry });
85 continue;
86 }
87 const amount = Math.min(entry.quantity, left);
88 if (amount > 0)
89 {
90 taken.push({ origin: entry.origin ?? null, quantity: amount });
91 left -= amount;
92 }
93 const rest = entry.quantity - amount;
94 if (rest > 0)
95 { remain.push({ origin: entry.origin ?? null, quantity: rest }); }
96 }
97 return { taken, remain };
98 }
99
100 export function attachOrigins (stack)
101 {
102 const origins = normalizeOrigins(stack);
103 const next = { ...stack, origins };
104 delete next.origin;
105 return next;
106 }
107
108 export function formatOriginBreakdown (stack)
109 {
110 const origins = normalizeOrigins(stack);
111 if (!origins.length)
112 { return ""; }
113 return origins
114 .map((entry) => `${entry.quantity} ${originLabel(entry.origin)}`)
115 .join(", ");
116 }
@@ -0,0 +1,116 @@
1export const ItemOriginKind = Object.freeze({
2 crafted: "crafted",
3 shop: "shop",
4 unknown: "unknown"
5});
6
7export function originKey (origin)
8{
9 if (!origin)
10 { return "none"; }
11 return JSON.stringify(origin);
12}
13
14export function originLabel (origin)
15{
16 if (!origin)
17 { return "unknown origin"; }
18 if (origin.kind === ItemOriginKind.crafted)
19 {
20 const name = origin.displayName?.trim() || "someone";
21 return `made by ${name}`;
22 }
23 if (origin.kind === ItemOriginKind.shop)
24 {
25 const name = origin.displayName?.trim() || "a shop";
26 return `bought from ${name}`;
27 }
28 return "unknown origin";
29}
30
31/** @returns {{ origin: object|null, quantity: number }[]} */
32export function normalizeOrigins (stack)
33{
34 if (!stack)
35 { return []; }
36 const qty = Math.max(0, Math.floor(Number(stack.quantity) || 0));
37 if (Array.isArray(stack.origins) && stack.origins.length)
38 {
39 return stack.origins.map((entry) => ({
40 origin: entry.origin ?? null,
41 quantity: Math.max(0, Math.floor(Number(entry.quantity) || 0))
42 })).filter((entry) => entry.quantity > 0);
43 }
44 if (qty <= 0)
45 { return []; }
46 return [{ origin: stack.origin ?? null, quantity: qty }];
47}
48
49export function mergeOriginLists (left, right)
50{
51 const map = new Map();
52 for (const entry of [...normalizeOriginsList(left), ...normalizeOriginsList(right)])
53 {
54 const key = originKey(entry.origin);
55 const prev = map.get(key) ?? { origin: entry.origin ?? null, quantity: 0 };
56 prev.quantity += entry.quantity;
57 map.set(key, prev);
58 }
59 return [...map.values()].filter((entry) => entry.quantity > 0);
60}
61
62function normalizeOriginsList (list)
63{
64 if (!Array.isArray(list))
65 { return []; }
66 return list.map((entry) => ({
67 origin: entry?.origin ?? null,
68 quantity: Math.max(0, Math.floor(Number(entry?.quantity) || 0))
69 })).filter((entry) => entry.quantity > 0);
70}
71
72/** FIFO split of origin quantities when taking from a stack. */
73export function splitOrigins (origins, takeQuantity)
74{
75 const take = Math.max(0, Math.floor(Number(takeQuantity) || 0));
76 const source = normalizeOriginsList(origins);
77 const taken = [];
78 const remain = [];
79 let left = take;
80 for (const entry of source)
81 {
82 if (left <= 0)
83 {
84 remain.push({ ...entry });
85 continue;
86 }
87 const amount = Math.min(entry.quantity, left);
88 if (amount > 0)
89 {
90 taken.push({ origin: entry.origin ?? null, quantity: amount });
91 left -= amount;
92 }
93 const rest = entry.quantity - amount;
94 if (rest > 0)
95 { remain.push({ origin: entry.origin ?? null, quantity: rest }); }
96 }
97 return { taken, remain };
98}
99
100export function attachOrigins (stack)
101{
102 const origins = normalizeOrigins(stack);
103 const next = { ...stack, origins };
104 delete next.origin;
105 return next;
106}
107
108export function formatOriginBreakdown (stack)
109{
110 const origins = normalizeOrigins(stack);
111 if (!origins.length)
112 { return ""; }
113 return origins
114 .map((entry) => `${entry.quantity} ${originLabel(entry.origin)}`)
115 .join(", ");
116}
shared/items/stackRules.js added +45 −0
@@ -0,0 +1,45 @@
1 import { ItemId, COIN_MAX_STACK, DEFAULT_MAX_STACK } from "../definitions/items.js";
2
3 /** Effective stack behaviour for inventory vs bank vault. */
4 export function stackRulesFor (definition, { inVault = false } = {})
5 {
6 if (!definition)
7 { return { stackable: false, maxStackSize: 1, uniqueInstance: true }; }
8 if (definition.itemId === ItemId.coins)
9 {
10 return {
11 stackable: true,
12 maxStackSize: COIN_MAX_STACK,
13 uniqueInstance: false
14 };
15 }
16 if (definition.uniqueInstance)
17 {
18 return { stackable: false, maxStackSize: 1, uniqueInstance: true };
19 }
20 if (definition.equipment && !inVault)
21 {
22 return { stackable: false, maxStackSize: 1, uniqueInstance: false };
23 }
24 if (definition.equipment && inVault)
25 {
26 return {
27 stackable: true,
28 maxStackSize: Number.POSITIVE_INFINITY,
29 uniqueInstance: false
30 };
31 }
32 if (inVault)
33 {
34 return {
35 stackable: definition.stackable !== false,
36 maxStackSize: Number.POSITIVE_INFINITY,
37 uniqueInstance: false
38 };
39 }
40 return {
41 stackable: definition.stackable !== false,
42 maxStackSize: definition.maxStackSize ?? DEFAULT_MAX_STACK,
43 uniqueInstance: false
44 };
45 }
@@ -0,0 +1,45 @@
1import { ItemId, COIN_MAX_STACK, DEFAULT_MAX_STACK } from "../definitions/items.js";
2
3/** Effective stack behaviour for inventory vs bank vault. */
4export function stackRulesFor (definition, { inVault = false } = {})
5{
6 if (!definition)
7 { return { stackable: false, maxStackSize: 1, uniqueInstance: true }; }
8 if (definition.itemId === ItemId.coins)
9 {
10 return {
11 stackable: true,
12 maxStackSize: COIN_MAX_STACK,
13 uniqueInstance: false
14 };
15 }
16 if (definition.uniqueInstance)
17 {
18 return { stackable: false, maxStackSize: 1, uniqueInstance: true };
19 }
20 if (definition.equipment && !inVault)
21 {
22 return { stackable: false, maxStackSize: 1, uniqueInstance: false };
23 }
24 if (definition.equipment && inVault)
25 {
26 return {
27 stackable: true,
28 maxStackSize: Number.POSITIVE_INFINITY,
29 uniqueInstance: false
30 };
31 }
32 if (inVault)
33 {
34 return {
35 stackable: definition.stackable !== false,
36 maxStackSize: Number.POSITIVE_INFINITY,
37 uniqueInstance: false
38 };
39 }
40 return {
41 stackable: definition.stackable !== false,
42 maxStackSize: definition.maxStackSize ?? DEFAULT_MAX_STACK,
43 uniqueInstance: false
44 };
45}
shared/protocol/constants.js +11 −1
@@ -103,6 +103,10 @@ export const MessageType = Object.freeze({
103 103 bankSnapshot: "BANK_SNAPSHOT",
104 104 bankDeposit: "BANK_DEPOSIT",
105 105 bankWithdraw: "BANK_WITHDRAW",
106 getBlankCheques: "GET_BLANK_CHEQUES",
107 returnBlankCheques: "RETURN_BLANK_CHEQUES",
108 writeCheque: "WRITE_CHEQUE",
109 redeemCheque: "REDEEM_CHEQUE",
106 110 claimInheritance: "CLAIM_INHERITANCE",
107 111 attack: "ATTACK",
108 112 cancelAttack: "CANCEL_ATTACK",
@@ -110,6 +114,7 @@ export const MessageType = Object.freeze({
110 114 combatSwing: "COMBAT_SWING",
111 115 combatHit: "COMBAT_HIT",
112 116 combatMiss: "COMBAT_MISS",
117 combatBlock: "COMBAT_BLOCK",
113 118 follow: "FOLLOW",
114 119 cancelFollow: "CANCEL_FOLLOW",
115 120 sendPigeon: "SEND_PIGEON",
@@ -119,6 +124,11 @@ export const MessageType = Object.freeze({
119 124 characterSearchResult: "CHARACTER_SEARCH_RESULT",
120 125 writeLetter: "WRITE_LETTER",
121 126 editLetter: "EDIT_LETTER",
122 openLetter: "OPEN_LETTER"
127 openLetter: "OPEN_LETTER",
128 skills: "SKILLS",
129 eatItem: "EAT_ITEM",
130 startCraft: "START_CRAFT",
131 cancelCraft: "CANCEL_CRAFT",
132 craftResult: "CRAFT_RESULT"
123 133 });
124 134
@@ -103,6 +103,10 @@ export const MessageType = Object.freeze({
103 bankSnapshot: "BANK_SNAPSHOT",
103 bankSnapshot: "BANK_SNAPSHOT",
104 bankDeposit: "BANK_DEPOSIT",
104 bankDeposit: "BANK_DEPOSIT",
105 bankWithdraw: "BANK_WITHDRAW",
105 bankWithdraw: "BANK_WITHDRAW",
106 getBlankCheques: "GET_BLANK_CHEQUES",
107 returnBlankCheques: "RETURN_BLANK_CHEQUES",
108 writeCheque: "WRITE_CHEQUE",
109 redeemCheque: "REDEEM_CHEQUE",
106 claimInheritance: "CLAIM_INHERITANCE",
110 claimInheritance: "CLAIM_INHERITANCE",
107 attack: "ATTACK",
111 attack: "ATTACK",
108 cancelAttack: "CANCEL_ATTACK",
112 cancelAttack: "CANCEL_ATTACK",
@@ -110,6 +114,7 @@ export const MessageType = Object.freeze({
110 combatSwing: "COMBAT_SWING",
114 combatSwing: "COMBAT_SWING",
111 combatHit: "COMBAT_HIT",
115 combatHit: "COMBAT_HIT",
112 combatMiss: "COMBAT_MISS",
116 combatMiss: "COMBAT_MISS",
117 combatBlock: "COMBAT_BLOCK",
113 follow: "FOLLOW",
118 follow: "FOLLOW",
114 cancelFollow: "CANCEL_FOLLOW",
119 cancelFollow: "CANCEL_FOLLOW",
115 sendPigeon: "SEND_PIGEON",
120 sendPigeon: "SEND_PIGEON",
@@ -119,6 +124,11 @@ export const MessageType = Object.freeze({
119 characterSearchResult: "CHARACTER_SEARCH_RESULT",
124 characterSearchResult: "CHARACTER_SEARCH_RESULT",
120 writeLetter: "WRITE_LETTER",
125 writeLetter: "WRITE_LETTER",
121 editLetter: "EDIT_LETTER",
126 editLetter: "EDIT_LETTER",
122 openLetter: "OPEN_LETTER"
127 openLetter: "OPEN_LETTER",
128 skills: "SKILLS",
129 eatItem: "EAT_ITEM",
130 startCraft: "START_CRAFT",
131 cancelCraft: "CANCEL_CRAFT",
132 craftResult: "CRAFT_RESULT"
123});
133});
124
134
shared/skills/progression.js added +68 −0
@@ -0,0 +1,68 @@
1 export const MAX_SKILL_LEVEL = 99;
2
3 /** XP needed to advance from level L to L+1 (doubles each level). */
4 export const SKILL_XP_BASE = 50;
5 export const SKILL_XP_GROWTH = 2;
6
7 export function xpToAdvanceFromLevel (level)
8 {
9 const lv = Math.max(1, Math.floor(Number(level) || 1));
10 if (lv >= MAX_SKILL_LEVEL)
11 { return 0; }
12 return Math.max(1, Math.floor(SKILL_XP_BASE * (SKILL_XP_GROWTH ** (lv - 1))));
13 }
14
15 /** Total XP required to reach the given level (level 1 = 0 XP). */
16 export function totalXpForLevel (level)
17 {
18 const target = Math.max(1, Math.floor(Number(level) || 1));
19 let total = 0;
20 for (let lv = 1; lv < target; lv++)
21 { total += xpToAdvanceFromLevel(lv); }
22 return total;
23 }
24
25 /** Total XP while still at max level (extra XP is discarded). */
26 export function maxTotalSkillXp ()
27 {
28 return totalXpForLevel(MAX_SKILL_LEVEL + 1) - 1;
29 }
30
31 /** Derive level and in-level progress from lifetime XP. */
32 export function xpProgress (totalXp)
33 {
34 let xp = Math.max(0, Math.floor(Number(totalXp) || 0));
35 let level = 1;
36 while (level < MAX_SKILL_LEVEL)
37 {
38 const need = xpToAdvanceFromLevel(level);
39 if (xp < need)
40 {
41 return {
42 level,
43 xpInLevel: xp,
44 xpToNext: need
45 };
46 }
47 xp -= need;
48 level += 1;
49 }
50 return {
51 level: MAX_SKILL_LEVEL,
52 xpInLevel: 0,
53 xpToNext: 0
54 };
55 }
56
57 export function levelFromTotalXp (totalXp)
58 {
59 return xpProgress(totalXp).level;
60 }
61
62 /** Split combat hit XP equally between hit and damage skills. */
63 export const COMBAT_HIT_XP_TOTAL = 10;
64
65 export function combatHitXpPerSkill ()
66 {
67 return COMBAT_HIT_XP_TOTAL / 2;
68 }
@@ -0,0 +1,68 @@
1export const MAX_SKILL_LEVEL = 99;
2
3/** XP needed to advance from level L to L+1 (doubles each level). */
4export const SKILL_XP_BASE = 50;
5export const SKILL_XP_GROWTH = 2;
6
7export function xpToAdvanceFromLevel (level)
8{
9 const lv = Math.max(1, Math.floor(Number(level) || 1));
10 if (lv >= MAX_SKILL_LEVEL)
11 { return 0; }
12 return Math.max(1, Math.floor(SKILL_XP_BASE * (SKILL_XP_GROWTH ** (lv - 1))));
13}
14
15/** Total XP required to reach the given level (level 1 = 0 XP). */
16export function totalXpForLevel (level)
17{
18 const target = Math.max(1, Math.floor(Number(level) || 1));
19 let total = 0;
20 for (let lv = 1; lv < target; lv++)
21 { total += xpToAdvanceFromLevel(lv); }
22 return total;
23}
24
25/** Total XP while still at max level (extra XP is discarded). */
26export function maxTotalSkillXp ()
27{
28 return totalXpForLevel(MAX_SKILL_LEVEL + 1) - 1;
29}
30
31/** Derive level and in-level progress from lifetime XP. */
32export function xpProgress (totalXp)
33{
34 let xp = Math.max(0, Math.floor(Number(totalXp) || 0));
35 let level = 1;
36 while (level < MAX_SKILL_LEVEL)
37 {
38 const need = xpToAdvanceFromLevel(level);
39 if (xp < need)
40 {
41 return {
42 level,
43 xpInLevel: xp,
44 xpToNext: need
45 };
46 }
47 xp -= need;
48 level += 1;
49 }
50 return {
51 level: MAX_SKILL_LEVEL,
52 xpInLevel: 0,
53 xpToNext: 0
54 };
55}
56
57export function levelFromTotalXp (totalXp)
58{
59 return xpProgress(totalXp).level;
60}
61
62/** Split combat hit XP equally between hit and damage skills. */
63export const COMBAT_HIT_XP_TOTAL = 10;
64
65export function combatHitXpPerSkill ()
66{
67 return COMBAT_HIT_XP_TOTAL / 2;
68}
shared/skills/state.js added +75 −0
@@ -0,0 +1,75 @@
1 import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS } from "../definitions/skills.js";
2 import { maxTotalSkillXp, totalXpForLevel, xpProgress, MAX_SKILL_LEVEL } from "./progression.js";
3
4 export function emptySkillXp ()
5 {
6 const xp = {};
7 for (const skillId of ALL_SKILL_IDS)
8 { xp[skillId] = 0; }
9 return xp;
10 }
11
12 export function normalizeSkillXp (raw)
13 {
14 const xp = emptySkillXp();
15 if (!raw || typeof raw !== "object")
16 { return xp; }
17 for (const skillId of ALL_SKILL_IDS)
18 {
19 const value = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
20 xp[skillId] = Number.isSafeInteger(value) ? value : 0;
21 }
22 return xp;
23 }
24
25 export function normalizePlayerSkills (stored)
26 {
27 return { xp: normalizeSkillXp(stored?.xp ?? stored) };
28 }
29
30 /** Starting skills for a new character (Health level 10, others level 1). */
31 export function defaultPlayerSkills ()
32 {
33 return normalizePlayerSkills({
34 [SkillId.health]: totalXpForLevel(10)
35 });
36 }
37
38 export function addSkillXp (skillsComponent, skillId, amount)
39 {
40 if (!skillsComponent?.xp)
41 { return false; }
42 const add = Math.max(0, Math.floor(Number(amount) || 0));
43 if (!add)
44 { return false; }
45 const current = skillsComponent.xp[skillId] ?? 0;
46 if (xpProgress(current).level >= MAX_SKILL_LEVEL)
47 { return false; }
48 skillsComponent.xp[skillId] = Math.min(maxTotalSkillXp(), current + add);
49 return skillsComponent.xp[skillId] !== current;
50 }
51
52 export function publicSkillsView (skillsComponent)
53 {
54 const xpMap = skillsComponent?.xp ?? null;
55 if (!xpMap)
56 { return []; }
57 return ALL_SKILL_IDS.map((skillId) =>
58 {
59 const def = SKILL_DEFINITIONS[skillId];
60 const progress = xpProgress(xpMap[skillId] ?? 0);
61 return {
62 skillId,
63 displayName: def?.displayName ?? skillId,
64 icon: `/assets/skills/${skillId}.svg`,
65 level: progress.level,
66 xp: progress.xpInLevel,
67 xpToNext: progress.xpToNext
68 };
69 });
70 }
71
72 export function storedSkillXp (skillsComponent)
73 {
74 return normalizeSkillXp(skillsComponent?.xp);
75 }
@@ -0,0 +1,75 @@
1import { SkillId, SKILL_DEFINITIONS, ALL_SKILL_IDS } from "../definitions/skills.js";
2import { maxTotalSkillXp, totalXpForLevel, xpProgress, MAX_SKILL_LEVEL } from "./progression.js";
3
4export function emptySkillXp ()
5{
6 const xp = {};
7 for (const skillId of ALL_SKILL_IDS)
8 { xp[skillId] = 0; }
9 return xp;
10}
11
12export function normalizeSkillXp (raw)
13{
14 const xp = emptySkillXp();
15 if (!raw || typeof raw !== "object")
16 { return xp; }
17 for (const skillId of ALL_SKILL_IDS)
18 {
19 const value = Math.max(0, Math.floor(Number(raw[skillId]) || 0));
20 xp[skillId] = Number.isSafeInteger(value) ? value : 0;
21 }
22 return xp;
23}
24
25export function normalizePlayerSkills (stored)
26{
27 return { xp: normalizeSkillXp(stored?.xp ?? stored) };
28}
29
30/** Starting skills for a new character (Health level 10, others level 1). */
31export function defaultPlayerSkills ()
32{
33 return normalizePlayerSkills({
34 [SkillId.health]: totalXpForLevel(10)
35 });
36}
37
38export function addSkillXp (skillsComponent, skillId, amount)
39{
40 if (!skillsComponent?.xp)
41 { return false; }
42 const add = Math.max(0, Math.floor(Number(amount) || 0));
43 if (!add)
44 { return false; }
45 const current = skillsComponent.xp[skillId] ?? 0;
46 if (xpProgress(current).level >= MAX_SKILL_LEVEL)
47 { return false; }
48 skillsComponent.xp[skillId] = Math.min(maxTotalSkillXp(), current + add);
49 return skillsComponent.xp[skillId] !== current;
50}
51
52export function publicSkillsView (skillsComponent)
53{
54 const xpMap = skillsComponent?.xp ?? null;
55 if (!xpMap)
56 { return []; }
57 return ALL_SKILL_IDS.map((skillId) =>
58 {
59 const def = SKILL_DEFINITIONS[skillId];
60 const progress = xpProgress(xpMap[skillId] ?? 0);
61 return {
62 skillId,
63 displayName: def?.displayName ?? skillId,
64 icon: `/assets/skills/${skillId}.svg`,
65 level: progress.level,
66 xp: progress.xpInLevel,
67 xpToNext: progress.xpToNext
68 };
69 });
70}
71
72export function storedSkillXp (skillsComponent)
73{
74 return normalizeSkillXp(skillsComponent?.xp);
75}