Repository navigation
Expand file tree
/
Copy pathgame.js
More file actions
3183 lines (2979 loc) · 106 KB
/
Copy pathgame.js
File metadata and controls
3183 lines (2979 loc) · 106 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
/** @typedef {import('pear-interface')} */ /* global Pear, Bare */
'use strict'
/**
* runa: the game loop.
*
* Two layers, and keeping them apart is the whole design. Walking is played
* with the keyboard and doors activate on contact. Combat advances on explicit
* input, while the strategy file decides what the character does each turn.
*
* bare-tui is Elm-shaped, so everything that happens arrives at `update` as a
* message and `view` only ever renders. Nothing here does IO inside `view`.
*
* A third layer sits on top of walking and is optional in the strongest sense:
* presence. Other people show up on the same map, they are drawn, and that is
* all. Nothing about them is saved and nothing about them is agreed on, so
* there is no state to reconcile and no failure worth recovering from. If the
* network is missing or breaks, presence turns itself off and the game is the
* single player game it already was.
*/
const { quit, every, key, textinput } = require('bare-tui')
const fs = require('bare-fs')
const { Walker, MAPS, TILES } = require('./map.js')
const { Player, shops, browse, EQUIPMENT_SLOTS } = require('./shop.js')
const { SLOT_COUNT } = require('./saves.js')
const { Field, Y_SCALE, WORLD_BOSS_PORTAL_CLEARANCE } = require('./field.js')
const { Dungeon } = require('./dungeon.js')
const { BossZone } = require('./boss-zone.js')
const { BarbarianCamp } = require('./barbarian-camp.js')
const render = require('./render.js')
const { parse } = require('./script.js')
const portraits = require('./portraits.js')
const { ARENA } = require('./world.js')
const { Duel, DuelCombat } = require('./duel.js')
const { WalletSession } = require('./wallet.js')
const CONTENT = require('./content.js')
/**
* The swarm, if there is one.
*
* Required behind a guard because playing alone is the common case, not the
* degraded one: net.js may not be installed, and it may fail to load when a
* dependency is missing. Either way this require is the only place that has to
* know, and everything below is written to work with `Presence` being null.
*/
let Presence = null
try {
Presence = require('./net.js').Presence || null
} catch {
Presence = null
}
/**
* La cadena, si es que hay.
*
* Detras del mismo guardia que la presencia y por el mismo motivo: arrastra
* criptografia empaquetada que en algun build podria no estar. Jugar sin cadena
* es el caso comun, no el degradado, y todo lo de abajo esta escrito para que
* `Chain` sea null sin que nada se entere.
*/
let Chain = null
try {
Chain = require('./stellar.js').Chain || null
} catch {
Chain = null
}
/** Simulation rate. Rendering follows the same clock; at this size it is cheap. */
const TICK_MS = 1000 / 15
/** World ticks resolved by one deliberate combat input. */
const COMBAT_TURN_TICKS = 6
/** Where the player's strategy lives. */
const SCRIPT_PATH = 'script.txt'
const LEGACY_DEFAULT_SCRIPT = [
'// tu estrategia. se relee sola mientras peleas.',
'// probá cambiarla en medio de una pelea y mirá qué pasa.',
'',
'?hp < 8',
' use potion',
':?foe.dist >= 5',
' equip crossbow',
':',
' equip sword',
''
].join('\n')
const DEFAULT_SCRIPT = [
'// tu estrategia. se relee sola mientras peleas.',
'// el combate usa el arma que equipaste con I.',
'// agrega "equip ..." solo si queres cambiar a otro objeto que poseas.',
'',
'?hp < 8',
' use potion',
''
].join('\n')
/** Recognise and migrate the strategy shipped before equipped gear won. */
function isLegacyDefaultScript(source) {
const commands = String(source || '')
.split(/\r?\n/)
.map((line) => line.split('//')[0].trim())
.filter(Boolean)
const legacyCommands = LEGACY_DEFAULT_SCRIPT.split(/\r?\n/)
.map((line) => line.split('//')[0].trim())
.filter(Boolean)
return JSON.stringify(commands) === JSON.stringify(legacyCommands)
}
/** Shown to other players when nobody picked a name. */
const DEFAULT_NAME = 'viajero'
/**
* The map announced while the player is off in the field.
*
* Presence only ever talks about a map and a position, so leaving town has to
* be said in that language: announce a map nobody draws and you are off every
* other player's screen without inventing a message for it.
*/
const AWAY_MAP = 'field'
/** How many arrivals may pile up between two ticks before the oldest drop. */
const QUEUE_MAX = 20
/** Drawn for another player when they do not offer a glyph of their own. */
const OTHER_GLYPH = 'o'
/** Persistent terminal button used to open the controls overlay. */
const CONTROLS_BUTTON = '[? CONTROLES]'
const INVENTORY_BUTTON = '[I INVENTARIO]'
const INVENTORY_CLOSE_BUTTON = '[I / ESC CERRAR]'
function controlsFooter(text) {
return `${CONTROLS_BUTTON} | ${text}`
}
function gameplayFooter(text) {
return `${INVENTORY_BUTTON} ${CONTROLS_BUTTON} | ${text}`
}
function inventoryFooter(text) {
return `${INVENTORY_CLOSE_BUTTON} ${CONTROLS_BUTTON} | ${text}`
}
const REALMS = Object.freeze([
Object.freeze({ id: 'runa', name: 'RUNA', about: 'reino del alba', mapId: 'city' }),
Object.freeze({ id: 'nox', name: 'NOX', about: 'reino enemigo', mapId: 'nox' })
])
function normalizeRealm(value) {
const id = String(value || '').toLowerCase()
return REALMS.some((realm) => realm.id === id) ? id : 'runa'
}
function realmDefinition(value) {
const id = normalizeRealm(value)
return REALMS.find((realm) => realm.id === id) || REALMS[0]
}
/** Repeatable content can join this table without adding another NPC handler. */
const QUESTS = Object.freeze({
mosquito_hunt: Object.freeze({
id: 'mosquito_hunt',
title: 'plaga de mosquitos',
target: 'mosquito',
count: 20,
reward: Object.freeze({ gold: 100, xp: 100 })
})
})
/**
* Cut a name down to something a pane can draw.
*
* Names come off the wire, which makes them the one string in this file that
* is not ours. The screen is ASCII only, so anything outside it is dropped
* rather than replaced: a name of question marks is worse than a short name.
*
* @param {string} raw
* @returns {string}
*/
function cleanName(raw) {
let out = ''
for (const ch of String(raw === null || raw === undefined ? '' : raw)) {
const cp = ch.codePointAt(0)
if (cp >= 32 && cp <= 126) out += ch
if (out.length >= 16) break
}
out = out.trim()
return out || DEFAULT_NAME
}
function nameInitial(raw) {
const match = cleanName(raw).match(/[A-Za-z0-9]/)
return match ? match[0].toUpperCase() : 'V'
}
function clampNumber(value, lo, hi) {
const number = Math.floor(Number(value))
if (!Number.isFinite(number)) return lo
return number < lo ? lo : number > hi ? hi : number
}
function questState(raw = {}) {
const out = {}
for (const quest of Object.values(QUESTS)) {
const saved = raw && typeof raw[quest.id] === 'object' ? raw[quest.id] : {}
const status = ['available', 'active', 'completed'].includes(saved.status)
? saved.status
: 'available'
out[quest.id] = {
status,
progress: status === 'completed' ? quest.count : clampNumber(saved.progress, 0, quest.count)
}
}
return out
}
function barbarianProgress(raw = {}) {
const cleared = Array.isArray(raw.cleared) ? [...new Set(raw.cleared.map(String))] : []
const camps = {}
if (raw.camps && typeof raw.camps === 'object') {
for (const [id, state] of Object.entries(raw.camps)) {
camps[String(id)] = state && typeof state === 'object' ? { ...state } : {}
}
}
return { cleared, camps }
}
function emptySlots() {
return Array.from({ length: SLOT_COUNT }, (_, index) => ({
slot: index + 1,
empty: true,
corrupt: false
}))
}
/**
* One printable character for another player.
*
* Space is excluded on purpose: an actor drawn as a space is an actor that is
* not drawn at all, and a peer should not be able to make itself invisible.
*
* @param {string} [raw]
* @returns {string}
*/
function cleanGlyph(raw) {
const ch = String(raw === null || raw === undefined ? '' : raw)[0]
if (!ch) return OTHER_GLYPH
const cp = ch.codePointAt(0)
return cp >= 33 && cp <= 126 ? ch : OTHER_GLYPH
}
/**
* Read the command line, which under Bare hangs off the Bare global because
* there is no process to ask.
*
* @returns {{ name: string|null, solo: boolean }}
*/
function argFlags() {
let argv = []
try {
argv = (typeof Bare !== 'undefined' && Bare.argv) || []
} catch {
argv = []
}
let name = null
let solo = false
for (let i = 0; i < argv.length; i++) {
const a = String(argv[i])
if (a === '--solo' || a === '--no-presence') solo = true
else if (a === '--name' && i + 1 < argv.length) name = String(argv[++i])
else if (a.slice(0, 7) === '--name=') name = a.slice(7)
}
return { name, solo }
}
/**
* A default nobody has to type, with enough tail on it that two people who
* never picked a name are still two people in the log.
*
* @returns {string}
*/
function anonName() {
const tail = Math.floor(Math.random() * 46656).toString(36)
return DEFAULT_NAME + '-' + ('000' + tail).slice(-3)
}
const tick = every(TICK_MS, () => ({ type: 'tick' }))
class Runa {
/**
* @param {object} [opts]
* @param {string} [opts.name] - what other players see
* @param {boolean} [opts.presence] - false plays alone no matter what
* @param {object} [opts.saves] - persistent slot store
*/
constructor(opts = {}) {
this.width = 80
this.height = 24
this.walker = new Walker('city')
this.dungeonReturn = null
this.castleReturn = null
this.player = new Player()
this.field = null
this.meadowField = null
this.meadowReturn = null
this.dungeonState = null
this.worldBossState = null
this.barbarianState = barbarianProgress()
this.duel = null
this.duelCombat = null
this.lastDuelResult = null
this.duelInvite = null
this.duelNetwork = null
this.duelMessages = []
this.shop = null
this.cursor = 0
this.inventoryOpen = false
this.inventoryHome = false
this.inventoryTab = 'carried'
this.inventoryCursor = 0
this.rankingOpen = false
this.rankingTab = 'level'
this.controlsOpen = false
this.animationTick = 0
this.quests = questState()
this.title = true
this.naming = false
this.nameError = ''
this.realm = 'runa'
this.realmCursor = 0
this.saves = opts.saves || null
this.slots = emptySlots()
this.menuPage = 'main'
this.menuCursor = 0
this.slotCursor = 0
this.activeSlot = null
this.pendingSlot = null
this.namingReturnPage = 'main'
this.replacing = ''
this.menuMessage = ''
this.saveFailure = ''
this.wallet = new WalletSession({ signer: opts.walletSigner })
this.walletOpen = false
this.walletEditing = false
this.walletError = ''
this.walletInput = textinput.create({ value: '', placeholder: 'G...', charLimit: 56 })
this.log = []
this.seen = new Set()
this.encounter = null
/** What the field rolled for the kill being settled this tick. */
this.earned = null
this.pending = null
this.scriptSource = ''
this.scriptMtime = 0
this.scriptErrors = []
// Presence is built here and started in init(). A constructor that opens a
// socket is a class that cannot be built in a test, and every test in this
// repo builds a Runa.
const args = argFlags()
const requestedName = opts.name || args.name || ''
this.requestedName = requestedName
this.name = cleanName(requestedName || anonName())
this.nameInput = textinput
.create({ value: requestedName, placeholder: 'tu nombre', charLimit: 16 })
.focus()
this.online = opts.presence !== false && args.solo === false && Presence !== null
this.presence = null
this.presenceStarted = false
this.arrivals = []
// La semilla del dia. Se pide una sola vez al entrar y no se espera nunca:
// hasta que llegue, el campo se siembra con lo local.
this.chain = Chain ? new Chain() : null
this.daySeed = null
this.dayNumber = null
if (this.online) {
try {
this.attachPresence(new Presence({ name: this.name }))
} catch {
this.dropPresence()
}
}
this.refreshSlots()
this.loadScript(true)
}
// -------------------------------------------------------------------------
/** Wire all network events through queues owned by the update loop. */
attachPresence(presence) {
this.presence = presence
if (!presence || typeof presence.on !== 'function') return presence
presence.on('join', (who) => this.noteLater('llego ' + cleanName(who)))
presence.on('leave', (who) => this.noteLater('se fue ' + cleanName(who)))
presence.on('duel', (message) => {
this.duelMessages.push(message)
if (this.duelMessages.length > QUEUE_MAX) this.duelMessages.shift()
})
presence.on('peer-leave', (peer) => {
this.duelMessages.push({ kind: 'peer-leave', ...peer })
if (this.duelMessages.length > QUEUE_MAX) this.duelMessages.shift()
})
return presence
}
/**
* Read the strategy file if it changed.
*
* Polling a stat is deliberate: file watching under Bare is one more thing
* that can behave differently per platform, and at 15 ticks a second a stat
* costs nothing. Re-reading on every tick would be the wasteful version.
*
* @param {boolean} [force]
* @returns {boolean} whether it reloaded
*/
loadScript(force = false) {
let stat = null
try {
stat = fs.statSync(SCRIPT_PATH)
} catch {
if (force) {
try {
fs.writeFileSync(SCRIPT_PATH, DEFAULT_SCRIPT)
stat = fs.statSync(SCRIPT_PATH)
} catch {
return false
}
} else {
return false
}
}
const mtime = stat.mtimeMs || (stat.mtime && stat.mtime.getTime()) || 0
if (!force && mtime === this.scriptMtime) return false
this.scriptMtime = mtime
try {
this.scriptSource = fs.readFileSync(SCRIPT_PATH, 'utf8')
if (isLegacyDefaultScript(this.scriptSource)) {
this.scriptSource = DEFAULT_SCRIPT
fs.writeFileSync(SCRIPT_PATH, this.scriptSource)
stat = fs.statSync(SCRIPT_PATH)
this.scriptMtime = stat.mtimeMs || (stat.mtime && stat.mtime.getTime()) || 0
}
} catch {
return false
}
const { errors } = parse(this.scriptSource)
this.scriptErrors = errors
if (errors.length) {
this.say(`script: ${errors[0].message} (linea ${errors[0].line})`)
} else {
// Both paths say it now. The guard used to silence exactly the wrong one:
// the automatic reload nobody asked for announced itself, and pressing
// `r` on purpose did its work in complete silence, which is
// indistinguishable from a key that does nothing.
this.say('script recargado')
}
if (this.field) this.field.setScript(this.scriptSource)
return true
}
/**
* News from the updater, shown as something that happened in the world.
*
* An update landing is not maintenance chatter here, it is the premise: the
* content is data, so a new release can change what lives in the field while
* someone is already playing.
*
* @param {string} text
*/
world(text) {
this.say(text)
}
/** @param {string} text */
say(text) {
this.log.push(text)
if (this.log.length > 40) this.log.shift()
}
// -------------------------------------------------------------------------
/**
* Park a line from the swarm until the next tick.
*
* Join and leave fire whenever the network feels like it, which includes the
* middle of a render. `view` has to stay pure, so nothing arriving from
* outside is allowed to touch the log on the spot: it waits in a queue that
* the tick drains, where every other mutation in this class already happens.
*
* @param {string} text
*/
noteLater(text) {
this.arrivals.push(text)
// Ten people joining at once must not grow a queue without bound.
if (this.arrivals.length > QUEUE_MAX) this.arrivals.shift()
}
/** Move whatever the swarm parked into the log. Called from the tick only. */
drainArrivals() {
if (this.arrivals.length === 0) return
const queued = this.arrivals
this.arrivals = []
for (const text of queued) this.say(text)
}
/**
* Join the swarm. Called from init(), never from the constructor.
*
* @returns {boolean} whether presence came up
*/
/**
* Con que numero se dibuja el campo.
*
* Con la semilla del dia si llego, y si no con algo derivado del jugador. Lo
* segundo no es un capricho: sin eso el campo sale siempre identico, que es
* justo lo que reporta la issue #3.
*/
fieldSeed() {
if (this.daySeed !== null) return this.daySeed
const xp = this.player ? this.player.xp || 0 : 0
const gold = this.player ? this.player.gold || 0 : 0
return (Math.imul(xp + 1, 2654435761) ^ Math.imul(gold + 1, 40503)) >>> 0
}
/**
* Pedirle a la cadena la semilla del dia.
*
* No devuelve nada y nadie la espera. El campo de hoy es el mismo para todos
* los que jueguen hoy, y eso es lo unico que la cadena aporta aca: un numero
* publico que ningun jugador y ningun dueno puede mover. Si no hay linea, el
* campo se siembra con lo local y el juego no cambia en nada mas.
*/
startChain() {
if (!this.chain || !this.chain.available) return
this.chain
.dailySeed()
.then((d) => {
if (!d) return
this.daySeed = d.seed
this.dayNumber = d.day
this.noteLater('el campo de hoy es el dia ' + d.day + ', igual para todos')
})
.catch(() => {})
}
startPresence() {
if (!this.presence || this.presenceStarted) return this.presenceStarted
try {
this.presence.start()
this.presenceStarted = true
// Greet first, announce second. If the very first announcement is the
// thing that fails, its line has to read after the greeting, not before.
this.say('sos ' + this.name + ', mirando quien mas anda por el pueblo')
this.announce()
return true
} catch {
this.dropPresence()
this.say('sin red, caminas solo')
return false
}
}
/** Leave the swarm. Safe to call on a game that never had one. */
stopPresence() {
const p = this.presence
this.dropPresence()
if (!p) return
try {
p.stop()
} catch {
// Leaving is best effort. The process is on its way out either way.
}
}
/**
* Forget the network and go back to being a single player game.
*
* There is nothing to salvage when presence breaks, because presence never
* held anything: no score, no inventory, no position anyone else needs. So
* it is dropped whole rather than retried.
*/
dropPresence() {
if (this.duelNetwork && this.duel && this.duelCombat) {
this.duelCombat.surrender(this.duelNetwork.rivalId)
this.finishDuel('desconexion', { broadcast: false })
}
this.presence = null
this.presenceStarted = false
this.online = false
this.arrivals = []
}
/**
* Say where we are, if anyone is listening.
*
* Sent after something moves the walker rather than on every tick: the
* position only changes on a key, and repeating it fifteen times a second is
* traffic that carries no news.
*/
announce() {
if (!this.presence || !this.presenceStarted) return
// Walking out of town has to take the player off everyone else's map, and
// the only thing presence knows about is the map you are standing on.
const mapId = this.field ? AWAY_MAP : this.walker.mapId
try {
const stats = this.player.snapshot()
this.presence.update(mapId, this.walker.x, this.walker.y, {
level: stats.level,
wins: (stats.pvp && stats.pvp.wins) || 0,
losses: (stats.pvp && stats.pvp.losses) || 0
})
} catch {
this.dropPresence()
this.say('se corto la red, seguis solo')
}
}
/**
* The other players standing on the map about to be drawn.
*
* Called from `view`, so it reads and does nothing else: it does not start,
* stop or repair anything, and a bad read is an empty town for one frame,
* which is what a single player sees anyway. Everything is checked again
* here because these coordinates came off the wire and land in a pane.
*
* @param {string} mapId
* @returns {Array<{x: number, y: number, glyph: string, name: string}>}
*/
others(mapId) {
if (!this.presence) return []
let list = null
try {
list = this.presence.others(mapId)
} catch {
return []
}
const out = []
for (const o of list || []) {
if (!o) continue
const x = Math.round(Number(o.x))
const y = Math.round(Number(o.y))
if (!Number.isFinite(x) || !Number.isFinite(y)) continue
out.push({
id: String(o.id || ''),
x,
y,
glyph: cleanGlyph(o.glyph),
name: cleanName(o.name),
level: clampNumber(o.level, 1, 999),
wins: clampNumber(o.wins, 0, 0x7fffffff),
losses: clampNumber(o.losses, 0, 0x7fffffff)
})
}
return out
}
/** Static resident occupying one logical city tile. */
npcAt(x, y) {
if (this.field) return null
const map = MAPS[this.walker.mapId]
for (const npc of (map && map.npcs) || []) {
if (npc.x === x && npc.y === y) return npc
}
return null
}
/** Nearest resident available for an `e` interaction. */
nearbyNpc(range = 1) {
if (this.field) return null
const map = MAPS[this.walker.mapId]
let nearest = null
let best = Infinity
for (const npc of (map && map.npcs) || []) {
const distance = Math.max(Math.abs(npc.x - this.walker.x), Math.abs(npc.y - this.walker.y))
if (distance > range || distance >= best) continue
nearest = npc
best = distance
}
return nearest
}
nearbyLandmark(range = 1) {
if (this.field) return null
const map = MAPS[this.walker.mapId]
for (const landmark of (map && map.landmarks) || []) {
const b = landmark.bounds
const dx = Math.max(b.x1 - this.walker.x, 0, this.walker.x - b.x2)
const dy = Math.max(b.y1 - this.walker.y, 0, this.walker.y - b.y2)
if (Math.max(dx, dy) <= range) return landmark
}
return null
}
openRanking() {
this.rankingOpen = true
this.rankingTab = 'level'
return true
}
rankingEntries() {
const entries = new Map()
for (const slot of this.slots || []) {
if (!slot || slot.empty || slot.corrupt) continue
entries.set('slot:' + slot.slot, {
id: 'slot:' + slot.slot,
name: cleanName(slot.name),
level: clampNumber(slot.level, 1, 999),
wins: clampNumber(slot.pvp && slot.pvp.wins, 0, 0x7fffffff),
losses: clampNumber(slot.pvp && slot.pvp.losses, 0, 0x7fffffff),
source: 'local'
})
}
const current = this.player.snapshot()
entries.set('slot:' + (this.activeSlot || 'current'), {
id: 'slot:' + (this.activeSlot || 'current'),
name: this.name,
level: current.level,
wins: current.pvp.wins,
losses: current.pvp.losses,
source: 'vos'
})
for (const peer of this.others()) {
entries.set('peer:' + peer.id, { ...peer, source: 'online' })
}
return [...entries.values()]
}
/** Talk to a resident, then perform the service their role provides. */
interactNpc(npc) {
if (!npc) return false
this.say(`${npc.name}, ${npc.role}: ${npc.line}`)
const action = npc.action
if (!action) return true
if (action.kind === 'shop') {
const s = shops[action.shop]
if (!s) return true
this.shop = action.shop
this.cursor = 0
return true
}
if (action.kind === 'church') {
this.player.hp = this.player.maxHp
this.say('hermana Alma cura todas tus heridas')
return true
}
if (action.kind === 'tavern') {
this.restAtTavern()
return true
}
if (action.kind === 'quest') return this.handleQuest(action.quest, npc.name)
return true
}
handleQuest(id, giver = 'el caballero') {
const quest = QUESTS[id]
const state = this.quests[id]
if (!quest || !state) return false
if (state.status === 'available') {
state.status = 'active'
state.progress = 0
this.say(`mision aceptada: elimina ${quest.count} mosquitos (0/${quest.count})`)
return true
}
if (state.status === 'completed') {
this.say(`${giver}: ya cumpliste la mision de los mosquitos`)
return true
}
if (state.progress < quest.count) {
this.say(`${giver}: llevas ${state.progress}/${quest.count} mosquitos`)
return true
}
this.player.gainGold(quest.reward.gold)
const up = this.player.gainXp(quest.reward.xp)
state.status = 'completed'
this.say(`mision completada: +${quest.reward.gold} oro, +${quest.reward.xp} exp`)
if (up.levels > 0) this.say('subiste a nivel ' + this.player.snapshot().level)
return true
}
recordQuestKill(kind) {
for (const quest of Object.values(QUESTS)) {
const state = this.quests[quest.id]
if (!state || state.status !== 'active' || kind !== quest.target) continue
if (state.progress >= quest.count) continue
state.progress++
if (state.progress === quest.count) {
this.say(
`mision lista: vuelve con el caballero de la plaza (${quest.count}/${quest.count})`
)
} else if (state.progress === 1 || state.progress % 5 === 0) {
this.say(`mision ${quest.title}: ${state.progress}/${quest.count}`)
}
}
}
/** The tavern is a small, explicit gold sink and a full heal. */
restAtTavern() {
const price = 3
if (this.player.hp >= this.player.maxHp) {
this.say('Bruno: ya estas descansado')
return false
}
if (this.player.gold < price) {
this.say(`Bruno: necesitas ${price} monedas para una cama`)
return false
}
this.player.gold -= price
this.player.hp = this.player.maxHp
this.say(`descansas en la taberna por ${price} monedas`)
return true
}
/**
* Handle the field's structured events. These are control signals, not text:
* the prose lives in the field's own news feed and is pulled separately, so
* one loud fight does not drown the log in duplicated lines.
* @param {object[]} events
*/
drain(events) {
for (const e of events || []) {
if (!e || !e.type) continue
switch (e.type) {
case 'town':
this.field = null
this.meadowField = null
this.meadowReturn = null
this.dungeonState = null
this.walker.travel('city')
this.announce()
this.say('volves a la ciudad')
break
case 'nox':
if (!this.field || this.field.mode !== 'field') break
this.field = null
this.meadowField = null
this.meadowReturn = null
this.dungeonState = null
this.walker.travel('nox')
this.announce()
this.say('atravesas el porton oriental y entras al reino oscuro de NOX')
break
case 'barbarian-enter': {
if (!this.field || this.field.mode !== 'field') break
const settlement = this.field.settlementAt
? this.field.settlementAt(this.field.player.x, this.field.player.y)
: null
if (!settlement || settlement.id !== e.campId) break
this.meadowField = this.field
this.meadowReturn = {
x: Math.max(1, settlement.x - 2),
y: settlement.y
}
this.field = new BarbarianCamp({
campId: settlement.id,
player: this.player,
script: this.scriptSource,
seed: this.fieldSeed(),
state: this.barbarianState.camps[settlement.id]
})
this.seen = new Set()
this.say(`atravesas la empalizada de ${settlement.name}`)
break
}
case 'barbarian-exit': {
if (!this.field || this.field.mode !== 'barbarian-camp') break
const camp = this.field.camp
this.barbarianState.camps[camp.id] = this.field.toJSON()
const wasCleared = this.barbarianState.cleared.includes(camp.id)
if (e.cleared && !wasCleared) {
this.barbarianState.cleared.push(camp.id)
this.player.gainGold(camp.reward)
}
const back = this.meadowReturn
const restored =
this.meadowField ||
new Field({
player: this.player,
seed: this.fieldSeed(),
script: this.scriptSource,
clearedSettlements: this.barbarianState.cleared
})
if (e.cleared) restored.clearSettlement(camp.id)
restored.player.hp = this.player.hp
restored.player.maxhp = this.player.maxHp
restored.player.potions = this.player.potions
restored.player.x = back ? back.x : Math.max(1, camp.x - 2)
restored.player.y = back ? back.y : camp.y
this.field = restored
this.meadowField = null
this.meadowReturn = null
this.seen = new Set()
if (e.cleared) {
this.say(`asentamiento ${camp.name} eliminado: +${wasCleared ? 0 : camp.reward} oro`)
} else {
this.say(`abandonas ${camp.name}; quedan barbaros y la empalizada permanece`)
}
break
}
case 'dungeon-enter':
if (!this.field || this.field.mode === 'dungeon') break
this.meadowField = this.field
this.meadowReturn = {
x: Math.max(1, this.field.dungeonEntrance.x - 3),
y: this.field.dungeonEntrance.y
}
this.dungeonState = null
this.openDungeonFloor(1, 'down')
this.say('cruzas la entrada de piedra y bajas al nivel 1 de la mazmorra')
break
case 'dungeon-floor':
this.openDungeonFloor(e.floor, e.direction)
this.say(
e.direction === 'up'
? `subis a la mazmorra nivel ${e.floor}`
: `bajas a la mazmorra nivel ${e.floor}`
)
break
case 'dungeon-exit': {
const back = this.meadowReturn
const restored =
this.meadowField ||
new Field({
player: this.player,
seed: this.fieldSeed(),
script: this.scriptSource,
clearedSettlements: this.barbarianState.cleared
})
restored.player.hp = this.player.hp
restored.player.maxhp = this.player.maxHp
restored.player.potions = this.player.potions
restored.player.x = back ? back.x : Math.max(1, restored.dungeonEntrance.x - 3)
restored.player.y = back ? back.y : restored.dungeonEntrance.y
this.field = restored
this.meadowField = null
this.meadowReturn = null
this.dungeonState = null
this.seen = new Set()
this.say('salis de la cripta y volves a la pradera')
break
}
case 'boss-enter':
if (!this.field || this.field.mode !== 'field') break
this.meadowField = this.field
this.meadowReturn = {
x: Math.max(1, this.field.worldBossPortal.x - WORLD_BOSS_PORTAL_CLEARANCE + 1),
y: this.field.worldBossPortal.y
}
this.field = new BossZone({
player: this.player,
script: this.scriptSource,
seed: this.fieldSeed(),
state: this.worldBossState
})
this.seen = new Set()
this.say('el portal te lleva a las ruinas volcanicas del Coloso')
break
case 'boss-exit': {
this.worldBossState = this.field && this.field.toJSON ? this.field.toJSON() : null
const back = this.meadowReturn
const restored =
this.meadowField ||
new Field({
player: this.player,
seed: this.fieldSeed(),
script: this.scriptSource,
clearedSettlements: this.barbarianState.cleared
})
restored.player.hp = this.player.hp
restored.player.maxhp = this.player.maxHp
restored.player.potions = this.player.potions
restored.player.x = back
? back.x
: Math.max(1, restored.worldBossPortal.x - WORLD_BOSS_PORTAL_CLEARANCE + 1)
restored.player.y = back ? back.y : restored.worldBossPortal.y
this.field = restored
this.meadowField = null
this.meadowReturn = null
this.seen = new Set()
this.say('atravesas el portal y reapareces en el yermo')
break
}