@pkmn/engine 0.1.0-dev.207fa86a → 0.1.0-dev.2c13d3ec

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +62 -31
  2. package/build/pkg/addon.d.ts +7 -0
  3. package/build/pkg/addon.js +112 -0
  4. package/build/pkg/addon.js.map +1 -0
  5. package/build/pkg/data/layout.json +25 -3
  6. package/build/pkg/data.d.ts +1 -2
  7. package/build/pkg/data.js +3 -5
  8. package/build/pkg/data.js.map +1 -1
  9. package/build/pkg/gen1.d.ts +5 -4
  10. package/build/pkg/gen1.js +47 -31
  11. package/build/pkg/gen1.js.map +1 -1
  12. package/build/pkg/index.d.ts +16 -13
  13. package/build/pkg/index.js +1 -1
  14. package/build/pkg/index.js.map +1 -1
  15. package/build/pkg/protocol.d.ts +4 -2
  16. package/build/pkg/protocol.js +5 -3
  17. package/build/pkg/protocol.js.map +1 -1
  18. package/build/test/display.js +400 -0
  19. package/build/test/display.js.map +1 -0
  20. package/build/tools/debug.js +133 -0
  21. package/build/tools/debug.js.map +1 -0
  22. package/build.zig +56 -51
  23. package/package.json +47 -35
  24. package/src/bin/install-pkmn-engine +68 -36
  25. package/src/bin/pkmn-debug +62 -0
  26. package/src/lib/binding/node.zig +46 -141
  27. package/src/lib/binding/wasm.zig +6 -4
  28. package/src/lib/common/data.zig +11 -11
  29. package/src/lib/common/debug.zig +74 -0
  30. package/src/lib/common/options.zig +12 -3
  31. package/src/lib/common/protocol.zig +239 -178
  32. package/src/lib/common/rng.zig +10 -10
  33. package/src/lib/gen1/README.md +131 -94
  34. package/src/lib/gen1/data/moves.zig +10 -10
  35. package/src/lib/gen1/data/species.zig +2 -2
  36. package/src/lib/gen1/data/types.zig +3 -3
  37. package/src/lib/gen1/data.zig +65 -44
  38. package/src/lib/gen1/helpers.zig +439 -36
  39. package/src/lib/gen1/mechanics.zig +1085 -628
  40. package/src/lib/gen2/data/items.zig +3 -3
  41. package/src/lib/gen2/data/moves.zig +1 -1
  42. package/src/lib/gen2/data/species.zig +1 -1
  43. package/src/lib/gen2/data/types.zig +3 -3
  44. package/src/lib/gen2/data.zig +37 -26
  45. package/src/lib/gen2/helpers.zig +9 -11
  46. package/src/lib/gen2/mechanics.zig +5 -4
  47. package/src/lib/pkmn.zig +68 -9
  48. package/src/test/display/pkmn.html.tmpl +368 -0
@@ -47,7 +47,7 @@ pub const PSRNG = extern struct {
47
47
  }
48
48
 
49
49
  pub fn range(self: *PSRNG, comptime T: type, from: T, to: Bound(T)) T {
50
- return @intCast(T, @as(u64, self.src.next()) * (to - from) / divisor + from);
50
+ return @intCast(@as(u64, self.src.next()) * (to - from) / divisor + from);
51
51
  }
52
52
 
53
53
  pub fn chance(self: *PSRNG, comptime T: type, numerator: T, denominator: Bound(T)) bool {
@@ -72,28 +72,28 @@ test PSRNG {
72
72
  // https://pkmn.cc/pokered/engine/battle/core.asm#L6644-L6693
73
73
  // https://pkmn.cc/pokecrystal/engine/battle/core.asm#L6922-L6938
74
74
  pub const Gen12 = extern struct {
75
- seed: [10]u8,
75
+ seed: [9]u8,
76
76
  index: u8 = 0,
77
77
 
78
78
  comptime {
79
- assert(@sizeOf(Gen12) == 11);
79
+ assert(@sizeOf(Gen12) == 10);
80
80
  }
81
81
 
82
82
  pub fn percent(p: u8) u8 {
83
- return @intCast(u8, (@as(u16, p) * 0xFF) / 100);
83
+ return @intCast((@as(u16, p) * 0xFF) / 100);
84
84
  }
85
85
 
86
86
  pub fn next(self: *Gen12) u8 {
87
87
  const val = 5 *% self.seed[self.index] +% 1;
88
88
  self.seed[self.index] = val;
89
- self.index = (self.index + 1) % 10;
89
+ self.index = (self.index + 1) % 9;
90
90
  return val;
91
91
  }
92
92
  };
93
93
 
94
94
  test Gen12 {
95
- const expected = [_]u8{ 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 31, 56, 81 };
96
- var rng = Gen12{ .seed = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } };
95
+ const expected = [_]u8{ 6, 11, 16, 21, 26, 31, 36, 41, 46, 31, 56, 81 };
96
+ var rng = Gen12{ .seed = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9 } };
97
97
  for (expected) |e| {
98
98
  try expectEqual(e, rng.next());
99
99
  }
@@ -114,7 +114,7 @@ pub const Gen34 = extern struct {
114
114
 
115
115
  pub fn next(self: *Gen34) u16 {
116
116
  self.advance();
117
- return @intCast(u16, self.seed >> 16);
117
+ return @intCast(self.seed >> 16);
118
118
  }
119
119
 
120
120
  pub fn advance(self: *Gen34) void {
@@ -144,7 +144,7 @@ pub const Gen56 = extern struct {
144
144
 
145
145
  pub fn next(self: *Gen56) u32 {
146
146
  self.advance();
147
- return @intCast(u32, self.seed >> 32);
147
+ return @intCast(self.seed >> 32);
148
148
  }
149
149
 
150
150
  pub fn advance(self: *Gen56) void {
@@ -190,7 +190,7 @@ pub fn FixedRNG(comptime gen: comptime_int, comptime len: usize) type {
190
190
 
191
191
  pub fn range(self: *Self, comptime T: type, from: T, to: Bound(T)) T {
192
192
  assert(showdown);
193
- return @intCast(T, @as(u64, self.next()) * (to - from) / divisor + from);
193
+ return @intCast(@as(u64, self.next()) * (to - from) / divisor + from);
194
194
  }
195
195
 
196
196
  pub fn chance(
@@ -28,35 +28,36 @@ list of additional reference [**resources**](#resources).
28
28
 
29
29
  The following information is required to simulate a Generation I Pokémon battle:
30
30
 
31
- | pkmn | Pokémon Red (pret) | Pokémon Showdown |
32
- | ------------------------------------ | ---------------------------------- | -------------------------------------- |
33
- | `battle.seed` | `Random{Add,Sub}` | `battle.seed` |
34
- | `battle.turn` | - | `battle.turn` |
35
- | `battle.last_damage` | `Damage` | `battle.lastDamage` |
36
- | `side.{active,pokemon}` | `PlayerMonNumber`/`BattleMon` | `side.active` |
37
- | `side.team` | `PartyMons` | `side.pokemon` |
38
- | `side.last_used_move` | `PlayerUsedMove` | `pokemon.lastMove` |
39
- | `side.last_selected_move` | `PlayerSelectedMove` | `side.lastSelectedMove` |
40
- | `battle.last_selected_indexes` | `PlayerMoveListIndex` | `side.lastMove` |
41
- | `side.order` | - | `pokemon.position` |
42
- | `{pokemon,active}.moves` | `{party,battle}_struct.{Moves,PP}` | `pokemon.{baseMoveSlots,moveSlots}` |
43
- | `pokemon.hp` | `{party,battle}_struct.HP` | `pokemon.hp` |
44
- | `{pokemon,active}.status` | `{party,battle}_struct.Status` | `pokemon.status` |
45
- | `{pokemon,active}.level` | `PlayerMonUnmodifiedLevel` | `pokemon.level` |
46
- | `pokemon.species` | `party_struct.Species` | `pokemon.baseSpecies` |
47
- | `pokemon.stats` | `box_struct.Stats` | `pokemon.baseStoredStats` |
48
- | `active.stats` | `battle_struct.Stats` | `pokemon.modifiedStats` |
49
- | `volatiles.transform` | `PlayerMonUnmodified*` | `pokemon.storedStats` |
50
- | `active.species` | `battle_struct.Species` | `pokemon.species` |
51
- | `{pokemon,active}.types` | `{party,battle}_struct.Type` | `pokemon.types` |
52
- | `active.boosts` | `PlayerMon*Mod` | `pokemon.boosts` |
53
- | `active.volatiles` | `PlayerBattleStatus{1,2,3}` | `pokemon.volatiles` |
54
- | `volatiles.state` | `PlayerBideAccumulatedDamage` | `volatiles.bide.totalDamage` |
55
- | `volatiles.attacks` | `PlayerNumAttacksLeft` | `volatiles.{bide,lockedmove}.duration` |
56
- | `volatiles.confusion` | `PlayerConfusedCounter` | `volatiles.confusion.duration` |
57
- | `volatiles.toxic` | `PlayerToxicCounter` | `volatiles.residualdmg.counter` |
58
- | `volatiles.substitute` | `PlayerSubstituteHP` | `volatiles.substitute.hp` |
59
- | `volatiles.disabled_{move,duration}` | `PlayerDisabledMove{,Number}` | `volatiles.disable.{move,time}` |
31
+ | pkmn | Pokémon Red (pret) | Pokémon Showdown |
32
+ | --------------------------------------- | ---------------------------------- | -------------------------------------- |
33
+ | `battle.seed` | `Random{Add,Sub}` | `battle.seed` |
34
+ | `battle.turn` | - | `battle.turn` |
35
+ | `battle.last_damage` | `Damage` | `battle.lastDamage` |
36
+ | `side.{active,pokemon}` | `PlayerMonNumber`/`BattleMon` | `side.active` |
37
+ | `side.team` | `PartyMons` | `side.pokemon` |
38
+ | `side.last_used_move` | `PlayerUsedMove` | `pokemon.lastMove` |
39
+ | `side.last_selected_move` | `PlayerSelectedMove` | `side.lastSelectedMove` |
40
+ | `battle.last_moves.{p1,p2}_index` | `PlayerMoveListIndex` | - |
41
+ | `battle.last_moves.{p1,p2}_counterable` | - | `side.lastMove` |
42
+ | `side.order` | - | `pokemon.position` |
43
+ | `{pokemon,active}.moves` | `{party,battle}_struct.{Moves,PP}` | `pokemon.{baseMoveSlots,moveSlots}` |
44
+ | `pokemon.hp` | `{party,battle}_struct.HP` | `pokemon.hp` |
45
+ | `{pokemon,active}.status` | `{party,battle}_struct.Status` | `pokemon.status` |
46
+ | `{pokemon,active}.level` | `PlayerMonUnmodifiedLevel` | `pokemon.level` |
47
+ | `pokemon.species` | `party_struct.Species` | `pokemon.baseSpecies` |
48
+ | `pokemon.stats` | `box_struct.Stats` | `pokemon.baseStoredStats` |
49
+ | `active.stats` | `battle_struct.Stats` | `pokemon.modifiedStats` |
50
+ | `volatiles.transform` | `PlayerMonUnmodified*` | `pokemon.storedStats` |
51
+ | `active.species` | `battle_struct.Species` | `pokemon.species` |
52
+ | `{pokemon,active}.types` | `{party,battle}_struct.Type` | `pokemon.types` |
53
+ | `active.boosts` | `PlayerMon*Mod` | `pokemon.boosts` |
54
+ | `active.volatiles` | `PlayerBattleStatus{1,2,3}` | `pokemon.volatiles` |
55
+ | `volatiles.state` | `PlayerBideAccumulatedDamage` | `volatiles.bide.totalDamage` |
56
+ | `volatiles.attacks` | `PlayerNumAttacksLeft` | `volatiles.{bide,lockedmove}.duration` |
57
+ | `volatiles.confusion` | `PlayerConfusedCounter` | `volatiles.confusion.duration` |
58
+ | `volatiles.toxic` | `PlayerToxicCounter` | `volatiles.residualdmg.counter` |
59
+ | `volatiles.substitute` | `PlayerSubstituteHP` | `volatiles.substitute.hp` |
60
+ | `volatiles.disabled_{move,duration}` | `PlayerDisabledMove{,Number}` | `volatiles.disable.{move,time}` |
60
61
 
61
62
  - Pokémon Showdown [does not implement the correct Generation I RNG](#rng) and as such its `seed` is
62
63
  different
@@ -68,6 +69,9 @@ The following information is required to simulate a Generation I Pokémon battle
68
69
  Counter and is not set and cleared in the correct locations. `Pokemon.lastMove` matches
69
70
  `PlayerUsedMove` more often so is what the engine attempts to model, despite the implications for
70
71
  Counter)
72
+ - `battle.last_moves` doesn't map precisely to cartridge concepts because it is used to track desyncs
73
+ which instead are represented on the cartridge as discrepancies between the two separate battle states
74
+ that exist in the link battle.
71
75
  - Pokémon Showdown does not implement the [partial-trapping move Mirror Move
72
76
  glitch](https://glitchcity.wiki/Partial_trapping_move_Mirror_Move_link_battle_glitch) and as such
73
77
  does not need to keep track of a player's last selected move index (`PlayerMoveListIndex`)
@@ -98,8 +102,8 @@ The following information is required to simulate a Generation I Pokémon battle
98
102
  store general information about the battle. Unlike in Pokémon Showdown there is a distinction
99
103
  between the data structure for the "active" Pokémon and its party members (see below).
100
104
 
101
- Due to layout constraints, the index of the last selected move for a side is stored in what would
102
- otherwise be the padding bytes of`Battle` (the `last_selected_indexes` field) instead of in `Side`.
105
+ Due to layout constraints, details about the last moves for a side are stored in what would
106
+ otherwise be the padding bytes of`Battle` (the `last_moves` field) instead of in `Side`.
103
107
 
104
108
  ### `Pokemon` / `ActivePokemon`
105
109
 
@@ -198,7 +202,7 @@ above, PP information isn't strictly necessary in Generation I so is dropped. `M
198
202
  a special sentinel value to indicate `null`. Move PP data is only included for testing and is not
199
203
  necessary for the actual engine implementation.
200
204
 
201
- In order to workaround various [Pokémon Showdown bugs](#bugs) and to support its protocol in traces,
205
+ In order to workaround various [Pokémon Showdown bugs](#bugs) and to support its protocol in logs,
202
206
  additional information is stored in `Move.Data` (`targets`) about what Pokémon Showdown believes the
203
207
  `Move.Target` to be (despite the concept of targeting not existing until Generation III when Double
204
208
  battles were introduced). More specifically, a move's "targeting" status is required in various
@@ -282,9 +286,9 @@ padding](https://en.wikipedia.org/wiki/Data_structure_alignment) and
282
286
  - the active Pokémon's level and current and max HP can always be referred to the `Pokemon`
283
287
  struct
284
288
  - **`Side`**: `ActivePokemon` + 6× `Pokemon` + active (`3`) + last used (`8`) + last selected
285
- (`8`)
289
+ (`8`) + counterable (`1`) + last move index (`3`)
286
290
  - `order` does not need to be stored as the party can always be rearranged as switches occur
287
- - **`Battle`**: 6× `Side` + seed (10× `8` + `4`) + turn (`10`) + last damage (`10`)
291
+ - **`Battle`**: 6× `Side` + seed (9× `8` + `4`) + turn (`10`) + last damage (`10`)
288
292
  - **`Type.CHART`**: attacking types (`15`) × defending types (`15`) × effectiveness (`2`)[^2]
289
293
  - **`Type.PRECEDENCE`**: 29× attacking type (`4`) + defending type (`4`) pairs
290
294
  - **`Moves.DATA`**: 165× base power (`6`) + effect (`7`) + accuracy (`4`) + type (`4`) + target
@@ -295,8 +299,8 @@ padding](https://en.wikipedia.org/wiki/Data_structure_alignment) and
295
299
  | ----------------- | ----------- | ------------ | -------- |
296
300
  | `Pokemon` | 192 | 147 | 30.6% |
297
301
  | `ActivePokemon` | 256 | 202 | 26.7% |
298
- | `Side` | 1472 | 1056 | 33.5% |
299
- | `Battle` | 3088 | 2216 | 33.7% |
302
+ | `Side` | 1472 | 1107 | 33.0% |
303
+ | `Battle` | 3088 | 2310 | 33.7% |
300
304
  | `Type.CHART` | 1800 | 450 | 300.0% |
301
305
  | `Type.PRECEDENCE` | 232 | 232 | 0.0% |
302
306
  | `Moves.DATA` | 5280 | 3960 | 33.3% |
@@ -331,32 +335,37 @@ does not produce an equivalent to Pokémon Showdown's `|request|` protocol messa
331
335
  must be gleaned through the `Battle` state). Useful size and offset information can be found in
332
336
  the [`layout.json`](../../data/layout.json) which exists to simplify writing driver code.
333
337
 
334
- Documentation of the wire protocol used for logging traces when `-Dtrace` is enabled can be found in
335
- [PROTOCOL.md](../../../docs/PROTOCOL.md).
338
+ Documentation of the wire protocol used for protocol message logging when `-Dlog` is enabled can be
339
+ found in [PROTOCOL.md](../../../docs/PROTOCOL.md). Note that the
340
+ [`pkmn-debug`](../../../README.md#pkmn-debug) tool exists to display the binary protocol and battle
341
+ data in the browser for ease of debugging.
336
342
 
337
343
  ### `Battle`
338
344
 
339
- | Start | End | Data | Description |
340
- | ------- | ------- | ----------------------- | ------------------------------------------------------- |
341
- | 0 | 184 | [`sides[0]`](#side) | Player 1's side |
342
- | 184 | 368 | [`sides[1]`](#side) | Player 2's side |
343
- | 368 | 370 | `turn` | The current turn number |
344
- | 370 | 372 | `last_damage` | The last damage dealt by either side |
345
- | 372 | 373-376 | `last_selected_indexes` | The slot index of the last selected moves for each side |
346
- | 373-376 | 384 | `rng` | The RNG state |
345
+ | Start | End | Data | Description |
346
+ | ------- | ------- | ------------------- | ------------------------------------------------------- |
347
+ | 0 | 184 | [`sides[0]`](#side) | Player 1's side |
348
+ | 184 | 368 | [`sides[1]`](#side) | Player 2's side |
349
+ | 368 | 370 | `turn` | The current turn number |
350
+ | 370 | 372 | `last_damage` | The last damage dealt by either side |
351
+ | 372 | 374-376 | `last_moves` | The slot index of the last selected moves for each side |
352
+ | 374-376 | 384 | `rng` | The RNG state |
347
353
 
348
354
  - the current `turn` is 2 bytes, written in native-endianness
349
- - `last_selected_indexes` layout depends on whether or not Pokémon Showdown compatibility mode is
350
- enabled (`-Dshowdown`). In either case it stores a move "slot", where 0 is used as an empty value and
351
- 1-4 represent actual moves:
352
- - if `showdown` is enabled bytes 372 and 373 are used to store the last selected move index of
353
- `side[0]` and bytes 374 and 375 store the last selected move index of `side[1]`
354
- - otherwise byte 372 stores the last selected move index of `side[0]` in its first 4 bits and
355
- `side[1]`'s in its second 4 bits
355
+ - `last_moves` layout depends on whether or not Pokémon Showdown compatibility mode is enabled
356
+ (`-Dshowdown`). In either case it stores the last selected move index and last executed move for
357
+ each player (required to detect desyncs). In the case of the move index, 0 is used as an empty
358
+ value and 1-4 represent actual moves:
359
+ - if `showdown` is enabled byte 372 is used to store the last selected move index of `side[0]` and
360
+ byte 373 is used to store whether or not the side's last executed move would have been considered
361
+ "counterable"; and bytes 374 and 375 store the same information for `side[1]`
362
+ - otherwise the first 4 bits of byte 372 stores the last selected move index of `side[0]` and the
363
+ next 4 bits store whether that side's last executed move would have been considered
364
+ "counterable", with the same information for `side[1]`'s being stored in the second byte
356
365
  - the `rng` depends on whether or not Pokémon Showdown compatibility mode is enabled (`-Dshowdown`):
357
366
  - if `showdown` is enabled, the RNG state begins on byte 376 and consists of a 64-bit seed,
358
367
  written in native-endianness
359
- - otherwise the RNG state begins on byte 373 and consists of the 10 bytes of the seed followed by
368
+ - otherwise the RNG state begins on byte 374 and consists of the 9 bytes of the seed followed by
360
369
  the index pointing to which byte of the seed is currently being used
361
370
 
362
371
  ### `Side`
@@ -467,7 +476,7 @@ Documentation of the wire protocol used for logging traces when `-Dtrace` is ena
467
476
 
468
477
  In addition to its alternative [RNG semantics](#rng), Pokémon Showdown's implementation of the first
469
478
  generation of Pokémon contains a number bugs, [many of which are known and have been documented on
470
- Smogon](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3524844/#post-5933177):
479
+ Smogon](https://www.smogon.com/forums/posts/5933177/show):
471
480
 
472
481
  - moves on Pokémon Showdown can do 0 damage instead of failing or causing a [division-by-zero
473
482
  freeze](https://pkmn.cc/bulba-glitch-1#Division_by_0).
@@ -476,12 +485,21 @@ Smogon](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3
476
485
  - Confusion self-hits use the wrong damage formula resulting in off-by-one errors (and also fail to
477
486
  account for an opponent's Reflect). Furthermore, the confusion self-hit damage will erroneously be
478
487
  inflicted to the confused user's substitute if the confused user had been attempting to use a
479
- self-targeting move.
488
+ self-targeting move. Finally, Pokémon Showdown erroneously considers the *uncapped* self-hit
489
+ damage for the purposes of tracking the battle's last damage.
480
490
 
481
491
  Beyond the general bugs listed above, several move effects are implemented incorrectly by Pokémon
482
492
  Showdown. Some of these moves are [too fundamentally broken to be implemented](#unimplementable) by
483
493
  the pkmn engine, but the following moves have their broken behavior preserved in `-Dshowdown` mode:
484
494
 
495
+ - **Bide**: Bide's damage can overflow if OHKO moves are involved because OHKO moves work by setting
496
+ the damage to 65535 - Pokémon Showdown doesn't implement this overflow and instead lets Bide's
497
+ damage grow unbounded. Additionally, if the opponent faints after Bide inflicts damage on Pokémon
498
+ Showdown residual damage incorrectly still gets applied to Bide's user.
499
+ - **Counter**: On Pokémon Showdown choices made while sleeping (which should not have been
500
+ registered) can erroneously cause Counter to trigger Desync Clause Mod behavior. Additionally,
501
+ because Pokémon Showdown neglects to zero the last battle damage if a move misses due to immunity
502
+ or invulnerability Counter will occasionally work on Pokémon Showdown when it should fail.
485
503
  - **Leech Seed**: Leech Seed fails to heal its source side if a seeded target faints due to
486
504
  recoil/crash damage on Pokémon Showdown.
487
505
  - **Pay Day**: Pay Day should still scatter coins if it hits (but doesn't break) and opponent's
@@ -490,9 +508,17 @@ the pkmn engine, but the following moves have their broken behavior preserved in
490
508
  instead cleared in Pokémon Showdown's "residual" phase, meaning the flinch status gets erroneously
491
509
  preserved across fainting (as fainting triggers Pokémon Showdown's "instaswitch" behavior which
492
510
  skips end-of-turn residuals).
511
+ - **Rage**: Rage boosts should still result in burn/paralysis [stat modification
512
+ errors](https://pkmn.cc/bulba-glitch-1#Stat_modification_errors) but don't on Pokémon Showdown.
513
+ Furthermore, Pokémon Showdown only builds Rage for Disable/Explosion (hit/miss) when attacking
514
+ into a Substitute instead of all moves. Pokémon Showdown also implements the [Rage and Thrash /
515
+ Petal Dance accuracy bug]( https://www.youtube.com/watch?v=NC5gbJeExbs) incorrectly, as the
516
+ accuracy only gets written when the volatile is present which can lead to incorrect accuracy
517
+ values on turns where Rage is used on the same turn as a move which modifies accuracy or evasion.
493
518
  - **Thrash** / **Petal Dance**: once a Pokémon is locked into a thrashing move they will lose all
494
519
  speed ties on Pokémon Showdown (due to the fact that if they win the speed tie their action will
495
- then get "changed" and inserted back into the queue after their opponent's action).
520
+ then get "changed" and inserted back into the queue after their opponent's action). Pokémon
521
+ Showdown also implements accuracy incorrectly, as covered above.
496
522
  - **Freeze** / **Sleep**: Pokémon Showdown requires a move to be selected when a Pokémon is frozen
497
523
  or sleeping and uses that in the event that the status is removed while on the cartridge no
498
524
  selection is possible and no turn exists for the thawed/woken Pokémon to act except in the case of
@@ -508,14 +534,21 @@ the pkmn engine, but the following moves have their broken behavior preserved in
508
534
  implement by Pokémon Showdown.
509
535
  - **Roar** / **Whirlwind**: these moves can miss on Pokémon Showdown (and advance the RNG when
510
536
  checking) which is incorrect (these moves should always fail, but do not check accuracy or advance
511
- the RNG).
537
+ the RNG). More importantly, these moves should *not* cause the tracked last battle damage to be
538
+ zeroed, but on Pokémon Showdown they do.
512
539
  - **Substitute**: in addition to the [Substitute + Confusion
513
540
  glitch](https://pkmn.cc/bulba-glitch-1#Substitute_.2B_Confusion_glitch) not being implemented
514
541
  correctly (covered above), the [Substitute 1/4
515
542
  glitch](https://glitchcity.wiki/Substitute_%C2%BC_HP_glitch) also fails in many cases due to
516
543
  Pokémon Showdown implementing the health check based on floating point division instead of integer
517
544
  divison like on the cartridge (meaning the Substitute 1/4 glitch will only occur if the Pokémon's
518
- maximum HP is evenly divisible by 4).
545
+ maximum HP is evenly divisible by 4). Substitute also incorrectly blocks Dream Eater on
546
+ Pokémon Showdown and will incorrectly still heal 1 HP for any draining moves if the attack does 0
547
+ damage. Finally, Pokémon Showdown uses a `subFainted` field to track whether a Substitute was
548
+ broken in order to know when to nullify a move's effect, only it doesn't get cleared at the end of
549
+ the turn and can result in incorrect behavior on subsequent turns with the moves Mirror Move and
550
+ Metronome that invoke `runMove` (which is where `subFainted` gets cleared) on the user but skips
551
+ calling it for the eventual true target.
519
552
 
520
553
  In addition to numerous cases where Pokémon Showdown uses the wrong type of message (e.g. `|-fail`
521
554
  vs. `|-miss|` vs. `|-immune|`, e.g. in the case of Leech Seed) which are not documented here, Pokémon
@@ -549,7 +582,7 @@ called out in the `|rule|` section at the beginning of a battle's log):
549
582
  `|rule|` section** in Generation I (or II) as the actual order of switches here does not have
550
583
  competitive implications like it does in Generation III, but it is still contrary to how the games
551
584
  work where the [host (Player 1)'s Pokemon would switch
552
- first](https://www.smogon.com/forums/threads/gen-3-on-ps-final-fixes.3527268/post-5989318).
585
+ first](https://www.smogon.com/forums/posts/5989318/show).
553
586
 
554
587
  Pokémon Showdown enforces several clauses *before* the battle: **Cleric Clause** (all Pokémon must
555
588
  have full HP and PP, and not have any status conditions prior to the battle), **Stat Tradeback
@@ -570,13 +603,12 @@ left up to a client to support.
570
603
 
571
604
  Numerous moves on Pokémon Showdown are broken not simply due to local issues in the implementation
572
605
  of their effects but instead due to **global issues** related to fundamental mechanics such as
573
- [broken move
574
- selection](https://www.smogon.com/forums/threads/rby-fight-button-simulation-improvements-fix-partial-trapping-improve-counter.3673280/#post-8655897),
575
- using move name instead of slot to determine move identity, implementing volatile statuses
576
- incorrectly or not understanding how moves which call other moves work means that it isn't possible
577
- to completely implement Pokémon Showdown's behavior for the following moves (the pkmn engine
578
- attempts to reproduce as much of the behavior that can be reproduced without making data structure
579
- changes or dramatically deviating from the correct control flow):
606
+ [broken move selection](https://www.smogon.com/forums/posts/8655897/show), using move name instead
607
+ of slot to determine move identity, implementing volatile statuses incorrectly or not understanding
608
+ how moves which call other moves work means that it isn't possible to completely implement Pokémon
609
+ Showdown's behavior for the following moves (the pkmn engine attempts to reproduce as much of the
610
+ behavior that can be reproduced without making data structure changes or dramatically deviating from
611
+ the correct control flow):
580
612
 
581
613
  - **Wrap**: Binding moves like Wrap are implemented on Pokémon Showdown with an artificial
582
614
  `partialtrappinglock` volatile as opposed to how it works on the cartridge which simply relies on
@@ -586,9 +618,9 @@ changes or dramatically deviating from the correct control flow):
586
618
  still gets a turn under the [trapping sleep
587
619
  glitch](https://glitchcity.wiki/Trapping_move_and_sleep_glitch), Wrap does 0 damage against
588
620
  Ghost-type Pokémon instead of properly respecting immunity, and binding effects are handled in the
589
- wrong order in the code.
590
- - **Counter**: On Pokémon Showdown choices made while sleeping (which should not have been
591
- registered) can erroneously cause Counter to trigger Desync Clause Mod behavior.
621
+ wrong order in the code which results in either out of order messaging or, more consequentially,
622
+ Pokémon using Rage/Bide or Thrashing/Charging moves being incorrectly forced to skip a turn when
623
+ the Pokémon using the Binding move switches.
592
624
  - **Mimic**: Pokémon Showdown checks that the user of Mimic has Mimic in one of their move slots,
593
625
  which means Mimic legally called via Metronome or Mirror Move will only work if the user also has
594
626
  Mimic (and the moved mimicked by Mimic called via Metronome / Mirror Move will erroneously
@@ -596,19 +628,27 @@ changes or dramatically deviating from the correct control flow):
596
628
  because Pokémon Showdown deducts PP based on a move's name instead of slot, if Mimic copies a move
597
629
  the Pokémon already knows, PP deduction for using either the original move of the mimicked move
598
630
  will instead deduct PP for whichever appears at the lower move slot index and the PP will be
599
- allowed to go negative (effectively allowing for infinite PP use).
600
- - **Mirror Move**: Binding moves misbehave when used via Mirror Move (though Pokémon Showdown has
601
- its own weird behavior and does not implement the [partial trapping move Mirror Move
631
+ allowed to go negative (effectively allowing for infinite PP use). Pokémon Showdown also doesn't
632
+ deduct PP from using Transform if it was copied by Mimic.
633
+ - **Mirror Move**: As covered above, both Substitute and Binding moves misbehave when used via
634
+ Mirror Move (though Pokémon Showdown has its own weird behavior and does not implement the
635
+ [partial trapping move Mirror Move
602
636
  glitch](https://glitchcity.wiki/Partial_trapping_move_Mirror_Move_link_battle_glitch) that exists
603
- on the cartridge).
604
- - **Metronome**: In addition to the issues with binding moves, Metronome and Mirror Move cannot
605
- mutually call each other more than 3 times in a row without causing the Pokémon Showdown simulator
606
- to crash due to defensive safety checks that do not exist on the cartridge.
607
- - **Transform**: Transform screws up the effect of Disable, because on Pokémon Showdown, Disable
637
+ on the cartridge). Additionally, Pokémon Showdown sets the last used move every turn a Pokémon is
638
+ Thrashing instead of just on the turn it is actually selected meaning Mirror Move will sometimes
639
+ successfully mirror a Thrashing move when it should fail. Finally, if Mirror Move copies
640
+ Struggle it should not deduct PP but on Pokémon Showdown it does.
641
+ - **Metronome**: In addition to the issues with binding moves and Substitute, Metronome and Mirror
642
+ Move cannot mutually call each other more than 3 times in a row without causing the Pokémon
643
+ Showdown simulator to crash due to defensive safety checks that do not exist on the cartridge.
644
+ - **Transform**: Transform screws up the effect of Disable, because on Pokémon Showdown, Disable
608
645
  prevents moves of a given *name* from being used (e.g. "Water Gun") as opposed to moves in a
609
646
  specific *slot* (e.g. the 2nd move slot), and a Pokémon's moves can change after Transform (this
610
- is not an issue with Disable + Mimic because Mimic happens to replace the same slot). Furthermore,
611
- transforming and then using Mirror Move / Metronome can result in [glitchy behavior and
647
+ is not an issue with Disable + Mimic because Mimic happens to replace the same slot). Transform
648
+ also has a bad interaction with Pokémon Showdown's buggy Haze implementation, as Haze on Pokémon
649
+ Showdown does not copy unmodified stats, leaving the Transformed Pokémon with incorrect stats.
650
+ Furthermore, transforming and then using Mirror Move / Metronome can result in [glitchy behavior
651
+ and
612
652
  softlocks](https://pkmn.cc/bulba/Transform_glitches#Transform_.2B_Mirror_Move.2FMetronome_PP_error)
613
653
  which Pokémon Showdown does not implement.
614
654
 
@@ -627,7 +667,7 @@ the pkmn engine aims to be as compatible with Pokémon Showdown as possible when
627
667
  compatibility mode, the implications of these differences are outlined below:
628
668
 
629
669
  - **RNG**: Pokémon Showdown uses the RNG from Generation V & VI in every generation, despite
630
- the seeds and algorithm being different. Pokémon Red uses a simple 8-bit RNG with 10 distinct
670
+ the seeds and algorithm being different. Pokémon Red uses a simple 8-bit RNG with 9 distinct
631
671
  seeds generated when the link connection is established, whereas Pokémon Showdown uses a 64-bit
632
672
  RNG with a 32-bit output.
633
673
  - **Algorithm**: As detailed in the table below, the algorithm used by Pokémon Showdown in the
@@ -662,13 +702,13 @@ compatibility mode, the implications of these differences are outlined below:
662
702
  when they are not relevant:
663
703
  - Roar / Whirlwind roll to hit and can "miss" as opposed to simply failing
664
704
 
665
- Finally, the **initial 10-byte seed for link battles on Pokémon Red cannot include bytes larger than
705
+ Finally, the **initial 9-byte seed for link battles on Pokémon Red cannot include bytes larger than
666
706
  the `SERIAL_PREAMBLE_BYTE`**, so must be in the range $\left[0, 252\right]$. This has implications
667
- on the first 10 random numbers generated during the battle and has [**non-trivial competitive
668
- implications**](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3524844/page-16#post-9068411)
669
- (at the start of the battle move effects become more likely, the ["1/256-miss"
670
- glitch](https://glitchcity.wiki/1/256_miss_glitch) cannot happen, Player 1 is more likely to win
671
- speed ties, etc) that Pokémon Showdown cannot replicate due to everything described above.
707
+ on the first 9 random numbers generated during the battle and has [**non-trivial competitive
708
+ implications**](https://www.smogon.com/forums/posts/9068411/show) (at the start of the battle move
709
+ effects become more likely, the ["1/256-miss" glitch](https://glitchcity.wiki/1/256_miss_glitch)
710
+ cannot happen, Player 1 is more likely to win speed ties, etc) that Pokémon Showdown cannot
711
+ replicate due to everything described above.
672
712
 
673
713
  All of places in the link battle code where randomness is required are outlined below:
674
714
 
@@ -688,7 +728,7 @@ All of places in the link battle code where randomness is required are outlined
688
728
  | **Paralysis** (full) | `beforeMove` | Trigger if $X < 63$ |
689
729
  | **Poison** (chance) | `Effects.poison` | Trigger if $X < 52$ ($103$ for Smog / Sludge) |
690
730
  | **Sleep** (duration) | `Effects.sleep` | <dl><dt>Pokémon Red</dt><dd>Continue generating until $X \land 7 \neq 0$</dd><dt>Pokémon Showdown</dt><dd>Generate $X \in \left[1, 8\right)$</dd></dl> |
691
- | **Bide** (duration) | `Effects.bide` | <dl><dt>Pokémon Red</dt><dd>Last for $\left(X \land 1\right) + 2$ turns</dd><dt>Pokémon Showdown</dt><dd>Last for $X \in \left[2, 4\right)$ turns</dd></dl> |
731
+ | **Bide** (duration) | `Effects.bide` | <dl><dt>Pokémon Red</dt><dd>Last for $\left(X \land 1\right) + 2$ turns</dd><dt>Pokémon Showdown</dt><dd>Last for $X \in \left[2, 4\right)$ turns</dd></dl> |
692
732
  | **Disable** (move) | `Effects.disable` | <dl><dt>Pokémon Red</dt><dd>Continue generating until $X \land 3$ is the index of a non-empty move slot</dd><dt>Pokémon Showdown</dt><dd>Generate $X \in \left[0, \|movesSlots\|\right)$</dd></dl> |
693
733
  | **Disable** (duration) | `Effects.disable` | <dl><dt>Pokémon Red</dt><dd>Last for $\left(X \land 7\right) + 1$ turns</dd><dt>Pokémon Showdown</dt><dd>Last for $X \in \left[1, 9\right)$ turns</dd></dl> |
694
734
  | **Metronome** (move) | `metronome` | <dl><dt>Pokémon Red</dt><dd>Continue generating until $X$ matches the index of a move which is not Struggle or Metronome</dd><dt>Pokémon Showdown</dt><dd>Generate $X \in \left[0, \|validMoves\|\right)$, where $validMoves$ is ordered set of moves with Struggle and Metronome removed <i>(indexes of moves > Metronome will be shifted down)</i></dd></dl> |
@@ -696,7 +736,7 @@ All of places in the link battle code where randomness is required are outlined
696
736
  | **Psywave** (power) | `specialDamage` | <dl><dt>Pokémon Red</dt><dd>Continue generating until $X < {3\over2} \cdot level$</dd><dt>Pokémon Showdown</dt><dd>Generate $X \in \left[0, {3\over2} \cdot level\right)$</dd></dl> |
697
737
  | **Thrash** (rampage) | `Effects.thrash` | <dl><dt>Pokémon Red</dt><dd>Last for $\left(X \land 1\right) + 2$ turns</dd><dt>Pokémon Showdown</dt><dd>Last for $X \in \left[2, 4\right)$ turns</dd></dl> |
698
738
  | **Thrash** (confusion) | `beforeMove` | <dl><dt>Pokémon Red</dt><dd>Last for $\left(X \land 3\right) + 2$ turns</dd><dt>Pokémon Showdown</dt><dd>Last for $X \in \left[2, 6\right)$ turns</dd></dl> |
699
- | **Binding** (duration) | `Effects.binding` | <dl><dt>Pokémon Red</dt><dd>Last for $\left(X \land 3\right) + 1$ further turns if $\left(X \land 3\right) < 2$<br /> otherwise last for $\left(Y \land 3\right) + 1$ further turns (reroll)</dd><dt>Pokémon Showdown</dt><dd>Last for $X \in \{2, 2, 3, 3, 4, 5\} - 1$ further turns</dd></dl> |
739
+ | **Binding** (duration) | `Effects.binding` | <dl><dt>Pokémon Red</dt><dd>Last for $\left(X \land 3\right) + 1$ further turns if $\left(X \land 3\right) < 2$<br /> otherwise last for $\left(Y \land 3\right) + 1$ further turns (reroll)</dd><dt>Pokémon Showdown</dt><dd>Last for $X \in \{2, 2, 2, 3, 3, 3, 4, 5 \} - 1$ further turns</dd></dl> |
700
740
  | **Multi-Hit** (hits) | `Effects.multiHit` | *Ibid.* |
701
741
  | **Unboost** (chance) | `Effects.unboost` | Trigger if $X < 85$ |
702
742
 
@@ -767,11 +807,8 @@ The pkmn engine attempts to adhere to certain naming conventions:
767
807
  ## Resources
768
808
 
769
809
  - [pret/pokered](https://github.com/pret/pokered/) disassembly
770
- - [Gen I Main Battle
771
- Function](https://www.smogon.com/forums/threads/past-gens-research-thread.3506992/#post-5878612) -
772
- Crystal_
810
+ - [Gen I Main Battle Function](https://www.smogon.com/forums/posts/5878612/show) - Crystal_
773
811
  - [Pokemon Showdown!](https://github.com/smogon/pokemon-showdown)
774
812
  - [List of glitches (Generation
775
813
  I)](https://bulbapedia.bulbagarden.net/wiki/List_of_glitches_(Generation_I))
776
- - [Pokémon Showdown RBY
777
- Bugs](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3524844/#post-5933177)
814
+ - [Pokémon Showdown RBY Bugs](https://www.smogon.com/forums/posts/5933177/show)
@@ -1602,44 +1602,44 @@ pub const Move = enum(u8) {
1602
1602
 
1603
1603
  /// Whether this effect activates during the "begin" step of move execution.
1604
1604
  pub inline fn onBegin(effect: Effect) bool {
1605
- return @enumToInt(effect) > 0 and @enumToInt(effect) <= 16;
1605
+ return @intFromEnum(effect) > 0 and @intFromEnum(effect) <= 16;
1606
1606
  }
1607
1607
 
1608
1608
  /// Whether this effect lowers stats.
1609
1609
  pub inline fn isStatDown(effect: Effect) bool {
1610
- return @enumToInt(effect) > 16 and @enumToInt(effect) <= 21;
1610
+ return @intFromEnum(effect) > 16 and @intFromEnum(effect) <= 21;
1611
1611
  }
1612
1612
 
1613
1613
  /// Whether this effect activates during the "end" step of move execution.
1614
1614
  pub inline fn onEnd(effect: Effect) bool {
1615
- return @enumToInt(effect) > 16 and @enumToInt(effect) <= 31;
1615
+ return @intFromEnum(effect) > 16 and @intFromEnum(effect) <= 31;
1616
1616
  }
1617
1617
 
1618
1618
  /// Whether this effect is considered to "always happen".
1619
1619
  pub inline fn alwaysHappens(effect: Effect) bool {
1620
- return @enumToInt(effect) > 31 and @enumToInt(effect) <= 38;
1620
+ return @intFromEnum(effect) > 31 and @intFromEnum(effect) <= 38;
1621
1621
  }
1622
1622
 
1623
1623
  /// Whether this effect is handled specially by the engine.
1624
1624
  pub inline fn isSpecial(effect: Effect) bool {
1625
1625
  // NB: isSpecial includes isMulti up to Twineedle
1626
- return @enumToInt(effect) > 31 and @enumToInt(effect) <= 46;
1626
+ return @intFromEnum(effect) > 31 and @intFromEnum(effect) <= 46;
1627
1627
  }
1628
1628
 
1629
1629
  /// Whether this effect is a multi-hit effect.
1630
1630
  pub inline fn isMulti(effect: Effect) bool {
1631
- return @enumToInt(effect) > 44 and @enumToInt(effect) <= 47;
1631
+ return @intFromEnum(effect) > 44 and @intFromEnum(effect) <= 47;
1632
1632
  }
1633
1633
 
1634
1634
  /// Whether this effect is has chance of lowering stats.
1635
1635
  pub inline fn isStatDownChance(effect: Effect) bool {
1636
- return @enumToInt(effect) > 47 and @enumToInt(effect) <= 51;
1636
+ return @intFromEnum(effect) > 47 and @intFromEnum(effect) <= 51;
1637
1637
  }
1638
1638
 
1639
1639
  /// Whether this effect has a secondary chance.
1640
1640
  pub inline fn isSecondaryChance(effect: Effect) bool {
1641
1641
  // NB: isSecondaryChance includes isStatDownChance as well as Twineedle
1642
- return (@enumToInt(effect) > 46 and @enumToInt(effect) <= 61);
1642
+ return (@intFromEnum(effect) > 46 and @intFromEnum(effect) <= 61);
1643
1643
  }
1644
1644
  };
1645
1645
 
@@ -1843,12 +1843,12 @@ pub const Move = enum(u8) {
1843
1843
  /// Returns the `Data` corresponding to the move.
1844
1844
  pub inline fn get(id: Move) Data {
1845
1845
  assert(id != .None and id != .SKIP_TURN);
1846
- return DATA[@enumToInt(id) - 1];
1846
+ return DATA[@intFromEnum(id) - 1];
1847
1847
  }
1848
1848
 
1849
1849
  /// Returns the base PP of the move.
1850
1850
  pub fn pp(id: Move) u8 {
1851
1851
  assert(id != .None);
1852
- return PP[@enumToInt(id) - 1];
1852
+ return PP[@intFromEnum(id) - 1];
1853
1853
  }
1854
1854
  };
@@ -1094,12 +1094,12 @@ pub const Species = enum(u8) {
1094
1094
  /// The Pokémon's critical hit rate=io out of 256.
1095
1095
  pub inline fn chance(id: Species) u8 {
1096
1096
  assert(id != .None);
1097
- return CHANCES[@enumToInt(id) - 1];
1097
+ return CHANCES[@intFromEnum(id) - 1];
1098
1098
  }
1099
1099
 
1100
1100
  /// Returns the `Data` corresponding to the species.
1101
1101
  pub fn get(id: Species) Data {
1102
1102
  assert(id != .None);
1103
- return DATA[@enumToInt(id) - 1];
1103
+ return DATA[@intFromEnum(id) - 1];
1104
1104
  }
1105
1105
  };
@@ -91,18 +91,18 @@ pub const Type = enum(u4) {
91
91
 
92
92
  /// Whether or not this type is considered to be special as opposed to physical.
93
93
  pub inline fn special(self: Type) bool {
94
- return @enumToInt(self) >= @enumToInt(Type.Fire);
94
+ return @intFromEnum(self) >= @intFromEnum(Type.Fire);
95
95
  }
96
96
 
97
97
  /// The `Effectiveness` of type `t2` vs. type `t1`.
98
98
  pub inline fn effectiveness(t1: Type, t2: Type) Effectiveness {
99
- return CHART[@enumToInt(t1)][@enumToInt(t2)];
99
+ return CHART[@intFromEnum(t1)][@intFromEnum(t2)];
100
100
  }
101
101
 
102
102
  /// The precedence order of type `t2` vs. type `t1`.
103
103
  pub fn precedence(t1: Type, t2: Type) u8 {
104
104
  for (PRECEDENCE, 0..) |matchup, i| {
105
- if (matchup.type1 == t1 and matchup.type2 == t2) return @intCast(u8, i);
105
+ if (matchup.type1 == t1 and matchup.type2 == t2) return @intCast(i);
106
106
  }
107
107
  unreachable;
108
108
  }