@pkmn/engine 0.1.0-dev.2ec67dba → 0.1.0-dev.3a273268

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pkmn/engine",
3
- "version": "0.1.0-dev.2ec67dba",
3
+ "version": "0.1.0-dev.3a273268",
4
4
  "description": "A minimal, complete, Pokémon battle simulation engine optimized for performance",
5
5
  "repository": "github:pkmn/engine",
6
6
  "license": "MIT",
@@ -9,6 +9,28 @@
9
9
  "types": "build/pkg/index.d.ts",
10
10
  "files": [
11
11
  "build.zig",
12
+ "build/pkg/data.d.ts",
13
+ "build/pkg/data.js.map",
14
+ "build/pkg/addon.d.ts",
15
+ "build/pkg/addon.js.map",
16
+ "build/pkg/addon.js",
17
+ "build/pkg/data.js",
18
+ "build/pkg/data/ids.json",
19
+ "build/pkg/data/layout.json",
20
+ "build/pkg/data/protocol.json",
21
+ "build/pkg/gen1.d.ts",
22
+ "build/pkg/gen1.js.map",
23
+ "build/pkg/gen1.js",
24
+ "build/pkg/index.d.ts",
25
+ "build/pkg/index.js.map",
26
+ "build/pkg/index.js",
27
+ "build/pkg/protocol.d.ts",
28
+ "build/pkg/protocol.js.map",
29
+ "build/pkg/protocol.js",
30
+ "build/test/display.js.map",
31
+ "build/test/display.js",
32
+ "build/tools/debug.js.map",
33
+ "build/tools/debug.js",
12
34
  "src/bin/install-pkmn-engine",
13
35
  "src/lib/binding/node.zig",
14
36
  "src/lib/binding/wasm.zig",
@@ -17,54 +39,41 @@
17
39
  "src/lib/common/options.zig",
18
40
  "src/lib/common/protocol.zig",
19
41
  "src/lib/common/rng.zig",
42
+ "src/lib/gen1/data.zig",
20
43
  "src/lib/gen1/data/moves.zig",
21
44
  "src/lib/gen1/data/species.zig",
22
45
  "src/lib/gen1/data/types.zig",
23
- "src/lib/gen1/data.zig",
24
46
  "src/lib/gen1/helpers.zig",
25
47
  "src/lib/gen1/mechanics.zig",
48
+ "src/lib/gen2/data.zig",
26
49
  "src/lib/gen2/data/items.zig",
27
50
  "src/lib/gen2/data/moves.zig",
28
51
  "src/lib/gen2/data/species.zig",
29
52
  "src/lib/gen2/data/types.zig",
30
- "src/lib/gen2/data.zig",
31
53
  "src/lib/gen2/helpers.zig",
32
54
  "src/lib/gen2/mechanics.zig",
33
55
  "src/lib/pkmn.zig",
34
- "build/pkg/data/ids.json",
35
- "build/pkg/data/layout.json",
36
- "build/pkg/data/protocol.json",
37
- "build/pkg/data.d.ts",
38
- "build/pkg/data.js",
39
- "build/pkg/data.js.map",
40
- "build/pkg/gen1.d.ts",
41
- "build/pkg/gen1.js",
42
- "build/pkg/gen1.js.map",
43
- "build/pkg/index.d.ts",
44
- "build/pkg/index.js",
45
- "build/pkg/index.js.map",
46
- "build/pkg/protocol.d.ts",
47
- "build/pkg/protocol.js",
48
- "build/pkg/protocol.js.map"
56
+ "src/test/display/pkmn.html.tmpl"
49
57
  ],
50
58
  "engines": {
51
59
  "node": ">=16.0.0"
52
60
  },
53
61
  "bin": {
54
- "install-pkmn-engine": "src/bin/install-pkmn-engine"
62
+ "install-pkmn-engine": "src/bin/install-pkmn-engine",
63
+ "pkmn-debug": "src/bin/pkmn-debug"
55
64
  },
56
65
  "publishConfig": {
57
66
  "access": "public"
58
67
  },
59
68
  "dependencies": {
60
- "@pkmn/data": "^0.7.34",
69
+ "@pkmn/data": "^0.7.36",
61
70
  "@pkmn/protocol": "^0.6.11"
62
71
  },
63
72
  "devDependencies": {
64
- "@pkmn/eslint-config": "^3.0.0-alpha.0",
73
+ "@pkmn/eslint-config": "^3.0.0",
65
74
  "@pkmn/img": "^0.2.8",
66
75
  "@pkmn/sets": "^5.0.4",
67
- "@pkmn/sim": "0.7.34",
76
+ "@pkmn/sim": "0.7.36",
68
77
  "@types/html-minifier": "^4.0.2",
69
78
  "@types/jest": "^29.5.0",
70
79
  "@types/minimist": "^1.2.2",
@@ -79,16 +88,17 @@
79
88
  "mustache": "^4.2.0",
80
89
  "source-map-support": "^0.5.21",
81
90
  "trakr": "^0.2.0",
82
- "typescript": "^5.0.2",
91
+ "typescript": "^5.0.3",
83
92
  "vitest": "^0.29.8"
84
93
  },
85
94
  "scripts": {
86
- "lint": "eslint --cache src --ext ts,js && eslint src/bin/install-pkmn-engine",
87
- "fix": "eslint --fix src --ext ts,js && eslint --fix src/bin/install-pkmn-engine",
95
+ "lint": "eslint --cache src --ext ts,js && eslint src/bin/*",
96
+ "fix": "eslint --fix src --ext ts,js && eslint --fix src/bin/*",
88
97
  "compile": "tsc -p .",
89
98
  "build": "npm run compile",
90
99
  "test": "vitest src/pkg",
91
100
  "test:integration": "vitest src/test",
101
+ "debug": "npm run compile && node build/tools/debug",
92
102
  "fuzz": "npm run compile && node build/test/fuzz",
93
103
  "generate": "npm run compile && node build/tools/generate",
94
104
  "release": "npm run compile && node build/tools/release",
@@ -15,8 +15,10 @@ 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;
18
19
 
19
20
  const sh = (cmd, args) => execFileSync(cmd, args, {encoding: 'utf8', cwd: ROOT});
21
+ const log = (...args) => { if (!SILENT) console.log(...args); };
20
22
 
21
23
  // This is hardly the browser fetch API, but it works for our primitive needs
22
24
  const fetch = url => new Promise((resolve, reject) => {
@@ -61,7 +63,7 @@ const unpack7 = (input, output) => new Promise((resolve, reject) => {
61
63
  require.resolve('7zip-min');
62
64
  } catch (err) {
63
65
  if (err.code !== 'MODULE_NOT_FOUND') throw err;
64
- console.log('Installing 7zip-min package locally to unpack the archive...');
66
+ log('Installing 7zip-min package locally to unpack the archive...');
65
67
  sh('npm', ['install', '7zip-min', '--no-audit', '--no-save']);
66
68
  }
67
69
 
@@ -83,7 +85,7 @@ const unpack = async (input, output) => {
83
85
  sh('tar', ['xf', input, '-C', output]);
84
86
  return;
85
87
  } catch {
86
- console.log('tar command not found, falling back to 7z');
88
+ log('tar command not found, falling back to 7z');
87
89
  }
88
90
  }
89
91
  // Try to use a 7z binary if we can, and only install 7zip-min as a last resort
@@ -120,10 +122,10 @@ const find = zig => {
120
122
  (!ZIG_VERSION.dev || (dev && dev >= ZIG_VERSION.dev)));
121
123
 
122
124
  if (compatible) {
123
- console.log('Found existing compatible Zig executable:', zig_exe);
125
+ log('Found existing compatible Zig executable:', zig_exe);
124
126
  return zig_exe;
125
127
  } else {
126
- console.log(`Existing Zig executable is not compatible (${version} < ${VERSION}):`, zig_exe);
128
+ log(`Existing Zig executable is not compatible (${version} < ${VERSION}):`, zig_exe);
127
129
  }
128
130
  } catch (err) {
129
131
  if (err.code !== 'ENOENT') throw err;
@@ -168,11 +170,11 @@ const install = async () => {
168
170
  let base = path.basename(url);
169
171
  const archive = path.join(dir, path.basename(url));
170
172
 
171
- console.log(`Downloading Zig tarball from ${url} to ${archive}`);
173
+ log(`Downloading Zig tarball from ${url} to ${archive}`);
172
174
  try {
173
175
  await download(url, archive, release.shasum);
174
176
 
175
- console.log(`Extracting tarball and installing to ${dir}`);
177
+ log(`Extracting tarball and installing to ${dir}`);
176
178
  await unpack(archive, dir);
177
179
  if (archive.endsWith('.zip')) {
178
180
  base = base.slice(0, -4);
@@ -187,17 +189,17 @@ const install = async () => {
187
189
  } catch (err) {
188
190
  if (err.code !== 'ENOENT') throw err;
189
191
  }
190
- console.log(`Zig${version === 'master' ? '' : ` v${version}`} executable:`, zig,
192
+ log(`Zig${version === 'master' ? '' : ` v${version}`} executable:`, zig,
191
193
  '(this version of Zig will be retained to speed up future updates)');
192
194
  const [pre, post] = tty.isatty(1) ? ['\x1b[1m\x1b[35m', '\x1b[0m'] : ['', ''];
193
- console.log(
195
+ log(
194
196
  `${pre}Consider moving the ${path.dirname(zig)} directory and adding it to your PATH`,
195
197
  `to use Zig on other projects, or delete this if you wish to save space.${post}`
196
198
  );
197
199
 
198
200
  return zig;
199
201
  } finally {
200
- console.log(`Cleaning up ${archive}`);
202
+ log(`Cleaning up ${archive}`);
201
203
  try { fs.rmSync(archive); } catch {}
202
204
  }
203
205
  };
@@ -206,17 +208,17 @@ const install = async () => {
206
208
  const downloadHeaders = async () => {
207
209
  const include = path.resolve(process.execPath, '..', '..', 'include', 'node');
208
210
  if (fs.existsSync(path.join(include, 'node.h'))) {
209
- console.log('Node headers:', include);
211
+ log('Node headers:', include);
210
212
  return include;
211
213
  }
212
214
 
213
215
  const dir = path.join(ROOT, 'build', 'include');
214
- const dest = path.join(dir, `node-${process.version}`, 'include', 'node');
216
+ const dest = path.join(dir, 'node');
215
217
  if (fs.existsSync(path.join(dest, 'node.h'))) {
216
- console.log('Node headers:', dest);
218
+ log('Node headers:', dest);
217
219
  return dest;
218
220
  } else {
219
- console.log(`Could not find Node headers at ${include}, downloading...`);
221
+ log(`Could not find Node headers at ${include}, downloading...`);
220
222
  }
221
223
 
222
224
  try {
@@ -227,20 +229,28 @@ const downloadHeaders = async () => {
227
229
 
228
230
  const url = process.release.headersUrl;
229
231
  const targz = path.join(dir, path.basename(url));
232
+ const unpacked = path.join(dir, `node-${process.version}`, 'include');
230
233
 
231
- console.log(`Downloading Node headers from ${url} to ${targz}`);
232
- await download(url, targz);
233
- await unpack(targz, dir);
234
+ log(`Downloading Node headers from ${url} to ${targz}`);
234
235
 
235
- console.log('Node headers:', dest);
236
+ try {
237
+ await download(url, targz);
238
+ await unpack(targz, dir);
239
+ fs.renameSync(path.join(unpacked, 'node'), dest);
236
240
 
237
- return dest;
241
+ log('Node headers:', dest);
242
+
243
+ return dest;
244
+ } finally {
245
+ try { fs.rmSync(targz); } catch {}
246
+ try { fs.rmSync(unpacked, {recursive: true}); } catch {}
247
+ }
238
248
  };
239
249
 
240
250
  const downloadImportLib = async () => {
241
251
  const library = path.resolve(process.execPath, '..', 'node.lib');
242
252
  if (fs.existsSync(path.join(library, 'node.h'))) {
243
- console.log('Node import library:', library);
253
+ log('Node import library:', library);
244
254
  return library;
245
255
  }
246
256
 
@@ -248,10 +258,10 @@ const downloadImportLib = async () => {
248
258
  const url = new URL('./win-x64/node.lib', process.release.headersUrl).href;
249
259
  const dest = path.join(dir, path.basename(url));
250
260
  if (fs.existsSync(path.join(dest))) {
251
- console.log('Node import library:', dest);
261
+ log('Node import library:', dest);
252
262
  return dest;
253
263
  } else {
254
- console.log(`Could not find Node import library at ${library}, downloading...`);
264
+ log(`Could not find Node import library at ${library}, downloading...`);
255
265
  }
256
266
 
257
267
  try {
@@ -260,24 +270,41 @@ const downloadImportLib = async () => {
260
270
  if (err.code !== 'EEXIST') throw err;
261
271
  }
262
272
 
263
- console.log(`Downloading Node import library from ${url} to ${dest}`);
273
+ log(`Downloading Node import library from ${url} to ${dest}`);
264
274
  await download(url, dest);
265
- console.log('Node import library:', dest);
275
+ log('Node import library:', dest);
266
276
 
267
277
  return dest;
268
278
  };
269
279
 
270
280
  (async () => {
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)) {
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) {
275
302
  console.error('Invalid arguments');
276
303
  process.exit(1);
277
304
  }
278
305
 
279
306
  const zig = await install();
280
- if (process.argv[2] === '--zig') process.exit(0);
307
+ if (only) process.exit(0);
281
308
 
282
309
  let tmp;
283
310
  try {
@@ -347,7 +374,7 @@ const downloadImportLib = async () => {
347
374
  opts.includes('-Dshowdown') || opts.includes('-Dshowdown=true') ? '-showdown' : '';
348
375
  const flags = opts.length ? ` (${opts.join(' ')})` : '';
349
376
  const artifact = path.join('build', 'lib', `pkmn${suffix}.${config.type}`);
350
- console.log(`Building ${artifact}${flags}`);
377
+ log(`Building ${artifact}${flags}`);
351
378
  sh(zig, args);
352
379
  // TODO: ziglang/zig#14647 broke emit_to so we get to rename the file ourselves...
353
380
  if (config.type === 'node') {
@@ -355,7 +382,7 @@ const downloadImportLib = async () => {
355
382
  const ext = process.platform === 'darwin'
356
383
  ? 'dylib' : process.platform === 'win32' ? 'dll' : 'so';
357
384
  const actual = path.join('build', 'lib', `${prefix}pkmn${suffix}.node.${ext}`);
358
- fs.renameSync(actual, artifact);
385
+ fs.renameSync(path.join(ROOT, actual), path.join(ROOT, artifact));
359
386
  }
360
387
  }
361
388
  })().catch(e => {
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ try {
5
+ require('source-map-support').install();
6
+ } catch (err) {
7
+ if (err.code !== 'MODULE_NOT_FOUND') throw err;
8
+ }
9
+
10
+ const {execFileSync} = require('child_process');
11
+ const {readFileSync} = require('fs');
12
+ const {join, resolve} = require('path');
13
+
14
+ const ROOT = resolve(__dirname, '..', '..');
15
+ const packageJSON = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
16
+
17
+ const missing = [];
18
+ for (const dep of ['@pkmn/img', 'html-minifier', 'mustache']) {
19
+ try {
20
+ require.resolve(dep);
21
+ } catch (e) {
22
+ if (e.code !== 'MODULE_NOT_FOUND') throw e;
23
+ missing.push(`${dep}@${packageJSON.devDependencies[dep]}`);
24
+ }
25
+ }
26
+
27
+ let Dex = undefined;
28
+ try {
29
+ Dex = require('@pkmn/sim').Dex;
30
+ } catch (err) {
31
+ if (err.code !== 'MODULE_NOT_FOUND') throw err;
32
+ try {
33
+ Dex = require('@pkmn/dex').Dex;
34
+ } catch (e) {
35
+ if (e.code !== 'MODULE_NOT_FOUND') throw e;
36
+ missing.push(`@pkmn/dex@${packageJSON.dependencies['@pkmn/data']}`);
37
+ }
38
+ }
39
+
40
+ if (missing.length) {
41
+ if (+/^v(\d+)/.exec(process.version)[1] < 16) {
42
+ console.error('pkmn-debug requires Node v16+');
43
+ process.exit(1);
44
+ }
45
+
46
+ execFileSync('npm', ['install', ...missing, '--global'], {encoding: 'utf8'});
47
+
48
+ const node_modules = execFileSync('npm', ['root', '--global'], {encoding: 'utf8'}).trim();
49
+ if (!process.env.NODE_PATH || !process.env.NODE_PATH.includes(node_modules)) {
50
+ console.error(`NODE_PATH must include npm's global node_modules directory: '${node_modules}'`);
51
+ process.exit(1);
52
+ }
53
+ }
54
+
55
+ const {Generations} = require('@pkmn/data');
56
+
57
+ const {run} = require('../../build/tools/debug');
58
+
59
+ run(new Generations(Dex)).catch(err => {
60
+ console.error(err.message);
61
+ process.exit(1);
62
+ });
@@ -34,11 +34,11 @@ fn bindings(env: c.napi_env) c.napi_value {
34
34
  }
35
35
 
36
36
  fn bind(env: c.napi_env, gen: anytype) c.napi_value {
37
- const options_size = @intCast(u32, gen.OPTIONS_SIZE);
37
+ const options_size = @intCast(u32, gen.CHOICES_SIZE);
38
38
  const logs_size = @intCast(u32, gen.LOGS_SIZE);
39
39
  var object = Object.init(env);
40
40
  const properties = [_]c.napi_property_descriptor{
41
- Property.init("OPTIONS_SIZE", .{ .value = Number.init(env, options_size) }),
41
+ Property.init("CHOICES_SIZE", .{ .value = Number.init(env, options_size) }),
42
42
  Property.init("LOGS_SIZE", .{ .value = Number.init(env, logs_size) }),
43
43
  Property.init("update", .{ .method = update(gen) }),
44
44
  Property.init("choices", .{ .method = choices(gen) }),
@@ -108,10 +108,10 @@ fn choices(gen: anytype) c.napi_callback {
108
108
  const request = @intToEnum(pkmn.Choice.Type, Number.get(env, argv[2], u8));
109
109
 
110
110
  assert(c.napi_get_arraybuffer_info(env, argv[3], &data, &len) == c.napi_ok);
111
- assert(len == gen.OPTIONS_SIZE);
111
+ assert(len == gen.CHOICES_SIZE);
112
112
  assert(data != null);
113
113
 
114
- var out = @ptrCast([*]pkmn.Choice, data.?)[0..gen.OPTIONS_SIZE];
114
+ var out = @ptrCast([*]pkmn.Choice, data.?)[0..gen.CHOICES_SIZE];
115
115
  const n = battle.choices(player, request, out);
116
116
  return Number.init(env, @bitCast(u8, n));
117
117
  }
@@ -4,7 +4,7 @@ const pkmn = @import("../pkmn.zig");
4
4
  export const SHOWDOWN = pkmn.options.showdown;
5
5
  export const TRACE = pkmn.options.trace;
6
6
 
7
- export const GEN1_OPTIONS_SIZE =
8
- std.math.ceilPowerOfTwo(u32, @intCast(u32, pkmn.gen1.OPTIONS_SIZE)) catch unreachable;
7
+ export const GEN1_CHOICES_SIZE =
8
+ std.math.ceilPowerOfTwo(u32, @intCast(u32, pkmn.gen1.CHOICES_SIZE)) catch unreachable;
9
9
  export const GEN1_LOGS_SIZE =
10
10
  std.math.ceilPowerOfTwo(u32, @intCast(u32, pkmn.gen1.LOGS_SIZE)) catch unreachable;
@@ -332,7 +332,9 @@ must be gleaned through the `Battle` state). Useful size and offset information
332
332
  the [`layout.json`](../../data/layout.json) which exists to simplify writing driver code.
333
333
 
334
334
  Documentation of the wire protocol used for logging traces when `-Dtrace` is enabled can be found in
335
- [PROTOCOL.md](../../../docs/PROTOCOL.md).
335
+ [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.
336
338
 
337
339
  ### `Battle`
338
340
 
@@ -467,7 +469,7 @@ Documentation of the wire protocol used for logging traces when `-Dtrace` is ena
467
469
 
468
470
  In addition to its alternative [RNG semantics](#rng), Pokémon Showdown's implementation of the first
469
471
  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):
472
+ Smogon](https://www.smogon.com/forums/posts/5933177/show):
471
473
 
472
474
  - moves on Pokémon Showdown can do 0 damage instead of failing or causing a [division-by-zero
473
475
  freeze](https://pkmn.cc/bulba-glitch-1#Division_by_0).
@@ -476,23 +478,36 @@ Smogon](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3
476
478
  - Confusion self-hits use the wrong damage formula resulting in off-by-one errors (and also fail to
477
479
  account for an opponent's Reflect). Furthermore, the confusion self-hit damage will erroneously be
478
480
  inflicted to the confused user's substitute if the confused user had been attempting to use a
479
- self-targeting move.
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.
480
483
 
481
484
  Beyond the general bugs listed above, several move effects are implemented incorrectly by Pokémon
482
485
  Showdown. Some of these moves are [too fundamentally broken to be implemented](#unimplementable) by
483
486
  the pkmn engine, but the following moves have their broken behavior preserved in `-Dshowdown` mode:
484
487
 
488
+ - **Bide**: If the opponent faints after Bide inflicts damage on Pokémon Showdown residual damage
489
+ incorrectly still gets applied to Bide's user.
485
490
  - **Leech Seed**: Leech Seed fails to heal its source side if a seeded target faints due to
486
- recoil/crash damage on Pokémon Showdown.
491
+ recoil/crash damage on Pokémon Showdown. Pokémon Showdown also updates the battle's last damage
492
+ field with the uncapped Leech Seed damage if the residual damage is applied which has consequences
493
+ for Bide and Counter.
487
494
  - **Pay Day**: Pay Day should still scatter coins if it hits (but doesn't break) and opponent's
488
495
  Substitute but doesn't on Pokémon Showdown.
489
496
  - **Flinch**: Flinching does not get cleared during move selection on Pokémon Showdown and is
490
497
  instead cleared in Pokémon Showdown's "residual" phase, meaning the flinch status gets erroneously
491
498
  preserved across fainting (as fainting triggers Pokémon Showdown's "instaswitch" behavior which
492
499
  skips end-of-turn residuals).
500
+ - **Rage**: Rage boosts should still result in burn/paralysis [stat modification
501
+ errors](https://pkmn.cc/bulba-glitch-1#Stat_modification_errors) but don't on Pokémon Showdown.
502
+ Furthermore, Pokémon Showdown only builds Rage for Disable/Explosion (hit/miss) when attacking
503
+ into a Substitute instead of all moves. Pokémon Showdown also implements the [Rage and Thrash /
504
+ Petal Dance accuracy bug]( https://www.youtube.com/watch?v=NC5gbJeExbs) incorrectly, as the
505
+ accuracy only gets written when the volatile is present which can lead to incorrect accuracy
506
+ values on turns where Rage is used on the same turn as a move which modifies accuracy or evasion.
493
507
  - **Thrash** / **Petal Dance**: once a Pokémon is locked into a thrashing move they will lose all
494
508
  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).
509
+ then get "changed" and inserted back into the queue after their opponent's action). Pokémon
510
+ Showdown also implements accuracy incorrectly, as covered above.
496
511
  - **Freeze** / **Sleep**: Pokémon Showdown requires a move to be selected when a Pokémon is frozen
497
512
  or sleeping and uses that in the event that the status is removed while on the cartridge no
498
513
  selection is possible and no turn exists for the thawed/woken Pokémon to act except in the case of
@@ -508,7 +523,8 @@ the pkmn engine, but the following moves have their broken behavior preserved in
508
523
  implement by Pokémon Showdown.
509
524
  - **Roar** / **Whirlwind**: these moves can miss on Pokémon Showdown (and advance the RNG when
510
525
  checking) which is incorrect (these moves should always fail, but do not check accuracy or advance
511
- the RNG).
526
+ the RNG). More importantly, these moves should *not* cause the tracked last battle damage to be
527
+ zeroed, but on Pokémon Showdown they do.
512
528
  - **Substitute**: in addition to the [Substitute + Confusion
513
529
  glitch](https://pkmn.cc/bulba-glitch-1#Substitute_.2B_Confusion_glitch) not being implemented
514
530
  correctly (covered above), the [Substitute 1/4
@@ -516,7 +532,8 @@ the pkmn engine, but the following moves have their broken behavior preserved in
516
532
  Pokémon Showdown implementing the health check based on floating point division instead of integer
517
533
  divison like on the cartridge (meaning the Substitute 1/4 glitch will only occur if the Pokémon's
518
534
  maximum HP is evenly divisible by 4). Finally, Substitute also incorrectly blocks Dream Eater on
519
- Pokémon Showdown.
535
+ Pokémon Showdown and will incorrectly still heal 1 HP for any draining moves if the attack does 0
536
+ damage.
520
537
 
521
538
  In addition to numerous cases where Pokémon Showdown uses the wrong type of message (e.g. `|-fail`
522
539
  vs. `|-miss|` vs. `|-immune|`, e.g. in the case of Leech Seed) which are not documented here, Pokémon
@@ -550,7 +567,7 @@ called out in the `|rule|` section at the beginning of a battle's log):
550
567
  `|rule|` section** in Generation I (or II) as the actual order of switches here does not have
551
568
  competitive implications like it does in Generation III, but it is still contrary to how the games
552
569
  work where the [host (Player 1)'s Pokemon would switch
553
- first](https://www.smogon.com/forums/threads/gen-3-on-ps-final-fixes.3527268/post-5989318).
570
+ first](https://www.smogon.com/forums/posts/5989318/show).
554
571
 
555
572
  Pokémon Showdown enforces several clauses *before* the battle: **Cleric Clause** (all Pokémon must
556
573
  have full HP and PP, and not have any status conditions prior to the battle), **Stat Tradeback
@@ -571,13 +588,12 @@ left up to a client to support.
571
588
 
572
589
  Numerous moves on Pokémon Showdown are broken not simply due to local issues in the implementation
573
590
  of their effects but instead due to **global issues** related to fundamental mechanics such as
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):
591
+ [broken move selection](https://www.smogon.com/forums/posts/8655897/show), using move name instead
592
+ of slot to determine move identity, implementing volatile statuses incorrectly or not understanding
593
+ how moves which call other moves work means that it isn't possible to completely implement Pokémon
594
+ Showdown's behavior for the following moves (the pkmn engine attempts to reproduce as much of the
595
+ behavior that can be reproduced without making data structure changes or dramatically deviating from
596
+ the correct control flow):
581
597
 
582
598
  - **Wrap**: Binding moves like Wrap are implemented on Pokémon Showdown with an artificial
583
599
  `partialtrappinglock` volatile as opposed to how it works on the cartridge which simply relies on
@@ -666,10 +682,10 @@ compatibility mode, the implications of these differences are outlined below:
666
682
  Finally, the **initial 10-byte seed for link battles on Pokémon Red cannot include bytes larger than
667
683
  the `SERIAL_PREAMBLE_BYTE`**, so must be in the range $\left[0, 252\right]$. This has implications
668
684
  on the first 10 random numbers generated during the battle and has [**non-trivial competitive
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.
685
+ implications**](https://www.smogon.com/forums/posts/9068411/show) (at the start of the battle move
686
+ effects become more likely, the ["1/256-miss" glitch](https://glitchcity.wiki/1/256_miss_glitch)
687
+ cannot happen, Player 1 is more likely to win speed ties, etc) that Pokémon Showdown cannot
688
+ replicate due to everything described above.
673
689
 
674
690
  All of places in the link battle code where randomness is required are outlined below:
675
691
 
@@ -768,11 +784,8 @@ The pkmn engine attempts to adhere to certain naming conventions:
768
784
  ## Resources
769
785
 
770
786
  - [pret/pokered](https://github.com/pret/pokered/) disassembly
771
- - [Gen I Main Battle
772
- Function](https://www.smogon.com/forums/threads/past-gens-research-thread.3506992/#post-5878612) -
773
- Crystal_
787
+ - [Gen I Main Battle Function](https://www.smogon.com/forums/posts/5878612/show) - Crystal_
774
788
  - [Pokemon Showdown!](https://github.com/smogon/pokemon-showdown)
775
789
  - [List of glitches (Generation
776
790
  I)](https://bulbapedia.bulbagarden.net/wiki/List_of_glitches_(Generation_I))
777
- - [Pokémon Showdown RBY
778
- Bugs](https://www.smogon.com/forums/threads/rby-tradebacks-bug-report-thread.3524844/#post-5933177)
791
+ - [Pokémon Showdown RBY Bugs](https://www.smogon.com/forums/posts/5933177/show)
@@ -17,16 +17,16 @@ const expectEqual = std.testing.expectEqual;
17
17
  const expect = std.testing.expect;
18
18
 
19
19
  /// The minimum size in bytes required to hold all Generation I choice options.
20
- pub const MAX_OPTIONS: usize = 9; // move 1..4, switch 2..6
20
+ pub const MAX_CHOICES: usize = 9; // move 1..4, switch 2..6
21
21
  /// The optimal size in bytes required to hold all Generation I choice options.
22
- /// At least as large as MAX_OPTIONS.
22
+ /// At least as large as MAX_CHOICES.
23
23
  pub const MAX_LOGS: usize = 180;
24
24
 
25
25
  /// The maximum number of bytes possibly logged by a single Generation I update.
26
- pub const OPTIONS_SIZE = if (builtin.mode == .ReleaseSmall)
27
- MAX_OPTIONS
26
+ pub const CHOICES_SIZE = if (builtin.mode == .ReleaseSmall)
27
+ MAX_CHOICES
28
28
  else
29
- std.math.ceilPowerOfTwo(usize, MAX_OPTIONS) catch unreachable;
29
+ std.math.ceilPowerOfTwo(usize, MAX_CHOICES) catch unreachable;
30
30
  /// The optimal size in bytes required to hold the largest amount of log data possible from a
31
31
  /// single Generation I update. At least as large as MAX_LOGS.
32
32
  pub const LOGS_SIZE = if (builtin.mode == .ReleaseSmall)
@@ -216,11 +216,7 @@ fn blocked(m: Move) bool {
216
216
  if (Move.get(m).effect == .Binding) return true;
217
217
  return switch (m) {
218
218
  .Counter,
219
- // FIXME: test and see if this can be removed or document
220
- .Rage,
221
219
  .Mimic,
222
- // FIXME: test and see if this can be removed or document
223
- .Bide,
224
220
  .Metronome,
225
221
  .MirrorMove,
226
222
  .Transform,