@pkmn/engine 0.1.0-dev.b9fb6eab → 0.1.0-dev.c4dec0f7

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.
package/build.zig CHANGED
@@ -1,6 +1,8 @@
1
1
  const std = @import("std");
2
2
  const builtin = @import("builtin");
3
3
 
4
+ const NativeTargetInfo = std.zig.system.NativeTargetInfo;
5
+
4
6
  pub const Options = struct { showdown: ?bool = null, trace: ?bool = null };
5
7
 
6
8
  pub fn module(b: *std.Build, options: Options) *std.Build.Module {
@@ -28,7 +30,7 @@ pub fn build(b: *std.Build) !void {
28
30
  const strip = b.option(bool, "strip", "Strip debugging symbols from binary") orelse false;
29
31
  const pic = b.option(bool, "pic", "Force position independent code") orelse false;
30
32
 
31
- const cmd = b.findProgram(&.{"strip"}, &.{}) catch null;
33
+ const cmd = b.findProgram(&[_][]const u8{"strip"}, &[_][]const u8{}) catch null;
32
34
 
33
35
  var parser = std.json.Parser.init(b.allocator, false);
34
36
  defer parser.deinit();
@@ -64,7 +66,7 @@ pub fn build(b: *std.Build) !void {
64
66
  lib.linkLibC();
65
67
  if (node_import_lib) |il| {
66
68
  lib.addObjectFile(il);
67
- } else if ((try std.zig.system.NativeTargetInfo.detect(target)).target.os.tag == .windows) {
69
+ } else if ((try NativeTargetInfo.detect(target)).target.os.tag == .windows) {
68
70
  try std.io.getStdErr().writeAll("Must provide --node-import-library path on Windows\n");
69
71
  std.process.exit(1);
70
72
  }
@@ -72,7 +74,7 @@ pub fn build(b: *std.Build) !void {
72
74
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
73
75
  if (pic) lib.force_pic = pic;
74
76
  // Always emit to build/lib because this is where the driver code expects to find it
75
- // TODO(ziglang/zig#2231): using the following used to work (though was hacky):
77
+ // TODO(ziglang/zig#2231): using the following used to work (though be hacky):
76
78
  //
77
79
  // lib.emit_bin = .{ .emit_to = b.fmt("build/lib/{s}", .{addon}) };
78
80
  // b.getInstallStep().dependOn(&lib.step);
@@ -96,10 +98,13 @@ pub fn build(b: *std.Build) !void {
96
98
  lib.rdynamic = true;
97
99
  lib.strip = strip;
98
100
  if (pic) lib.force_pic = pic;
99
- const opt = b.findProgram(&.{"wasm-opt"}, &.{"./node_modules/.bin"}) catch null;
101
+ const opt = b.findProgram(
102
+ &[_][]const u8{"wasm-opt"},
103
+ &[_][]const u8{"./node_modules/.bin"},
104
+ ) catch null;
100
105
  if (optimize != .Debug and opt != null) {
101
106
  const out = b.fmt("build/lib/{s}.wasm", .{name});
102
- const sh = b.addSystemCommand(&.{ opt.?, "-O4" });
107
+ const sh = b.addSystemCommand(&[_][]const u8{ opt.?, "-O4" });
103
108
  sh.addArtifactArg(lib);
104
109
  sh.addArg("-o");
105
110
  sh.addFileSourceArg(.{ .path = out });
@@ -230,7 +235,7 @@ fn maybeStrip(
230
235
  if (mac and artifact.isDynamicLibrary()) return;
231
236
  // Assuming GNU strip, which complains "illegal pathname found in archive member"...
232
237
  if (!mac and artifact.isStaticLibrary()) return;
233
- const sh = b.addSystemCommand(&.{ cmd.?, if (mac) "-x" else "-s" });
238
+ const sh = b.addSystemCommand(&[_][]const u8{ cmd.?, if (mac) "-x" else "-s" });
234
239
  sh.addArtifactArg(artifact);
235
240
  step.dependOn(&sh.step);
236
241
  }
@@ -243,7 +248,7 @@ const Config = struct {
243
248
  cmd: ?[]const u8,
244
249
  };
245
250
 
246
- const TESTS = .{
251
+ const TESTS = [_][]const u8{
247
252
  "src/lib/common/test.zig",
248
253
  "src/lib/gen1/test.zig",
249
254
  "src/lib/gen2/test.zig",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pkmn/engine",
3
- "version": "0.1.0-dev.b9fb6eab",
3
+ "version": "0.1.0-dev.c4dec0f7",
4
4
  "description": "A minimal, complete, Pokémon battle simulation engine optimized for performance",
5
5
  "repository": "github:pkmn/engine",
6
6
  "license": "MIT",
@@ -15,10 +15,8 @@ const DEV = ZIG_VERSION.dev ? `-dev.${ZIG_VERSION.dev}` : '';
15
15
  const VERSION = `${ZIG_VERSION.major}.${ZIG_VERSION.minor}.${ZIG_VERSION.patch}${DEV}`;
16
16
  const INDEX = 'https://ziglang.org/download/index.json';
17
17
  const ROOT = path.resolve(__dirname, '..', '..');
18
- let SILENT = false;
19
18
 
20
19
  const sh = (cmd, args) => execFileSync(cmd, args, {encoding: 'utf8', cwd: ROOT});
21
- const log = (...args) => { if (!SILENT) console.log(...args); };
22
20
 
23
21
  // This is hardly the browser fetch API, but it works for our primitive needs
24
22
  const fetch = url => new Promise((resolve, reject) => {
@@ -63,7 +61,7 @@ const unpack7 = (input, output) => new Promise((resolve, reject) => {
63
61
  require.resolve('7zip-min');
64
62
  } catch (err) {
65
63
  if (err.code !== 'MODULE_NOT_FOUND') throw err;
66
- log('Installing 7zip-min package locally to unpack the archive...');
64
+ console.log('Installing 7zip-min package locally to unpack the archive...');
67
65
  sh('npm', ['install', '7zip-min', '--no-audit', '--no-save']);
68
66
  }
69
67
 
@@ -85,7 +83,7 @@ const unpack = async (input, output) => {
85
83
  sh('tar', ['xf', input, '-C', output]);
86
84
  return;
87
85
  } catch {
88
- log('tar command not found, falling back to 7z');
86
+ console.log('tar command not found, falling back to 7z');
89
87
  }
90
88
  }
91
89
  // Try to use a 7z binary if we can, and only install 7zip-min as a last resort
@@ -122,10 +120,10 @@ const find = zig => {
122
120
  (!ZIG_VERSION.dev || (dev && dev >= ZIG_VERSION.dev)));
123
121
 
124
122
  if (compatible) {
125
- log('Found existing compatible Zig executable:', zig_exe);
123
+ console.log('Found existing compatible Zig executable:', zig_exe);
126
124
  return zig_exe;
127
125
  } else {
128
- log(`Existing Zig executable is not compatible (${version} < ${VERSION}):`, zig_exe);
126
+ console.log(`Existing Zig executable is not compatible (${version} < ${VERSION}):`, zig_exe);
129
127
  }
130
128
  } catch (err) {
131
129
  if (err.code !== 'ENOENT') throw err;
@@ -170,11 +168,11 @@ const install = async () => {
170
168
  let base = path.basename(url);
171
169
  const archive = path.join(dir, path.basename(url));
172
170
 
173
- log(`Downloading Zig tarball from ${url} to ${archive}`);
171
+ console.log(`Downloading Zig tarball from ${url} to ${archive}`);
174
172
  try {
175
173
  await download(url, archive, release.shasum);
176
174
 
177
- log(`Extracting tarball and installing to ${dir}`);
175
+ console.log(`Extracting tarball and installing to ${dir}`);
178
176
  await unpack(archive, dir);
179
177
  if (archive.endsWith('.zip')) {
180
178
  base = base.slice(0, -4);
@@ -189,17 +187,17 @@ const install = async () => {
189
187
  } catch (err) {
190
188
  if (err.code !== 'ENOENT') throw err;
191
189
  }
192
- log(`Zig${version === 'master' ? '' : ` v${version}`} executable:`, zig,
190
+ console.log(`Zig${version === 'master' ? '' : ` v${version}`} executable:`, zig,
193
191
  '(this version of Zig will be retained to speed up future updates)');
194
192
  const [pre, post] = tty.isatty(1) ? ['\x1b[1m\x1b[35m', '\x1b[0m'] : ['', ''];
195
- log(
193
+ console.log(
196
194
  `${pre}Consider moving the ${path.dirname(zig)} directory and adding it to your PATH`,
197
195
  `to use Zig on other projects, or delete this if you wish to save space.${post}`
198
196
  );
199
197
 
200
198
  return zig;
201
199
  } finally {
202
- log(`Cleaning up ${archive}`);
200
+ console.log(`Cleaning up ${archive}`);
203
201
  try { fs.rmSync(archive); } catch {}
204
202
  }
205
203
  };
@@ -208,17 +206,17 @@ const install = async () => {
208
206
  const downloadHeaders = async () => {
209
207
  const include = path.resolve(process.execPath, '..', '..', 'include', 'node');
210
208
  if (fs.existsSync(path.join(include, 'node.h'))) {
211
- log('Node headers:', include);
209
+ console.log('Node headers:', include);
212
210
  return include;
213
211
  }
214
212
 
215
213
  const dir = path.join(ROOT, 'build', 'include');
216
- const dest = path.join(dir, 'node');
214
+ const dest = path.join(dir, `node-${process.version}`, 'include', 'node');
217
215
  if (fs.existsSync(path.join(dest, 'node.h'))) {
218
- log('Node headers:', dest);
216
+ console.log('Node headers:', dest);
219
217
  return dest;
220
218
  } else {
221
- log(`Could not find Node headers at ${include}, downloading...`);
219
+ console.log(`Could not find Node headers at ${include}, downloading...`);
222
220
  }
223
221
 
224
222
  try {
@@ -229,28 +227,20 @@ const downloadHeaders = async () => {
229
227
 
230
228
  const url = process.release.headersUrl;
231
229
  const targz = path.join(dir, path.basename(url));
232
- const unpacked = path.join(dir, `node-${process.version}`, 'include');
233
230
 
234
- log(`Downloading Node headers from ${url} to ${targz}`);
231
+ console.log(`Downloading Node headers from ${url} to ${targz}`);
232
+ await download(url, targz);
233
+ await unpack(targz, dir);
235
234
 
236
- try {
237
- await download(url, targz);
238
- await unpack(targz, dir);
239
- fs.renameSync(path.join(unpacked, 'node'), dest);
240
-
241
- log('Node headers:', dest);
235
+ console.log('Node headers:', dest);
242
236
 
243
- return dest;
244
- } finally {
245
- try { fs.rmSync(targz); } catch {}
246
- try { fs.rmSync(unpacked, {recursive: true}); } catch {}
247
- }
237
+ return dest;
248
238
  };
249
239
 
250
240
  const downloadImportLib = async () => {
251
241
  const library = path.resolve(process.execPath, '..', 'node.lib');
252
242
  if (fs.existsSync(path.join(library, 'node.h'))) {
253
- log('Node import library:', library);
243
+ console.log('Node import library:', library);
254
244
  return library;
255
245
  }
256
246
 
@@ -258,10 +248,10 @@ const downloadImportLib = async () => {
258
248
  const url = new URL('./win-x64/node.lib', process.release.headersUrl).href;
259
249
  const dest = path.join(dir, path.basename(url));
260
250
  if (fs.existsSync(path.join(dest))) {
261
- log('Node import library:', dest);
251
+ console.log('Node import library:', dest);
262
252
  return dest;
263
253
  } else {
264
- log(`Could not find Node import library at ${library}, downloading...`);
254
+ console.log(`Could not find Node import library at ${library}, downloading...`);
265
255
  }
266
256
 
267
257
  try {
@@ -270,41 +260,24 @@ const downloadImportLib = async () => {
270
260
  if (err.code !== 'EEXIST') throw err;
271
261
  }
272
262
 
273
- log(`Downloading Node import library from ${url} to ${dest}`);
263
+ console.log(`Downloading Node import library from ${url} to ${dest}`);
274
264
  await download(url, dest);
275
- log('Node import library:', dest);
265
+ console.log('Node import library:', dest);
276
266
 
277
267
  return dest;
278
268
  };
279
269
 
280
270
  (async () => {
281
- let only = false;
282
- let options = undefined;
283
- let error = false;
284
- for (let i = 2; i < process.argv.length; i++) {
285
- switch (process.argv[i]) {
286
- case "--silent": {
287
- SILENT = true;
288
- break;
289
- }
290
- case "--zig": {
291
- if (options || only) error = true;
292
- only = true;
293
- break;
294
- }
295
- default: {
296
- if (options || only || !process.argv[i].startsWith('--options=')) error = true;
297
- options = process.argv[i].slice(10).split(' ');
298
- }
299
- }
300
- }
301
- if (error) {
271
+ const options = (process.argv[2] || '').startsWith('--options=')
272
+ ? process.argv[2].slice(10).split(' ') : undefined;
273
+ if (process.argv.length > 3 ||
274
+ process.argv.length === 3 && !(process.argv[2] === '--zig' || options)) {
302
275
  console.error('Invalid arguments');
303
276
  process.exit(1);
304
277
  }
305
278
 
306
279
  const zig = await install();
307
- if (only) process.exit(0);
280
+ if (process.argv[2] === '--zig') process.exit(0);
308
281
 
309
282
  let tmp;
310
283
  try {
@@ -374,7 +347,7 @@ const downloadImportLib = async () => {
374
347
  opts.includes('-Dshowdown') || opts.includes('-Dshowdown=true') ? '-showdown' : '';
375
348
  const flags = opts.length ? ` (${opts.join(' ')})` : '';
376
349
  const artifact = path.join('build', 'lib', `pkmn${suffix}.${config.type}`);
377
- log(`Building ${artifact}${flags}`);
350
+ console.log(`Building ${artifact}${flags}`);
378
351
  sh(zig, args);
379
352
  // TODO: ziglang/zig#14647 broke emit_to so we get to rename the file ourselves...
380
353
  if (config.type === 'node') {
@@ -382,7 +355,7 @@ const downloadImportLib = async () => {
382
355
  const ext = process.platform === 'darwin'
383
356
  ? 'dylib' : process.platform === 'win32' ? 'dll' : 'so';
384
357
  const actual = path.join('build', 'lib', `${prefix}pkmn${suffix}.node.${ext}`);
385
- fs.renameSync(path.join(ROOT, actual), path.join(ROOT, artifact));
358
+ fs.renameSync(actual, artifact);
386
359
  }
387
360
  }
388
361
  })().catch(e => {
@@ -467,7 +467,7 @@ Documentation of the wire protocol used for logging traces when `-Dtrace` is ena
467
467
 
468
468
  In addition to its alternative [RNG semantics](#rng), Pokémon Showdown's implementation of the first
469
469
  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/posts/5933177/show):
470
+ Smogon](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3524844/#post-5933177):
471
471
 
472
472
  - moves on Pokémon Showdown can do 0 damage instead of failing or causing a [division-by-zero
473
473
  freeze](https://pkmn.cc/bulba-glitch-1#Division_by_0).
@@ -482,19 +482,14 @@ Beyond the general bugs listed above, several move effects are implemented incor
482
482
  Showdown. Some of these moves are [too fundamentally broken to be implemented](#unimplementable) by
483
483
  the pkmn engine, but the following moves have their broken behavior preserved in `-Dshowdown` mode:
484
484
 
485
- - **Bide**: If the opponent faints after Bide inflicts damage on Pokémon Showdown residual damage
486
- incorrectly still gets applied to Bide's user.
487
485
  - **Leech Seed**: Leech Seed fails to heal its source side if a seeded target faints due to
488
- recoil/crash damage on Pokémon Showdown. Pokémon Showdown also updates the battle's last damage
489
- field with the uncapped Leech Seed damage which has consequences for Bide and Counter.
486
+ recoil/crash damage on Pokémon Showdown.
490
487
  - **Pay Day**: Pay Day should still scatter coins if it hits (but doesn't break) and opponent's
491
488
  Substitute but doesn't on Pokémon Showdown.
492
489
  - **Flinch**: Flinching does not get cleared during move selection on Pokémon Showdown and is
493
490
  instead cleared in Pokémon Showdown's "residual" phase, meaning the flinch status gets erroneously
494
491
  preserved across fainting (as fainting triggers Pokémon Showdown's "instaswitch" behavior which
495
492
  skips end-of-turn residuals).
496
- - **Rage**: Rage boosts should still result in burn/paralysis [stat modification
497
- errors](https://pkmn.cc/bulba-glitch-1#Stat_modification_errors) but don't on Pokémon Showdown.
498
493
  - **Thrash** / **Petal Dance**: once a Pokémon is locked into a thrashing move they will lose all
499
494
  speed ties on Pokémon Showdown (due to the fact that if they win the speed tie their action will
500
495
  then get "changed" and inserted back into the queue after their opponent's action).
@@ -513,8 +508,7 @@ the pkmn engine, but the following moves have their broken behavior preserved in
513
508
  implement by Pokémon Showdown.
514
509
  - **Roar** / **Whirlwind**: these moves can miss on Pokémon Showdown (and advance the RNG when
515
510
  checking) which is incorrect (these moves should always fail, but do not check accuracy or advance
516
- the RNG). More importantly, these moves should *not* cause the tracked last battle damage to be
517
- zeroed, but on Pokémon Showdown they do.
511
+ the RNG).
518
512
  - **Substitute**: in addition to the [Substitute + Confusion
519
513
  glitch](https://pkmn.cc/bulba-glitch-1#Substitute_.2B_Confusion_glitch) not being implemented
520
514
  correctly (covered above), the [Substitute 1/4
@@ -556,7 +550,7 @@ called out in the `|rule|` section at the beginning of a battle's log):
556
550
  `|rule|` section** in Generation I (or II) as the actual order of switches here does not have
557
551
  competitive implications like it does in Generation III, but it is still contrary to how the games
558
552
  work where the [host (Player 1)'s Pokemon would switch
559
- first](https://www.smogon.com/forums/posts/5989318/show).
553
+ first](https://www.smogon.com/forums/threads/gen-3-on-ps-final-fixes.3527268/post-5989318).
560
554
 
561
555
  Pokémon Showdown enforces several clauses *before* the battle: **Cleric Clause** (all Pokémon must
562
556
  have full HP and PP, and not have any status conditions prior to the battle), **Stat Tradeback
@@ -577,12 +571,13 @@ left up to a client to support.
577
571
 
578
572
  Numerous moves on Pokémon Showdown are broken not simply due to local issues in the implementation
579
573
  of their effects but instead due to **global issues** related to fundamental mechanics such as
580
- [broken move selection](https://www.smogon.com/forums/posts/8655897/show), using move name instead
581
- of slot to determine move identity, implementing volatile statuses incorrectly or not understanding
582
- how moves which call other moves work means that it isn't possible to completely implement Pokémon
583
- Showdown's behavior for the following moves (the pkmn engine attempts to reproduce as much of the
584
- behavior that can be reproduced without making data structure changes or dramatically deviating from
585
- the correct control flow):
574
+ [broken move
575
+ selection](https://www.smogon.com/forums/threads/rby-fight-button-simulation-improvements-fix-partial-trapping-improve-counter.3673280/#post-8655897),
576
+ using move name instead of slot to determine move identity, implementing volatile statuses
577
+ incorrectly or not understanding how moves which call other moves work means that it isn't possible
578
+ to completely implement Pokémon Showdown's behavior for the following moves (the pkmn engine
579
+ attempts to reproduce as much of the behavior that can be reproduced without making data structure
580
+ changes or dramatically deviating from the correct control flow):
586
581
 
587
582
  - **Wrap**: Binding moves like Wrap are implemented on Pokémon Showdown with an artificial
588
583
  `partialtrappinglock` volatile as opposed to how it works on the cartridge which simply relies on
@@ -671,10 +666,10 @@ compatibility mode, the implications of these differences are outlined below:
671
666
  Finally, the **initial 10-byte seed for link battles on Pokémon Red cannot include bytes larger than
672
667
  the `SERIAL_PREAMBLE_BYTE`**, so must be in the range $\left[0, 252\right]$. This has implications
673
668
  on the first 10 random numbers generated during the battle and has [**non-trivial competitive
674
- implications**](https://www.smogon.com/forums/posts/9068411/show) (at the start of the battle move
675
- effects become more likely, the ["1/256-miss" glitch](https://glitchcity.wiki/1/256_miss_glitch)
676
- cannot happen, Player 1 is more likely to win speed ties, etc) that Pokémon Showdown cannot
677
- replicate due to everything described above.
669
+ implications**](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3524844/page-16#post-9068411)
670
+ (at the start of the battle move effects become more likely, the ["1/256-miss"
671
+ glitch](https://glitchcity.wiki/1/256_miss_glitch) cannot happen, Player 1 is more likely to win
672
+ speed ties, etc) that Pokémon Showdown cannot replicate due to everything described above.
678
673
 
679
674
  All of places in the link battle code where randomness is required are outlined below:
680
675
 
@@ -773,8 +768,11 @@ The pkmn engine attempts to adhere to certain naming conventions:
773
768
  ## Resources
774
769
 
775
770
  - [pret/pokered](https://github.com/pret/pokered/) disassembly
776
- - [Gen I Main Battle Function](https://www.smogon.com/forums/posts/5878612/show) - Crystal_
771
+ - [Gen I Main Battle
772
+ Function](https://www.smogon.com/forums/threads/past-gens-research-thread.3506992/#post-5878612) -
773
+ Crystal_
777
774
  - [Pokemon Showdown!](https://github.com/smogon/pokemon-showdown)
778
775
  - [List of glitches (Generation
779
776
  I)](https://bulbapedia.bulbagarden.net/wiki/List_of_glitches_(Generation_I))
780
- - [Pokémon Showdown RBY Bugs](https://www.smogon.com/forums/posts/5933177/show)
777
+ - [Pokémon Showdown RBY
778
+ Bugs](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3524844/#post-5933177)
@@ -347,7 +347,6 @@ fn doTurn(
347
347
  if (try checkFaint(battle, player, log)) |r| return r;
348
348
  } else if (foe_choice.type == .Pass) return null;
349
349
 
350
- residual = true;
351
350
  replace = battle.side(foe_player).stored().hp == 0;
352
351
  if (try executeMove(battle, foe_player, foe_choice, foe_from, &residual, log)) |r| return r;
353
352
  if (!replace) {
@@ -435,7 +434,7 @@ fn executeMove(
435
434
 
436
435
  var skip_can = false;
437
436
  var skip_pp = false;
438
- switch (try beforeMove(battle, player, from, residual, log)) {
437
+ switch (try beforeMove(battle, player, from, log)) {
439
438
  .done => return null,
440
439
  .skip_can => skip_can = true,
441
440
  .skip_pp => skip_pp = true,
@@ -452,13 +451,7 @@ fn executeMove(
452
451
 
453
452
  const BeforeMove = union(enum) { done, skip_can, skip_pp, ok, err };
454
453
 
455
- fn beforeMove(
456
- battle: anytype,
457
- player: Player,
458
- from: ?Move,
459
- residual: *bool,
460
- log: anytype,
461
- ) !BeforeMove {
454
+ fn beforeMove(battle: anytype, player: Player, from: ?Move, log: anytype) !BeforeMove {
462
455
  var side = battle.side(player);
463
456
  const foe = battle.foe(player);
464
457
  var active = &side.active;
@@ -544,7 +537,7 @@ fn beforeMove(
544
537
 
545
538
  if (confused) {
546
539
  assert(!volatiles.MultiHit);
547
- if (!volatiles.Rage) volatiles.state = 0;
540
+ volatiles.state = 0;
548
541
  volatiles.Bide = false;
549
542
  volatiles.Thrashing = false;
550
543
  volatiles.MultiHit = false;
@@ -585,7 +578,7 @@ fn beforeMove(
585
578
  battle.rng.next() < Gen12.percent(25);
586
579
 
587
580
  if (paralyzed) {
588
- if (!volatiles.Rage) volatiles.state = 0;
581
+ volatiles.state = 0;
589
582
  volatiles.Bide = false;
590
583
  volatiles.Thrashing = false;
591
584
  volatiles.Charging = false;
@@ -621,15 +614,7 @@ fn beforeMove(
621
614
  }
622
615
 
623
616
  _ = try applyDamage(battle, player.foe(), player.foe(), .None, log);
624
- if (foe.stored().hp > 0) try buildRage(battle, player.foe(), log);
625
-
626
- // For reasons passing understanding, Pokémon Showdown still inflicts residual damage to
627
- // Bide's user even if the above damage has caused the foe to faint. It's simpler to always
628
- // run residual here regardless of whether the foe fainted and opt-out of the default flow
629
- if (showdown) {
630
- residual.* = false;
631
- try handleResidual(battle, player, log);
632
- }
617
+ try buildRage(battle, player.foe(), log);
633
618
 
634
619
  return .done;
635
620
  }
@@ -947,7 +932,7 @@ fn doMove(
947
932
  if (foe.stored().hp == 0) return null;
948
933
 
949
934
  // Pokémon Showdown builds Rage at the wrong time for non-MultiHit moves
950
- if (late and move.effect != .Disable) try buildRage(battle, player.foe(), log);
935
+ if (late) try buildRage(battle, player.foe(), log);
951
936
 
952
937
  if (!move.effect.isSpecial()) {
953
938
  // On the cartridge Rage is not considered to be "special" and thus gets executed for a
@@ -960,9 +945,7 @@ fn doMove(
960
945
  if (move.effect == .Twineedle) {
961
946
  if (!showdown) try Effects.poison(battle, player, Move.get(.PoisonSting), log);
962
947
  } else if (move.effect == .Disable) {
963
- const result = try Effects.disable(battle, player, move, log);
964
- if (showdown) try buildRage(battle, player.foe(), log);
965
- return result;
948
+ return Effects.disable(battle, player, move, log);
966
949
  } else {
967
950
  try moveEffect(battle, player, move, log);
968
951
  }
@@ -1128,7 +1111,7 @@ fn specialDamage(battle: anytype, player: Player, move: Move.Data, log: anytype)
1128
1111
  if (battle.last_damage == 0) return if (showdown) null else Result.Error;
1129
1112
 
1130
1113
  _ = try applyDamage(battle, player.foe(), player.foe(), .None, log);
1131
- if (battle.foe(player).stored().hp > 0) try buildRage(battle, player.foe(), log);
1114
+ try buildRage(battle, player.foe(), log);
1132
1115
 
1133
1116
  return null;
1134
1117
  }
@@ -1452,15 +1435,6 @@ fn handleResidual(battle: anytype, player: Player, log: anytype) !void {
1452
1435
  }
1453
1436
 
1454
1437
  if (volatiles.LeechSeed) {
1455
- var foe = battle.foe(player);
1456
- var foe_stored = foe.stored();
1457
- const foe_ident = battle.active(player.foe());
1458
-
1459
- if (foe_stored.hp == 0) {
1460
- assert(showdown);
1461
- return;
1462
- }
1463
-
1464
1438
  var damage = @max(stored.stats.hp / 16, 1);
1465
1439
 
1466
1440
  // GLITCH: Leech Seed + Toxic glitch
@@ -1469,12 +1443,13 @@ fn handleResidual(battle: anytype, player: Player, log: anytype) !void {
1469
1443
  damage *= volatiles.toxic;
1470
1444
  }
1471
1445
 
1472
- // Pokémon Showdown erroneously updates last damage with uncapped Leech Seed damage
1473
- if (showdown) battle.last_damage = damage;
1474
-
1475
1446
  const amount = @min(damage, stored.hp);
1476
1447
  stored.hp -= amount;
1477
1448
 
1449
+ var foe = battle.foe(player);
1450
+ var foe_stored = foe.stored();
1451
+ const foe_ident = battle.active(player.foe());
1452
+
1478
1453
  // As above, Pokémon Showdown uses damageOf but its not relevant
1479
1454
  if (amount > 0) try log.damage(ident, stored, .LeechSeed);
1480
1455
 
@@ -2256,9 +2231,8 @@ pub const Effects = struct {
2256
2231
  fn switchAndTeleport(battle: anytype, player: Player, move: Move.Data, log: anytype) !void {
2257
2232
  if (!showdown or battle.side(player).last_selected_move == .Teleport) return;
2258
2233
 
2259
- // Whirlwind/Roar should not roll to hit/reset damage but Pokémon Showdown does anyway
2234
+ // Whirlwind/Roar should not roll to hit but Pokémon Showdown does anyway
2260
2235
  _ = try checkHit(battle, player, move, log);
2261
- battle.last_damage = 0;
2262
2236
  }
2263
2237
 
2264
2238
  fn thrashing(battle: anytype, player: Player) void {
@@ -2343,8 +2317,6 @@ pub const Effects = struct {
2343
2317
  const stat = unmodifiedStats(battle, player).atk;
2344
2318
  stats.atk = @min(MAX_STAT_VALUE, stat * mod[0] / mod[1]);
2345
2319
  try log.boost(ident, reason, n);
2346
- // Pokémon Showdown doesn't re-apply status modifiers after Rage boosts
2347
- if (showdown and move.effect == .Rage) return;
2348
2320
  },
2349
2321
  .DefenseUp1, .DefenseUp2 => {
2350
2322
  assert(boosts.def >= -6 and boosts.def <= 6);
@@ -2595,14 +2567,9 @@ fn disabled(side: *Side, ident: ID, log: anytype) !bool {
2595
2567
  if (side.active.volatiles.disabled_move != 0) {
2596
2568
  // A Pokémon that transforms after being disabled may end up with less move slots
2597
2569
  const m = side.active.moves[side.active.volatiles.disabled_move - 1].id;
2598
- // side.last_selected_move can be Struggle here on Pokemon Showdown we need an extra check
2599
- const last = if (showdown and m == .Bide and side.active.volatiles.Bide)
2600
- m
2601
- else
2602
- side.last_selected_move;
2603
- if (m != .None and m == last) {
2570
+ if (m != .None and m == side.last_selected_move) {
2604
2571
  side.active.volatiles.Charging = false;
2605
- try log.disabled(ident, last);
2572
+ try log.disabled(ident, side.last_selected_move);
2606
2573
  return true;
2607
2574
  }
2608
2575
  }
@@ -2765,10 +2732,8 @@ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Cho
2765
2732
  const m = active.moves[slot - 1];
2766
2733
  if (m.id == .None) break;
2767
2734
  if (m.id == side.last_selected_move) {
2768
- // Pokémon Showdown displays Struggle if limited to Bide but unable to pick
2769
- const struggle =
2770
- m.id == .Bide and (m.pp == 0 or active.volatiles.disabled_move == slot);
2771
- const s = if (struggle) 0 else slot;
2735
+ // Pokémon Showdown displays Struggle if limited to Bide when out of PP
2736
+ const s = if (m.pp == 0 and m.id == .Bide) 0 else slot;
2772
2737
  out[n] = .{ .type = .Move, .data = s };
2773
2738
  n += 1;
2774
2739
  return n;