@pkmn/engine 0.1.0-dev.c5fe6d07 → 0.1.0-dev.d3e796d5

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
@@ -235,9 +235,9 @@ pub fn build(b: *std.Build) !void {
235
235
  const dump = tool(b, "src/tools/dump.zig", tools);
236
236
  const transitions = tool(b, "src/tools/transitions.zig", tools);
237
237
 
238
- // FIXME: serde randomly fails to build in recent Windows release configurations...
238
+ // FIXME: serde randomly fails to build in some release configurations
239
239
  var hack = tools;
240
- if (builtin.os.tag == .windows and optimize != .Debug) hack.tool.tests = null;
240
+ if (optimize != .Debug) hack.tool.tests = null;
241
241
  const serde = tool(b, "src/tools/serde.zig", hack);
242
242
 
243
243
  b.step("analyze", "Run LLVM analysis tool").dependOn(&analyze.step);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pkmn/engine",
3
- "version": "0.1.0-dev.c5fe6d07",
3
+ "version": "0.1.0-dev.d3e796d5",
4
4
  "description": "A minimal, complete, Pokémon battle simulation engine optimized for performance",
5
5
  "repository": "github:pkmn/engine",
6
6
  "license": "MIT",
@@ -73,30 +73,30 @@
73
73
  "access": "public"
74
74
  },
75
75
  "dependencies": {
76
- "@pkmn/data": "^0.7.46",
77
- "@pkmn/protocol": "^0.6.12"
76
+ "@pkmn/data": "^0.7.50",
77
+ "@pkmn/protocol": "^0.6.13"
78
78
  },
79
79
  "devDependencies": {
80
- "@pkmn/eslint-config": "^5.0.0",
81
- "@pkmn/img": "^0.2.13",
80
+ "@pkmn/eslint-config": "^5.2.0",
81
+ "@pkmn/img": "^0.2.15",
82
82
  "@pkmn/sets": "^5.0.4",
83
- "@pkmn/sim": "0.7.46",
83
+ "@pkmn/sim": "0.7.50",
84
84
  "@types/html-minifier": "^4.0.2",
85
- "@types/jest": "^29.5.3",
85
+ "@types/jest": "^29.5.4",
86
86
  "@types/minimist": "^1.2.2",
87
87
  "@types/mustache": "^4.2.2",
88
- "@types/node": "^20.4.2",
88
+ "@types/node": "^20.5.9",
89
89
  "@vitest/coverage-c8": "^0.33.0",
90
90
  "binaryen": "^114.0.0",
91
- "eslint": "^8.44.0",
91
+ "eslint": "^8.48.0",
92
92
  "html-minifier": "^4.0.0",
93
93
  "json-stringify-pretty-compact": "3.0.0",
94
94
  "minimist": "^1.2.8",
95
95
  "mustache": "^4.2.0",
96
96
  "source-map-support": "^0.5.21",
97
97
  "trakr": "^0.2.0",
98
- "typescript": "^5.1.6",
99
- "vitest": "^0.33.0"
98
+ "typescript": "^5.2.2",
99
+ "vitest": "^0.34.4"
100
100
  },
101
101
  "scripts": {
102
102
  "lint": "eslint --cache src --ext ts,js && eslint src/bin/*",
@@ -136,6 +136,8 @@ pub const Damage = enum(u8) {
136
136
  Confusion,
137
137
  LeechSeed,
138
138
  RecoilOf,
139
+
140
+ Spikes,
139
141
  };
140
142
 
141
143
  pub const Status = enum(u8) {
@@ -264,7 +266,15 @@ pub fn Log(comptime Writer: type) type {
264
266
  if (!enabled) return;
265
267
 
266
268
  try self.writer.writeAll(&.{ @intFromEnum(ArgType.Switch), @as(u8, @bitCast(ident)) });
267
- try self.writer.writeAll(&.{ @intFromEnum(pokemon.species), pokemon.level });
269
+ if (@hasField(@TypeOf(pokemon.*), "dvs")) {
270
+ try self.writer.writeAll(&.{
271
+ @intFromEnum(pokemon.species),
272
+ @intFromEnum(pokemon.dvs.gender),
273
+ pokemon.level,
274
+ });
275
+ } else {
276
+ try self.writer.writeAll(&.{ @intFromEnum(pokemon.species), pokemon.level });
277
+ }
268
278
  try self.writer.writeIntNative(u16, pokemon.hp);
269
279
  try self.writer.writeIntNative(u16, pokemon.stats.hp);
270
280
  try self.writer.writeAll(&.{pokemon.status});
@@ -646,9 +656,13 @@ pub const ByteStream = struct {
646
656
  };
647
657
 
648
658
  pub const Kind = enum { Move, Species, Type, Status };
649
- pub const Formatter = fn (Kind, u8) []const u8;
650
659
 
651
- pub fn format(comptime formatter: Formatter, a: []const u8, b: ?[]const u8, color: bool) void {
660
+ pub fn format(
661
+ comptime gen: anytype,
662
+ a: []const u8,
663
+ b: ?[]const u8,
664
+ color: bool,
665
+ ) void {
652
666
  print("\n", .{});
653
667
 
654
668
  var i: usize = 0;
@@ -701,17 +715,27 @@ pub fn format(comptime formatter: Formatter, a: []const u8, b: ?[]const u8, colo
701
715
  .Move => {
702
716
  const source = ID.from(@intCast(a[i]));
703
717
  printc(" {s}({d})", .{ @tagName(source.player), source.id }, a, b, &i, 1, color);
704
- printc(" {s}", .{formatter(.Move, a[i])}, a, b, &i, 1, color);
718
+ printc(" {s}", .{formatter(gen, .Move, a[i])}, a, b, &i, 1, color);
705
719
  const target = ID.from(@intCast(a[i]));
706
720
  printc(" {s}({d})", .{ @tagName(target.player), target.id }, a, b, &i, 1, color);
707
721
  const reason: Move = @enumFromInt(a[i]);
708
722
  printc(" {s}", .{@tagName(reason)}, a, b, &i, 1, color);
709
- if (reason == .From) printc(" {s}", .{formatter(.Move, a[i])}, a, b, &i, 1, color);
723
+ if (reason == .From) {
724
+ printc(" {s}", .{formatter(gen, .Move, a[i])}, a, b, &i, 1, color);
725
+ }
710
726
  },
711
727
  .Switch => {
712
728
  const id = ID.from(@intCast(a[i]));
713
729
  printc(" {s}({d})", .{ @tagName(id.player), id.id }, a, b, &i, 1, color);
714
- printc(" {s}", .{formatter(.Species, a[i])}, a, b, &i, 1, color);
730
+ printc(" {s}", .{formatter(gen, .Species, a[i])}, a, b, &i, 1, color);
731
+ if (@hasDecl(gen, "Gender")) {
732
+ if (a[i] == N(gen.Gender.Unknown)) {
733
+ i += 1;
734
+ } else {
735
+ var gender = if (a[i] == N(gen.Gender.Male)) "M" else "F";
736
+ printc(", {s}", .{gender}, a, b, &i, 1, color);
737
+ }
738
+ }
715
739
  printc(" L{d}", .{a[i]}, a, b, &i, 1, color);
716
740
  switch (endian) {
717
741
  .Big => {
@@ -727,7 +751,7 @@ pub fn format(comptime formatter: Formatter, a: []const u8, b: ?[]const u8, colo
727
751
  printc("/{d}", .{hp}, a, b, &i, 2, color);
728
752
  },
729
753
  }
730
- printc(" {s}", .{formatter(.Status, a[i])}, a, b, &i, 1, color);
754
+ printc(" {s}", .{formatter(gen, .Status, a[i])}, a, b, &i, 1, color);
731
755
  },
732
756
  .Cant => {
733
757
  const id = ID.from(@intCast(a[i]));
@@ -735,7 +759,7 @@ pub fn format(comptime formatter: Formatter, a: []const u8, b: ?[]const u8, colo
735
759
  const reason: Cant = @enumFromInt(a[i]);
736
760
  printc(" {s}", .{@tagName(reason)}, a, b, &i, 1, color);
737
761
  if (reason == .Disable) {
738
- printc(" {s}", .{formatter(.Move, a[i])}, a, b, &i, 1, color);
762
+ printc(" {s}", .{formatter(gen, .Move, a[i])}, a, b, &i, 1, color);
739
763
  }
740
764
  },
741
765
  .Faint,
@@ -775,7 +799,7 @@ pub fn format(comptime formatter: Formatter, a: []const u8, b: ?[]const u8, colo
775
799
  printc("/{d}", .{hp}, a, b, &i, 2, color);
776
800
  },
777
801
  }
778
- printc(" {s}", .{formatter(.Status, a[i])}, a, b, &i, 1, color);
802
+ printc(" {s}", .{formatter(gen, .Status, a[i])}, a, b, &i, 1, color);
779
803
  if (arg == .Damage) {
780
804
  const reason: Damage = @enumFromInt(a[i]);
781
805
  printc(" {s}", .{@tagName(reason)}, a, b, &i, 1, color);
@@ -795,15 +819,17 @@ pub fn format(comptime formatter: Formatter, a: []const u8, b: ?[]const u8, colo
795
819
  .Status => {
796
820
  const id = ID.from(@intCast(a[i]));
797
821
  printc(" {s}({d})", .{ @tagName(id.player), id.id }, a, b, &i, 1, color);
798
- printc(" {s}", .{formatter(.Status, a[i])}, a, b, &i, 1, color);
822
+ printc(" {s}", .{formatter(gen, .Status, a[i])}, a, b, &i, 1, color);
799
823
  const reason: Status = @enumFromInt(a[i]);
800
824
  printc(" {s}", .{@tagName(reason)}, a, b, &i, 1, color);
801
- if (reason == .From) printc(" {s}", .{formatter(.Move, a[i])}, a, b, &i, 1, color);
825
+ if (reason == .From) {
826
+ printc(" {s}", .{formatter(gen, .Move, a[i])}, a, b, &i, 1, color);
827
+ }
802
828
  },
803
829
  .CureStatus => {
804
830
  const id = ID.from(@intCast(a[i]));
805
831
  printc(" {s}({d})", .{ @tagName(id.player), id.id }, a, b, &i, 1, color);
806
- printc(" {s}", .{formatter(.Status, a[i])}, a, b, &i, 1, color);
832
+ printc(" {s}", .{formatter(gen, .Status, a[i])}, a, b, &i, 1, color);
807
833
  const reason: CureStatus = @enumFromInt(a[i]);
808
834
  printc(" {s}", .{@tagName(reason)}, a, b, &i, 1, color);
809
835
  },
@@ -826,7 +852,7 @@ pub fn format(comptime formatter: Formatter, a: []const u8, b: ?[]const u8, colo
826
852
  .Prepare => {
827
853
  const id = ID.from(@intCast(a[i]));
828
854
  printc(" {s}({d})", .{ @tagName(id.player), id.id }, a, b, &i, 1, color);
829
- printc(" {s}", .{formatter(.Move, a[i])}, a, b, &i, 1, color);
855
+ printc(" {s}", .{formatter(gen, .Move, a[i])}, a, b, &i, 1, color);
830
856
  },
831
857
  .Activate => {
832
858
  const id = ID.from(@intCast(a[i]));
@@ -841,12 +867,12 @@ pub fn format(comptime formatter: Formatter, a: []const u8, b: ?[]const u8, colo
841
867
  if (@as(Start, @enumFromInt(reason)) == .TypeChange) {
842
868
  const types = @as(gen1.Types, @bitCast(a[i]));
843
869
  const args = .{
844
- formatter(.Type, @intFromEnum(types.type1)),
845
- formatter(.Type, @intFromEnum(types.type2)),
870
+ formatter(gen, .Type, @intFromEnum(types.type1)),
871
+ formatter(gen, .Type, @intFromEnum(types.type2)),
846
872
  };
847
873
  printc(" {s}/{s}", args, a, b, &i, 1, color);
848
874
  } else if (reason >= @intFromEnum(Start.Disable)) {
849
- printc(" {s}", .{formatter(.Move, a[i])}, a, b, &i, 1, color);
875
+ printc(" {s}", .{formatter(gen, .Move, a[i])}, a, b, &i, 1, color);
850
876
  }
851
877
  },
852
878
  .End => {
@@ -896,7 +922,7 @@ fn printc(
896
922
  }
897
923
 
898
924
  pub fn expectLog(
899
- comptime formatter: Formatter,
925
+ comptime gen: anytype,
900
926
  expected: []const u8,
901
927
  actual: []const u8,
902
928
  offset: usize,
@@ -915,8 +941,8 @@ pub fn expectLog(
915
941
 
916
942
  expectEqualBytes(expected, actual, offset) catch |err| switch (err) {
917
943
  error.TestExpectedEqual => {
918
- format(formatter, expected, null, color);
919
- format(formatter, actual, expected, color);
944
+ format(gen, expected, null, color);
945
+ format(gen, actual, expected, color);
920
946
  return err;
921
947
  },
922
948
  else => return err,
@@ -956,6 +982,11 @@ const gen1 = struct {
956
982
  pub const helpers = @import("../gen1/helpers.zig");
957
983
  };
958
984
 
985
+ const gen2 = struct {
986
+ pub usingnamespace @import("../gen2/data.zig");
987
+ pub const helpers = @import("../gen2/helpers.zig");
988
+ };
989
+
959
990
  var buf: [gen1.LOGS_SIZE]u8 = undefined;
960
991
  var stream = ByteStream{ .buffer = &buf };
961
992
  var log: FixedLog = .{ .writer = stream.writer() };
@@ -964,15 +995,19 @@ const M = gen1.Move;
964
995
  const S = gen1.Species;
965
996
 
966
997
  fn expectLog1(expected: []const u8, actual: []const u8) !void {
967
- return expectLog(gen1Formatter, expected, actual, 0);
998
+ return expectLog(gen1, expected, actual, 0);
968
999
  }
969
1000
 
970
- fn gen1Formatter(kind: Kind, byte: u8) []const u8 {
1001
+ fn expectLog2(expected: []const u8, actual: []const u8) !void {
1002
+ return expectLog(gen2, expected, actual, 0);
1003
+ }
1004
+
1005
+ fn formatter(comptime gen: anytype, kind: Kind, byte: u8) []const u8 {
971
1006
  return switch (kind) {
972
- .Move => @tagName(@as(M, @enumFromInt(byte))),
973
- .Species => @tagName(@as(S, @enumFromInt(byte))),
974
- .Type => @tagName(@as(gen1.Type, @enumFromInt(byte))),
975
- .Status => gen1.Status.name(byte),
1007
+ .Move => @tagName(@as(gen.Move, @enumFromInt(byte))),
1008
+ .Species => @tagName(@as(gen.Species, @enumFromInt(byte))),
1009
+ .Type => @tagName(@as(gen.Type, @enumFromInt(byte))),
1010
+ .Status => gen.Status.name(byte),
976
1011
  };
977
1012
  }
978
1013
 
@@ -1057,6 +1092,25 @@ test "|switch|" {
1057
1092
  };
1058
1093
  try expectLog1(expected, buf[0..9]);
1059
1094
  stream.reset();
1095
+
1096
+ var blissey = gen2.helpers.Pokemon.init(.{ .species = .Blissey, .moves = &.{.Splash} });
1097
+ blissey.level = 91;
1098
+ blissey.hp = 200;
1099
+ blissey.stats.hp = 400;
1100
+ blissey.status = gen2.Status.init(.PAR);
1101
+ try log.switched(p2.ident(3), &blissey);
1102
+ expected = &(.{
1103
+ N(ArgType.Switch),
1104
+ 0b1011,
1105
+ N(gen2.Species.Blissey),
1106
+ N(gen2.Gender.Female),
1107
+ 91,
1108
+ } ++ switch (endian) {
1109
+ .Big => .{ 0, 200, 1, 144, par },
1110
+ .Little => .{ 200, 0, 144, 1, par },
1111
+ });
1112
+ try expectLog2(expected, buf[0..10]);
1113
+ stream.reset();
1060
1114
  }
1061
1115
 
1062
1116
  test "|cant|" {
@@ -29,7 +29,6 @@ const Optional = optional.Optional;
29
29
  const Rational = rational.Rational;
30
30
 
31
31
  const PointerType = util.PointerType;
32
- const FieldType = util.FieldType;
33
32
 
34
33
  const Actions = chance.Actions;
35
34
  const Action = chance.Action;
@@ -214,12 +214,9 @@ fn selectMove(
214
214
  }
215
215
  break :ok true;
216
216
  };
217
-
218
217
  assert(struggle);
219
- saveMove(battle, player, choice);
220
- } else {
221
- saveMove(battle, player, choice);
222
218
  }
219
+ saveMove(battle, player, choice);
223
220
 
224
221
  return null;
225
222
  }
@@ -219,6 +219,81 @@ much overhead the preceding representations have after taking into consideration
219
219
  padding](https://en.wikipedia.org/wiki/Data_structure_alignment) and
220
220
  [denormalization](https://en.wikipedia.org/wiki/Denormalization):
221
221
 
222
+ ## Details
223
+
224
+ | pkmn | Pokémon Crystal (pret) |
225
+ | ------------------------- | ------------------------------------------------- |
226
+ | `start` | `DoBattle` |
227
+ | `update` | `BattleTurn` |
228
+ | `selectMove` / `saveMove` | `CheckPlayerLockedIn` / `ParsePlayerAction` |
229
+ | `switchIn` | `SwitchPlayerMon` / `SendOutPlayerMon` |
230
+ | `turnOrder` | `DetermineMoveOrder` |
231
+ | `doTurn` | `DoTurn` |
232
+ | `executeMove` | `DoMove` |
233
+ | `beforeMove` | `CheckTurn` |
234
+ | `canMove` | |
235
+ | `decrementPP` | |
236
+ | `doMove` | |
237
+ | `checkCriticalHit` | `BattleCommand_Critical` |
238
+ | `calcDamage` | `BattleCommand_DamageCalc` / `PlayerAttackDamage` |
239
+ | `adjustDamage` | `BattleCommand_Stab` |
240
+ | `randomizeDamage` | `BattleCommand_DamageVariation` |
241
+ | `specialDamage` | `BattleCommand_ConstantDamage` |
242
+ | `applyDamage` | `BattleCommand_ApplyDamage` |
243
+ | `checkHit` | `BattleCommand_CheckHit` |
244
+ | `checkFaint` | `CheckFaint` |
245
+ | `handleResidual` | `ResidualDamage` |
246
+ | `endTurn` | `EndTurn` |
247
+
248
+ DoBattle
249
+ BattleTurn
250
+ - HandleBerserkGene
251
+ - CheckPlayerLockedIn
252
+ - BattleMenu
253
+ - ParsePlayerAction
254
+ - DetermineMoveOrder
255
+ - CompareMovePriority
256
+ - GetMovePriority
257
+ - Battle_*
258
+ - Handle*Switch
259
+ - SwitchPlayerMon
260
+ - BreakAttraction
261
+ - SendOutPlayerMon
262
+ - SpikesDamage
263
+ - *Turn_EndOpponentProtectEndureDestinyBond
264
+ - EndUserDestinyBond
265
+ - Do*Turn
266
+ - EndOpponentProtectEndureDestinyBond
267
+ - ResidualDamage
268
+ - CheckFaint_*
269
+ - HandleBetweenTurnEffects
270
+ - HandleFutureSight
271
+ - HandleWeather
272
+ - HandleWrap
273
+ - HandlePerishSong
274
+ - HandleLeftovers
275
+ - HandleMysteryBerry
276
+ - HandleDefrost
277
+ - HandleSafeguard
278
+ - HandleScreens
279
+ - HandleStatBoostingHeldItems
280
+ - HandleHealingItems
281
+ - HandleEncore
282
+
283
+ DoTurn
284
+ DoMove = executeMove
285
+ CheckTurn = beforeMove
286
+ BattleCommand_Critical = checkCriticalHit
287
+ BattleCommand_Stab = adjustDamage
288
+ BattleCommand_DamageVariation = randomizeDamage
289
+ BattleCommand_CheckHit = checkHit
290
+ BattleCommand_ApplyDamage = applyDamage
291
+ BattleCommand_CheckFaint
292
+ BattleCommand_BuildOpponentRage = buildRage
293
+ BattleCommand_DamageCalc (PlayerAttackDamage / EnemyAttackDamage) = calcDamage
294
+ BattleCommand_ConstantDamage = specialDamage
295
+ DoEnemyDamage / DoPlayerDamage / DoSubstituteDamage
296
+
222
297
  ==**TODO**==
223
298
 
224
299
  ## Protocol
@@ -279,9 +279,11 @@ pub const Move = enum(u8) {
279
279
  target: Target,
280
280
  /// The chance of the move's secondary effect occurring.
281
281
  chance: u8 = 0,
282
+ /// The priority of the move
283
+ priority: i8 = 0,
282
284
 
283
285
  comptime {
284
- assert(@sizeOf(Data) == 7);
286
+ assert(@sizeOf(Data) == 8);
285
287
  }
286
288
  };
287
289
 
@@ -450,6 +452,7 @@ pub const Move = enum(u8) {
450
452
  .pp = 20,
451
453
  .accuracy = 100,
452
454
  .target = .Other,
455
+ .priority = -1,
453
456
  },
454
457
  // Fly
455
458
  .{
@@ -709,6 +712,7 @@ pub const Move = enum(u8) {
709
712
  .pp = 20,
710
713
  .accuracy = 100,
711
714
  .target = .Other,
715
+ .priority = -1,
712
716
  },
713
717
  // Sing
714
718
  .{
@@ -916,6 +920,7 @@ pub const Move = enum(u8) {
916
920
  .pp = 20,
917
921
  .accuracy = 100,
918
922
  .target = .Depends,
923
+ .priority = -1,
919
924
  },
920
925
  // SeismicToss
921
926
  .{
@@ -1191,6 +1196,7 @@ pub const Move = enum(u8) {
1191
1196
  .pp = 30,
1192
1197
  .accuracy = 100,
1193
1198
  .target = .Other,
1199
+ .priority = 1,
1194
1200
  },
1195
1201
  // Rage
1196
1202
  .{
@@ -1962,6 +1968,7 @@ pub const Move = enum(u8) {
1962
1968
  .pp = 10,
1963
1969
  .accuracy = 100,
1964
1970
  .target = .Self,
1971
+ .priority = 2,
1965
1972
  },
1966
1973
  // MachPunch
1967
1974
  .{
@@ -1971,6 +1978,7 @@ pub const Move = enum(u8) {
1971
1978
  .pp = 30,
1972
1979
  .accuracy = 100,
1973
1980
  .target = .Other,
1981
+ .priority = 1,
1974
1982
  },
1975
1983
  // ScaryFace
1976
1984
  .{
@@ -2102,6 +2110,7 @@ pub const Move = enum(u8) {
2102
2110
  .pp = 5,
2103
2111
  .accuracy = 100,
2104
2112
  .target = .Self,
2113
+ .priority = 2,
2105
2114
  },
2106
2115
  // BoneRush
2107
2116
  .{
@@ -2156,6 +2165,7 @@ pub const Move = enum(u8) {
2156
2165
  .pp = 10,
2157
2166
  .accuracy = 100,
2158
2167
  .target = .Self,
2168
+ .priority = 2,
2159
2169
  },
2160
2170
  // Charm
2161
2171
  .{
@@ -2433,6 +2443,7 @@ pub const Move = enum(u8) {
2433
2443
  .pp = 10,
2434
2444
  .accuracy = 100,
2435
2445
  .target = .Other,
2446
+ .priority = -1,
2436
2447
  },
2437
2448
  // MorningSun
2438
2449
  .{
@@ -2525,6 +2536,7 @@ pub const Move = enum(u8) {
2525
2536
  .pp = 20,
2526
2537
  .accuracy = 100,
2527
2538
  .target = .Depends,
2539
+ .priority = -1,
2528
2540
  },
2529
2541
  // PsychUp
2530
2542
  .{
@@ -2543,6 +2555,7 @@ pub const Move = enum(u8) {
2543
2555
  .pp = 5,
2544
2556
  .accuracy = 100,
2545
2557
  .target = .Other,
2558
+ .priority = 1,
2546
2559
  },
2547
2560
  // AncientPower
2548
2561
  .{
@@ -2770,7 +2783,7 @@ pub const Move = enum(u8) {
2770
2783
 
2771
2784
  comptime {
2772
2785
  assert(@sizeOf(Move) == 1);
2773
- assert(@sizeOf(@TypeOf(DATA)) == 1757);
2786
+ assert(@sizeOf(@TypeOf(DATA)) == 2008);
2774
2787
  }
2775
2788
 
2776
2789
  /// The number of Pokémon moves in this generation.
@@ -5,6 +5,7 @@ const pkmn = @import("../pkmn.zig");
5
5
 
6
6
  const data = @import("../common/data.zig");
7
7
  const DEBUG = @import("../common/debug.zig").print;
8
+ const protocol = @import("../common/protocol.zig");
8
9
  const rng = @import("../common/rng.zig");
9
10
  const util = @import("../common/util.zig");
10
11
 
@@ -15,6 +16,8 @@ const types = @import("data/types.zig");
15
16
 
16
17
  const gen1 = @import("../gen1/data.zig");
17
18
 
19
+ const calc = @import("calc.zig");
20
+ const chance = @import("chance.zig");
18
21
  const mechanics = @import("mechanics.zig");
19
22
 
20
23
  const assert = std.debug.assert;
@@ -33,6 +36,9 @@ pub const LOGS_SIZE = if (builtin.mode == .ReleaseSmall)
33
36
  else
34
37
  std.math.ceilPowerOfTwo(usize, MAX_LOGS) catch unreachable;
35
38
 
39
+ /// Null object pattern implementation of pkmn.battle.Options for Generation II.
40
+ pub const NULL = pkmn.battle.options(protocol.NULL, chance.NULL, calc.NULL);
41
+
36
42
  const Choice = data.Choice;
37
43
  const ID = data.ID;
38
44
  const Player = data.Player;
@@ -82,7 +88,7 @@ test Battle {
82
88
  try expectEqual(496, @sizeOf(Battle(PRNG)));
83
89
  }
84
90
 
85
- const Field = packed struct {
91
+ pub const Field = packed struct {
86
92
  weather: Weather = .None,
87
93
  weather_duration: u4 = 0,
88
94
 
@@ -91,19 +97,21 @@ const Field = packed struct {
91
97
  }
92
98
  };
93
99
 
94
- const Weather = enum(u4) {
100
+ pub const Weather = enum(u4) {
95
101
  None,
96
102
  Rain,
97
103
  Sun,
98
104
  Sandstorm,
99
105
  };
100
106
 
101
- const Side = extern struct {
107
+ pub const Side = extern struct {
102
108
  pokemon: [6]Pokemon = [_]Pokemon{.{}} ** 6,
103
109
  active: ActivePokemon = .{},
104
- conditions: Conditions,
105
- last_used_move: Move = .None,
110
+ conditions: Conditions = .{},
111
+ // NB: wCurPlayerMove / wCurEnemyMove (?)
106
112
  _: u8 = 0,
113
+ // NB: wLastPlayerCounterMove / wLastEnemyCounterMove (wLastPlayerMove / wLastEnemyMove)
114
+ last_used_move: Move = .None,
107
115
 
108
116
  const Conditions = packed struct {
109
117
  Spikes: bool = false,
@@ -136,17 +144,30 @@ const Side = extern struct {
136
144
  assert(@typeInfo(@TypeOf(self)).Pointer.child == Side);
137
145
  return self.get(1);
138
146
  }
147
+
148
+ pub inline fn lastMove(self: anytype, encore: bool) Move {
149
+ assert(self.last_used_move != .None or !self.active.volatiles.dirty);
150
+ if (encore) return self.last_used_move;
151
+ return if (self.active.volatiles.dirty) .None else self.last_used_move;
152
+ }
153
+
154
+ // TODO
155
+ // pub inline fn useMove(self: anytype) void {
156
+ // assert(side.last_selected_move != .None);
157
+ // self.last_used_move = side.last_selected_move;
158
+ // self.active.volatiles.dirty = false;
159
+ // }
139
160
  };
140
161
 
141
162
  // NOTE: DVs (Gender & Hidden Power) and Happiness are stored only in Pokemon
142
- const ActivePokemon = extern struct {
143
- volatiles: Volatile align(4) = .{},
163
+ pub const ActivePokemon = extern struct {
164
+ volatiles: Volatiles align(4) = .{},
144
165
  stats: Stats(u16) = .{},
145
166
  moves: [4]MoveSlot = [_]MoveSlot{.{}} ** 4,
146
167
  boosts: Boosts = .{},
168
+ types: Types = .{},
147
169
  species: Species = .None,
148
- item: Item = .None,
149
- last_move: Move = .None,
170
+
150
171
  _: u8 = 0,
151
172
 
152
173
  comptime {
@@ -161,7 +182,7 @@ const ActivePokemon = extern struct {
161
182
  }
162
183
  };
163
184
 
164
- const Pokemon = extern struct {
185
+ pub const Pokemon = extern struct {
165
186
  stats: Stats(u16) = .{},
166
187
  moves: [4]MoveSlot = [_]MoveSlot{.{}} ** 4,
167
188
  types: Types = .{},
@@ -192,7 +213,7 @@ pub const Gender = enum(u2) {
192
213
  Unknown,
193
214
  };
194
215
 
195
- const DVs = packed struct {
216
+ pub const DVs = packed struct {
196
217
  gender: Gender = .Male,
197
218
  pow: u6 = 40,
198
219
  type: Type = .Dark,
@@ -248,7 +269,7 @@ test DVs {
248
269
  try expectEqual(Gender.Female, dvs.gender);
249
270
  }
250
271
 
251
- const MoveSlot = packed struct {
272
+ pub const MoveSlot = packed struct {
252
273
  id: Move = .None,
253
274
  pp_ups: u2 = 3,
254
275
  pp: u6 = 0,
@@ -260,7 +281,7 @@ const MoveSlot = packed struct {
260
281
 
261
282
  pub const Status = gen1.Status;
262
283
 
263
- const Volatile = packed struct {
284
+ pub const Volatiles = packed struct {
264
285
  Bide: bool = false,
265
286
  Thrashing: bool = false,
266
287
  Flinch: bool = false,
@@ -294,8 +315,9 @@ const Volatile = packed struct {
294
315
  trapped: bool = false,
295
316
  switched: bool = false,
296
317
  switching: bool = false,
318
+ dirty: bool = false,
297
319
 
298
- _: u5 = 0,
320
+ _: u4 = 0,
299
321
 
300
322
  bind: u4 = 0,
301
323
  future_sight: FutureSight = .{},
@@ -306,10 +328,11 @@ const Volatile = packed struct {
306
328
  toxic: u8 = 0,
307
329
  confusion: u4 = 0,
308
330
  encore: u4 = 0,
331
+ // TODO merge with attacks (ie rollout/thrashing)? need to be zeroed at same time
309
332
  fury_cutter: u4 = 0,
310
333
  perish_song: u4 = 0,
311
334
  protect: u4 = 0,
312
- rollout: u4 = 0,
335
+ attacks: u4 = 0, // bide/thrashing/rollout turns
313
336
 
314
337
  const Disabled = packed struct {
315
338
  move: u4 = 0,
@@ -322,7 +345,7 @@ const Volatile = packed struct {
322
345
  };
323
346
 
324
347
  comptime {
325
- assert(@sizeOf(Volatile) == 16);
348
+ assert(@sizeOf(Volatiles) == 16);
326
349
  }
327
350
  };
328
351
 
@@ -406,6 +429,7 @@ test Move {
406
429
  try expectEqual(Move.Effect.ConfusionChance, move.effect);
407
430
  try expectEqual(@as(u8, 50), move.accuracy);
408
431
  try expectEqual(@as(u8, 5), move.pp);
432
+ try expectEqual(@as(i8, -1), Move.get(.Counter).priority);
409
433
  }
410
434
 
411
435
  pub const Species = species.Species;
@@ -48,7 +48,7 @@ pub const Battle = struct {
48
48
  comptime rolls: anytype,
49
49
  p1: []const Pokemon,
50
50
  p2: []const Pokemon,
51
- ) data.Battle(rng.FixedRNG(1, rolls.len)) {
51
+ ) data.Battle(rng.FixedRNG(2, rolls.len)) {
52
52
  return .{
53
53
  .rng = .{ .rolls = rolls },
54
54
  .sides = .{ Side.init(p1), Side.init(p2) },
@@ -87,7 +87,7 @@ pub const Side = struct {
87
87
 
88
88
  for (0..ps.len) |i| {
89
89
  side.pokemon[i] = Pokemon.init(ps[i]);
90
- // FIXME side.order[i] = i + 1;
90
+ side.pokemon[i].position = @as(u4, @intCast(i)) + 1;
91
91
  }
92
92
  return side;
93
93
  }
@@ -98,7 +98,7 @@ pub const Side = struct {
98
98
 
99
99
  for (0..n) |i| {
100
100
  side.pokemon[i] = Pokemon.random(rand, opt);
101
- side.pokemon[i].position = i + 1;
101
+ side.pokemon[i].position = @as(u4, @intCast(i)) + 1;
102
102
  }
103
103
 
104
104
  return side;
@@ -139,7 +139,7 @@ pub const Pokemon = struct {
139
139
  .id = m,
140
140
  .pp_ups = 3,
141
141
  // NB: PP can be at most 61 legally (though can overflow to 63)
142
- .pp = @intCast(@min(Move.pp(m) / 5 * 8, 61)),
142
+ .pp = @intCast(@min(Move.get(m).pp / 5 * 8, 61)),
143
143
  };
144
144
  }
145
145
  pokemon.item = p.item;
@@ -151,7 +151,7 @@ pub const Pokemon = struct {
151
151
  pokemon.status = p.status;
152
152
  pokemon.types = species.types;
153
153
  pokemon.level = p.level;
154
- pokemon.dvs = DVs.from(p.dvs);
154
+ pokemon.dvs = DVs.from(p.species, p.dvs);
155
155
  return pokemon;
156
156
  }
157
157
 
@@ -189,7 +189,8 @@ pub const Pokemon = struct {
189
189
  const pp_ups: u8 =
190
190
  if (!opt.cleric and rand.chance(u8, 1, 10)) rand.range(u2, 0, 2 + 1) else 3;
191
191
  // NB: PP can be at most 61 legally (though can overflow to 63)
192
- const max_pp: u8 = @intCast(Move.pp(m) + pp_ups * @min(Move.pp(m) / 5, 7));
192
+ var base = Move.get(m).pp;
193
+ const max_pp: u8 = @intCast(base + pp_ups * @min(base / 5, 7));
193
194
  ms[i] = .{
194
195
  .id = m,
195
196
  .pp_ups = pp_ups,
@@ -199,7 +200,7 @@ pub const Pokemon = struct {
199
200
  return .{
200
201
  .species = s,
201
202
  .types = species.types,
202
- .dvs = DVs.from(dvs),
203
+ .dvs = DVs.from(s, dvs),
203
204
  .level = lvl,
204
205
  .stats = stats,
205
206
  .hp = if (opt.cleric) stats.hp else rand.range(u16, 0, stats.hp + 1),
@@ -36,19 +36,483 @@ const Stats = data.Stats;
36
36
  const Status = data.Status;
37
37
 
38
38
  pub fn update(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Result {
39
+ assert(c1.type != .Pass or c2.type != .Pass or battle.turn == 0);
40
+ if (battle.turn == 0) return start(battle, options);
41
+
42
+ if (try turnOrder(battle, c1, c2, options) == .P1) {
43
+ if (try doTurn(battle, .P1, c1, .P2, c2, options)) |r| return r;
44
+ } else {
45
+ if (try doTurn(battle, .P2, c2, .P1, c1, options)) |r| return r;
46
+ }
47
+
48
+ return endTurn(battle, options);
49
+ }
50
+
51
+ fn start(battle: anytype, options: anytype) !Result {
52
+ const p1 = battle.side(.P1);
53
+ const p2 = battle.side(.P2);
54
+
55
+ var p1_slot = findFirstAlive(p1);
56
+ assert(!showdown or p1_slot == 1);
57
+ if (p1_slot == 0) return if (findFirstAlive(p2) == 0) Result.Tie else Result.Lose;
58
+
59
+ var p2_slot = findFirstAlive(p2);
60
+ assert(!showdown or p2_slot == 1);
61
+ if (p2_slot == 0) return Result.Win;
62
+
63
+ try switchIn(battle, .P1, p1_slot, true, options);
64
+ try switchIn(battle, .P2, p2_slot, true, options);
65
+
66
+ return endTurn(battle, options);
67
+ }
68
+
69
+ fn findFirstAlive(side: *const Side) u8 {
70
+ for (side.pokemon, 0..) |pokemon, i| if (pokemon.hp > 0) return side.pokemon[i].position;
71
+ return 0;
72
+ }
73
+
74
+ fn selectMove(battle: anytype, player: Player, choice: Choice) void {
75
+ if (choice.type == .Pass) return; // FIXME BATON PASS
76
+
77
+ var side = battle.side(player);
78
+ var volatiles = &side.active.volatiles;
79
+
80
+ // pre-battle menu
81
+ const forced = forced: {
82
+ if (volatiles.Recharging) break :forced true;
83
+ // Pokémon Showdown removes Flinch at the end-of-turn in its residual handler
84
+ if (!showdown) {
85
+ volatiles.Flinch = false;
86
+ battle.foe(player).active.volatiles.Flinch = false;
87
+ }
88
+ break :forced (volatiles.Thrashing or volatiles.Charging or volatiles.Rollout);
89
+ };
90
+
91
+ // battle menu
92
+ if (choice.type == .Switch) return;
93
+ assert(choice.type == .Move and (!forced or choice.data == @intFromBool(showdown)));
94
+
95
+ done: {
96
+ if (forced) break :done;
97
+ // pre-move select
98
+ if (volatiles.Encore) {
99
+ // TODO wCurPlayerMove = side.lastMove(true);
100
+ // assert(wCurPlayerMove != .None);
101
+ volatiles.Bide = false; // FIXME wPlayerCharging vs. SUBSTATUS_BIDE?
102
+ const effect = Move.get(.Pound).effect; // TODO
103
+ if (effect != .FuryCutter) volatiles.fury_cutter = false;
104
+ if (effect != .Rage) {
105
+ volatiles.Rage = false;
106
+ volatiles.rage = 0;
107
+ }
108
+ if (effect != .Protect and effect != .Endure) volatiles.protect = 0;
109
+ return;
110
+ }
111
+ if (volatiles.Bide) break :done;
112
+ // move select
113
+ if (choice.data == 0) {
114
+ const struggle = ok: {
115
+ for (side.active.moves, 0..) |move, i| {
116
+ if (move.pp > 0 and volatiles.disabled_move != i + 1) break :ok false;
117
+ }
118
+ break :ok true;
119
+ };
120
+ assert(struggle);
121
+ // TODO wCurPlayerMove = .Struggle;
122
+ } else {
123
+ assert(showdown or side.active.volatiles.disabled_move != choice.data);
124
+ const move = side.active.move(choice.data);
125
+ // You cannot *select* a move with 0 PP
126
+ assert(move.pp != 0);
127
+ // TODO wCurPlayerMove = move.id;
128
+ // battle.lastMove(player).index = @intCast(c.data);
129
+ }
130
+ }
131
+
132
+ volatiles.Rage = false;
133
+ volatiles.rage = 0;
134
+ volatiles.fury_cutter = 0;
135
+ volatiles.protect = 0;
136
+ }
137
+
138
+ fn saveMove(battle: anytype) void {
39
139
  _ = battle;
40
- _ = c1;
41
- _ = c2;
140
+ return null;
141
+ }
142
+
143
+ fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: anytype) !void {
144
+ var side = battle.side(player);
145
+ var foe = battle.foe(player);
146
+
147
+ var active = &side.active;
148
+ const incoming = side.get(slot);
149
+
150
+ assert(incoming.hp != 0);
151
+ assert(slot != 1 or initial);
152
+
153
+ const out = side.pokemon[0].position;
154
+ side.pokemon[0].position = side.pokemon[slot - 1].position;
155
+ side.pokemon[slot - 1].position = out;
156
+
157
+ side.last_used_move = .None;
158
+ foe.active.volatiles.dirty = true;
159
+
160
+ active.volatiles = .{};
161
+ active.stats = incoming.stats;
162
+ active.moves = incoming.moves;
163
+ active.boosts = .{};
164
+ active.types = incoming.types;
165
+ active.species = incoming.species;
166
+
167
+ statusModify(incoming.status, &active.stats);
168
+
169
+ try options.log.switched(battle.active(player), incoming);
170
+ // TODO: options.chance.switched(player, side.order[0], out);
171
+
172
+ if (side.conditions.Spikes and !active.types.includes(.Flying)) {
173
+ incoming.hp -|= @max(incoming.stats.hp / 8, 1);
174
+ try options.log.damage(battle.active(player), incoming, .Spikes);
175
+ }
176
+ }
177
+
178
+ fn turnOrder(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Player {
179
+ assert(c1.type != .Pass or c2.type != .Pass);
180
+
181
+ if (c1.type == .Pass) return .P2;
182
+ if (c2.type == .Pass) return .P1;
183
+
184
+ // Pokémon Showdown always rolls for Quick Claw every turn, even if no Pokémon hold Quick Claw
185
+ // TODO: add to pending and only commit roll on Pokémon Showdown if roll is used
186
+ const qkc = showdown and try Rolls.quickClaw(battle, .P1, options);
187
+
188
+ if ((c1.type == .Switch) != (c2.type == .Switch)) return if (c1.type == .Switch) .P1 else .P2;
189
+
190
+ // https://www.smogon.com/forums/threads/adv-switch-priority.3622189/
191
+ // > In Gen 1 it's irrelevant [which player switches first] because switches happen instantly on
192
+ // > your own screen without waiting for the other player's choice (and their choice will appear
193
+ // > to happen first for them too, unless they attacked in which case your switch happens first)
194
+ // A cartridge-compatible implemention must not advance the RNG so we simply default to P1
195
+ const double_switch = c1.type == .Switch and c2.type == .Switch;
196
+ if (!showdown and double_switch) return .P1;
197
+
198
+ const m1 = .Pound; // TODO battle.side(.P1).last_selected_move;
199
+ const m2 = .Pound; // TODO battle.side(.P2).last_selected_move;
200
+ if (!showdown or !double_switch) {
201
+ const pri1 = Move.get(m1).priority;
202
+ const pri2 = Move.get(m2).priority;
203
+ if (pri1 != pri2) return if (pri1 > pri2) .P1 else .P2;
204
+
205
+ const qkc1 = battle.side(.P1).stored().item == .QuickClaw;
206
+ const qkc2 = battle.side(.P2).stored().item == .QuickClaw;
207
+ if (!showdown and qkc1 and qkc2) {
208
+ // If both Pokémon have Quick Claw the cartridge checks them in order and exits early if
209
+ // the first one procs, meaning the host has a slightly higher chance of going first
210
+ if (try Rolls.quickClaw(battle, .P1, options)) return .P1;
211
+ if (try Rolls.quickClaw(battle, .P2, options)) return .P2;
212
+ } else if (qkc1) {
213
+ const proc = if (showdown) qkc else try Rolls.quickClaw(battle, .P1, options);
214
+ if (proc) return .P1;
215
+ } else if (qkc2) {
216
+ const proc = if (showdown) qkc else try Rolls.quickClaw(battle, .P2, options);
217
+ if (proc) return .P2;
218
+ }
219
+ }
220
+
221
+ const spe1 = battle.side(.P1).active.stats.spe;
222
+ const spe2 = battle.side(.P2).active.stats.spe;
223
+ if (spe1 == spe2) {
224
+ // Pokémon Showdown's beforeTurnCallback shenanigans
225
+ if (showdown and !double_switch and hasCallback(m1) and hasCallback(m2)) {
226
+ battle.rng.advance(1);
227
+ }
228
+
229
+ const p1 = try Rolls.speedTie(battle, options);
230
+ if (!showdown) return if (p1) .P1 else .P2;
231
+
232
+ // Pokémon Showdown's "lockedmove" volatile's onBeforeTurn uses BattleQueue#changeAction,
233
+ // meaning that if a side is locked into a thrashing move and wins the speed tie, it
234
+ // actually uses its priority to simply insert its actual changed action into the queue,
235
+ // causing it to then execute *after* the side which should go second...
236
+ const t1 = battle.side(.P1).active.volatiles.Thrashing;
237
+ const t2 = battle.side(.P2).active.volatiles.Thrashing;
238
+ // If *both* sides are thrashing it really should be another speed tie, but we've patched
239
+ // that out and enforce host ordering of events, so P1 just goes first regardless of who
240
+ // won the original coin flip
241
+ if (t1 and t2) return .P1;
242
+ return if (p1) if (t1 and !t2) .P2 else .P1 else if (t2 and !t1) .P1 else .P2;
243
+ }
244
+
245
+ return if (spe1 > spe2) .P1 else .P2;
246
+ }
247
+
248
+ fn hasCallback(m: Move) bool {
249
+ return switch (m) {
250
+ .Counter, .MirrorCoat, .Pursuit => true,
251
+ else => false,
252
+ };
253
+ }
254
+
255
+ fn doTurn(
256
+ battle: anytype,
257
+ player: Player,
258
+ player_choice: Choice,
259
+ foe_player: Player,
260
+ foe_choice: Choice,
261
+ options: anytype,
262
+ ) !?Result {
263
+ assert(player_choice.type != .Pass);
264
+
265
+ const volatiles = &battle.side(player).active.volatiles;
266
+ const foe_volatiles = &battle.foe(player).active.volatiles;
267
+
268
+ volatiles.DestinyBond = false;
269
+ if (try executeMove(battle, player, player_choice, options)) |r| return r;
270
+ foe_volatiles.Protect = false;
271
+ foe_volatiles.Endure = false;
272
+ foe_volatiles.DestinyBond = false;
273
+
274
+ // foe_volatiles.DestinyBond = false;
275
+ if (try executeMove(battle, foe_player, foe_choice, options)) |r| return r;
276
+ volatiles.Protect = false;
277
+ volatiles.Endure = false;
278
+ volatiles.DestinyBond = false;
279
+
280
+ return null;
281
+ }
282
+
283
+ fn executeMove(battle: anytype, player: Player, choice: Choice, options: anytype) !?Result {
284
+ if (choice.type == .Switch) {
285
+ try switchIn(battle, player, choice.data, false, options);
286
+ return null;
287
+ }
288
+
289
+ assert(choice.type == .Move);
290
+ var mslot: u4 = @intCast(choice.data);
291
+
292
+ // const move = Move.get(side.last_selected_move);
293
+
294
+ // CheckTurn
295
+
296
+ return doMove(battle, player, options, mslot);
297
+ }
298
+
299
+ fn decrementPP(side: *Side, mslot: u4) void {
300
+ var active = &side.active;
301
+ const volatiles = &active.volatiles;
302
+
303
+ // TODO assert(side.last_selected_move != .Struggle);
304
+ assert(!volatiles.Charging and !volatiles.BeatUp and !volatiles.Thrashing and !volatiles.Bide);
305
+
306
+ assert(active.move(mslot).pp > 0);
307
+ active.move(mslot).pp = @as(u6, @intCast(active.move(mslot).pp)) -% 1;
308
+ if (volatiles.Transform) return;
309
+
310
+ // FIXME mimic
311
+
312
+ assert(side.stored().move(mslot).pp > 0);
313
+ side.stored().move(mslot).pp = @as(u6, @intCast(side.stored().move(mslot).pp)) -% 1;
314
+ assert(active.move(mslot).pp == side.stored().move(mslot).pp);
315
+ }
316
+
317
+ fn doMove(battle: anytype, player: Player, options: anytype, mslot: u4) !?Result {
42
318
  _ = options;
319
+ var side = battle.side(player);
320
+ const move = Move.get(.Teleport); // side.last_selected_move
321
+ switch (move.effect) {
322
+ .Teleport => {
323
+ // side.useMove();
324
+ decrementPP(side, mslot);
325
+ },
326
+ else => @panic("TODO"),
327
+ }
328
+ return null;
329
+ }
330
+
331
+ fn endTurn(battle: anytype, options: anytype) @TypeOf(options.log).Error!Result {
332
+ battle.turn += 1;
333
+
334
+ if (showdown and battle.turn >= 1000) {
335
+ try options.log.tie();
336
+ return Result.Tie;
337
+ } else if (battle.turn >= 65535) {
338
+ return Result.Error;
339
+ }
340
+
341
+ try options.log.turn(battle.turn);
43
342
 
44
343
  return Result.Default;
45
344
  }
46
345
 
346
+ pub const Effects = struct {
347
+ fn teleport(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
348
+ _ = battle;
349
+ _ = player;
350
+ _ = move;
351
+ _ = options;
352
+ }
353
+ };
354
+
355
+ fn statusModify(status: u8, stats: *Stats(u16)) void {
356
+ if (Status.is(status, .PAR)) {
357
+ stats.spe = @max(stats.spe / 4, 1);
358
+ } else if (Status.is(status, .BRN)) {
359
+ stats.atk = @max(stats.atk / 2, 1);
360
+ }
361
+ }
362
+
363
+ inline fn isForced(active: anytype) bool {
364
+ return active.volatiles.Recharging or active.volatiles.Rage or
365
+ active.volatiles.Thrashing or active.volatiles.Charging or
366
+ // FIXME TODO Underground or Flying?
367
+ active.volatiles.Underground or active.volatiles.Flying or
368
+ active.volatiles.Rollout;
369
+ }
370
+
371
+ pub const Rolls = struct {
372
+ inline fn speedTie(battle: anytype, options: anytype) !bool {
373
+ const p1 = if (options.calc.overridden(.P1, .speed_tie)) |player|
374
+ player == .P1
375
+ else if (showdown)
376
+ battle.rng.range(u8, 0, 2) == 0
377
+ else
378
+ battle.rng.next() < Gen12.percent(50) + 1;
379
+
380
+ try options.chance.speedTie(p1);
381
+ return p1;
382
+ }
383
+
384
+ inline fn quickClaw(battle: anytype, player: Player, options: anytype) !bool {
385
+ const qkc = if (options.calc.overridden(player, .quick_claw)) |val|
386
+ val == .true
387
+ else if (showdown)
388
+ battle.rng.chance(u8, 60, 256)
389
+ else
390
+ battle.rng.next() < 60;
391
+
392
+ try options.chance.quickClaw(player, qkc);
393
+ return qkc;
394
+ }
395
+ };
396
+
397
+ test "RNG agreement" {
398
+ if (!showdown) return;
399
+ var expected: [256]u32 = undefined;
400
+ for (0..expected.len) |i| {
401
+ expected[i] = @intCast(i * 0x1000000);
402
+ }
403
+
404
+ var spe = rng.FixedRNG(2, expected.len){ .rolls = expected };
405
+ var qkc = rng.FixedRNG(2, expected.len){ .rolls = expected };
406
+
407
+ for (0..expected.len) |i| {
408
+ try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1);
409
+ try expectEqual(qkc.chance(u8, 60, 256), i < 60);
410
+ }
411
+ }
412
+
47
413
  pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 {
48
- _ = battle;
49
- _ = player;
50
- _ = request;
51
- _ = out;
414
+ var n: u8 = 0;
415
+ switch (request) {
416
+ .Pass => {
417
+ out[n] = .{};
418
+ n += 1;
419
+ },
420
+ .Switch => {
421
+ const side = battle.side(player);
422
+ var slot: u4 = 2;
423
+ while (slot <= 6) : (slot += 1) {
424
+ const id = side.order[slot - 1];
425
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
426
+ out[n] = .{ .type = .Switch, .data = slot };
427
+ n += 1;
428
+ }
429
+ if (n == 0) {
430
+ out[n] = .{};
431
+ n += 1;
432
+ }
433
+ },
434
+ .Move => {
435
+ const side = battle.side(player);
52
436
 
53
- return 0;
437
+ var active = &side.active;
438
+ const stored = side.stored();
439
+
440
+ // While players are not given any input options on the cartridge in these cases,
441
+ // Pokémon Showdown instead produces a list with a single move that must be chosen.
442
+ //
443
+ // Given that no input is allowed on the cartridge 'Pass' seems like it would be logical
444
+ // here when not in compatibility mode, but the engine needs to be able to differentiate
445
+ // between passing while waiting for an opponent's forced switch after fainting and
446
+ // passing due to being forced into using a move. Instead of introducing another option
447
+ // we simply repurpose Move with no move slot, even though pedantically this is not
448
+ // strictly correct as the player would not have been presented the option to move or
449
+ // switch at all.
450
+ if (isForced(active)) {
451
+ out[n] = .{ .type = .Move, .data = @intFromBool(showdown) };
452
+ n += 1;
453
+ return n;
454
+ }
455
+
456
+ var slot: u4 = 2;
457
+ while (!active.volatiles.trapped and slot <= 6) : (slot += 1) {
458
+ const id = side.order[slot - 1];
459
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
460
+ out[n] = .{ .type = .Switch, .data = slot };
461
+ n += 1;
462
+ }
463
+
464
+ const limited = active.volatiles.Bide or active.volatiles.bind > 0;
465
+ // On the cartridge, all of these happen after "FIGHT" (indicating you are not
466
+ // switching) but before you are allowed to select a move. Pokémon Showdown instead
467
+ // either disables all other moves in the case of limited or requires you to select a
468
+ // move normally if sleeping/frozen/bound.
469
+ if (!showdown and (limited or
470
+ Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP)))
471
+ {
472
+ out[n] = .{ .type = .Move, .data = 0 };
473
+ n += 1;
474
+ return n;
475
+ }
476
+
477
+ slot = 1;
478
+ // Pokémon Showdown handles Bide and Binding moves by checking if the move in question
479
+ // is present in the Pokémon's moveset (which means moves called via Metronome / Mirror
480
+ // Move will not result in forcing the subsequent use unless the user also had the
481
+ // proc-ed move in their moveset) and disabling all other moves.
482
+ if (limited) {
483
+ assert(showdown);
484
+ assert(side.last_selected_move != .None);
485
+ while (slot <= 4) : (slot += 1) {
486
+ const m = active.moves[slot - 1];
487
+ if (m.id == .None) break;
488
+ if (m.id == if (active.volatiles.Bide) .Bide else side.last_selected_move) {
489
+ // Pokémon Showdown displays Struggle if limited to Bide but unable to pick
490
+ const struggle =
491
+ m.id == .Bide and (m.pp == 0 or active.volatiles.disabled_move == slot);
492
+ const s = if (struggle) 0 else slot;
493
+ out[n] = .{ .type = .Move, .data = s };
494
+ n += 1;
495
+ return n;
496
+ }
497
+ }
498
+ }
499
+
500
+ const before = n;
501
+ slot = 1;
502
+ while (slot <= 4) : (slot += 1) {
503
+ const m = active.moves[slot - 1];
504
+ if (m.id == .None) break;
505
+ if (m.pp == 0) continue;
506
+ if (active.volatiles.disabled_move == slot) continue;
507
+ out[n] = .{ .type = .Move, .data = slot };
508
+ n += 1;
509
+ }
510
+ // Struggle (Pokémon Showdown would use 'move 1' here)
511
+ if (n == before) {
512
+ out[n] = .{ .type = .Move, .data = 0 };
513
+ n += 1;
514
+ }
515
+ },
516
+ }
517
+ return n;
54
518
  }