-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.js
More file actions
1395 lines (1261 loc) · 50.2 KB
/
engine.js
File metadata and controls
1395 lines (1261 loc) · 50.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
// CodeDungeon - 码渊 Game Engine
// Usage:
// node engine.js tick (called by PostToolUse hook, reads stdin JSON)
// node engine.js action <cmd> (called by player via !g)
const fs = require('fs');
const path = require('path');
const os = require('os');
const GAME_DIR = __dirname;
const STATE_FILE = path.join(GAME_DIR, 'state.json');
const LEGACY_FILE = path.join(GAME_DIR, 'legacy.json');
const SETTINGS_FILE = path.join(os.homedir(), '.claude', 'settings.json');
const ORIGINAL_SL_FILE = path.join(GAME_DIR, 'original-statusline.json');
const ORIGINAL_SPINNER_FILE = path.join(GAME_DIR, 'original-spinner.json');
const SPINNER_FILE = path.join(GAME_DIR, 'data', 'spinner.json');
// ==================== StatusLine & Spinner Switch ====================
function toBashPath(p) { return p.replace(/\\/g, '/').replace(/^([A-Za-z]):/, (_, l) => '/' + l.toLowerCase()); }
function setStatusLine(useGame) {
try {
const settings = JSON.parse(fs.readFileSync(SETTINGS_FILE, 'utf8'));
if (useGame) {
settings.statusLine = { type: 'command', command: `node "${toBashPath(GAME_DIR)}/hud.js"` };
// Restore dungeon spinner
try {
const spinnerData = JSON.parse(fs.readFileSync(SPINNER_FILE, 'utf8'));
settings.spinnerVerbs = { mode: 'replace', verbs: spinnerData.explore };
} catch {}
} else {
// Restore original statusLine
try {
settings.statusLine = JSON.parse(fs.readFileSync(ORIGINAL_SL_FILE, 'utf8'));
} catch {
delete settings.statusLine;
}
// Restore original spinner
try {
settings.spinnerVerbs = JSON.parse(fs.readFileSync(ORIGINAL_SPINNER_FILE, 'utf8'));
} catch {
delete settings.spinnerVerbs;
}
}
fs.writeFileSync(SETTINGS_FILE, JSON.stringify(settings, null, 2));
} catch {}
}
// ==================== Data ====================
const MONSTERS = JSON.parse(fs.readFileSync(path.join(GAME_DIR, 'data', 'monsters.json'), 'utf8'));
const ITEMS = JSON.parse(fs.readFileSync(path.join(GAME_DIR, 'data', 'items.json'), 'utf8'));
const SKILLS = JSON.parse(fs.readFileSync(path.join(GAME_DIR, 'data', 'skills.json'), 'utf8'));
const FLOORS = JSON.parse(fs.readFileSync(path.join(GAME_DIR, 'data', 'floors.json'), 'utf8'));
const EVENTS = JSON.parse(fs.readFileSync(path.join(GAME_DIR, 'data', 'events.json'), 'utf8'));
// ==================== Helpers ====================
function rand(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
function pick(arr) { return arr[rand(0, arr.length - 1)]; }
function clamp(val, min, max) { return Math.max(min, Math.min(max, val)); }
function print(msg) { process.stdout.write(msg + '\n'); }
// ==================== State ====================
const CLASS_STATS = {
warrior: { name: '战士', emoji: '⚔️', hp: 120, mp: 20, atk: 10, def: 5, spd: 5 },
mage: { name: '法师', emoji: '🔮', hp: 80, mp: 50, atk: 6, def: 3, spd: 5 },
rogue: { name: '盗贼', emoji: '🗡️', hp: 90, mp: 25, atk: 8, def: 3, spd: 8 },
paladin: { name: '圣骑士', emoji: '🛡️', hp: 110, mp: 30, atk: 7, def: 7, spd: 4 }
};
function loadLegacy() {
try { return JSON.parse(fs.readFileSync(LEGACY_FILE, 'utf8')); }
catch { return { points: 0, spent: 0, upgrades: { hpBonus: 0, atkBonus: 0, trapReduce: false, bagExtra: 0, restBonus: false }, unlockedClasses: ['warrior'], achievements: [], bestFloor: 0, bestKills: 0, totalRuns: 0 }; }
}
function saveLegacy(leg) { fs.writeFileSync(LEGACY_FILE, JSON.stringify(leg, null, 2)); }
function loadState() {
try { return JSON.parse(fs.readFileSync(STATE_FILE, 'utf8')); }
catch { return null; }
}
function saveState(state) { fs.writeFileSync(STATE_FILE, JSON.stringify(state, null, 2)); }
function initState(className = 'warrior') {
const leg = loadLegacy();
const base = CLASS_STATS[className] || CLASS_STATS.warrior;
const hpBonus = (leg.upgrades.hpBonus || 0) * 10;
const atkBonus = (leg.upgrades.atkBonus || 0) * 2;
const bagSize = 6 + (leg.upgrades.bagExtra || 0);
const state = {
enabled: true,
alive: true,
character: {
class: className,
className: base.name,
classEmoji: base.emoji,
level: 1,
xp: 0,
xpToNext: 30,
hp: base.hp + hpBonus,
maxHp: base.hp + hpBonus,
mp: base.mp,
maxMp: base.mp,
atk: base.atk + atkBonus,
def: base.def,
spd: base.spd,
gold: 0,
karma: 0
},
dungeon: {
floor: 1,
roomIndex: 0,
rooms: [],
floorName: '',
revealed: false
},
combat: null, // { monster, turn, summons[] }
event: null, // { id, stepsLeft }
pendingLevelUp: false,
inventory: [], // [{ id, name, qty }]
bagSize: bagSize,
equipment: { weapon: null, armor: null, accessory: null },
buffs: [], // [{ stat, value, turnsLeft }]
shield: 0, // blocks remaining
stats: { kills: 0, totalGold: 0, roomsExplored: 0 },
roomsSinceRegen: 0, // for regen_ring
lastTick: Date.now()
};
generateFloor(state);
return state;
}
// ==================== Floor & Room Generation ====================
function getFloorTheme(floorNum) {
for (const f of FLOORS) {
if (floorNum >= f.floors[0] && floorNum <= f.floors[1]) return f;
}
return FLOORS[FLOORS.length - 1];
}
function generateFloor(state) {
const floorNum = state.dungeon.floor;
const theme = getFloorTheme(floorNum);
const totalRooms = rand(10, 15);
const rooms = [];
for (let i = 0; i < totalRooms; i++) {
if (i === totalRooms - 1 && floorNum % 5 === 0) {
rooms.push({ type: 'boss', explored: false });
} else if (i === 0) {
rooms.push({ type: 'entrance', explored: true });
} else {
rooms.push({ type: rollRoomType(floorNum), explored: false });
}
}
state.dungeon.rooms = rooms;
state.dungeon.roomIndex = 0;
state.dungeon.floorName = theme.name;
state.dungeon.revealed = false;
state.dungeon.totalRooms = totalRooms;
}
function rollRoomType(floorNum) {
const r = Math.random();
if (r < 0.35) return 'empty';
if (r < 0.60) return 'monster';
if (r < 0.70) return 'chest';
if (r < 0.78) return 'trap';
if (r < 0.85) return 'shop';
if (r < 0.90) return 'rest';
return 'event';
}
// ==================== Monster Selection ====================
function pickMonster(floorNum) {
const eligible = MONSTERS.normal.filter(m => floorNum >= m.floors[0] && floorNum <= m.floors[1]);
if (eligible.length === 0) {
// For deep floors, pick strongest available
const sorted = [...MONSTERS.normal].sort((a, b) => b.floors[1] - a.floors[1]);
return cloneMonster(sorted[0], floorNum);
}
return cloneMonster(pick(eligible), floorNum);
}
function pickBoss(floorNum) {
const boss = MONSTERS.bosses.find(b => b.floor === floorNum);
if (!boss) return pickMonster(floorNum); // fallback
return { ...JSON.parse(JSON.stringify(boss)), currentHp: boss.hp, maxHp: boss.hp, isBoss: true };
}
function cloneMonster(template, floorNum) {
// Scale up for deep floors
const scale = floorNum > 20 ? 1 + (floorNum - 20) * 0.1 : 1;
return {
...JSON.parse(JSON.stringify(template)),
currentHp: Math.floor(template.hp * scale),
maxHp: Math.floor(template.hp * scale),
atk: Math.floor(template.atk * scale),
def: Math.floor(template.def * scale),
isBoss: false
};
}
// ==================== Shop Generation ====================
function generateShop(floorNum) {
const items = [];
const count = rand(3, 5);
const pool = [];
// Add consumables
for (const c of ITEMS.consumables) {
if (c.id !== 'revive_coin' || floorNum >= 5) pool.push({ ...c, slot: 'consumable' });
}
// Add equipment for this floor range
for (const w of ITEMS.weapons) {
if (floorNum >= w.floors[0] && floorNum <= w.floors[1]) pool.push({ ...w, slot: 'weapon' });
}
for (const a of ITEMS.armors) {
if (floorNum >= a.floors[0] && floorNum <= a.floors[1]) pool.push({ ...a, slot: 'armor' });
}
for (const ac of ITEMS.accessories) {
if (floorNum >= ac.floors[0] && floorNum <= ac.floors[1]) pool.push({ ...ac, slot: 'accessory' });
}
// Pick random items from pool
const shuffled = pool.sort(() => Math.random() - 0.5);
for (let i = 0; i < Math.min(count, shuffled.length); i++) {
items.push(shuffled[i]);
}
return items;
}
// ==================== Combat ====================
function calcDamage(attackerAtk, defenderDef) {
const raw = attackerAtk - defenderDef * 0.5;
return Math.max(1, Math.floor(raw));
}
function getEffectiveAtk(state) {
let atk = state.character.atk;
if (state.equipment.weapon) atk += state.equipment.weapon.stats.atk || 0;
for (const b of state.buffs) {
if (b.stat === 'atk' && b.multiplier) atk = Math.floor(atk * b.multiplier);
if (b.stat === 'atk' && b.value) atk += b.value;
}
return atk;
}
function getEffectiveDef(state) {
let def = state.character.def;
if (state.equipment.armor) def += state.equipment.armor.stats.def || 0;
if (state.equipment.accessory && state.equipment.accessory.stats.def) def += state.equipment.accessory.stats.def;
for (const b of state.buffs) {
if (b.stat === 'def' && b.value !== undefined) def = b.value; // override (e.g., def=0 debuff)
}
return Math.max(0, def);
}
function playerAttack(state, multiplier = 1.0, hits = 1) {
const mon = state.combat.monster;
const atk = getEffectiveAtk(state);
let totalDmg = 0;
const msgs = [];
for (let i = 0; i < hits; i++) {
// Check phys_miss special
if (mon.special && mon.special.type === 'phys_miss' && multiplier === 1.0) {
if (Math.random() < mon.special.chance) {
msgs.push('攻击被幽灵闪避了!');
continue;
}
}
let dmg = calcDamage(Math.floor(atk * multiplier), mon.def);
// Bug bonus
if (state.equipment.weapon && state.equipment.weapon.stats.bugBonus && mon.id === 'wild_bug') {
dmg = Math.floor(dmg * state.equipment.weapon.stats.bugBonus);
}
totalDmg += dmg;
mon.currentHp -= dmg;
msgs.push(`你造成了${dmg}点伤害!`);
}
mon.currentHp = Math.max(0, mon.currentHp);
return msgs;
}
function monsterAttack(state) {
const mon = state.combat.monster;
const msgs = [];
// Monster specials (pre-attack)
if (mon.special) {
switch (mon.special.type) {
case 'regen':
mon.currentHp = Math.min(mon.maxHp, mon.currentHp + mon.special.value);
msgs.push(`${mon.name}回复了${mon.special.value}HP!`);
break;
case 'grow_hp':
mon.maxHp += mon.special.value;
mon.currentHp += mon.special.value;
msgs.push(`${mon.name}膨胀了!MaxHP+${mon.special.value}!`);
break;
case 'split':
if (!state.combat.summons) state.combat.summons = [];
if (Math.random() < mon.special.chance && state.combat.summons.length < 2) {
state.combat.summons.push({ name: '分裂体', hp: Math.floor(mon.currentHp * 0.5), atk: mon.atk });
msgs.push(`${mon.name}分裂出一个分身!`);
}
break;
case 'berserk': {
const hpRatio = mon.currentHp / mon.maxHp;
const berserkMultiplier = 1 + (1 - hpRatio);
mon._effectiveAtk = Math.floor(mon.atk * berserkMultiplier);
break;
}
}
}
// Check if monster is dead before its attack
if (mon.currentHp <= 0) return msgs;
const monAtk = mon._effectiveAtk || mon.atk;
const attackCount = (mon.special && mon.special.type === 'twin') ? mon.special.attacks : 1;
for (let i = 0; i < attackCount; i++) {
if (state.shield > 0) {
state.shield--;
msgs.push('护盾挡下了攻击!');
continue;
}
// Crit check
let dmgMultiplier = 1;
if (mon.special && mon.special.type === 'crit' && Math.random() < mon.special.chance) {
dmgMultiplier = mon.special.multiplier;
msgs.push('暴击!');
}
const dmg = Math.max(1, Math.floor(monAtk * dmgMultiplier) - Math.floor(getEffectiveDef(state) * 0.5));
state.character.hp -= dmg;
msgs.push(`${mon.name}攻击!你受到${dmg}点伤害!`);
}
// Summons attack too
if (state.combat.summons) {
for (const s of state.combat.summons) {
if (s.hp > 0) {
const sDmg = Math.max(1, s.atk - Math.floor(getEffectiveDef(state) * 0.5));
state.character.hp -= sDmg;
msgs.push(`${s.name}攻击!你受到${sDmg}点伤害!`);
}
}
}
state.character.hp = Math.max(0, state.character.hp);
delete mon._effectiveAtk;
return msgs;
}
function endCombat(state, victory) {
const mon = state.combat.monster;
const msgs = [];
if (victory) {
const goldDrop = rand(mon.goldDrop[0], mon.goldDrop[1]);
// Gold bonus from accessory
let gold = goldDrop;
if (state.equipment.accessory && state.equipment.accessory.stats.goldBonus) {
gold = Math.floor(gold * (1 + state.equipment.accessory.stats.goldBonus));
}
state.character.gold += gold;
state.stats.totalGold += gold;
state.stats.kills++;
msgs.push(`击败了${mon.name}!+${mon.xp}XP +${gold}🪙`);
// Boss drops
if (mon.isBoss && mon.drop) {
const drop = mon.drop;
if (drop.type === 'weapon' || drop.type === 'armor' || drop.type === 'accessory') {
const equipItem = { id: drop.id, name: drop.name, type: drop.type, stats: drop.stats, desc: drop.description };
state.equipment[drop.type] = equipItem;
msgs.push(`获得Boss掉落:【${drop.name}】${drop.description}!已自动装备。`);
}
}
addXP(state, mon.xp, msgs);
}
state.combat = null;
return msgs;
}
// ==================== XP & Level ====================
function addXP(state, amount, msgs) {
state.character.xp += amount;
while (state.character.xp >= state.character.xpToNext) {
state.character.xp -= state.character.xpToNext;
state.character.level++;
state.character.xpToNext = state.character.level * 20 + 10;
state.character.hp = Math.min(state.character.hp + 10, state.character.maxHp);
state.character.mp = Math.min(state.character.mp + 5, state.character.maxMp);
state.pendingLevelUp = true;
msgs.push(`🎉 升级!Lv.${state.character.level}!输入 !g grow atk/def/mag 选择成长方向`);
}
}
// ==================== Inventory ====================
function addToInventory(state, itemId, qty = 1) {
const itemData = ITEMS.consumables.find(c => c.id === itemId);
if (!itemData) return false;
const existing = state.inventory.find(i => i.id === itemId);
if (existing && itemData.stackable) {
existing.qty += qty;
return true;
}
if (state.inventory.length >= state.bagSize) return false;
state.inventory.push({ id: itemId, name: itemData.name, qty, desc: itemData.desc });
return true;
}
function removeFromInventory(state, itemId, qty = 1) {
const idx = state.inventory.findIndex(i => i.id === itemId);
if (idx === -1) return false;
state.inventory[idx].qty -= qty;
if (state.inventory[idx].qty <= 0) state.inventory.splice(idx, 1);
return true;
}
// ==================== Buff Management ====================
function tickBuffs(state) {
state.buffs = state.buffs.filter(b => {
b.turnsLeft--;
return b.turnsLeft > 0;
});
}
// ==================== Room Enter Logic ====================
function enterRoom(state) {
const room = state.dungeon.rooms[state.dungeon.roomIndex];
if (!room) return [];
room.explored = true;
state.stats.roomsExplored++;
const msgs = [];
const floor = state.dungeon.floor;
const theme = getFloorTheme(floor);
// Env effect (cold damage in ice corridor)
if (theme.envEffect && theme.envEffect.type === 'cold_damage') {
if (state.stats.roomsExplored % theme.envEffect.interval === 0) {
state.character.hp -= theme.envEffect.damage;
msgs.push(`寒气侵蚀!-${theme.envEffect.damage}HP`);
}
}
// Regen ring check
if (state.equipment.accessory && state.equipment.accessory.stats.regenPerRooms) {
state.roomsSinceRegen++;
if (state.roomsSinceRegen >= state.equipment.accessory.stats.regenPerRooms) {
state.roomsSinceRegen = 0;
const heal = state.equipment.accessory.stats.regenValue;
state.character.hp = Math.min(state.character.maxHp, state.character.hp + heal);
msgs.push(`回血戒指生效!+${heal}HP`);
}
}
// Paladin passive: heal every 10 rooms
if (state.character.class === 'paladin' && state.stats.roomsExplored % 10 === 0) {
state.character.hp = Math.min(state.character.maxHp, state.character.hp + 10);
msgs.push('圣骑士被动:+10HP');
}
// Mage passive: MP regen on edit
if (state.character.class === 'mage') {
state.character.mp = Math.min(state.character.maxMp, state.character.mp + 3);
}
switch (room.type) {
case 'entrance':
msgs.push('你站在入口处,前方一片幽暗...');
break;
case 'empty': {
const ambience = theme.ambience ? pick(theme.ambience) : '空旷的走廊';
msgs.push(ambience);
break;
}
case 'monster': {
const mon = pickMonster(floor);
state.combat = { monster: mon, turn: 1, summons: [] };
msgs.push(`⚔️ 遭遇${mon.name}!(♥${mon.currentHp} ⚔️${mon.atk} 🛡${mon.def})`);
if (mon.special) msgs.push(`特殊:${mon.special.desc}`);
msgs.push('→ fight / flee / spell <名> / item <名>');
break;
}
case 'boss': {
const boss = pickBoss(floor);
state.combat = { monster: boss, turn: 1, summons: [] };
msgs.push(`👹 BOSS出现!${boss.name}!(♥${boss.currentHp} ⚔️${boss.atk} 🛡${boss.def})`);
if (boss.special) msgs.push(`特殊:${boss.special.desc}`);
msgs.push('→ fight / flee / spell <名> / item <名>');
break;
}
case 'chest': {
// 20% chance mimic
if (Math.random() < 0.2) {
const mon = pickMonster(floor);
mon.name = '宝箱怪(' + mon.name + ')';
state.combat = { monster: mon, turn: 1, summons: [] };
msgs.push(`🎁 你打开宝箱...是宝箱怪!`);
msgs.push('→ fight / flee');
} else {
room.chest = generateChestLoot(floor);
msgs.push(`🎁 发现宝箱!→ open / ignore`);
}
break;
}
case 'trap': {
const legacy = loadLegacy();
if (legacy.upgrades.trapReduce && Math.random() < 0.5) {
msgs.push('你的直觉帮你避开了陷阱!');
} else if (state.character.class === 'rogue') {
msgs.push('盗贼的敏锐让你轻松绕过了陷阱。');
} else {
const dmg = rand(5, 10 + floor * 2);
state.character.hp -= dmg;
state.character.hp = Math.max(0, state.character.hp);
msgs.push(`⚠️ 踩到陷阱!-${dmg}HP`);
}
break;
}
case 'shop': {
room.shopItems = generateShop(floor);
const legacy = loadLegacy();
const karmaMod = state.character.karma >= 5 ? 0.9 : state.character.karma <= -5 ? 1.2 : 1.0;
msgs.push('🏪 商店!可购买:');
room.shopItems.forEach((item, i) => {
const price = Math.floor(item.price * karmaMod);
item._price = price;
msgs.push(` ${i + 1}. ${item.name}(${item.desc}) ${price}🪙`);
});
msgs.push('→ buy <编号> / leave');
break;
}
case 'rest': {
const legacy = loadLegacy();
const restPercent = legacy.upgrades.restBonus ? 0.5 : 0.3;
const heal = Math.floor(state.character.maxHp * restPercent);
state.character.hp = Math.min(state.character.maxHp, state.character.hp + heal);
state.character.mp = Math.min(state.character.maxMp, state.character.mp + Math.floor(state.character.maxMp * 0.3));
msgs.push(`🔥 篝火休息!回复${heal}HP,MP也恢复了一些。`);
break;
}
case 'event': {
const evt = pick(EVENTS);
state.event = { id: evt.id, stepsLeft: 5 };
room.eventData = evt;
msgs.push(`❓ ${evt.name}`);
msgs.push(`"${evt.desc}"`);
const choiceLabels = evt.choices.map(c => c.cmd).join(' / ');
msgs.push(`→ ${choiceLabels}`);
break;
}
}
return msgs;
}
function generateChestLoot(floorNum) {
const r = Math.random();
if (r < 0.5) {
return { type: 'gold', amount: rand(10, 20 + floorNum * 5) };
} else if (r < 0.8) {
const potions = ITEMS.consumables.filter(c => c.price <= 20);
const p = pick(potions);
return { type: 'item', id: p.id, name: p.name };
} else {
// Equipment
const allEquip = [...ITEMS.weapons, ...ITEMS.armors, ...ITEMS.accessories]
.filter(e => floorNum >= e.floors[0] && floorNum <= e.floors[1]);
if (allEquip.length > 0) {
const e = pick(allEquip);
return { type: 'equipment', item: e };
}
return { type: 'gold', amount: rand(15, 30 + floorNum * 3) };
}
}
// ==================== Death ====================
function handleDeath(state) {
state.alive = false;
const leg = loadLegacy();
const earned = state.dungeon.floor * 3 + state.stats.kills + Math.floor(state.stats.totalGold / 10);
leg.points += earned;
leg.totalRuns++;
if (state.dungeon.floor > leg.bestFloor) leg.bestFloor = state.dungeon.floor;
if (state.stats.kills > leg.bestKills) leg.bestKills = state.stats.kills;
// Achievement checks
if (!leg.achievements.includes('first_blood') && state.stats.kills >= 1) {
leg.achievements.push('first_blood');
}
if (!leg.achievements.includes('floor5') && state.dungeon.floor > 5) {
leg.achievements.push('floor5');
}
if (!leg.achievements.includes('floor20') && state.dungeon.floor > 20) {
leg.achievements.push('floor20');
}
saveLegacy(leg);
return [
`💀 你倒在了 B${state.dungeon.floor}·${state.dungeon.floorName}...`,
`击杀: ${state.stats.kills} | 最深: B${state.dungeon.floor} | 传承点+${earned}`,
`→ restart / legacy`
];
}
// ==================== Tick (Hook Entry) ====================
function tick(state, toolName, sessionId) {
if (!state || !state.enabled || !state.alive) return;
// Session lock: only the first session to touch state gets to advance
// Prevents double-advance when multiple Claude Code windows are open
if (sessionId) {
if (!state.sessionId) {
state.sessionId = sessionId;
} else if (state.sessionId !== sessionId) {
// Different session — skip tick, don't interfere
return;
}
}
// Scouting tools don't advance rooms
if (['Read', 'Grep', 'Glob'].includes(toolName)) return;
// If in combat, decrement event timeout but don't advance
if (state.combat) {
if (state.event && state.event.stepsLeft > 0) {
state.event.stepsLeft--;
if (state.event.stepsLeft <= 0) state.event = null;
}
return;
}
// If there's a pending event, decrement
if (state.event) {
state.event.stepsLeft--;
if (state.event.stepsLeft <= 0) {
state.event = null;
}
return;
}
// If pending level up, don't advance
if (state.pendingLevelUp) return;
// Advance to next room
state.dungeon.roomIndex++;
// Check if floor complete
if (state.dungeon.roomIndex >= state.dungeon.rooms.length) {
// Floor complete, offer descend
state.dungeon.roomIndex = state.dungeon.rooms.length - 1;
return; // wait for !g descend
}
// Enter new room
enterRoom(state);
// Check death
if (state.character.hp <= 0) {
// Check revive coin
const reviveIdx = state.inventory.findIndex(i => i.id === 'revive_coin');
if (reviveIdx !== -1) {
state.character.hp = Math.floor(state.character.maxHp * 0.3);
state.inventory.splice(reviveIdx, 1);
} else {
handleDeath(state);
}
}
state.lastTick = Date.now();
}
// ==================== Action (Player Entry) ====================
function action(state, cmd, args) {
if (!cmd) {
print('码渊 - !g <命令>');
print(' fight/flee/spell/item - 战斗');
print(' walk/buy/open/descend - 探索');
print(' status/bag/map - 查看');
print(' on/off/restart/legacy/session/grow - 系统');
return;
}
// System commands that work without state
if (cmd === 'on') {
if (!state) state = initState();
state.enabled = true;
saveState(state);
setStatusLine(true);
print('🏰 码渊已开启!开始你的冒险...');
return;
}
if (cmd === 'off') {
if (state) { state.enabled = false; saveState(state); }
setStatusLine(false);
print('码渊已关闭。StatusLine 已恢复 claude-hud。');
return;
}
if (cmd === 'session') {
// Reset session lock so a different window can take over
if (state) { state.sessionId = null; saveState(state); }
print('会话锁已重置。下一个触发 tick 的窗口将接管游戏。');
return;
}
if (cmd === 'restart') {
const className = (args[0] && CLASS_STATS[args[0]]) ? args[0] : 'warrior';
const leg = loadLegacy();
if (!leg.unlockedClasses.includes(className)) {
print(`职业 ${className} 未解锁!已解锁:${leg.unlockedClasses.join(', ')}`);
return;
}
state = initState(className);
saveState(state);
const theme = getFloorTheme(1);
print(`🏰 新的冒险开始了!你是一名 ${state.character.classEmoji}${state.character.className}`);
print(`踏入了${theme.name}...`);
const msgs = enterRoom(state);
msgs.forEach(m => print(m));
saveState(state);
return;
}
if (cmd === 'legacy') {
const leg = loadLegacy();
print('=== 传承 ===');
print(`传承点: ${leg.points} (已用: ${leg.spent})`);
print(`总轮数: ${leg.totalRuns} | 最深: B${leg.bestFloor} | 最多击杀: ${leg.bestKills}`);
print(`已解锁职业: ${leg.unlockedClasses.join(', ')}`);
print(`成就: ${leg.achievements.length > 0 ? leg.achievements.join(', ') : '无'}`);
print('--- 强化 ---');
print(`体质: +${leg.upgrades.hpBonus * 10}HP (${leg.upgrades.hpBonus}/5)`);
print(`攻击: +${leg.upgrades.atkBonus * 2}ATK (${leg.upgrades.atkBonus}/5)`);
print(`陷阱减免: ${leg.upgrades.trapReduce ? '是' : '否'}`);
print(`背包扩充: +${leg.upgrades.bagExtra} (${leg.upgrades.bagExtra}/2)`);
print(`休息加成: ${leg.upgrades.restBonus ? '50%' : '30%'}`);
print('--- 可购买 ---');
print(' !g upgrade hp (10点) 起始HP+10');
print(' !g upgrade atk (15点) 起始ATK+2');
print(' !g upgrade trap (20点) 陷阱率-50%');
print(' !g upgrade bag (25点) 背包+1');
print(' !g upgrade rest (20点) 休息回复50%');
print(' !g upgrade mage (50点) 解锁法师');
print(' !g upgrade rogue (50点) 解锁盗贼');
print(' !g upgrade paladin(80点) 解锁圣骑士');
return;
}
if (cmd === 'upgrade') {
const leg = loadLegacy();
const target = args[0];
const costs = { hp: 10, atk: 15, trap: 20, bag: 25, rest: 20, mage: 50, rogue: 50, paladin: 80 };
const cost = costs[target];
if (!cost) { print('无效的升级目标。用 !g legacy 查看选项。'); return; }
const available = leg.points - leg.spent;
if (available < cost) { print(`传承点不足!需要${cost},可用${available}`); return; }
let ok = false;
switch (target) {
case 'hp':
if (leg.upgrades.hpBonus >= 5) { print('已满级!'); return; }
leg.upgrades.hpBonus++; ok = true; break;
case 'atk':
if (leg.upgrades.atkBonus >= 5) { print('已满级!'); return; }
leg.upgrades.atkBonus++; ok = true; break;
case 'trap':
if (leg.upgrades.trapReduce) { print('已购买!'); return; }
leg.upgrades.trapReduce = true; ok = true; break;
case 'bag':
if (leg.upgrades.bagExtra >= 2) { print('已满级!'); return; }
leg.upgrades.bagExtra++; ok = true; break;
case 'rest':
if (leg.upgrades.restBonus) { print('已购买!'); return; }
leg.upgrades.restBonus = true; ok = true; break;
case 'mage':
if (leg.unlockedClasses.includes('mage')) { print('已解锁!'); return; }
leg.unlockedClasses.push('mage'); ok = true; break;
case 'rogue':
if (leg.unlockedClasses.includes('rogue')) { print('已解锁!'); return; }
leg.unlockedClasses.push('rogue'); ok = true; break;
case 'paladin':
if (leg.unlockedClasses.includes('paladin')) { print('已解锁!'); return; }
leg.unlockedClasses.push('paladin'); ok = true; break;
}
if (ok) {
leg.spent += cost;
saveLegacy(leg);
print(`✅ 升级成功!消耗${cost}传承点。`);
}
return;
}
// All remaining commands need a valid game state
if (!state || !state.enabled) {
print('游戏未开启。输入 !g on 开始冒险。');
return;
}
if (!state.alive) {
print('你已阵亡。输入 !g restart 重新开始,或 !g legacy 查看传承。');
return;
}
switch (cmd) {
case 'status': {
const c = state.character;
print(`=== ${c.classEmoji} ${c.className} Lv.${c.level} ===`);
print(`❤️ HP: ${c.hp}/${c.maxHp} ⚡ MP: ${c.mp}/${c.maxMp}`);
print(`⚔️ ATK: ${c.atk}(+${getEffectiveAtk(state) - c.atk}) 🛡 DEF: ${c.def}(+${getEffectiveDef(state) - c.def}) 🎯 SPD: ${c.spd}`);
print(`🪙 ${c.gold} XP: ${c.xp}/${c.xpToNext} Karma: ${c.karma}`);
print(`🏰 B${state.dungeon.floor}·${state.dungeon.floorName} 房间${state.dungeon.roomIndex + 1}/${state.dungeon.totalRooms}`);
print(`装备: 武器[${state.equipment.weapon ? state.equipment.weapon.name : '无'}] 护甲[${state.equipment.armor ? state.equipment.armor.name : '无'}] 饰品[${state.equipment.accessory ? state.equipment.accessory.name : '无'}]`);
print(`击杀: ${state.stats.kills} 探索房间: ${state.stats.roomsExplored}`);
if (state.buffs.length > 0) print(`Buffs: ${state.buffs.map(b => `${b.stat}${b.multiplier ? 'x' + b.multiplier : '+' + b.value}(${b.turnsLeft}回合)`).join(', ')}`);
const avail = SKILLS.filter(s => s.level <= state.character.level);
if (avail.length) print(`技能: ${avail.map(s => `${s.name}(${s.mpCost}MP)`).join(', ')}`);
break;
}
case 'bag': {
print(`=== 背包 ${state.inventory.length}/${state.bagSize} ===`);
if (state.inventory.length === 0) { print('空空如也...'); break; }
state.inventory.forEach((item, i) => {
print(` ${i + 1}. ${item.name} x${item.qty} - ${item.desc}`);
});
break;
}
case 'map': {
const rooms = state.dungeon.rooms;
const symbols = rooms.map((r, i) => {
if (i === state.dungeon.roomIndex) return '[@]';
if (r.explored || state.dungeon.revealed) {
const sym = { entrance: '[入]', empty: '[·]', monster: '[怪]', chest: '[箱]', trap: '[陷]', shop: '[店]', rest: '[火]', event: '[?]', boss: '[王]' };
return sym[r.type] || '[?]';
}
return '[░]';
});
print(`B${state.dungeon.floor}·${state.dungeon.floorName}: ${symbols.join('')}`);
break;
}
case 'fight': {
if (!state.combat) { print('没有战斗目标。'); break; }
const atkMsgs = playerAttack(state);
atkMsgs.forEach(m => print(m));
if (state.combat.monster.currentHp <= 0) {
const endMsgs = endCombat(state, true);
endMsgs.forEach(m => print(m));
tickBuffs(state);
// Check if stairs available
if (state.dungeon.roomIndex >= state.dungeon.rooms.length - 1) {
print('🪜 发现了通往下一层的楼梯!→ descend');
}
break;
}
state.combat.turn++;
const monMsgs = monsterAttack(state);
monMsgs.forEach(m => print(m));
tickBuffs(state);
if (state.character.hp <= 0) {
const reviveIdx = state.inventory.findIndex(i => i.id === 'revive_coin');
if (reviveIdx !== -1) {
state.character.hp = Math.floor(state.character.maxHp * 0.3);
state.inventory.splice(reviveIdx, 1);
print('💫 复活币生效!你复活了!');
} else {
handleDeath(state).forEach(m => print(m));
}
break;
}
print(`--- ❤️${state.character.hp} ⚡${state.character.mp} | ${state.combat.monster.name} ♥${state.combat.monster.currentHp} ---`);
break;
}
case 'flee': {
if (!state.combat) { print('没有战斗目标。'); break; }
if (state.character.class === 'rogue') {
state.combat = null;
print('盗贼的身手!成功逃脱!');
break;
}
const monSpd = state.combat.monster.spd || 5;
const chance = state.character.spd / (state.character.spd + monSpd);
if (Math.random() < chance) {
state.combat = null;
print('成功逃脱!');
} else {
print('逃跑失败!');
const monMsgs = monsterAttack(state);
monMsgs.forEach(m => print(m));
if (state.character.hp <= 0) {
const reviveIdx = state.inventory.findIndex(i => i.id === 'revive_coin');
if (reviveIdx !== -1) {
state.character.hp = Math.floor(state.character.maxHp * 0.3);
state.inventory.splice(reviveIdx, 1);
print('💫 复活币生效!');
} else {
handleDeath(state).forEach(m => print(m));
}
}
}
break;
}
case 'spell': {
if (!state.combat) { print('只能在战斗中使用技能。'); break; }
const skillName = args.join(' ');
const skill = SKILLS.find(s => s.name === skillName && s.level <= state.character.level);
if (!skill) { print(`未知技能或等级不足。可用:${SKILLS.filter(s => s.level <= state.character.level).map(s => s.name).join(', ')}`); break; }
if (state.character.mp < skill.mpCost) { print(`MP不足!需要${skill.mpCost},当前${state.character.mp}`); break; }
state.character.mp -= skill.mpCost;
const msgs = [];
switch (skill.effect.type) {
case 'attack': {
const hits = skill.effect.hits || 1;
const atkMsgs = playerAttack(state, skill.effect.multiplier, hits);
msgs.push(`释放【${skill.name}】!`);
msgs.push(...atkMsgs);
// Mage spell bonus
if (state.character.class === 'mage') {
const bonusDmg = Math.floor(getEffectiveAtk(state) * 0.3);
state.combat.monster.currentHp -= bonusDmg;
msgs.push(`法师加成!额外${bonusDmg}伤害!`);
}
break;
}
case 'heal':
state.character.hp = Math.min(state.character.maxHp, state.character.hp + skill.effect.value);
msgs.push(`释放【${skill.name}】!回复${skill.effect.value}HP`);
break;
case 'inspect':
const mon = state.combat.monster;
msgs.push(`【${skill.name}】${mon.name}: HP${mon.currentHp}/${mon.maxHp} ATK${mon.atk} DEF${mon.def} SPD${mon.spd || '?'}`);
if (mon.special) msgs.push(`特殊能力:${mon.special.desc}`);
break;
case 'fire_attack': {
let dmg = skill.effect.damage;
// Check ice multiplier
if (state.combat.monster.special && state.combat.monster.special.type === 'ice_armor') {
dmg *= skill.effect.iceMultiplier;
state.combat.monster.def = 0;
state.combat.monster._fireBreak = 2;
msgs.push('火焰破防!防御归零!');
}
state.combat.monster.currentHp -= dmg;
msgs.push(`释放【${skill.name}】!造成${dmg}点火焰伤害!`);
break;
}
case 'shield':
state.shield = skill.effect.blocks;
msgs.push(`释放【${skill.name}】!获得护盾,抵挡下一次攻击。`);
break;
case 'execute': {
const mon = state.combat.monster;
const hpRatio = mon.currentHp / mon.maxHp;
const mult = hpRatio <= skill.effect.hpThreshold ? skill.effect.multiplier : 1;
const atkMsgs = playerAttack(state, mult);
if (mult > 1) msgs.push(`释放【${skill.name}】!目标半血以下,${mult}倍伤害!`);
else msgs.push(`释放【${skill.name}】!目标血量过高,伤害正常。`);
msgs.push(...atkMsgs);
break;
}
}
msgs.forEach(m => print(m));
if (state.combat && state.combat.monster.currentHp <= 0) {