@pkmn/engine 0.1.0-dev.cf6f5d2c → 0.1.0-dev.d1b39ff0

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 (60) hide show
  1. package/LICENSE +1 -3
  2. package/README.md +95 -59
  3. package/build/pkg/addon.js +9 -9
  4. package/build/pkg/addon.js.map +1 -1
  5. package/build/pkg/data/ids.json +12 -12
  6. package/build/pkg/data/layout.json +27 -5
  7. package/build/pkg/data/protocol.json +69 -12
  8. package/build/pkg/data.d.ts +4 -4
  9. package/build/pkg/data.js.map +1 -1
  10. package/build/pkg/gen1.d.ts +2 -1
  11. package/build/pkg/gen1.js +38 -20
  12. package/build/pkg/gen1.js.map +1 -1
  13. package/build/pkg/index.d.ts +7 -4
  14. package/build/pkg/index.js.map +1 -1
  15. package/build/pkg/protocol.d.ts +4 -2
  16. package/build/pkg/protocol.js +65 -44
  17. package/build/pkg/protocol.js.map +1 -1
  18. package/build/test/display.js +15 -6
  19. package/build/test/display.js.map +1 -1
  20. package/build/tools/debug.js +5 -4
  21. package/build/tools/debug.js.map +1 -1
  22. package/build.zig +148 -126
  23. package/package.json +53 -24
  24. package/src/bin/install-pkmn-engine +35 -22
  25. package/src/lib/common/battle.zig +17 -0
  26. package/src/lib/common/data.zig +19 -31
  27. package/src/lib/common/debug.zig +22 -13
  28. package/src/lib/common/js.zig +118 -0
  29. package/src/lib/common/optional.zig +67 -0
  30. package/src/lib/common/options.zig +11 -0
  31. package/src/lib/common/protocol.zig +906 -367
  32. package/src/lib/common/rational.zig +454 -0
  33. package/src/lib/common/rng.zig +35 -26
  34. package/src/lib/common/util.zig +12 -0
  35. package/src/lib/gen1/calc.zig +802 -0
  36. package/src/lib/gen1/chance.zig +1159 -0
  37. package/src/lib/gen1/data/moves.zig +202 -190
  38. package/src/lib/gen1/data/species.zig +5 -5
  39. package/src/lib/gen1/data/types.zig +10 -10
  40. package/src/lib/gen1/data.zig +104 -90
  41. package/src/lib/gen1/helpers.zig +140 -42
  42. package/src/lib/gen1/mechanics.zig +1135 -773
  43. package/src/lib/gen2/calc.zig +135 -0
  44. package/src/lib/gen2/chance.zig +895 -0
  45. package/src/lib/gen2/data/items.zig +14 -20
  46. package/src/lib/gen2/data/moves.zig +664 -570
  47. package/src/lib/gen2/data/species.zig +2 -2
  48. package/src/lib/gen2/data/types.zig +137 -34
  49. package/src/lib/gen2/data.zig +130 -92
  50. package/src/lib/gen2/generated.zig +806 -0
  51. package/src/lib/gen2/helpers.zig +50 -26
  52. package/src/lib/gen2/mechanics.zig +3568 -12
  53. package/src/lib/node.zig +131 -0
  54. package/src/lib/pkmn.zig +81 -5
  55. package/src/lib/wasm.zig +13 -0
  56. package/src/test/display/pkmn.html.tmpl +5 -5
  57. package/src/lib/binding/node.zig +0 -229
  58. package/src/lib/binding/wasm.zig +0 -10
  59. package/src/lib/gen1/README.md +0 -804
  60. package/src/lib/gen2/README.md +0 -309
@@ -1,804 +0,0 @@
1
- # Pokémon Generation I: RBY
2
-
3
- This document exists to describe the design of pkmn's Generation I ("RBY") engine. A high level
4
- overview of the project's design can be found in the [top level design
5
- document](../../../docs/DESIGN.md). The Generation I engine is implemented and tested across the
6
- following files:
7
-
8
- - [`data.zig`](data.zig) ([`data`](data)): contains definitions of all of the data structures used
9
- by the engine, described in detail [below](#data-structures)
10
- - [`helpers.zig`](helpers.zig): helpers used to construct complex data types with
11
- sensible defaults (internally used by tests and tools)
12
- - [`mechanics.zig`](mechanics.zig): code which manipulates the data structures in order to implement
13
- the mechanics of the game
14
- - [`test.zig`](test.zig): unit tests for `mechanics.zig` (the code is also tested by [integration
15
- tests](../../../docs/TESTING.md) at a higher level)
16
-
17
- The engine also relies on the [data types](../common/data.zig), [protocol](../common/protocol.zig),
18
- and [RNG](../common/rng.zig) logic which is shared across generations and lives in
19
- [`lib/common`](../common).
20
-
21
- Covered below is a description of the [**data structures**](#data-structures) used including the
22
- [**information**](#information) they contain and their [**layout**](#layout), a list of
23
- [**bugs**](#bugs) that are introduced by `-Dshowdown` for Pokémon Showdown compatibility, an
24
- [**RNG**](#rng) table, high level [**details**](#details) about the control flow of the engine and a
25
- list of additional reference [**resources**](#resources).
26
-
27
- ## Data Structures
28
-
29
- The following information is required to simulate a Generation I Pokémon battle:
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}` |
60
-
61
- - Pokémon Showdown [does not implement the correct Generation I RNG](#rng) and as such its `seed` is
62
- different
63
- - `battle.turn` only needs to be tracked in order to be compatible with the Pokémon Showdown
64
- protocol
65
- - Pokémon Showdown tracks several last used move variables (`Battle.lastMove`, `Side.lastMove`, and
66
- `Pokemon.lastMove`), none of which accurately match the `PlayerUsedMove` variable from the
67
- cartridge (`Side.lastMove` should be what is used, but is used by Pokémon Showdown only for
68
- Counter and is not set and cleared in the correct locations. `Pokemon.lastMove` matches
69
- `PlayerUsedMove` more often so is what the engine attempts to model, despite the implications for
70
- Counter)
71
- - Pokémon Showdown does not implement the [partial-trapping move Mirror Move
72
- glitch](https://glitchcity.wiki/Partial_trapping_move_Mirror_Move_link_battle_glitch) and as such
73
- does not need to keep track of a player's last selected move index (`PlayerMoveListIndex`)
74
- - Battle results (win, lose, draw) and request states are communicated via the return value of
75
- `Battle.update`
76
- - Nicknames (`BattleMonNick`/`pokemon.name`) are not handled by the pkmn engine as they are expected
77
- to be handled by driver code if required
78
- - Pokémon Red's `LastSwitchInEnemyMonHP`, `InHandlePlayerMonFainted`, `PlayerNumHits`,
79
- `PlayerMonMinimized`, and `Move{DidntMiss,Missed}` are relevant for messaging/UI only
80
- - Pokémon Red's `TransformedEnemyMonOriginalDVs` is only relevant for the [Transform DV manipulation
81
- glitch](https://pkmn.cc/bulba/Transform_glitches#Transform_DV_manipulation_glitch)
82
- - Pokémon Red's `PlayerMove*` tracks information that is stored in the `Move` class
83
- - Pokémon Red's `PlayerStatsToDouble`/`PlayerStatsToHalve` are constants which are always 0
84
- - pkmn does not store the DVs/stat experience of Pokémon as they are expected to already be
85
- accounted for in the `Pokemon` `stats` and never need to be referenced in-battle (though a `DVs`
86
- struct exists to simplify generating legal test data)
87
- - Instead of storing unmodified stats like Pokémon Red or Pokémon Showdown, pkmn simply tracks the
88
- identity of the Pokémon that has been transformed into in the `active.volatiles.transform` field
89
- - pkmn uses `volatiles.state` for total accumulated damage for Bide but also for implementing
90
- accuracy overwrite mechanics for certain moves (this glitch is present on the device but is not
91
- correctly implemented by Pokémon Showdown currently)
92
-
93
- ### `Battle` / `Side`
94
-
95
- `Battle` and `Side` are analogous to the classes of the
96
- [same](https://github.com/smogon/pokemon-showdown/blob/master/sim/battle.ts)
97
- [name](https://github.com/smogon/pokemon-showdown/blob/master/sim/side.ts) in Pokémon Showdown and
98
- store general information about the battle. Unlike in Pokémon Showdown there is a distinction
99
- between the data structure for the "active" Pokémon and its party members (see below).
100
-
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`.
103
-
104
- ### `Pokemon` / `ActivePokemon`
105
-
106
- Similar to the cartridge, in order to save space different information is stored depending on
107
- whether a [Pokémon](https://pkmn.cc/bulba/Pok%c3%a9mon_data_structure_%28Generation_I%29) is
108
- actively participating in battle vs. is switched out (pret's [`battle_struct` vs.
109
- `party_struct`](https://pkmn.cc/pokered/macros/ram.asm)). In Pokémon Showdown, all the Pokémon in a
110
- battle are represented by the same
111
- [`Pokemon`](https://github.com/smogon/pokemon-showdown/blob/master/sim/pokemon.ts) class, and static
112
- party information is saved in fields beginning with "`stored`" or "`base`".
113
-
114
- #### `MoveSlot`
115
-
116
- A `MoveSlot` is a data-type for a `(move, current pp)` pair. A pared down version of Pokémon
117
- Showdown's `Pokemon.moveSlot`, it also stores data from the cartridge's `battle_struct::Move` macro
118
- and can be used to replace the `PlayerMove*` data. Move PP is stored as a full byte instead of how
119
- the cartridge (`battle_struct::PP`) stores it (6 bits for current PP and the remaining 2 bits used
120
- to store the number of applied PP Ups). PP Up bits do not actually need to be stored on move slot
121
- as max PP is never relevant in Generation I.
122
-
123
- #### `Status`
124
-
125
- Bitfield representation of a Pokémon's major [status
126
- condition](https://pkmn.cc/bulba/Status_condition), mirroring how it is stored on the cartridge. A
127
- value of `0x00` means that the Pokémon is not affected by any major status, otherwise the lower 3
128
- bits represent the remaining duration for Sleep. Other status are denoted by the presence of
129
- individual bits - at most one status should be set at any given time.
130
-
131
- In Generation I & II, the "badly poisoned" status (Toxic) is instead treated as a volatile (see
132
- below), so the upper most bit of `Status` is instead used to track state required to implement Pokémon
133
- quirks:
134
-
135
- - when combined with a valid sleep duration (or 0), it indicates that the `SLP` status was
136
- self-inflicted (required in order to implement Pokémon Showdown's "Sleep Clause Mod")
137
- - when combined with `PSN` it indicates that the Pokémon is actually badly poisoned (required in
138
- order to send the same incorrect protocol messages as Pokémon Showdown - the Toxic volatile
139
- alone is not sufficient in compatibility mode because it gets lost on switch)
140
-
141
- #### `Volatiles`
142
-
143
- Active Pokémon can have ["volatile" status
144
- conditions](https://pkmn.cc/bulba/Status_condition#Volatile_status) (called ["battle
145
- status"](https://pkmn.cc/pokered/constants/battle_constants.asm#L73) bits in pret), all of which are
146
- boolean flags that are cleared when the Pokémon faints or switches out:
147
-
148
- | pkmn | Pokémon Red (pret) | Pokémon Showdown |
149
- | -------------- | -------------------------- | ------------------ |
150
- | `Bide` | `STORING_ENERGY` | `bide` |
151
- | `Thrashing` | `TRASHING_ABOUT` | `lockedmove` |
152
- | `MultiHit` | `ATTACKING_MULTIPLE_TIMES` | `Move#multihit` |
153
- | `Flinch` | `FLINCHED` | `flinch` |
154
- | `Charging` | `CHARGING_UP` | `twoturnmove` |
155
- | `Binding` | `USING_TRAPPING_MOVE` | `partiallytrapped` |
156
- | `Invulnerable` | `INVULNERABLE` | `Move#onLockMove` |
157
- | `Confusion` | `CONFUSED` | `confusion` |
158
- | `Mist` | `PROTECTED_BY_MIST` | `mist` |
159
- | `FocusEnergy` | `GETTING_PUMPED` | `focusenergy` |
160
- | `Substitute` | `HAS_SUBSTITUTE_UP` | `substitute` |
161
- | `Recharging` | `NEEDS_TO_RECHARGE` | `mustrecharge` |
162
- | `Rage` | `USING_RAGE` | `rage` |
163
- | `LeechSeed` | `SEEDED` | `leechseed` |
164
- | `Toxic` | `BADLY_POISONED` | `toxic` |
165
- | `LightScreen` | `HAS_LIGHT_SCREEN_UP` | `lightscreen` |
166
- | `Reflect` | `HAS_REFLECT_UP` | `reflect` |
167
- | `Transform` | `TRANSFORMED` | `transform` |
168
-
169
- [Bide](https://pkmn.cc/bulba/Bide_(move)) (damage),
170
- [Substitute](https://pkmn.cc/bulba/Substitute_(move)) (substitute HP),
171
- [Confusion](https://pkmn.cc/bulba/Confusion_(status_condition)) (duration),
172
- [Toxic](https://pkmn.cc/bulba/Toxic_(move)) (counter),
173
- [Transform](https://pkmn.cc/bulba/Transform_(move)) (identity), and
174
- [Disable](https://pkmn.cc/bulba/Disable_(move)) (move and duration), and multi-hit attacks all
175
- require additional information that is also stored in the `Volatiles` structure. `MultiHit` is not
176
- strictly required to be stored as it should always be 0 after updates barring errors, however it is
177
- convenient to maintain as it maps neatly to the cartridge and is effectively "free" space-wise due
178
- to padding.
179
-
180
- The `state` field of `Volatiles` is effectively treated as a union:
181
-
182
- - if `volatiles.Bide` is set, `volatiles.data.state` reflects the total accumulated Bide damage
183
- - otherwise, `volatiles.data.state` reflects the last computed move accuracy (required in order to
184
- implement the [Rage and Thrash / Petal Dance accuracy
185
- bug](https://www.youtube.com/watch?v=NC5gbJeExbs))
186
-
187
- #### `Stats` / `Boosts`
188
-
189
- [Stats](https://pkmn.cc/bulba/Stat) and [boosts (stat
190
- modifiers)](https://pkmn.cc/bulba/Stat#Stat_modifiers) are stored logically, with the exception that
191
- boosts should always range from `-6`...`6` instead of `1`...`13` as on the cartridge.
192
-
193
- ### `Move` / `Move.Data`
194
-
195
- `Move` serves as an identifier for a unique [Pokémon move](https://pkmn.cc/bulba/Move) that can be
196
- used to retrieve `Move.Data` with information regarding base power, accuracy, and type. As covered
197
- above, PP information isn't strictly necessary in Generation I so is dropped. `Move.None` exists as
198
- a special sentinel value to indicate `null`. Move PP data is only included for testing and is not
199
- necessary for the actual engine implementation.
200
-
201
- In order to workaround various [Pokémon Showdown bugs](#bugs) and to support its protocol in logs,
202
- additional information is stored in `Move.Data` (`targets`) about what Pokémon Showdown believes the
203
- `Move.Target` to be (despite the concept of targeting not existing until Generation III when Double
204
- battles were introduced). More specifically, a move's "targeting" status is required in various
205
- places to determine which protocol messages to print.
206
-
207
- | pkmn | Pokémon Showdown |
208
- | ----------- | ---------------- |
209
- | `AllOthers` | `allAdjacent` |
210
- | (`Self`) | `allyTeam` |
211
- | `Any` | `any` |
212
- | `Other` | `normal` |
213
- | `RandomFoe` | `randomNormal` |
214
- | `Depends` | `scripted` |
215
- | `Self` | `self` |
216
-
217
- ### `Species` / `Species.Data`
218
-
219
- `Species` just serves as an identifier for a unique [Pokémon
220
- species](https://pkmn.cc/bulba/Pokémon_species_data_structure_(Generation_I)) as the base stats
221
- of a species are already accounted for in the computed stats in the `Pokemon` structure and nothing
222
- in battle requires these to be recomputed. Similarly, Type is unnecessary to include as it is also
223
- already present in the `Pokemon` struct. `Species.None` exists as a special sentinel value to
224
- indicate `null`. `Species.Data` is only included for testing and is not necessary for the actual
225
- engine implementation, outside of `Species.CHANCES` which is required as the base speed / 2 of the
226
- species is necessary for computing critical hit probability.
227
-
228
- ### `Type` / `Types` / `Effectiveness`
229
-
230
- The [Pokémon types](https://pkmn.cc/bulba/Type) are enumerated by `Type`. `Types` represents a tuple
231
- of 2 types, but due to limitations in Zig this can't be represented as a `[2]Type` array and thus
232
- instead takes the form of a packed struct. `Effectiveness` serves as an enum for tracking a moves
233
- effectiveness - like the cartridge, effectiveness is stored as `0`, `5`, `10`, and `20`
234
- (technically only a 2-bit value is required, but as with `Types` Zig only allows a minimum of a byte
235
- to be stored at each address of an array).
236
-
237
- The 'precedence' of the various type matchups matters beyond just the [dual-type damage
238
- misinformation
239
- glitch](https://pkmn.cc/bulba/List_of_glitches_(Generation_I)#Dual-type_damage_misinformation) -
240
- type effectiveness modifiers are applied based on the (haphazard) ordering of the effectiveness
241
- table as opposed to first applying modifiers for a species's first type and then second type. The
242
- engine maintains a `Type.PRECEDENCE` table with just the matchups that are relevant in game (certain
243
- type combinations cannot crop up with the limited Generation I species pool and as such are pruned
244
- for efficiency) and only looks up precedence when necessary to minimize expensive searches. Pokémon
245
- Showdown does not implement type precedence.
246
-
247
- ## Information
248
-
249
- The information of each field (in terms of [bits of
250
- entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory))) is as follows:
251
-
252
- | Data | Range | Bits | | Data | Range | Bits |
253
- | --------------- | --------- | ---- | --- | ----------------- | -------- | ---- |
254
- | **seed** | 0...255 | 8 | | **turn** | 1...1000 | 10 |
255
- | **team index** | 1...6 | 3 | | **move index** | 1...4 | 2 |
256
- | **species** | 1...151 | 8 | | **move** | 1...165 | 8 |
257
- | **stat** | 1...999 | 10 | | **boost** | 0...13 | 4 |
258
- | **level** | 1...100 | 7 | | **volatiles** | *17* | 17 |
259
- | **bide** | 0...65635 | 16 | | **substitute** | 0...179 | 8 |
260
- | **confusion** | 0...5 | 3 | | **toxic** | 0...31 | 5 |
261
- | **multi hits** | 0...5 | 3 | | **base power** | 0...40 | 6 |
262
- | **base PP** | 1...8 | 3 | | **PP Ups** | 0...3 | 2 |
263
- | **PP** | 0...64 | 7 | | **HP / damage** | 0...704 | 10 |
264
- | **status** | 0...13 | 4 | | **effectiveness** | 0...3 | 2 |
265
- | **type** | 0...15 | 4 | | **accuracy** | 6...20 | 4 |
266
- | **disabled** | 0...8 | 4 | | **DVs** | 0...15 | 4 |
267
- | **move effect** | 0..66 | 7 | | **attacks** | 0..4 | 3 |
268
- | **crit chance** | 7..65 | 6 | | **transform** | 0..15 | 4 |
269
- | **target** | 0..4 | 3 | | | | |
270
-
271
- From this we can determine the minimum bits[^1] required to store each data structure to determine
272
- how much overhead the representations above have after taking into consideration [alignment &
273
- padding](https://en.wikipedia.org/wiki/Data_structure_alignment) and
274
- [denormalization](https://en.wikipedia.org/wiki/Denormalization):
275
-
276
- - **`Pokemon`**: 5× stats (`50`) + 4× move slot (`60`) + HP (`10`) + status (`4`) + species (`8`) +
277
- types (`8`) + level (`7`)
278
- - **`ActivePokemon`**: 4× stats (`40`) + 4× move slot (`60`) + 6× boosts (`24`) + volatile data
279
- (`35`) + volatiles (`17`) + species (`8`) + types (`8`) + disabled (`6`) + transform (`4`)
280
- - the active Pokémon's stats/species/move slots/types may change in the case of Transform
281
- - the active Pokémon's types may change due to Conversion
282
- - the active Pokémon's level and current and max HP can always be referred to the `Pokemon`
283
- struct
284
- - **`Side`**: `ActivePokemon` + 6× `Pokemon` + active (`3`) + last used (`8`) + last selected
285
- (`8`)
286
- - `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`)
288
- - **`Type.CHART`**: attacking types (`15`) × defending types (`15`) × effectiveness (`2`)[^2]
289
- - **`Type.PRECEDENCE`**: 29× attacking type (`4`) + defending type (`4`) pairs
290
- - **`Moves.DATA`**: 165× base power (`6`) + effect (`7`) + accuracy (`4`) + type (`4`) + target
291
- (`3`)
292
- - **`Species.CHANCES`**: 151× crit chance (`6`)
293
-
294
- | Data | Actual bits | Minimum bits | Overhead |
295
- | ----------------- | ----------- | ------------ | -------- |
296
- | `Pokemon` | 192 | 147 | 30.6% |
297
- | `ActivePokemon` | 256 | 202 | 26.7% |
298
- | `Side` | 1472 | 1056 | 33.5% |
299
- | `Battle` | 3088 | 2216 | 33.7% |
300
- | `Type.CHART` | 1800 | 450 | 300.0% |
301
- | `Type.PRECEDENCE` | 232 | 232 | 0.0% |
302
- | `Moves.DATA` | 5280 | 3960 | 33.3% |
303
- | `Species.CHANCES` | 1208 | 906 | 33.3% |
304
-
305
- In the case of `Type.CHART`/`Type.PRECEDENCE`/`Moves.DATA`/`Species.CHANCES`, technically only the
306
- values which are used by any given simulation are required, which could be as low as 1 in both
307
- circumstances (e.g. all Normal Pokémon each only using the single move Tackle), though taking into
308
- consideration the worst case all Pokémon types are required and 48 moves. The `Moves.DATA` array
309
- could be eliminated and instead the `Move` data actually required by each `Pokemon` could be placed
310
- beside the `MoveSlot`, though this is both less general and adds unnecessary complexity.
311
-
312
- [^1]: For data with lower cardinality it is possible to save memory by ordinalizing the values and
313
- turning them into indices into a lookup table (e.g. encode all possible move base powers in a lookup
314
- table and store the index into that table instead of the actual base power). While this approach may
315
- minimize the absolute memory used, performance is more likely to suffer as the goal is to minimize
316
- uncached memory lookups, not total memory usage.
317
-
318
- [^2]: Instead of storing as a sparse multi-dimensional array the type chart could instead only
319
- [store values which are not normal
320
- effectiveness](https://github.com/pret/pokered/blob/master/data/types/type_matchups.asm) in 820 bits
321
- as 82× attacking type (`4`) + defending type (`4`) + non-Normal effectiveness (`2`). This would
322
- avoid having to do two memory lookups at the cost of a longer time scanning, but the second lookup
323
- should already be fast due to locality of reference meaning it will likely already be in the cache.
324
- This approach would also render `Type.PRECEDENCE` unnecessary.
325
-
326
- ## Layout
327
-
328
- The precise layout of the engine's data structures is important to those implementing driver code,
329
- as clients must directly probe the engine's state through these structures (i.e. the pkmn engine
330
- does not produce an equivalent to Pokémon Showdown's `|request|` protocol message, this information
331
- must be gleaned through the `Battle` state). Useful size and offset information can be found in
332
- the [`layout.json`](../../data/layout.json) which exists to simplify writing driver code.
333
-
334
- Documentation of the wire protocol used for protocol message logging when `-Dlog` is enabled can be
335
- found in [PROTOCOL.md](../../../docs/PROTOCOL.md). Note that the
336
- [`pkmn-debug`](../../../README.md#pkmn-debug) tool exists to display the binary protocol and battle
337
- data in the browser for ease of debugging.
338
-
339
- ### `Battle`
340
-
341
- | Start | End | Data | Description |
342
- | ------- | ------- | ----------------------- | ------------------------------------------------------- |
343
- | 0 | 184 | [`sides[0]`](#side) | Player 1's side |
344
- | 184 | 368 | [`sides[1]`](#side) | Player 2's side |
345
- | 368 | 370 | `turn` | The current turn number |
346
- | 370 | 372 | `last_damage` | The last damage dealt by either side |
347
- | 372 | 373-376 | `last_selected_indexes` | The slot index of the last selected moves for each side |
348
- | 373-376 | 384 | `rng` | The RNG state |
349
-
350
- - the current `turn` is 2 bytes, written in native-endianness
351
- - `last_selected_indexes` layout depends on whether or not Pokémon Showdown compatibility mode is
352
- enabled (`-Dshowdown`). In either case it stores a move "slot", where 0 is used as an empty value and
353
- 1-4 represent actual moves:
354
- - if `showdown` is enabled bytes 372 and 373 are used to store the last selected move index of
355
- `side[0]` and bytes 374 and 375 store the last selected move index of `side[1]`
356
- - otherwise byte 372 stores the last selected move index of `side[0]` in its first 4 bits and
357
- `side[1]`'s in its second 4 bits
358
- - the `rng` depends on whether or not Pokémon Showdown compatibility mode is enabled (`-Dshowdown`):
359
- - if `showdown` is enabled, the RNG state begins on byte 376 and consists of a 64-bit seed,
360
- written in native-endianness
361
- - otherwise the RNG state begins on byte 373 and consists of the 10 bytes of the seed followed by
362
- the index pointing to which byte of the seed is currently being used
363
-
364
- ### `Side`
365
-
366
- | Start | End | Data | Description |
367
- | ----- | --- | -------------------------- | --------------------------------------- |
368
- | 0 | 24 | [`pokemon[0]`](#pokemon) | The player's first Pokémon |
369
- | 24 | 48 | [`pokemon[1]`](#pokemon) | The player's second Pokémon |
370
- | 48 | 72 | [`pokemon[2]`](#pokemon) | The player's third Pokémon |
371
- | 72 | 96 | [`pokemon[3]`](#pokemon) | The player's fourth Pokémon |
372
- | 96 | 120 | [`pokemon[4]`](#pokemon) | The player's fifth Pokémon |
373
- | 120 | 144 | [`pokemon[5]`](#pokemon) | The player's sixth Pokémon |
374
- | 144 | 176 | [`active`](#activepokemon) | The player's active Pokémon |
375
- | 176 | 182 | `order` | The current order of the player's party |
376
- | 182 | 183 | `last_selected_move` | The last move the player selected |
377
- | 183 | 184 | `last_used_move` | The last move the player used |
378
-
379
- - `order` is a 6 byte array where `order[i]` represents the "slot" of `pokemon[i]`, where the slot
380
- is usually a unique value from 1-6 but can be 0 in situations where a player brings less than six
381
- Pokémon to battle (note however that if `order[i]` is 0 than for all j > 0 `order[i+j]` **must**
382
- equal 0).
383
-
384
- ### `ActivePokemon`
385
-
386
- | Start | End | Data | Description |
387
- | ----- | --- | ---------------------------------- | ---------------------------------------------------------- |
388
- | 0 | 2 | `stats.hp` | The active Pokémon's computed max HP stat |
389
- | 2 | 4 | `stats.atk` | The active Pokémon's modified Attack stat |
390
- | 4 | 6 | `stats.def` | The active Pokémon's modified Defense stat |
391
- | 6 | 8 | `stats.spe` | The active Pokémon's modified Speed stat |
392
- | 8 | 10 | `stats.spc` | The active Pokémon's modified Special stat |
393
- | 10 | 11 | `species` | The active Pokémon's species |
394
- | 11 | 12 | `type1`/`type2` | The active Pokémon's types |
395
- | 12 | 13 | `boosts.atk`/`boosts.def` | The active Pokémon's Attack and Defense boosts |
396
- | 13 | 14 | `boosts.spe`/`boosts.spd` | The active Pokémon's Speed and Special boosts |
397
- | 14 | 15 | `boosts.accuracy`/`boosts.evasion` | The active Pokémon's Accuracy and Evasion boosts |
398
- | 15 | 16 | - | *Zero padding* |
399
- | 16 | 24 | [`volatiles`](#volatiles-1) | The active Pokémon's volatile statuses and associated data |
400
- | 24 | 25 | `moves[0].id` | The active Pokémon's second move |
401
- | 25 | 26 | `moves[0].pp` | The PP of the active Pokémon's first move |
402
- | 26 | 27 | `moves[1].id` | The active Pokémon's second move |
403
- | 27 | 28 | `moves[1].pp` | The PP of the active Pokémon's second move |
404
- | 28 | 29 | `moves[2].id` | The active Pokémon's third move |
405
- | 29 | 30 | `moves[2].pp` | The PP of the active Pokémon's third move |
406
- | 30 | 31 | `moves[3].id` | The active Pokémon's fourth move |
407
- | 31 | 32 | `moves[3].pp` | The PP of the active Pokémon's fourth moe |
408
-
409
- - the active Pokémon's `stats.hp` is always identical to the corresponding stored Pokémon's `stats.hp`
410
- - `boosts` and `types` includes bytes which store two 4-bit fields each
411
-
412
- #### `Volatiles`
413
-
414
- > **NOTE:** The offsets in the following table represent *bits* and **not** bytes.
415
-
416
- | Start | End | Data | Description |
417
- | ----- | --- | ------------------- | ----------------------------------------------------------- |
418
- | 0 | 1 | `Bide` | Whether the "Bide" volatile status is present |
419
- | 1 | 2 | `Thrashing` | Whether the "Thrashing" volatile status is present |
420
- | 2 | 3 | `MultiHit` | Whether the "MultiHit" volatile status is present |
421
- | 3 | 4 | `Flinch` | Whether the "Flinch" volatile status is present |
422
- | 4 | 5 | `Charging` | Whether the "Charging" volatile status is present |
423
- | 5 | 6 | `Binding` | Whether the "Binding" volatile status is present |
424
- | 6 | 7 | `Invulnerable` | Whether the "Invulnerable" volatile status is present |
425
- | 7 | 8 | `Confusion` | Whether the "Confusion" volatile status is present |
426
- | 8 | 9 | `Mist` | Whether the "Mist" volatile status is present |
427
- | 9 | 10 | `FocusEnergy` | Whether the "FocusEnergy" volatile status is present |
428
- | 10 | 11 | `Substitute` | Whether the "Substitute" volatile status is present |
429
- | 11 | 12 | `Recharging` | Whether the "Recharging" volatile status is present |
430
- | 12 | 13 | `Rage` | Whether the "Rage" volatile status is present |
431
- | 13 | 14 | `LeechSeed` | Whether the "LeechSeed" volatile status is present |
432
- | 14 | 15 | `Toxic` | Whether the "Toxic" volatile status is present |
433
- | 15 | 16 | `LightScreen` | Whether the "LightScreen" volatile status is present |
434
- | 16 | 17 | `Reflect` | Whether the "Reflect" volatile status is present |
435
- | 17 | 18 | `Transform` | Whether the "Transform" volatile status is present |
436
- | 18 | 21 | `confusion` | The remaining turns of confusion |
437
- | 21 | 24 | `attacks` | The number of attacks remaining |
438
- | 24 | 40 | `state` | A union of either: <ul><li>the total accumulated damage from Bide</li><li>the overwritten accuracy of certain moves</li></ul> |
439
- | 40 | 48 | `substitute` | The remaining HP of the Substitute |
440
- | 48 | 52 | `transform` | The identity of whom the active Pokémon is transformed into |
441
- | 52 | 56 | `disabled_duration` | The remaining turns the move is disabled |
442
- | 56 | 59 | `disabled_move` | The move slot (1-4) that is disabled |
443
- | 59 | 64 | `toxic` | The number of turns toxic damage has been accumulating |
444
-
445
- ### `Pokemon`
446
-
447
- | Start | End | Data | Description |
448
- | ----- | --- | --------------- | ------------------------------------------ |
449
- | 0 | 2 | `stats.hp` | The Pokémon's computed max HP stat |
450
- | 2 | 4 | `stats.atk` | The Pokémon's unmodified Attack stat |
451
- | 4 | 6 | `stats.def` | The Pokémon's unmodified Defense stat |
452
- | 6 | 8 | `stats.spe` | The Pokémon's unmodified Speed stat |
453
- | 8 | 10 | `stats.spc` | The Pokémon's unmodified Special stat |
454
- | 10 | 11 | `moves[0].id` | The Pokémon's first stored move |
455
- | 11 | 12 | `moves[0].pp` | The PP of the Pokémon's first stored move |
456
- | 12 | 13 | `moves[1].id` | The Pokémon's second stored move |
457
- | 13 | 14 | `moves[1].pp` | The PP of the Pokémon's second stored move |
458
- | 14 | 15 | `moves[2].id` | The Pokémon's third stored move |
459
- | 15 | 16 | `moves[2].pp` | The PP of the Pokémon's third stored move |
460
- | 16 | 17 | `moves[3].id` | The Pokémon's fourth stored move |
461
- | 17 | 18 | `moves[3].pp` | The PP of the Pokémon's fourth stored move |
462
- | 18 | 20 | `hp` | The Pokémon's current HP |
463
- | 20 | 21 | `status` | The Pokémon's current status |
464
- | 21 | 22 | `species` | The Pokémon's stored species |
465
- | 22 | 23 | `type1`/`type2` | The Pokémon's stored types |
466
- | 23 | 24 | `level` | The Pokémon's level |
467
-
468
- ## Bugs
469
-
470
- In addition to its alternative [RNG semantics](#rng), Pokémon Showdown's implementation of the first
471
- generation of Pokémon contains a number bugs, [many of which are known and have been documented on
472
- Smogon](https://www.smogon.com/forums/posts/5933177/show):
473
-
474
- - moves on Pokémon Showdown can do 0 damage instead of failing or causing a [division-by-zero
475
- freeze](https://pkmn.cc/bulba-glitch-1#Division_by_0).
476
- - Pokémon Showdown does not implement type effectiveness precedence correctly.
477
- - Pokémon Showdown checks for type and OHKO immunity before accuracy.
478
- - Confusion self-hits use the wrong damage formula resulting in off-by-one errors (and also fail to
479
- account for an opponent's Reflect). Furthermore, the confusion self-hit damage will erroneously be
480
- inflicted to the confused user's substitute if the confused user had been attempting to use a
481
- self-targeting move. Finally, Pokémon Showdown erroneously considers the *uncapped* self-hit
482
- damage for the purposes of tracking the battle's last damage.
483
-
484
- Beyond the general bugs listed above, several move effects are implemented incorrectly by Pokémon
485
- Showdown. Some of these moves are [too fundamentally broken to be implemented](#unimplementable) by
486
- the pkmn engine, but the following moves have their broken behavior preserved in `-Dshowdown` mode:
487
-
488
- - **Counter**: On Pokémon Showdown choices made while sleeping (which should not have been
489
- registered) can erroneously cause Counter to trigger Desync Clause Mod behavior.
490
- - **Leech Seed**: Leech Seed fails to heal its source side if a seeded target faints due to
491
- recoil/crash damage on Pokémon Showdown.
492
- - **Pay Day**: Pay Day should still scatter coins if it hits (but doesn't break) and opponent's
493
- Substitute but doesn't on Pokémon Showdown.
494
- - **Flinch**: Flinching does not get cleared during move selection on Pokémon Showdown and is
495
- instead cleared in Pokémon Showdown's "residual" phase, meaning the flinch status gets erroneously
496
- preserved across fainting (as fainting triggers Pokémon Showdown's "instaswitch" behavior which
497
- skips end-of-turn residuals).
498
- - **Rage**: Rage boosts should still result in burn/paralysis [stat modification
499
- errors](https://pkmn.cc/bulba-glitch-1#Stat_modification_errors) but don't on Pokémon Showdown.
500
- Furthermore, Pokémon Showdown only builds Rage for Disable/Explosion (hit/miss) when attacking
501
- into a Substitute instead of all moves. Pokémon Showdown also implements the [Rage and Thrash /
502
- Petal Dance accuracy bug]( https://www.youtube.com/watch?v=NC5gbJeExbs) incorrectly, as the
503
- accuracy only gets written when the volatile is present which can lead to incorrect accuracy
504
- values on turns where Rage is used on the same turn as a move which modifies accuracy or evasion.
505
- - **Thrash** / **Petal Dance**: once a Pokémon is locked into a thrashing move they will lose all
506
- speed ties on Pokémon Showdown (due to the fact that if they win the speed tie their action will
507
- then get "changed" and inserted back into the queue after their opponent's action). Pokémon
508
- Showdown also implements accuracy incorrectly, as covered above.
509
- - **Freeze** / **Sleep**: Pokémon Showdown requires a move to be selected when a Pokémon is frozen
510
- or sleeping and uses that in the event that the status is removed while on the cartridge no
511
- selection is possible and no turn exists for the thawed/woken Pokémon to act except in the case of
512
- a Fire-type move thawing a slower Pokémon (which should result in the [Freeze top move selection
513
- glitch](https://glitchcity.wiki/Freeze_top_move_selection_glitch), which is not implemented and
514
- would also likely be incorrect if it were to be implemented due to how Pokémon Showdown
515
- incorrectly saves arbitrary moves with its choice selection semantics). Furthermore, thrashing
516
- volatiles should not be cleared if the user misses a turn due to freeze / sleep.
517
- - **Hyper Beam**: due to improperly implemented selection mechanics, the [Hyper Beam
518
- automatic-selection glitch](https://glitchcity.wiki/Hyper_Beam_automatic_selection_glitch) does
519
- not exist on Pokémon Showdown. Additionally, Hyper Beam being able to cause [Freeze permanent
520
- helplessness](https://pkmn.cc/bulba-glitch-1#Hyper_Beam_.2B_Freeze_permanent_helplessness) is not
521
- implement by Pokémon Showdown.
522
- - **Roar** / **Whirlwind**: these moves can miss on Pokémon Showdown (and advance the RNG when
523
- checking) which is incorrect (these moves should always fail, but do not check accuracy or advance
524
- the RNG). More importantly, these moves should *not* cause the tracked last battle damage to be
525
- zeroed, but on Pokémon Showdown they do.
526
- - **Substitute**: in addition to the [Substitute + Confusion
527
- glitch](https://pkmn.cc/bulba-glitch-1#Substitute_.2B_Confusion_glitch) not being implemented
528
- correctly (covered above), the [Substitute 1/4
529
- glitch](https://glitchcity.wiki/Substitute_%C2%BC_HP_glitch) also fails in many cases due to
530
- Pokémon Showdown implementing the health check based on floating point division instead of integer
531
- divison like on the cartridge (meaning the Substitute 1/4 glitch will only occur if the Pokémon's
532
- maximum HP is evenly divisible by 4). Substitute also incorrectly blocks Dream Eater on
533
- Pokémon Showdown and will incorrectly still heal 1 HP for any draining moves if the attack does 0
534
- damage. Finally, Pokémon Showdown uses a `subFainted` field to track whether a Substitute was
535
- broken in order to know when to nullify a move's effect, only it doesn't get cleared at the end of
536
- the turn and can result in incorrect behavior on subsequent turns with the moves Mirror Move and
537
- Metronome that invoke `runMove` (which is where `subFainted` gets cleared) on the user but skips
538
- calling it for the eventual true target.
539
-
540
- In addition to numerous cases where Pokémon Showdown uses the wrong type of message (e.g. `|-fail`
541
- vs. `|-miss|` vs. `|-immune|`, e.g. in the case of Leech Seed) which are not documented here, Pokémon
542
- Showdown sometimes gets message ordering incorrect (which does not effect the outcome
543
- of the battle, only pedantic UI correctness):
544
-
545
- - **Rage**: Rage should report the `|-boost|` before the Disable `|-miss|`, not after.
546
- - **Haze**: Haze clears the status/volatiles in an incorrect order.
547
- - **Twineedle**: the `|-hitcount|` ("Hit 2 times") should come before the `|-status|` message, not
548
- after.
549
- - **Thrash** / **Petal Dance**: confusion should silently get applied before the `|move|` message,
550
- not after.
551
-
552
- Pokémon Showdown also implements a number of modifications to the cartridge (usually but not always
553
- called out in the `|rule|` section at the beginning of a battle's log):
554
-
555
- - **Sleep Clause Mod**: players are prevented from putting more than one of their opponent's Pokémon
556
- to sleep at a time (usage of the move will fail).
557
- - **Freeze Clause Mod**: players are prevented from freezing more than one of their opponent's
558
- Pokémon at a time (usage of the move will fail).
559
- - **Desync Clause Mod**: If the usage of a move would cause a desync it instead causes a
560
- failure. However, this mod does not trigger for [**division by
561
- zero**](https://pkmn.cc/bulba/List_of_glitches_(Generation_I)#Division_by_0) - instead of failing,
562
- Pokémon Showdown silently patches the damage calculation to divide by 1 instead of 0. The
563
- definition of the Desync Clause Mod should be extended or the code should be changed to fail
564
- instead of succeeding in these cases.
565
- - **Endless Battle Clause**: Prematurely ends the battle in a tie after 1000 turns or in certain
566
- situations where it is trivially detectable that no progress can be made.
567
- - **Switch Priority Clause Mod**: When both player switch out their Pokémon at the same time the
568
- faster Pokémon switches first. This mod is **not broadcast at the start of the battle in the
569
- `|rule|` section** in Generation I (or II) as the actual order of switches here does not have
570
- competitive implications like it does in Generation III, but it is still contrary to how the games
571
- work where the [host (Player 1)'s Pokemon would switch
572
- first](https://www.smogon.com/forums/posts/5989318/show).
573
-
574
- Pokémon Showdown enforces several clauses *before* the battle: **Cleric Clause** (all Pokémon must
575
- have full HP and PP, and not have any status conditions prior to the battle), **Stat Tradeback
576
- Clause** (Pokémon may not have moves obtained from trading back from Pokémon Gold/Silver/Crystal,
577
- though may have DV spreads which would otherwise be unobtainable), **Species Clause** (players may
578
- not have more than one of the same Pokémon species on their team) and bans specific moves via
579
- **Evasion Clause**, **OHKO Clause**, and the **Invulnerability Clause** - none of these are
580
- implemented by the pkmn engine as they can all be accomplished at a higher level by the client.
581
- Similarly, Pokémon Showdown's UI mods, the **HP Percentage Mod** which displays the HP percentage of
582
- a Pokémon instead of pixel information and the **Move Effectiveness Mod** which corrects for the
583
- [dual-type damage misinformation
584
- glitch](https://pkmn.cc/bulba/List_of_glitches_(Generation_I)#Dual-type_damage_misinformation) or
585
- the correction to [Poison/Burn animation with 0
586
- HP](https://pkmn.cc/bulba/List_of_glitches_(Generation_I)#Poison.2FBurn_animation_with_0_HP) are all
587
- left up to a client to support.
588
-
589
- ### Unimplementable
590
-
591
- Numerous moves on Pokémon Showdown are broken not simply due to local issues in the implementation
592
- of their effects but instead due to **global issues** related to fundamental mechanics such as
593
- [broken move selection](https://www.smogon.com/forums/posts/8655897/show), using move name instead
594
- of slot to determine move identity, implementing volatile statuses incorrectly or not understanding
595
- how moves which call other moves work means that it isn't possible to completely implement Pokémon
596
- Showdown's behavior for the following moves (the pkmn engine attempts to reproduce as much of the
597
- behavior that can be reproduced without making data structure changes or dramatically deviating from
598
- the correct control flow):
599
-
600
- - **Bide**: Bide's damage can overflow if OHKO moves are involved because OHKO moves work by setting
601
- the damage to 65535 - Pokémon Showdown doesn't implement this overflow and instead lets Bide's
602
- damage grow unbounded. Additionally, if the opponent faints after Bide inflicts damage on Pokémon
603
- Showdown residual damage incorrectly still gets applied to Bide's user.
604
- - **Wrap**: Binding moves like Wrap are implemented on Pokémon Showdown with an artificial
605
- `partialtrappinglock` volatile as opposed to how it works on the cartridge which simply relies on
606
- the `Binding` volatile of the opponent. This mistake results in choice locking not being reported
607
- properly when the binding move was initiated via another move such as Metronome or Mirror Move.
608
- Binding moves also have some local implementation issues - on Pokémon Showdown a bound Pokémon
609
- still gets a turn under the [trapping sleep
610
- glitch](https://glitchcity.wiki/Trapping_move_and_sleep_glitch), Wrap does 0 damage against
611
- Ghost-type Pokémon instead of properly respecting immunity, and binding effects are handled in the
612
- wrong order in the code which results in either out of order messaging or, more consequentially,
613
- Pokémon using Rage/Bide or Thrashing/Charging moves being incorrectly forced to skip a turn when
614
- the Pokémon using the Binding move switches.
615
- - **Mimic**: Pokémon Showdown checks that the user of Mimic has Mimic in one of their move slots,
616
- which means Mimic legally called via Metronome or Mirror Move will only work if the user also has
617
- Mimic (and the moved mimicked by Mimic called via Metronome / Mirror Move will erroneously
618
- override the Mimic move slot instead of the Metronome / Mirror Move move slot). Furthermore,
619
- because Pokémon Showdown deducts PP based on a move's name instead of slot, if Mimic copies a move
620
- the Pokémon already knows, PP deduction for using either the original move of the mimicked move
621
- will instead deduct PP for whichever appears at the lower move slot index and the PP will be
622
- allowed to go negative (effectively allowing for infinite PP use).
623
- - **Mirror Move**: As covered above, both Substitute and Binding moves misbehave when used via
624
- Mirror Move (though Pokémon Showdown has its own weird behavior and does not implement the
625
- [partial trapping move Mirror Move
626
- glitch](https://glitchcity.wiki/Partial_trapping_move_Mirror_Move_link_battle_glitch) that exists
627
- on the cartridge). Additionally, Pokémon Showdown sets the last used move every turn a Pokémon is
628
- Thrashing instead of just on the turn it is actually selected meaning Mirror Move will sometimes
629
- successfully mirror a Thrashing move when it should fail. Finally, if Mirror Move copies
630
- Struggle it should not deduct PP but on Pokémon Showdown it does.
631
- - **Metronome**: In addition to the issues with binding moves and Substitute, Metronome and Mirror
632
- Move cannot mutually call each other more than 3 times in a row without causing the Pokémon
633
- Showdown simulator to crash due to defensive safety checks that do not exist on the cartridge.
634
- - **Transform**: Transform screws up the effect of Disable, because on Pokémon Showdown, Disable
635
- prevents moves of a given *name* from being used (e.g. "Water Gun") as opposed to moves in a
636
- specific *slot* (e.g. the 2nd move slot), and a Pokémon's moves can change after Transform (this
637
- is not an issue with Disable + Mimic because Mimic happens to replace the same slot). Transform
638
- also has a bad interaction with Pokémon Showdown's buggy Haze implementation, as Haze on Pokémon
639
- Showdown does not copy unmodified stats, leaving the Transformed Pokémon with inccorect stats.
640
- Furthermore, transforming and then using Mirror Move / Metronome can result in [glitchy behavior
641
- and
642
- softlocks](https://pkmn.cc/bulba/Transform_glitches#Transform_.2B_Mirror_Move.2FMetronome_PP_error)
643
- which Pokémon Showdown does not implement.
644
-
645
- Importantly, Pokémon Showdown's **speed tie RNG mechanics are unimplementable** in the pkmn engine
646
- as they rely on internal implementation decisions made by Pokémon Showdown that are impossible to
647
- replicate without also mimicking Pokémon Showdown's (incorrect) event and "action" systems (see
648
- below).
649
-
650
- ## RNG
651
-
652
- **The pkmn engine aims to match the cartridge's RNG frame-accurately**, in that provided with the
653
- same initial seed and inputs it should produce the same battle playout as the Pokémon Red cartridge.
654
- **Pokémon Showdown does not correctly implement frame-accurate RNG in any generation**, and along
655
- with the [bugs](#bugs) discussed above this results in large differences in the codebase. Because
656
- the pkmn engine aims to be as compatible with Pokémon Showdown as possible when in `-Dshowdown`
657
- compatibility mode, the implications of these differences are outlined below:
658
-
659
- - **RNG**: Pokémon Showdown uses the RNG from Generation V & VI in every generation, despite
660
- the seeds and algorithm being different. Pokémon Red uses a simple 8-bit RNG with 10 distinct
661
- seeds generated when the link connection is established, whereas Pokémon Showdown uses a 64-bit
662
- RNG with a 32-bit output.
663
- - **Algorithm**: As detailed in the table below, the algorithm used by Pokémon Showdown in the
664
- places randomness is required is often different than on the cartridge, so even if Pokémon
665
- Showdown were using the correct RNG the values would still diverge (including using a completely
666
- incorrect distribution for multi-hit moves).
667
- - **Bias**: Pokémon Showdown often needs to reduce its 32-bit output range to a smaller range in
668
- order to implement various effects, and does so using a [biased integer multiplication
669
- method](http://www.pcg-random.org/posts/bounded-rands.html) as opposed to debiasing via rejection
670
- sampling to ensure uniformity as is done on the cartridge. This means that certain values are
671
- fractionally more likely to be chosen than others, though this bias is usually quite small (e.g.
672
- in the case of Metronome instead of selecting moves with an equal $1\over163$ chance, Pokémon
673
- Showdown will select some with a $1\over2^{32}$ greater chance than others).
674
- - **Order of operations**: RNG calls effectively introduce something similar to a ["memory
675
- barrier"](https://en.wikipedia.org/wiki/Memory_barrier) in that they must be sequenced correctly
676
- (though operations which occur between them may happen in any order). Pokémon Showdown violates
677
- this by introducing additional operations (see below) and changing up the order of existing
678
- operations (e.g. choosing to check for hit/miss, determine the number of hits for moves with
679
- multiple hits, determine if a move hit critically and then the damage instead of checking for
680
- hit/miss and determining number of hits *after* the other two). While it is often desirable to
681
- rearrange code for performance or to improve readability this can only be done if it does not
682
- affect accuracy.
683
- - **Speed-ties**: In addition to [breaking switch-in speed ties with an RNG
684
- call](https://www.smogon.com/forums/threads/adv-switch-priority.3622189/), speed ties in Pokémon
685
- Showdown actually result in a large number of spurious frame advancements due to the internal
686
- implementation details of Pokémon Showdown's event and "action" systems. Ultimately, without
687
- keeping track of all of the handlers for the internal events Pokémon Showdown invents and
688
- implementing the same "action" system, matching Pokémon Showdown's RNG in the presence of speed
689
- ties proves impossible, and thus the reference Pokémon Showdown implementation pkmn engine aims to
690
- match has been [patched](../../../docs/TESTING.md#patches) to change this behavior.
691
- - **Effects**: Pokémon Showdown occasionally incorrectly inserts RNG calls in move effect handlers
692
- when they are not relevant:
693
- - Roar / Whirlwind roll to hit and can "miss" as opposed to simply failing
694
-
695
- Finally, the **initial 10-byte seed for link battles on Pokémon Red cannot include bytes larger than
696
- the `SERIAL_PREAMBLE_BYTE`**, so must be in the range $\left[0, 252\right]$. This has implications
697
- on the first 10 random numbers generated during the battle and has [**non-trivial competitive
698
- implications**](https://www.smogon.com/forums/posts/9068411/show) (at the start of the battle move
699
- effects become more likely, the ["1/256-miss" glitch](https://glitchcity.wiki/1/256_miss_glitch)
700
- cannot happen, Player 1 is more likely to win speed ties, etc) that Pokémon Showdown cannot
701
- replicate due to everything described above.
702
-
703
- All of places in the link battle code where randomness is required are outlined below:
704
-
705
- | Type | Location | Description |
706
- | ------------------------ | ------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
707
- | **Speed Tie** | `turnOrder` | Player 1 if $X < 127$, otherwise Player 2 |
708
- | **Critical Hit** | `checkCriticalHit` | <dl><dt>Pokémon Red</dt><dd>Inflict a critical hit if $X' < chance$ where $X'$ is $X$ with its bits rotated left three times</dd><dt>Pokémon Showdown</dt><dd>Critical hit if $X < chance$</dd></dl> |
709
- | **Damage** (range) | `randomizeDamage` | <dl><dt>Pokémon Red</dt><dd>Continue generating until $X' \geq 217$ where $X'$ is $X$ with its bits rotated right once</dd><dt>Pokémon Showdown</dt><dd>Generate $X \in \left[217, 256\right)$</dd></dl> |
710
- | **Hit / Miss** | `checkHit` | Hit if $X < scaledAccuracy$ |
711
- | **Burn** (chance) | `Effects.burnChance` | Trigger if $X < 26$ ($77$ for Fire Blast) |
712
- | **Confusion** (chance) | `Effects.confusion` | Trigger if $X< 25$ |
713
- | **Confusion** (duration) | `Effects.confusion` | <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> |
714
- | **Confusion** (self-hit) | `beforeMove` | Trigger if $X \geq 128$ |
715
- | **Flinch** (chance) | `Effects.flinchChance` | Trigger if $X < 26$ ($77$ for Stomp / Headbutt / Rolling Kick / Low Kick) |
716
- | **Freeze** (chance) | `Effects.freezeChance` | Trigger if $X < 26$ |
717
- | **Paralysis** (chance) | `Effects.paralyzeChance` | Trigger if $X< 26$ ($77$ for Body Slam / Lick) |
718
- | **Paralysis** (full) | `beforeMove` | Trigger if $X < 63$ |
719
- | **Poison** (chance) | `Effects.poison` | Trigger if $X < 52$ ($103$ for Smog / Sludge) |
720
- | **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> |
721
- | **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> |
722
- | **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> |
723
- | **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> |
724
- | **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> |
725
- | **Mimic** (move) | `Effects.mimic` | <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> |
726
- | **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> |
727
- | **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> |
728
- | **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> |
729
- | **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> |
730
- | **Multi-Hit** (hits) | `Effects.multiHit` | *Ibid.* |
731
- | **Unboost** (chance) | `Effects.unboost` | Trigger if $X < 85$ |
732
-
733
- *In the table above,* $X$ *is always in the range* $\left[0, 256\right)$ *for Pokémon Red and for
734
- Pokémon Showdown is always **scaled** from the 32-bit output range of the RNG to either be in that
735
- range or to whichever range is specified by the description.*
736
-
737
- ## Details
738
-
739
- The engine's Generation I mechanics code loosely mirrors the structure and naming of the pret
740
- decompilation of the Pokémon Red source, though has been simplified (e.g. a single method for both
741
- sides as opposed to having separate duplicated code for each) and optimized. Furthermore, the
742
- control flow has been modified to handle both the correct Pokémon Red order of operations and
743
- Pokémon Showdown's order when in compatibility mode - as such, there are many `if (showdown)` blocks
744
- which handle Pokémon Showdown's divergent behavior (this is most evident in `doMove`). The following
745
- table provides a rough mapping between pkmn and Pokémon Red methods:
746
-
747
- | pkmn | Pokémon Red (pret) |
748
- | ------------------------- | ------------------------------------------------------- |
749
- | `start` | `StartBattle` |
750
- | `update` | `MainInBattleLoop` |
751
- | `findFirstAlive` | `findFirstAlive*MonLoop` / `AnyPartyAlive` |
752
- | `selectMove` / `saveMove` | `selectPlayerMove` |
753
- | `switchIn` | `SwitchPlayerMon` / `SendOutMon` |
754
- | `turnOrder` | `MainInBattleLoop` |
755
- | `doTurn` | `MainInBattleLoop` |
756
- | `executeMove` | `ExecutePlayerMove` |
757
- | `beforeMove` | `CheckPlayerStatusConditions` |
758
- | `canMove` | `CheckIfPlayerNeedsToChargeUp` / `PlayerCanExecuteMove` |
759
- | `decrementPP` | `DecrementPP` |
760
- | `doMove` | `PlayerCalcMoveDamage` / `CalculateDamage` |
761
- | `checkCriticalHit` | `CriticalHitTest` |
762
- | `calcDamage` | `GetDamageVarsForPlayerAttack` / `CalculateDamage` |
763
- | `adjustDamage` | `AdjustDamageForMoveType` |
764
- | `randomizeDamage` | `RandomizeDamage` |
765
- | `specialDamage` | `ApplyAttackToEnemyPokemon` |
766
- | `counterDamage` | `HandleCounterMove` |
767
- | `applyDamage` | `ApplyDamageToEnemyPokemon` / `AttackSubstitute` |
768
- | `mirrorMove` | `MirrorMoveCheck` / `MirrorMoveCopyMove` |
769
- | `metronome` | `metronomeCheck` / `MetronomePickMove` |
770
- | `checkHit` / `moveHit` | `MoveHitTest` |
771
- | `checkFaint` | `HasMonFainted` / `HandlePlayerMonFainted` |
772
- | `faint` | `FaintEnemyPokemon` |
773
- | `handleResidual` | `HandlePoisonBurnLeechSeed` |
774
- | `endTurn` / `checkEBC` | - |
775
-
776
- Pokémon Red groups move effect handlers together into several groups, these have also been renamed for clarification in the pkmn engine:
777
-
778
- | pkmn | Pokémon Red (pret) |
779
- | --------------- | ------------------------- |
780
- | `onBeforeMove` | `ResidualEffects1` |
781
- | `onEndMove` | `ResidualEffects2` |
782
- | `alwaysHappens` | `AlwaysHappensSideEffect` |
783
- | `isSpecial` | `SpecialEffects` |
784
-
785
- ### Naming
786
-
787
- The pkmn engine attempts to adhere to certain naming conventions:
788
-
789
- - **`p1`** & **`p2`** always correspond to the `Side` of `Player.P1` and `Player.P2` respectively
790
- - **`player`** is the executing turn `Player` (`hWhoseTurn`) and **`player.foe()`** is their
791
- opponent
792
- - if `player` (executing turn player) is present then **`side`** will always correspond to their
793
- `Side` and **`foe`** the opposing `Side`, however `side` can refer to an arbitrary `Side` object
794
- if there is no `player` in scope (e.g. in helper functions)
795
- - **`target_player`** is a target `Player` whose corresponding `Side` is **`target`**
796
-
797
- ## Resources
798
-
799
- - [pret/pokered](https://github.com/pret/pokered/) disassembly
800
- - [Gen I Main Battle Function](https://www.smogon.com/forums/posts/5878612/show) - Crystal_
801
- - [Pokemon Showdown!](https://github.com/smogon/pokemon-showdown)
802
- - [List of glitches (Generation
803
- I)](https://bulbapedia.bulbagarden.net/wiki/List_of_glitches_(Generation_I))
804
- - [Pokémon Showdown RBY Bugs](https://www.smogon.com/forums/posts/5933177/show)