-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.lua
More file actions
6045 lines (5740 loc) · 245 KB
/
Copy pathmain.lua
File metadata and controls
6045 lines (5740 loc) · 245 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
------------------------------------------------------------------------
-- AI Rivals
------------------------------------------------------------------------
-- Four persistent AI trainers walk Kanto on their own clock. They route
-- across the real map graph, train, queue at gym doors, win and LOSE gym
-- battles, keep their own badge case, and turn up to fight the player with
-- whatever party they actually have at that moment.
--
-- WHAT THIS FILE OWNS
-- * the module loader (this mod is many files; the engine loads one)
-- * RivalManager: the roster, the save bucket, the engine seams
-- * every subscription and hook link
-- The thinking lives in src/; nothing below decides anything about a rival.
--
-- THE THREE SEAMS THAT MAKE IT WORK WITHOUT A SECOND BATTLE ENGINE
-- 1. `trainers` registry + the `trainer.party` hook. Each rival owns one
-- trainer record whose party is a placeholder. When a battle against
-- that class starts, the hook swaps in the rival's LIVE party -- so the
-- player fights CHARMELEON Lv28 because the rival really has one.
-- 2. `mod.world:spawnNpc` / `removeNpc`. A rival is a real overworld
-- object only while the player shares its map; everywhere else it is a
-- row in a table being advanced by the tick.
-- 3. `core.update`. One accumulator, one tick every 1.5s, a bounded
-- number of rivals per tick. Nothing in this mod runs per frame.
------------------------------------------------------------------------
------------------------------------------------------------------------
-- Module loader
------------------------------------------------------------------------
-- The engine loads exactly one chunk per mod, so a multi-file mod brings its
-- own require. `mod:read` is the supported way to get at a file inside the
-- mod directory -- it works identically from a folder install and from a
-- packed .modpkg (mod:read works in both installs). Each module receives
-- (req, mod) as varargs, which is why every file opens `local req, mod = ...`.
return function(mod)
local loaded, loading = {}, {}
local function req(name)
local hit = loaded[name]
if hit ~= nil then return hit end
if loading[name] then
error("ai_rivals: circular require of " .. name, 0)
end
loading[name] = true
local source = mod:read(name .. ".lua")
if not source then
error("ai_rivals: missing module " .. name .. ".lua", 0)
end
-- Sandbox binds load/loadstring to the mod env; prefer loadstring (works
-- on Lua 5.1 AND as a 5.2 alias), then the 5.2+ string `load`. Both are
-- pcall'd so a build where the other does not take a string never kills
-- the mod load.
local chunk, err
if type(loadstring) == "function" then
local ok, c = pcall(loadstring, source, "@ai_rivals/" .. name .. ".lua")
if ok then chunk = c else err = c end
end
if not chunk and type(load) == "function" then
local ok, c = pcall(load, source, "@ai_rivals/" .. name .. ".lua")
if ok then chunk = c else err = c end
end
if not chunk then error("ai_rivals: " .. tostring(err), 0) end
local value = chunk(req, mod)
loading[name] = nil
loaded[name] = value == nil and true or value
return loaded[name]
end
local Util = req("src/Util")
local MapGraph = req("src/MapGraph")
local Pathfinder = req("src/Pathfinder")
local BattleSim = req("src/BattleSim")
local Rival = req("src/Rival")
local AI = req("src/AI")
local Simulation = req("src/Simulation")
local Sprites = req("src/Sprites")
local Version = req("src/Version")
local Dialogue = req("src/Dialogue")
local DoubleBattles = req("src/DoubleBattles")
local WonderTrade = req("src/WonderTrade")
local KantoCompat = req("src/KantoCompat")
local Memory = req("src/Memory")
local Relationships = req("src/Relationships")
local TeamPlan = req("src/TeamPlan")
local Story = req("src/Story")
local Presence = req("src/Presence")
local Weather = req("src/Weather")
local Economy = req("src/Economy")
local League = req("src/League")
local LifePath = req("src/LifePath")
local Career = req("src/Career")
local Phone = req("src/Phone")
local Comms = req("src/Comms")
local BattleFlow = req("src/BattleFlow")
local RuntimePolicy = req("src/RuntimePolicy")
local RosterPolicy = req("src/RosterPolicy")
local Gen2Talk = req("src/Gen2Talk")
local Scout = req("src/Scout")
local Achievements = req("src/Achievements")
local Rankings = req("src/Rankings")
local NOTABLE = req("data/notable")
local Pokegear = req("src/Pokegear")
local Tournaments = req("src/Tournaments")
local Status = req("src/ui/Status")
local Commands = req("src/debug/Commands")
local Compat = req("src/Compat")
-- The complete double-battle implementation is bundled into this mod so a
-- companion works without a second installation.
DoubleBattles(mod)
local ROSTER = req("data/rivals")
-- A roster row's home maps for the game actually loaded. Accepts the flat
-- list form too, so a third-party roster written before 2.10 keeps working.
local function homeMapsFor(def)
local maps = def and def.homeMaps
if type(maps) ~= "table" then return {} end
if type(maps[1]) == "string" then return maps end
return maps[(M and M.versionKey) or "default"] or maps.default or {}
end
local PERSONALITIES = req("data/personalities")
local GYMS = req("data/gyms")
local LINES = req("data/dialogue")
local SAVE_VERSION = 9
local TALK_TEXT = "AIR_RIVAL_TALK" -- the text id our spawned NPCs carry
local SCREEN = "AiRivalsStatus"
-- The manager. Declared up here -- before the map helpers below reference
-- it -- so a closure is never left holding the global `M` (which would be
-- nil and crash the first gauntlet resolution). `Sprites` is already
-- required above.
local M = {
game = nil,
data = nil,
graph = nil,
-- 3.5.0 (from the 3.4.1 patch): ONE rival battle at a time.
--
-- A rival battle is a TRANSACTION, not an instant: dialogue, the deferred
-- launch, the battle itself, then the bookkeeping and gauntlet progression
-- that follow battle.ended. Every one of those windows could previously be
-- re-entered -- by a second talk in the same frame, a nearby rival's duel
-- AI, a repeated Gen 2 engagement event, or a stale delayed callback -- and
-- the second entrant would corrupt the first's state.
--
-- The sequence ID is what makes a STALE callback distinguishable from a live
-- one: a callback carrying an older id cannot start anything.
rivalBattleSequenceActive = false,
rivalBattleSequenceId = 0,
rivalBattleActiveRivalId = nil,
rivals = {}, -- ordered list
byId = {},
sim = nil,
sprites = Sprites.new(mod),
dialogue = nil,
spawned = {}, -- rival id -> npc handle id, current map only
pending = nil, -- the rival whose battle is about to start
ready = false,
generation = 1,
news = {}, -- 1.14.0: ring buffer of world-news lines
ticker = { text = nil, age = 0, duration = 8, offset = 0 },
tickerQueue = {},
companionId = nil,
worldStartPending = false,
pendingRivalMenu = nil,
pendingRivalAction = nil,
pendingPhoneTrainer = nil,
pendingTrainerContact = nil,
phoneTrainerDefs = {},
phoneContactObjects = {},
radioStation = "POKEMON_MUSIC",
radioEnabled = false,
customMusicFolder = "custom_music",
customMusicTrack = nil,
customMusicSource = nil,
challengeModes = {},
tournaments = nil,
tournamentExpActive = false,
perf = {
simulation = { samples = 0, average = 0, maximum = 0 },
walking = { samples = 0, average = 0, maximum = 0 },
-- Observational only: whole core.update body, so it sees the steady-state
-- cost (F1/F2/F4-F7 in docs/performance.md) that sim/walk cannot. Does not
-- feed slowStrikes/autoLowSeconds -- adding a measurement must not change
-- when the mod decides it is struggling.
frame = { samples = 0, average = 0, maximum = 0 },
autoLowSeconds = 0, recoveries = 0,
},
log = {}, -- replaced below with the news-writing function
}
-- Player tournament matches are special events: every ordinary EXP award
-- produced by the engine during one of these battles is doubled. The flag is
-- raised only after the bracket launches its player match and is cleared by
-- battle.ended/blackout, so wild battles and ordinary rival challenges are
-- untouched.
mod.hooks:wrap("exp.gain", function(next, c)
local gained = next(c)
if M.tournamentExpActive then
return math.max(1, math.floor((tonumber(gained) or 0) * 2))
end
return gained
end)
local function performanceClockMs()
local value
pcall(function()
if love and love.timer and love.timer.getTime then
value = love.timer.getTime() * 1000
elseif os and os.clock then
value = os.clock() * 1000
end
end)
return value
end
function M:recordPerformance(kind, started)
local finished = performanceClockMs()
if not (started and finished) then return end
local elapsed = math.max(0, finished - started)
local row = self.perf and self.perf[kind]
if not row then return end
row.samples = (row.samples or 0) + 1
row.average = row.samples == 1 and elapsed
or (row.average * 0.9 + elapsed * 0.1)
row.maximum = math.max(row.maximum or 0, elapsed)
local limit = kind == "walking" and 8 or 12
if elapsed > limit then
row.slowStrikes = (row.slowStrikes or 0) + 1
else
row.slowStrikes = math.max(0, (row.slowStrikes or 0) - 1)
end
if row.slowStrikes >= 3 then
self.perf.autoLowSeconds = math.max(self.perf.autoLowSeconds or 0, 20)
row.slowStrikes = 0
end
end
-- The world log is a function the simulation calls for every event; it turns
-- each one into a line of news the player can read ("Matt caught a Pikachu",
-- "Larissa beat Misty"). `news` holds the freshest lines.
M.log = function(rival, event)
return M:addNews(rival, event)
end
-- The newest news line, for the status screen.
function M:latestNews()
local news = self.news
return news[#news] and news[#news].text or "The world is quiet."
end
-- Turn a simulation event into a line of news. Every event the tick logs
-- (catches, levels, evolutions, gym results, duels, trainer battles, ghost
-- hunts, League runs) becomes a sentence the player can read.
function M:addNews(rival, event)
if not (rival and event and type(event) == "table") then return end
local name = rival.name or rival.id or "?"
local line
local kind = event.kind
if event.gym ~= nil then
line = event.won
and (name .. " beat " .. tostring(event.gym.leader or "a Gym Leader") .. "!")
or (name .. " lost to " .. tostring(event.gym.leader or "a Gym Leader") .. ".")
elseif kind == "caught" then
line = name .. " caught a " .. Util.spaced(event.species or "Pokemon") .. "."
elseif kind == "level" then
line = name .. "'s " .. Util.spaced(event.species or "mon")
.. " reached Lv" .. tostring(event.level) .. "."
elseif kind == "evolve" then
line = name .. "'s " .. Util.spaced(event.from or "mon") .. " evolved into "
.. Util.spaced(event.into or "something") .. "!"
elseif kind == "move" then
line = name .. " learned " .. Util.spaced(event.move or "a move") .. "."
elseif kind == "tournament_eliminated" then
line = name .. " was knocked out of a " .. tostring(event.format or "SINGLE"):lower()
.. " tournament by " .. tostring(event.by or "another rival") .. "."
elseif kind == "tournament_won" then
line = name .. " won a " .. tostring(event.format or "SINGLE"):lower() .. " tournament!"
elseif kind == "duel" then
if event.dethroned then
line = name .. " dethroned the Champion!"
else
line = name .. (event.won and " beat " or " lost to ")
.. tostring(event.vs or "a rival") .. " in a duel."
end
elseif kind == "skirmish" then
line = name .. (event.won and " beat " or " lost to ")
.. tostring(event.vs or "a rival") .. " in a skirmish."
elseif kind == "trainer_battle" then
line = name .. (event.won and " beat " or " lost to ")
.. Util.spaced(event.trainer or "a trainer") .. "."
elseif kind == "ghost" then
line = name .. (event.won and " beat " or " lost to ")
.. tostring(event.ghost or "a ghost") .. "."
elseif kind == "title_match" then
-- 4.6.0. Named from the CHALLENGER's side either way, because "X took the
-- title from Y" and "Y held them off" are the same event told once.
local holder = event.holderName or tostring(event.holder or "the Champion")
local challengerName = event.challengerName or tostring(event.challenger or "a rival")
if event.won then
line = challengerName .. " took the title from " .. holder .. "!"
else
line = holder .. " held the title against " .. challengerName .. "."
end
elseif kind == "league" then
if event.won and event.qualified then
-- Cleared the Elite Four while somebody else wears the crown: this is a
-- challenger now, not a champion, and saying so is the point.
line = name .. " cleared the Elite Four and wants a title shot."
elseif event.won then
line = name .. " conquered the League!"
elseif event.stage then
-- Saying WHERE they fell is what makes a repeated failure a story rather
-- than a repeated line. The escalating gate above means this is now a
-- handful of items over a session instead of one every sixteen ticks.
line = name .. " fell at the League, stage " .. tostring(event.stage) .. "."
else
line = name .. " fell at the League."
end
elseif kind == "champion" then
line = tostring(event.text or name)
elseif kind == "bought_balls" then
line = name .. " bought " .. tostring(event.count or 0) .. " Poke Ball(s)."
elseif kind == "tm_found" then
line = name .. " found a TM for " .. Util.spaced(event.move or "a move") .. "."
elseif kind == "tm_bought" then
line = name .. " bought a TM for " .. Util.spaced(event.move or "a move") .. "."
elseif kind == "tm_learned" then
line = name .. " taught " .. Util.spaced(event.move or "a move")
.. " to " .. Util.spaced(event.species or "a Pokemon") .. "."
elseif kind == "hm_obtained" then
line = name .. " obtained the HM for " .. Util.spaced(event.move or "a field move") .. "."
elseif kind == "hm_taught" then
line = name .. " taught " .. Util.spaced(event.move or "an HM")
.. " to " .. Util.spaced(event.species or "a Pokémon") .. "."
elseif kind == "hm_used" then
line = name .. " used " .. Util.spaced(event.move or "an HM")
.. " to reach " .. Util.spaced(event.map or "a new area") .. "."
elseif kind == "hm_hunt" then
line = name .. " is hunting " .. Util.spaced(event.species or "a Pokémon")
.. " that can learn " .. Util.spaced(event.move or "an HM") .. "."
elseif kind == "sold" then
line = name .. " sold " .. tostring(event.count or 0)
.. " duplicate(s) for Y" .. tostring(event.money or 0) .. "."
elseif kind == "candy" then
line = name .. " used a Rare Candy on "
.. Util.spaced(event.species or "a Pokemon") .. "."
elseif kind == "dex" then
line = name .. " filled " .. tostring(event.milestone or 0)
.. " Pokédex entries!"
elseif kind == "hunt" then
line = name .. " is hunting a " .. Util.spaced(event.species or "Pokemon") .. "."
elseif kind == "trade" then
line = name .. " traded a " .. Util.spaced(event.gave or "Pokemon")
.. " for " .. Util.spaced(event.got or "Pokemon")
.. " with " .. tostring(event.with or "a rival") .. "."
elseif kind == "wonder_trade" then
line = name .. " Wonder Traded " .. Util.spaced(event.gave or "a duplicate")
.. " for a shiny " .. Util.spaced(event.got or "Pokemon") .. "!"
elseif kind == "ace" then
line = name .. " made " .. Util.spaced(event.species or "a Pokemon")
.. " their team ace after forming a special bond."
elseif kind == "rematch" then
line = name .. (event.won and " beat " or " lost to ")
.. Util.spaced(event.trainer or "a leader") .. " in a rematch."
elseif kind == "life_transition" then
line = LifePath.transitionHeadline(name, event.from, event.to)
elseif kind == "life_path" then
-- §22/§23: phrased as something the world noticed, never as a system
-- announcement, and rare by construction -- at most two rivals per save
-- can ever produce one of these.
line = LifePath.headline(name, event.path)
elseif kind == "career" then
line = Career.promotionHeadline(name, rival and rival:lifePathId(), event.level)
elseif kind == "sighting" then
-- Already rate-limited and already phrased by Presence.observe; this arm
-- exists so sightings share the one news channel rather than opening a
-- second one the player has to watch.
line = event.note
elseif kind == "camp" then
return -- a camp is something you FIND, not something you are told about
elseif kind == "milestone" then
-- §21/§31: milestones are recorded for every rival, but only the flagged
-- ones are worth interrupting the player for.
if event.notable ~= true then return end
line = Story.milestoneHeadline(name, Story.MILESTONE_BY_ID[event.milestone])
elseif kind == "chapter" then
line = Story.chapterHeadline(name, event.chapter, event.facts)
elseif kind == "team_style" then
-- 1.34.0. Only an actual identity CHANGE reaches here, and identity moves
-- only on accumulated evidence, so this is rare by construction.
line = name .. " is rebuilding their team around a "
.. TeamPlan.label(event.style):lower() .. " strategy."
elseif kind == "relationship" then
-- 1.33.0. Only a DERIVED state transition reaches here, and only through
-- Relationships.headline, so the player is never told the same shift twice
-- in two different sentences. A change with no headline (into NEUTRAL,
-- say) is real but not news.
local other = self.byId[event.with]
line = Relationships.headline(name, other and other.name or "the player",
event.state)
elseif kind == "news" then
line = tostring(event.text)
end
if not line then return end
self.news[#self.news + 1] = { tick = self.sim and self.sim.tick or 0, text = line }
if #self.news > 40 then table.remove(self.news, 1) end
local headline = "WORLD NEWS • " .. line
if self.ticker and self.ticker.text then
self.tickerQueue = self.tickerQueue or {}
local previous = self.tickerQueue[#self.tickerQueue] or self.ticker.text
if previous ~= headline then
self.tickerQueue[#self.tickerQueue + 1] = headline
-- Headlines are transient UI, not history. Keep the newest few so rapid
-- training events cannot create an unbounded, increasingly stale queue.
while #self.tickerQueue > 8 do table.remove(self.tickerQueue, 1) end
end
else
self.ticker = { text = headline, age = 0, duration = 8, offset = 0 }
end
return line
end
-- The map where the intro gauntlet plays out.
-- pret/pokered (and gen1recomp) use OAKS_LAB for the interior lab map and
-- PALLET_TOWN for the outdoor town. The player receives their starter and
-- meets Oak *inside* OAKS_LAB, so that is the primary home for the gauntlet.
-- PALLET_TOWN is kept as a fallback for total conversions that only ship the
-- outdoor map. Gen 2 has neither under these names, so the gauntlet simply
-- does not start there (same as 1.6.0).
-- pret/pokered and Yellow both use OAKS_LAB for the interior. Resolve from
-- the live map table first (graph can lag if build ran on incomplete data).
--
-- 2.7.0 -- GOLD. The comment above used to claim "Gen 2 has neither under
-- these names, so the gauntlet simply does not start there", and the code did
-- not do that: the candidate list held only Kanto maps and the fallback
-- RETURNED "OAKS_LAB" regardless. On Gold that named a map the game does not
-- have, so the mod announced a gauntlet in Oak's Lab, told the player the
-- rivals were waiting there, and sent them to a room that does not exist.
--
-- Gold's equivalents are Elm's lab and New Bark Town. They are candidates in
-- their own right rather than aliases, and the fallback is now nil -- a boot
-- with none of these really has nowhere to hold the gauntlet, and saying so is
-- better than naming a room at random.
local GAUNTLET_LAB_CANDIDATES = {
"OAKS_LAB", "ELMS_LAB", "PALLET_TOWN", "NEW_BARK_TOWN",
}
local function mapExists(id)
if not id then return false end
local g = M.graph
if type(g) == "table" then
if type(g.has) == "function" then
local ok, hit = pcall(g.has, g, id)
if ok and hit then return true end
elseif type(g.nodes) == "table" and g.nodes[id] then
return true
end
end
local maps = M.data and (M.data.maps or M.data.gen2Maps)
if type(maps) == "table" and maps[id] then return true end
local game = M.game
local gmaps = game and game.data and game.data.maps
if type(gmaps) == "table" and gmaps[id] then return true end
return false
end
local function resolveGauntletLab(graph)
for _, id in ipairs(GAUNTLET_LAB_CANDIDATES) do
if mapExists(id) then return id end
if type(graph) == "table" then
if type(graph.has) == "function" then
local ok, hit = pcall(graph.has, graph, id)
if ok and hit then return id end
elseif type(graph.nodes) == "table" and graph.nodes[id] then
return id
end
end
end
-- No lab and no starting town in this boot. nil is the honest answer; every
-- caller below treats it as "there is no gauntlet here".
return nil
end
local function gauntletLabId()
return resolveGauntletLab(M.graph)
end
-- Is the intro gauntlet possible in this game at all? Read by the intro
-- screen, so a boot with no lab never offers a battle it cannot stage.
function M:gauntletLab()
return resolveGauntletLab(M.graph)
end
function M:gauntletPossible()
return self:gauntletLab() ~= nil
end
-- The room's name as a player would say it. Known rooms get their real name;
-- anything else (a conversion, a randomiser) falls back to the spaced map id,
-- which is at least true -- unlike naming somebody else's laboratory.
local LAB_LABELS = {
OAKS_LAB = "Oak's Lab",
ELMS_LAB = "Elm's Lab",
PALLET_TOWN = "Pallet Town",
NEW_BARK_TOWN = "New Bark Town",
}
function M:labLabel(id)
id = id or self:gauntletLab()
if not id then return "the lab" end
return LAB_LABELS[id] or Util.spaced(id)
end
-- Gen 2 only: rival id -> the numeric class constant its overworld object
-- must carry to engage a trainer battle. Filled at registration time.
local GEN2_CLASS = {}
local REGISTERED_TRAINERS = {}
------------------------------------------------------------------------
-- Options
------------------------------------------------------------------------
mod.options:define({
{ key = "rivals", label = "RIVALS", type = "choice", default = "all",
choices = { { "OFF", "off" }, { "TWO", "two" }, { "ALL", "all" } } },
{ key = "encounters", label = "RIVAL DUELS", type = "toggle", default = true },
{ key = "pace", label = "WORLD PACE", type = "choice", default = "normal",
choices = { { "SLOW", "slow" }, { "NORMAL", "normal" }, { "FAST", "fast" } } },
{ key = "performance", label = "WALKING COST", type = "choice", default = "balanced",
choices = { { "LOW", "low" }, { "BALANCED", "balanced" }, { "FULL", "full" } } },
{ key = "relationships", label = "RIVAL BONDS", type = "toggle", default = true },
{ key = "sightings", label = "RIVAL SIGHTINGS", type = "toggle", default = true },
{ key = "life_paths", label = "RIVAL LIFE PATHS", type = "toggle", default = true },
{ key = "news_ticker", label = "NEWS TICKER", type = "toggle", default = true },
{ key = "debug", label = "LK DEBUG", type = "toggle", default = false },
})
local PACE = { slow = 3.0, normal = 1.5, fast = 0.6 }
local function runningOnIOS()
local ok, os = pcall(function()
return love and love.system and love.system.getOS and love.system.getOS()
end)
return ok and (os == "iOS" or os == "IOS")
end
-- Gen 2 tells us so by having no Gen 1 map-script dispatch. We ask the
-- manifest-independent way: mod.game is Gold's Game2 instance, whose data
-- carries gen2Maps. Nothing here changes behaviour except the routes we can
-- take to start a battle and show text.
local function detectGeneration(data)
if data and (data.gen2Maps or data.gen2Trainers) and not data.maps then
return 2
end
return 1
end
local function mapsTable(data)
if not data then return {} end
return data.maps or data.gen2Maps or {}
end
local function activeRoster()
local chosen
pcall(function()
chosen = tonumber(mod.save:get("aiRivalCount"))
end)
return RosterPolicy.active(ROSTER, chosen, mod.options:get("rivals"))
end
------------------------------------------------------------------------
-- Content registration (load time)
------------------------------------------------------------------------
-- GEN 1 registration: one trainer record per rival. `parties` must be
-- non-empty and valid at registration time because the schema checks it, but
-- the party the player actually fights never comes from here -- see the
-- trainer.party hook. The placeholder is the rival's own first starter
-- preference, so even if the hook were somehow bypassed the battle is coherent
-- rather than empty.
-- Every cross-reference in a trainers record is schema-checked against the
-- MERGED tables, so naming a species, portrait or AI class the loaded game
-- does not have is a load error rather than a warning. That is the correct
-- strictness, and it means this mod must resolve each reference against the
-- game in front of it: Yellow, a randomizer, a total conversion and the
-- ROM-free fixture dataset all carry different id sets. A field whose target
-- is missing is OMITTED (the engine's own default covers it); only the party
-- species has no default, so it walks the preference chain and the record is
-- skipped entirely if nothing in it exists.
local function registerGen1Trainers(data)
local versionKey = Version.starterKey(data)
local pokemon = (data and data.pokemon) or {}
local trainers = (data and data.trainers) or {}
local aiClasses = (data and data.ai_classes) or {}
for _, def in ipairs(ROSTER) do
local species = Rival.firstAvailableStarter(def, versionKey, pokemon,
nil, M:starterOpts())
if species then
-- Also recognise an already-merged record after a hot reload. The local
-- guard covers boot + ready in one load; this covers a replaced mod
-- chunk while the engine's content registry remains alive.
if trainers[def.trainerClass] then
REGISTERED_TRAINERS[def.trainerClass] = true
end
local record = {
id = def.trainerClass,
name = def.name,
parties = { { { species = species, level = 5 } } },
baseMoney = def.baseMoney or 50,
}
-- borrow the vanilla class's portrait and battle AI only where they
-- exist; without them the engine draws its default pic and uses the
-- generic AI, which is a coherent trainer, just a plainer one
if trainers[def.basePic] then record.basePic = def.basePic end
if aiClasses[def.aiClass] then record.aiClass = def.aiClass end
if not REGISTERED_TRAINERS[def.trainerClass] then
local ok = Util.guard("trainers:register:" .. def.id, function()
mod.content.trainers:register(def.trainerClass, record)
end)
if ok then REGISTERED_TRAINERS[def.trainerClass] = true end
end
end
end
end
-- GEN 2 registration. Gold's trainers table is shaped differently: it is
-- keyed by CLASS, each class carries a numeric `index` and a `trainers`
-- MEMBER list, and each member row carries its own `party` (Gen 1's `parties`
-- list does not exist). Registering a Gen 1-shaped record is a schema miss,
-- so the whole branch is Gen 2-shaped or nothing.
--
-- Two strategies, per rival:
--
-- * `gen2Shadow` names a vanilla class whose every member's party is
-- replaced in place. The story rival's classes (RIVAL1, RIVAL2) become
-- this rival: no new record is registered, the class keeps its own index,
-- portrait, AI and member ids, and every scripted battle of that class --
-- however the story scripts call it -- is a battle against this rival.
-- * without one, a fresh class is registered past the highest index the
-- game has, so a rival with no vanilla slot to ride still exists as a
-- schema-valid class. The player can meet it but Gold has no way to
-- start a trainer battle against it without the engine patch (docs).
local function registerGen2Trainers(data)
local gen2 = data and (data.gen2Trainers or data.trainers)
local classes = gen2 and gen2.classes
if type(classes) ~= "table" then return end
local maxIndex = 0
for _, cls in pairs(classes) do
if type(cls) == "table" and type(cls.index) == "number" then
maxIndex = math.max(maxIndex, cls.index)
end
end
local fresh = maxIndex
local pokemon = (data and data.pokemon) or {}
for _, def in ipairs(ROSTER) do
local species = Rival.firstAvailableStarter(def, "gen2", pokemon,
nil, M:starterOpts())
if species then
local placeholder = { { species = species, level = 5 } }
local shadow = def.gen2Shadow and classes[def.gen2Shadow]
if shadow then
local members = shadow.trainers
if type(members) == "table" and #members > 0 then
for _, row in ipairs(members) do
row.party = Util.copy(placeholder)
end
if def.baseMoney and not shadow.baseMoney then
shadow.baseMoney = def.baseMoney
end
end
-- the numeric class constant the spawned overworld object carries so
-- the A press engages this class
GEN2_CLASS[def.id] = type(shadow.index) == "number" and shadow.index or 0
else
fresh = fresh + 1
local record = {
id = def.trainerClass,
name = def.name,
index = fresh,
baseMoney = def.baseMoney or 50,
trainers = { {
index = 1,
id = def.id .. "1",
name = def.name,
party = Util.copy(placeholder),
} },
}
local existing = classes[def.trainerClass]
if existing then
REGISTERED_TRAINERS[def.trainerClass] = true
GEN2_CLASS[def.id] = tonumber(existing.index) or fresh
else
GEN2_CLASS[def.id] = fresh
end
if not REGISTERED_TRAINERS[def.trainerClass] then
local ok = Util.guard("trainers:register:" .. def.id, function()
mod.content.trainers:register(def.trainerClass, record)
end)
if ok then REGISTERED_TRAINERS[def.trainerClass] = true end
end
end
end
end
end
local function registerTrainers(data)
if detectGeneration(data) == 2 then
registerGen2Trainers(data)
return
end
registerGen1Trainers(data)
end
-- One shared handler for every Gen 1 map. Dynamic NPCs are only interactable
-- when they carry a text ID whose map has a matching map_scripts.talk entry;
-- world.interacted is notification-only/absent in several engine builds.
local function rivalTalkHandler(game, ow, npc, done)
local npcKey
pcall(function() npcKey = npc and (npc.id or npc.name or (npc.def and npc.def.name)) end)
local rival = M:rivalAtNpc(npcKey) or M:facedRival()
if not rival then if done then done() end return end
if M:gauntletActive() then
local rows = M:talkGauntlet(rival)
if type(rows) == "table" and ow and ow.runner then
ow.runner:run(rows, { npc = npc, onDone = done })
elseif done then done() end
return
end
-- Normal world interaction: show the greeting text box first, then open
-- the action menu once the player advances past it. This keeps dialogue
-- readable and avoids the previous deferred-menu flag getting stuck.
M.game = game or M.game
if M.rivalInteractionOpen then
if done then done() end
return
end
M.rivalInteractionOpen = true
local line = M.pendingLine or (M.dialogue and M.dialogue:greeting(rival)) or (rival.name .. ".")
M.pendingLine = nil
local rows = { { "show_text", tostring(line) } }
local function finishOpen()
-- Script callbacks still run inside the event dispatcher on some builds.
-- Let core.update push the menu from the next idle overworld frame.
M.pendingRivalMenu = rival.id
if done then done() end
end
if ow and ow.runner and type(ow.runner.run) == "function" then
local okRun = pcall(function()
ow.runner:run(rows, { npc = npc, onDone = finishOpen })
end)
if not okRun then
-- Runner refused; fall back to immediate menu after a one-shot ticker.
local flat = tostring(line):gsub("[\n\r\v\f]+", " "):gsub("%s+", " "):match("^%s*(.-)%s*$") or ""
M.ticker = { text = flat, age = 0, duration = 6, offset = 0 }
finishOpen()
end
else
local flat = tostring(line):gsub("[\n\r\v\f]+", " "):gsub("%s+", " "):match("^%s*(.-)%s*$") or ""
M.ticker = { text = flat, age = 0, duration = 6, offset = 0 }
finishOpen()
end
end
-- Register the stable text ID beside every loaded Gen 1 map. Compose
-- registration does not replace vanilla scripts; unsupported conversion maps
-- fail locally and retain the event-hook fallback.
local function registerTalkScripts(data)
if detectGeneration(data) == 2 then
-- Gold reaches a mod-spawned NPC through OverworldController.talkTo, not
-- through map_scripts.talk (which needs a `text` id the Gen 2 interact
-- ladder never consults) and not through world.interacted (which Gold
-- only raises with kind "npc" for objects carrying a cart scriptKey).
-- See src/Gen2Talk.lua for the full reasoning. Registering the handler
-- is free; the router installs itself once a world exists.
Gen2Talk.register("ai_rivals:rivals", function(world, npc)
local key = Gen2Talk.npcKey(npc)
local rival = M:rivalAtNpc(key) or M:facedRival()
if not rival then return false end
local game = (world and world.game) or M.game or mod.game
rivalTalkHandler(game, world, npc, nil)
return true
end, 40)
Gen2Talk.install()
return
end
local ids = { OAKS_LAB = true, PALLET_TOWN = true }
for id in pairs(mapsTable(data) or {}) do ids[id] = true end
M.talkScriptMaps = M.talkScriptMaps or {}
for id in pairs(ids) do
if not M.talkScriptMaps[id] then
local ok = pcall(function() mod.content.map_scripts:register(id, {
priority = -5,
talk = { [TALK_TEXT] = rivalTalkHandler },
}) end)
if ok then M.talkScriptMaps[id] = true end
end
end
end
------------------------------------------------------------------------
-- Roster construction
------------------------------------------------------------------------
function M:seedAffectionGraph()
local seed = tonumber(self.seedValue) or tonumber(self.pathSeed) or self:worldSeed() or 1
for _, rival in ipairs(self.rivals or {}) do
rival.bonds = type(rival.bonds) == "table" and rival.bonds or Relationships.new()
Relationships.seedAffection(rival.bonds, "player", seed, rival.id)
for _, other in ipairs(self.rivals or {}) do
if other.id ~= rival.id then
Relationships.seedAffection(rival.bonds, other.id, seed, rival.id)
end
end
end
end
function M:build(data)
self.data = data
self.generation = detectGeneration(data)
-- which starting set the roster hands out; see src/Version.lua
self.versionKey = Version.starterKey(data)
self.graph = MapGraph.build(mapsTable(data))
-- 4.2.0: build the Kanto trainer phone directory from the loaded ROM data.
-- The directory is derived at runtime, so Red/Blue/Yellow keep their own
-- trainer roster and no ROM-derived trainer data is shipped by the mod.
self.phoneTrainerDefs = Comms.discoverTrainers(data, self.graph, self.generation)
self.byTrainerClass = Comms.indexByTrainerClass(self.phoneTrainerDefs)
self.phoneContactObjects = {}
-- 2.5.0: the phone, absorbed from 1.30. Guarded at every step -- Gen 1 has
-- no Pokegear, so on Red/Blue/Yellow the numbers exist for save
-- compatibility and calls are delivered through the news ticker instead.
self.phone = Phone.new(self)
self.comms = self.comms or Comms.new(nil)
Util.guard("phone", function() self.phone:bootstrapAll() end)
self.dialogue = Dialogue.new(LINES, GYMS,
{ compat = self.compat, save = mod.save,
relationships = function() return self:relationshipsEnabled() end })
-- Resolve the data-file map name lists against the game that is actually
-- loaded, so a name this cache does not have is dropped rather than routed
-- to. Yellow renames a couple of maps; a total conversion renames many.
-- The ladder itself is per generation: Gold's badges are Johto's, so the
-- gen2 section carries its own order/centers/training lists.
local source = self.generation == 2 and GYMS.gen2 or GYMS
local gyms = Util.copy(source)
gyms.centers = self.graph:filterExisting(source.centers)
gyms.training = self.graph:matching(source.trainingPrefixes)
-- the badge ladder is the ENGINE's, not ours: constants.badges is what the
-- player's own trainer card reads, so the rivals climb the same one
local badges = data and data.constants and data.constants.badges
if type(badges) == "table" and #badges > 0 then
local order = {}
for _, entry in ipairs(badges) do
local id = type(entry) == "table" and entry.id or entry
if type(id) == "string" and gyms.byBadge[id] then order[#order + 1] = id end
end
if #order > 0 then gyms.order = order end
end
self.gyms = gyms
local ctx = { data = data, personalities = PERSONALITIES,
graph = self.graph, gyms = gyms,
-- AI.Destination.HEAL and Rival:isAtPokemonCenter/
-- blackoutToNearestPokemonCenter read ctx.healingMaps; the
-- one place that ever built the actual list wrote it onto
-- gyms.centers instead (see Rival.lua's OWN correct read at
-- self.ctx.gyms.centers). The three readers therefore always
-- saw nil/empty -- a rival told to HEAL routed to "wherever
-- it already is", and a blackout had no real Center to fall
-- back to. Same table, both names, until the readers are
-- unified onto gyms.centers directly.
healingMaps = gyms.centers,
versionKey = self.versionKey,
compat = self.compat, save = mod.save,
-- the emergency-party fallback in Rival:battleParty needs the
-- same deal the manager uses, or it would hand out a species
-- from a different permutation
starterSeed = self:worldSeed(), roster = ROSTER,
-- 1.33.0: the relationship gate reaches attemptDuel, which is
-- handed a rival rather than a world view. Refreshed each tick
-- below so toggling the option takes effect immediately.
relationships = self:relationshipsEnabled(),
manager = self }
self.rivalContext = ctx
self.rivals, self.byId = {}, {}
for _, def in ipairs(activeRoster()) do
local rival = Rival.new(def, ctx)
self.rivals[#self.rivals + 1] = rival
self.byId[def.id] = rival
end
self.rivalCount = #self.rivals
self:seedAffectionGraph()
local performance = mod.options:get("performance") or "balanced"
self.sim = Simulation.new({
budget = performance == "low" and 1 or (performance == "full" and 4 or 2),
socialInterval = performance == "low" and 4
or (performance == "full" and 1 or 2),
tickSeconds = PACE[mod.options:get("pace")] or PACE.normal,
})
self.tournaments = Tournaments.new(self)
self.ready = true
end
-- Apply the new-game roster-size answer immediately. Trainer and sprite
-- definitions remain registered for compatibility, but only these live Rival
-- objects are simulated, spawned, saved, or placed in the intro gauntlet.
function M:setRivalCount(value)
local count = RosterPolicy.clamp(value, #ROSTER, 4)
if not self.rivalContext then return false end
local old = self.byId or {}
local rivals, byId = {}, {}
for i = 1, count do
local def = ROSTER[i]
local rival = old[def.id] or Rival.new(def, self.rivalContext)
rivals[#rivals + 1], byId[def.id] = rival, rival
end
for id, rival in pairs(old) do
if not byId[id] then
local npcId = self.spawned and self.spawned[id]
if npcId then pcall(function() mod.world:removeNpc(npcId) end) end
if self.spawned then self.spawned[id] = nil end
if self.companionId == id then self.companionId = nil end
if self.pending and self.pending.id == id then self.pending = nil end
end
end
self.rivals, self.byId, self.rivalCount = rivals, byId, count
if self.gauntlet and type(self.gauntlet.order) == "table" then
local order = {}
for _, rival in ipairs(rivals) do order[#order + 1] = rival.id end
self.gauntlet.order = order
self.gauntlet.index = math.min(tonumber(self.gauntlet.index) or 1, #order)
if self.gauntlet.active then
local lab = self.gauntlet.lab or gauntletLabId()
for _, rival in ipairs(rivals) do
rival.map, rival.x, rival.y = lab, nil, nil
rival.destination, rival.route, rival.routeIndex = nil, nil, 1
rival.path = nil
if #rival.party == 0 then
local species = Rival.firstAvailableStarter(
rival.def, self.versionKey, self.data and self.data.pokemon,
nil, self:starterOpts())
if species then rival:markStarter(rival:addPokemon(species, 5)) end
end
rival:setState("IDLE", "in the lab")
end
end
end
return true
end
-- A brand new rival: put it on its home map with one starter, the way the
-- player starts. Growth is earned from here, never granted.
function M:seed(rival)
local def = rival.def
local home
for _, id in ipairs(homeMapsFor(def)) do
if self.graph:has(id) then home = id break end
end
rival.map = home or next(self.graph.nodes)
rival.x, rival.y = nil, nil
-- Seed a starter only into an EMPTY party. M:load re-seeds on every
-- empty bucket during boot + New Game; an unguarded add used to stack a
-- starter per call, which is how a rival reached the lab with a full
-- party of starters.
if #rival.party == 0 then
local species = Rival.firstAvailableStarter(def, self.versionKey,
self.data and self.data.pokemon,
nil, self:starterOpts())
if species then rival:markStarter(rival:addPokemon(species, 5)) end
end
rival:setState("IDLE", "new")
AI.evaluate(rival, self:worldView())
end
-- ------------------------------------------------------------------
-- The intro gauntlet (Oak's lab)
-- ------------------------------------------------------------------
-- On a new game every rival starts in Oak's lab and battles the player IN
-- TURN, once each, before anyone heads out into Kanto. The player's party
-- is healed between battles, so each fight is the fair starter-vs-starter
-- showdown the moment is supposed to be.
--
-- Rules that keep it honest and removable:
-- * It is a NEW-GAME feature: a save that has no gauntlet bucket (an older
-- save, or one made mid-playthrough) simply plays without one.
-- * Gen 2 has no Oak's lab, so the gate is `does the graph have the map`.
-- * During the gauntlet the world tick is paused: no rival grinds, catches
-- or leaves town until the player has fought them all.
-- * The battles are forced through the talk verb (a plot battle, so the