@pkmn/engine 0.1.0-dev.f3aaee39 → 0.1.0-dev.fc150752

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.
@@ -20,6 +20,7 @@ const Result = common.Result;
20
20
 
21
21
  const showdown = pkmn.options.showdown;
22
22
 
23
+ const Cant = protocol.Cant;
23
24
  const Damage = protocol.Damage;
24
25
  const Heal = protocol.Heal;
25
26
 
@@ -34,21 +35,924 @@ const Side = data.Side;
34
35
  const Species = data.Species;
35
36
  const Stats = data.Stats;
36
37
  const Status = data.Status;
38
+ const Type = data.Type;
39
+ const Types = data.Types;
40
+ const Volatiles = data.Volatiles;
41
+
42
+ // zig fmt: off
43
+ const STAT_BOOSTS = &[_][2]u8{
44
+ .{ 25, 100 }, // -6
45
+ .{ 28, 100 }, // -5
46
+ .{ 33, 100 }, // -4
47
+ .{ 40, 100 }, // -3
48
+ .{ 50, 100 }, // -2
49
+ .{ 66, 100 }, // -1
50
+ .{ 1, 1 }, // 0
51
+ .{ 15, 10 }, // +1
52
+ .{ 2, 1 }, // +2
53
+ .{ 25, 10 }, // +3
54
+ .{ 3, 1 }, // +4
55
+ .{ 35, 10 }, // +5
56
+ .{ 4, 1 }, // +6
57
+ };
58
+
59
+ const ACCURACY_BOOSTS = &[_][2]u8{
60
+ .{ 33, 100 }, // -6
61
+ .{ 36, 100 }, // -5
62
+ .{ 43, 100 }, // -4
63
+ .{ 50, 100 }, // -3
64
+ .{ 60, 100 }, // -2
65
+ .{ 75, 100 }, // -1
66
+ .{ 1, 1 }, // 0
67
+ .{ 133, 100 }, // +1
68
+ .{ 166, 100 }, // +2
69
+ .{ 2, 1 }, // +3
70
+ .{ 233, 100 }, // +4
71
+ .{ 133, 50 }, // +5
72
+ .{ 3, 1 }, // +6
73
+ };
74
+
75
+ const CRITICAL_HITS = &[_]u8{
76
+ 256 / 15, // 0
77
+ 256 / 8, // +1
78
+ 256 / 4, // +2
79
+ 256 / 3, // +3
80
+ 256 / 2, // +4
81
+ };
82
+ // zig fmt: on
83
+
84
+ const MAX_STAT_VALUE = 999;
85
+
86
+ const DISTRIBUTION = [_]u3{ 2, 2, 2, 3, 3, 3, 4, 5 };
37
87
 
38
88
  pub fn update(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Result {
89
+ assert(c1.type != .Pass or c2.type != .Pass or battle.turn == 0);
90
+ if (battle.turn == 0) return start(battle, options);
91
+
92
+ if (try turnOrder(battle, c1, c2, options) == .P1) {
93
+ if (try doTurn(battle, .P1, c1, .P2, c2, options)) |r| return r;
94
+ } else {
95
+ if (try doTurn(battle, .P2, c2, .P1, c1, options)) |r| return r;
96
+ }
97
+
98
+ return endTurn(battle, options);
99
+ }
100
+
101
+ fn start(battle: anytype, options: anytype) !Result {
102
+ const p1 = battle.side(.P1);
103
+ const p2 = battle.side(.P2);
104
+
105
+ var p1_slot = findFirstAlive(p1);
106
+ assert(!showdown or p1_slot == 1);
107
+ if (p1_slot == 0) return if (findFirstAlive(p2) == 0) Result.Tie else Result.Lose;
108
+
109
+ var p2_slot = findFirstAlive(p2);
110
+ assert(!showdown or p2_slot == 1);
111
+ if (p2_slot == 0) return Result.Win;
112
+
113
+ try switchIn(battle, .P1, p1_slot, true, options);
114
+ try switchIn(battle, .P2, p2_slot, true, options);
115
+
116
+ return endTurn(battle, options);
117
+ }
118
+
119
+ fn findFirstAlive(side: *const Side) u8 {
120
+ for (side.pokemon, 0..) |pokemon, i| if (pokemon.hp > 0) return side.pokemon[i].position;
121
+ return 0;
122
+ }
123
+
124
+ fn selectMove(battle: anytype, player: Player, choice: Choice) void {
125
+ if (choice.type == .Pass) return; // FIXME BATON PASS
126
+
127
+ var side = battle.side(player);
128
+ var volatiles = &side.active.volatiles;
129
+
130
+ // pre-battle menu
131
+ const forced = forced: {
132
+ if (volatiles.Recharging) break :forced true;
133
+ // Pokémon Showdown removes Flinch at the end-of-turn in its residual handler
134
+ if (!showdown) {
135
+ volatiles.Flinch = false;
136
+ battle.foe(player).active.volatiles.Flinch = false;
137
+ }
138
+ break :forced (volatiles.Thrashing or volatiles.Charging or volatiles.Rollout);
139
+ };
140
+
141
+ // battle menu
142
+ if (choice.type == .Switch) return;
143
+ assert(choice.type == .Move and (!forced or choice.data == @intFromBool(showdown)));
144
+
145
+ done: {
146
+ if (forced) break :done;
147
+ // pre-move select
148
+ if (volatiles.Encore) {
149
+ // TODO wCurPlayerMove = side.lastMove(true);
150
+ // assert(wCurPlayerMove != .None);
151
+ volatiles.Bide = false; // FIXME wPlayerCharging vs. SUBSTATUS_BIDE?
152
+ const effect = Move.get(.Pound).effect; // TODO
153
+ if (effect != .FuryCutter) volatiles.fury_cutter = false;
154
+ if (effect != .Rage) {
155
+ volatiles.Rage = false;
156
+ volatiles.rage = 0;
157
+ }
158
+ if (effect != .Protect and effect != .Endure) volatiles.protect = 0;
159
+ return;
160
+ }
161
+ if (volatiles.Bide) break :done;
162
+ // move select
163
+ if (choice.data == 0) {
164
+ const struggle = ok: {
165
+ for (side.active.moves, 0..) |move, i| {
166
+ if (move.pp > 0 and volatiles.disabled_move != i + 1) break :ok false;
167
+ }
168
+ break :ok true;
169
+ };
170
+ assert(struggle);
171
+ // TODO wCurPlayerMove = .Struggle;
172
+ } else {
173
+ assert(showdown or side.active.volatiles.disabled_move != choice.data);
174
+ const move = side.active.move(choice.data);
175
+ // You cannot *select* a move with 0 PP
176
+ assert(move.pp != 0);
177
+ // TODO wCurPlayerMove = move.id;
178
+ // battle.lastMove(player).index = @intCast(c.data);
179
+ }
180
+ }
181
+
182
+ volatiles.Rage = false;
183
+ volatiles.rage = 0;
184
+ volatiles.fury_cutter = 0;
185
+ volatiles.protect = 0;
186
+ }
187
+
188
+ fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: anytype) !void {
189
+ var side = battle.side(player);
190
+ var foe = battle.foe(player);
191
+
192
+ var active = &side.active;
193
+ const incoming = side.get(slot);
194
+
195
+ assert(incoming.hp != 0);
196
+ assert(slot != 1 or initial);
197
+
198
+ const out = side.pokemon[0].position;
199
+ side.pokemon[0].position = side.pokemon[slot - 1].position;
200
+ side.pokemon[slot - 1].position = out;
201
+
202
+ side.last_used_move = .None;
203
+ foe.active.volatiles.dirty = true;
204
+
205
+ active.volatiles = .{};
206
+ active.stats = incoming.stats;
207
+ active.moves = incoming.moves;
208
+ active.boosts = .{};
209
+ active.types = incoming.types;
210
+ active.species = incoming.species;
211
+
212
+ statusModify(incoming.status, &active.stats);
213
+
214
+ try options.log.switched(battle.active(player), incoming);
215
+ options.chance.switched(player, side.pokemon[0].position, out);
216
+
217
+ if (side.conditions.Spikes and !active.types.includes(.Flying)) {
218
+ incoming.hp -|= @max(incoming.stats.hp / 8, 1);
219
+ try options.log.damage(battle.active(player), incoming, .Spikes);
220
+ }
221
+ }
222
+
223
+ fn turnOrder(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Player {
224
+ assert(c1.type != .Pass or c2.type != .Pass);
225
+
226
+ if (c1.type == .Pass) return .P2;
227
+ if (c2.type == .Pass) return .P1;
228
+
229
+ // Pokémon Showdown always rolls for Quick Claw every turn, even if no Pokémon hold Quick Claw
230
+ // TODO: add to pending and only commit roll on Pokémon Showdown if roll is used
231
+ const qkc = showdown and try Rolls.quickClaw(battle, .P1, options);
232
+
233
+ if ((c1.type == .Switch) != (c2.type == .Switch)) return if (c1.type == .Switch) .P1 else .P2;
234
+
235
+ // https://www.smogon.com/forums/threads/adv-switch-priority.3622189/
236
+ // > In Gen 1 it's irrelevant [which player switches first] because switches happen instantly on
237
+ // > your own screen without waiting for the other player's choice (and their choice will appear
238
+ // > to happen first for them too, unless they attacked in which case your switch happens first)
239
+ // A cartridge-compatible implemention must not advance the RNG so we simply default to P1
240
+ const double_switch = c1.type == .Switch and c2.type == .Switch;
241
+ if (!showdown and double_switch) return .P1;
242
+
243
+ const m1 = .Pound; // TODO battle.side(.P1).last_selected_move;
244
+ const m2 = .Pound; // TODO battle.side(.P2).last_selected_move;
245
+ if (!showdown or !double_switch) {
246
+ const pri1 = Move.get(m1).priority;
247
+ const pri2 = Move.get(m2).priority;
248
+ if (pri1 != pri2) return if (pri1 > pri2) .P1 else .P2;
249
+
250
+ const qkc1 = battle.side(.P1).stored().item == .QuickClaw;
251
+ const qkc2 = battle.side(.P2).stored().item == .QuickClaw;
252
+ if (!showdown and qkc1 and qkc2) {
253
+ // If both Pokémon have Quick Claw the cartridge checks them in order and exits early if
254
+ // the first one procs, meaning the host has a slightly higher chance of going first
255
+ if (try Rolls.quickClaw(battle, .P1, options)) return .P1;
256
+ if (try Rolls.quickClaw(battle, .P2, options)) return .P2;
257
+ } else if (qkc1) {
258
+ const proc = if (showdown) qkc else try Rolls.quickClaw(battle, .P1, options);
259
+ if (proc) return .P1;
260
+ } else if (qkc2) {
261
+ const proc = if (showdown) qkc else try Rolls.quickClaw(battle, .P2, options);
262
+ if (proc) return .P2;
263
+ }
264
+ }
265
+
266
+ const spe1 = battle.side(.P1).active.stats.spe;
267
+ const spe2 = battle.side(.P2).active.stats.spe;
268
+ if (spe1 == spe2) {
269
+ // Pokémon Showdown's beforeTurnCallback shenanigans
270
+ if (showdown and !double_switch and hasCallback(m1) and hasCallback(m2)) {
271
+ battle.rng.advance(1);
272
+ }
273
+
274
+ const p1 = try Rolls.speedTie(battle, options);
275
+ if (!showdown) return if (p1) .P1 else .P2;
276
+
277
+ // Pokémon Showdown's "lockedmove" volatile's onBeforeTurn uses BattleQueue#changeAction,
278
+ // meaning that if a side is locked into a thrashing move and wins the speed tie, it
279
+ // actually uses its priority to simply insert its actual changed action into the queue,
280
+ // causing it to then execute *after* the side which should go second...
281
+ const t1 = battle.side(.P1).active.volatiles.Thrashing;
282
+ const t2 = battle.side(.P2).active.volatiles.Thrashing;
283
+ // If *both* sides are thrashing it really should be another speed tie, but we've patched
284
+ // that out and enforce host ordering of events, so P1 just goes first regardless of who
285
+ // won the original coin flip
286
+ if (t1 and t2) return .P1;
287
+ return if (p1) if (t1 and !t2) .P2 else .P1 else if (t2 and !t1) .P1 else .P2;
288
+ }
289
+
290
+ return if (spe1 > spe2) .P1 else .P2;
291
+ }
292
+
293
+ fn hasCallback(m: Move) bool {
294
+ return switch (m) {
295
+ .Counter, .MirrorCoat, .Pursuit => true,
296
+ else => false,
297
+ };
298
+ }
299
+
300
+ fn doTurn(
301
+ battle: anytype,
302
+ player: Player,
303
+ player_choice: Choice,
304
+ foe_player: Player,
305
+ foe_choice: Choice,
306
+ options: anytype,
307
+ ) !?Result {
308
+ assert(player_choice.type != .Pass);
309
+
310
+ const volatiles = &battle.side(player).active.volatiles;
311
+ const foe_volatiles = &battle.foe(player).active.volatiles;
312
+
313
+ volatiles.DestinyBond = false;
314
+ if (try executeMove(battle, player, player_choice, options)) |r| return r;
315
+ foe_volatiles.Protect = false;
316
+ foe_volatiles.Endure = false;
317
+ foe_volatiles.DestinyBond = false;
318
+
319
+ // foe_volatiles.DestinyBond = false;
320
+ if (try executeMove(battle, foe_player, foe_choice, options)) |r| return r;
321
+ volatiles.Protect = false;
322
+ volatiles.Endure = false;
323
+ volatiles.DestinyBond = false;
324
+
325
+ return null;
326
+ }
327
+
328
+ fn executeMove(battle: anytype, player: Player, choice: Choice, options: anytype) !?Result {
329
+ if (choice.type == .Switch) {
330
+ try switchIn(battle, player, choice.data, false, options);
331
+ return null;
332
+ }
333
+
334
+ assert(choice.type == .Move);
335
+ var mslot: u4 = @intCast(choice.data);
336
+
337
+ // const move = Move.get(side.last_selected_move);
338
+
339
+ // CheckTurn
340
+
341
+ return doMove(battle, player, options, mslot);
342
+ }
343
+
344
+ fn beforeMove(battle: anytype, player: Player, options: anytype) !void {
345
+ var log = options.log;
346
+ var side = battle.side(player);
347
+ // const foe = battle.foe(player);
348
+ var active = &side.active;
349
+ var stored = side.stored();
350
+ const ident = battle.active(player);
351
+ var volatiles = &active.volatiles;
352
+
353
+ const move = Move.Pound; // TODO
354
+
355
+ if (volatiles.Recharging) {
356
+ volatiles.Recharging = false;
357
+ cantMove(volatiles);
358
+ try log.cant(ident, .Recharge);
359
+ return .done;
360
+ }
361
+
362
+ if (Status.is(stored.status, .SLP)) slp: {
363
+ const before = stored.status;
364
+ // Even if the EXT bit is set this will still correctly modify the sleep duration
365
+ // if (options.calc.modify(player, .sleep)) |extend| {
366
+ // if (!extend) stored.status = 0;
367
+ // } else {
368
+ stored.status -= 1;
369
+ // }
370
+
371
+ const duration = Status.duration(stored.status);
372
+ // if (!Status.is(stored.status, .EXT)) {
373
+ // try options.chance.sleep(player, duration);
374
+ // }
375
+
376
+ if (duration == 0) {
377
+ try log.curestatus(ident, before, .Message);
378
+ stored.status = 0; // clears EXT if present
379
+ cantMove(volatiles);
380
+ volatiles.Nightmare = false;
381
+ } else {
382
+ try log.cant(ident, .Sleep);
383
+ if (move == .Snore or move == .SleepTalk) break :slp;
384
+ cantMove(volatiles);
385
+ return .done;
386
+ }
387
+ }
388
+
389
+ if (Status.is(stored.status, .FRZ) and !(move == .FlameWheel or move == .SacredFire)) {
390
+ try log.cant(ident, .Freeze);
391
+ cantMove(volatiles);
392
+ return .done;
393
+ }
394
+ }
395
+
396
+ fn cantMove(volatiles: *Volatiles) void {
397
+ volatiles.Bide = false;
398
+ volatiles.Thrashing = false;
399
+ volatiles.Charging = false;
400
+ volatiles.Underground = false;
401
+ volatiles.Flying = false;
402
+ volatiles.Rollout = false;
403
+
404
+ volatiles.fury_cutter = 0;
405
+ }
406
+
407
+ fn canMove(battle: anytype, player: Player, options: anytype) !bool {
39
408
  _ = battle;
40
- _ = c1;
41
- _ = c2;
409
+ _ = player;
42
410
  _ = options;
411
+ return false;
412
+ }
43
413
 
44
- return Result.Default;
414
+ fn decrementPP(side: *Side, mslot: u4) void {
415
+ var active = &side.active;
416
+ const volatiles = &active.volatiles;
417
+
418
+ // TODO assert(side.last_selected_move != .Struggle);
419
+ assert(!volatiles.Charging and !volatiles.BeatUp and !volatiles.Thrashing and !volatiles.Bide);
420
+
421
+ assert(active.move(mslot).pp > 0);
422
+ active.move(mslot).pp = @as(u6, @intCast(active.move(mslot).pp)) -% 1;
423
+ if (volatiles.Transform) return;
424
+
425
+ // FIXME mimic
426
+
427
+ assert(side.stored().move(mslot).pp > 0);
428
+ side.stored().move(mslot).pp = @as(u6, @intCast(side.stored().move(mslot).pp)) -% 1;
429
+ assert(active.move(mslot).pp == side.stored().move(mslot).pp);
45
430
  }
46
431
 
47
- pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 {
432
+ fn doMove(battle: anytype, player: Player, options: anytype, mslot: u4) !?Result {
433
+ _ = options;
434
+ var side = battle.side(player);
435
+ const move = Move.get(.Teleport); // side.last_selected_move
436
+ switch (move.effect) {
437
+ .Teleport => {
438
+ // side.useMove();
439
+ decrementPP(side, mslot);
440
+ },
441
+ else => @panic("TODO"),
442
+ }
443
+ return null;
444
+ }
445
+
446
+ fn checkCriticalHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !bool {
447
+ if (move.bp == 0) return false;
448
+
449
+ const side = battle.side(player);
450
+ const pokemon = side.stored();
451
+
452
+ var stage: u8 =
453
+ if ((pokemon.species == .Chansey and pokemon.item == .LuckyPunch) or
454
+ (pokemon.species == .Farfetchd and pokemon.item == .Stick)) 2 else 0;
455
+ if (stage == 0) {
456
+ if (side.active.volatiles.FocusEnergy) stage += 1;
457
+ if (move.effect.isHighCritical()) stage += 2;
458
+ if (pokemon.item == .ScopeLens) stage += 1;
459
+ }
460
+ assert(stage <= 4);
461
+
462
+ return Rolls.criticalHit(battle, player, CRITICAL_HITS[stage], options);
463
+ }
464
+
465
+ fn calcDamage(
466
+ battle: anytype,
467
+ player: Player,
468
+ target_player: Player,
469
+ m: ?Move.Data,
470
+ crit: bool,
471
+ ) u16 {
48
472
  _ = battle;
49
473
  _ = player;
50
- _ = request;
51
- _ = out;
52
-
474
+ _ = target_player;
475
+ _ = m;
476
+ _ = crit;
53
477
  return 0;
54
478
  }
479
+ const FORESIGHT: Types = .{ .type1 = .Normal, .type2 = .Fighting };
480
+
481
+ fn adjustDamage(battle: anytype, player: Player, m: Move, damage: u16, effectiveness: *u16) u16 {
482
+ if (m == .Struggle) return;
483
+
484
+ const side = battle.side(player);
485
+ const foe = battle.foe(player);
486
+ const types = foe.active.types;
487
+ const move = Move.get(side.m);
488
+
489
+ var d = damage;
490
+ if ((move.type == .Water and battle.field.weather == .Rain) or
491
+ (move.type == .Fire and battle.field.weather == .Sun))
492
+ {
493
+ d = d *% @intFromEnum(Effectiveness.Super) / 10;
494
+ } else if ((move.type == .Water and battle.field.weather == .Sun) or
495
+ ((move.type == .Fire or m == .SolarBeam) and battle.field.weather == .Rain))
496
+ {
497
+ d = d *% @intFromEnum(Effectiveness.Resisted) / 10;
498
+ }
499
+
500
+ if (side.active.types.includes(move.type)) d +%= d / 2;
501
+
502
+ const neutral = @intFromEnum(Effectiveness.Neutral);
503
+ const foresight = foe.active.volatiles.Foresight and FORESIGHT.includes(move.type);
504
+ const eff1: u16 = if (foresight and types.type1 == .Ghost)
505
+ 10
506
+ else
507
+ @intFromEnum(move.type.effectiveness(types.type1));
508
+ const eff2: u16 = if (foresight and types.type2 == .Ghost)
509
+ 10
510
+ else
511
+ @intFromEnum(move.type.effectiveness(types.type2));
512
+
513
+ // Type effectiveness matchup precedence only matters with (NVE, SE)
514
+ if (!showdown and (eff1 + eff2) == Effectiveness.mismatch and
515
+ Type.precedence(move.type, types.type1) > Type.precedence(move.type, types.type2))
516
+ {
517
+ assert(eff2 != neutral);
518
+ d = d *% eff2 / 10;
519
+ assert(types.type1 != types.type2);
520
+ assert(eff1 != neutral);
521
+ d = d *% eff1 / 10;
522
+ } else {
523
+ if (eff1 != neutral) d = d *% eff1 / 10;
524
+ if (types.type1 != types.type2 and eff2 != neutral) d = d *% eff2 / 10;
525
+ }
526
+
527
+ effectiveness.* = if (types.type1 == types.type2) eff1 * neutral else eff1 * eff2;
528
+ return d;
529
+ }
530
+
531
+ fn randomizeDamage(battle: anytype, player: Player, damage: u16, options: anytype) !u16 {
532
+ if (damage <= 1) return;
533
+ const random = try Rolls.damage(battle, player, options);
534
+ options.calc.base(player.foe(), damage);
535
+ damage = @intCast(@as(u32, damage) *% random / 255);
536
+ options.calc.final(player.foe(), damage);
537
+ return damage;
538
+ }
539
+
540
+ fn applyDamage(
541
+ battle: anytype,
542
+ player: Player,
543
+ options: anytype,
544
+ ) !bool {
545
+ _ = battle;
546
+ _ = player;
547
+ _ = options;
548
+ return false;
549
+ }
550
+
551
+ fn checkHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !bool {
552
+ if (moveHit(battle, player, move, options)) return true;
553
+
554
+ try options.chance.commit(player, .miss);
555
+ try options.log.lastmiss();
556
+ try options.log.miss(battle.active(player));
557
+
558
+ return false;
559
+ }
560
+
561
+ // TODO: set damage = 0 if missed and not (High) Jump Kick
562
+ fn moveHit(
563
+ battle: anytype,
564
+ player: Player,
565
+ move: Move.Data,
566
+ options: anytype,
567
+ ) !bool {
568
+ const side = battle.side(player);
569
+ const foe = battle.foe(player);
570
+
571
+ if (move.effect == .DreamEater and !Status.is(foe.stored().status, .SLP)) return false;
572
+ if (foe.active.volatiles.Protect) return false;
573
+ const drain = move.effect == .DrainHP or move.effect == .DreamEater;
574
+ if (drain and foe.active.volatiles.Substitute) return false;
575
+ if (side.active.volatiles.LockOn) {
576
+ return !(foe.active.volatiles.Flying and move.flags.undeground);
577
+ }
578
+ assert(!(foe.active.volatiles.Flying and foe.active.volatiles.Underground));
579
+ if (foe.active.volatiles.Flying) {
580
+ if (!move.flags.flying) return false;
581
+ } else if (foe.active.volatiles.Underground) {
582
+ if (!move.flags.underground) return false;
583
+ }
584
+ if (move.effect == .Thunder and battle.field.weather == .Rain) return true;
585
+ if (move.effect == .AlwaysHit) return true;
586
+
587
+ var accuracy: u16 = move.accuracy;
588
+ if (foe.active.boosts.evasion <= side.active.boosts.accuracy or
589
+ !foe.active.volatiles.Foresight)
590
+ {
591
+ var boost = ACCURACY_BOOSTS[@as(u4, @intCast(@as(i8, side.active.boosts.accuracy) + 6))];
592
+ accuracy = accuracy * boost[0] / boost[1];
593
+ boost = ACCURACY_BOOSTS[@as(u4, @intCast(@as(i8, -foe.active.boosts.evasion) + 6))];
594
+ accuracy = accuracy * boost[0] / boost[1];
595
+ accuracy = @min(255, @max(1, accuracy));
596
+ }
597
+
598
+ if (foe.stored().item == .BrightPowder) {
599
+ accuracy = @min(0, accuracy -% 20);
600
+ }
601
+
602
+ // The accuracy roll is skipped entirely if maxed
603
+ if (accuracy == 255) return true;
604
+ return !try Rolls.hit(battle, player, @intCast(accuracy), options);
605
+ }
606
+
607
+ fn checkFaint(
608
+ battle: anytype,
609
+ player: Player,
610
+ options: anytype,
611
+ ) @TypeOf(options.log).Error!?Result {
612
+ _ = battle;
613
+ _ = player;
614
+ return null;
615
+ }
616
+
617
+ fn faint(battle: anytype, player: Player, done: bool, options: anytype) !?Result {
618
+ _ = battle;
619
+ _ = player;
620
+ _ = done;
621
+ _ = options;
622
+ return null;
623
+ }
624
+
625
+ fn handleResidual(battle: anytype, player: Player, options: anytype) !void {
626
+ var side = battle.side(player);
627
+ var stored = side.stored();
628
+ const ident = battle.active(player);
629
+ var volatiles = &side.active.volatiles;
630
+
631
+ // TODO if (stored.hp == 0) return;
632
+ assert(stored.hp > 0);
633
+
634
+ const brn = Status.is(stored.status, .BRN);
635
+ if (brn or Status.is(stored.status, .PSN)) {
636
+ var damage: u16 = undefined;
637
+ if (volatiles.Toxic) {
638
+ volatiles.toxic += 1;
639
+ damage = @max(stored.stats.hp / 16, 1) * volatiles.toxic;
640
+ } else {
641
+ damage = @max(stored.stats.hp / 8, 1);
642
+ }
643
+ damage = @min(damage, stored.hp);
644
+
645
+ if (!showdown or damage > 0) {
646
+ stored.hp -= damage;
647
+ // Pokémon Showdown uses damageOf here but its not relevant in Generation II
648
+ try options.log.damage(ident, stored, if (brn) Damage.Burn else Damage.Poison);
649
+ if (stored.hp == 0) return;
650
+ }
651
+ }
652
+
653
+ if (volatiles.LeechSeed) {
654
+ var foe = battle.foe(player);
655
+ var foe_stored = foe.stored();
656
+ const foe_ident = battle.active(player.foe());
657
+
658
+ // if (foe_stored.hp == 0) {
659
+ // assert(showdown);
660
+ // return;
661
+ // }
662
+
663
+ const damage = @min(@max(stored.stats.hp / 8, 1), stored.hp);
664
+ stored.hp -= damage;
665
+ // As above, Pokémon Showdown uses damageOf but its not relevant
666
+ if (damage > 0) try options.log.damage(ident, stored, .LeechSeed);
667
+
668
+ const before = foe_stored.hp;
669
+ foe_stored.hp = @min(foe_stored.hp + damage, foe_stored.stats.hp);
670
+ // Pokémon Showdown uses the less specific heal here instead of drain... because reasons?
671
+ if (foe_stored.hp > before) try options.log.heal(foe_ident, foe_stored, .Silent);
672
+ if (stored.hp == 0) return;
673
+ }
674
+
675
+ if (volatiles.Nightmare) {
676
+ const damage = @min(@max(stored.stats.hp / 4, 1), stored.hp);
677
+ if (!showdown or damage > 0) {
678
+ stored.hp -= damage;
679
+ // ibid
680
+ try options.log.damage(ident, stored, Damage.Nightmare);
681
+ if (stored.hp == 0) return;
682
+ }
683
+ }
684
+
685
+ if (volatiles.Curse) {
686
+ const damage = @min(@max(stored.stats.hp / 4, 1), stored.hp);
687
+ if (!showdown or damage > 0) {
688
+ stored.hp -= damage;
689
+ // ibid
690
+ try options.log.damage(ident, stored, Damage.Curse);
691
+ if (stored.hp == 0) return;
692
+ }
693
+ }
694
+ }
695
+
696
+ fn betweenTurn(battle: anytype, options: anytype) !void {
697
+ var p1 = battle.side(.P1);
698
+ var p2 = battle.side(.P2);
699
+
700
+ _ = p1;
701
+ _ = p2;
702
+ _ = options;
703
+
704
+ // TODO checkFaintThen(p1, p2);
705
+
706
+ }
707
+
708
+ fn endTurn(battle: anytype, options: anytype) @TypeOf(options.log).Error!Result {
709
+ battle.turn += 1;
710
+
711
+ if (showdown and battle.turn >= 1000) {
712
+ try options.log.tie();
713
+ return Result.Tie;
714
+ } else if (battle.turn >= 65535) {
715
+ return Result.Error;
716
+ }
717
+
718
+ try options.log.turn(battle.turn);
719
+
720
+ return Result.Default;
721
+ }
722
+
723
+ pub const Effects = struct {
724
+ fn protect(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
725
+ var side = battle.side(player);
726
+ var volatiles = &side.active.volatiles;
727
+
728
+ // TODO or if we didn't go first
729
+ if (volatiles.Substitute) return try options.log.fail(battle.active(player), .None);
730
+
731
+ // TODO
732
+
733
+ if (move.effect == .Endure) {
734
+ volatiles.Endure = true;
735
+ } else {
736
+ volatiles.Protect = true;
737
+ }
738
+ try options.log.singleturn(battle.active(player), move.id);
739
+ }
740
+ };
741
+
742
+ fn statusModify(status: u8, stats: *Stats(u16)) void {
743
+ if (Status.is(status, .PAR)) {
744
+ stats.spe = @max(stats.spe / 4, 1);
745
+ } else if (Status.is(status, .BRN)) {
746
+ stats.atk = @max(stats.atk / 2, 1);
747
+ }
748
+ }
749
+
750
+ inline fn isForced(active: anytype) bool {
751
+ return active.volatiles.Recharging or active.volatiles.Rage or
752
+ active.volatiles.Thrashing or active.volatiles.Charging or
753
+ // FIXME TODO Underground or Flying?
754
+ active.volatiles.Underground or active.volatiles.Flying or
755
+ active.volatiles.Rollout;
756
+ }
757
+
758
+ pub const Rolls = struct {
759
+ inline fn speedTie(battle: anytype, options: anytype) !bool {
760
+ const p1 = if (options.calc.overridden(.P1, .speed_tie)) |player|
761
+ player == .P1
762
+ else if (showdown)
763
+ battle.rng.range(u8, 0, 2) == 0
764
+ else
765
+ battle.rng.next() < Gen12.percent(50) + 1;
766
+
767
+ try options.chance.speedTie(p1);
768
+ return p1;
769
+ }
770
+
771
+ inline fn quickClaw(battle: anytype, player: Player, options: anytype) !bool {
772
+ const qkc = if (options.calc.overridden(player, .quick_claw)) |val|
773
+ val == .true
774
+ else if (showdown)
775
+ battle.rng.chance(u8, 60, 256)
776
+ else
777
+ battle.rng.next() < 60;
778
+
779
+ try options.chance.quickClaw(player, qkc);
780
+ return qkc;
781
+ }
782
+
783
+ inline fn criticalHit(battle: anytype, player: Player, rate: u8, options: anytype) !bool {
784
+ const crit = if (options.calc.overridden(player, .critical_hit)) |val|
785
+ val == .true
786
+ else if (showdown)
787
+ battle.rng.chance(u8, rate, 256)
788
+ else
789
+ battle.rng.next() < rate;
790
+
791
+ try options.chance.criticalHit(player, crit, rate);
792
+ return crit;
793
+ }
794
+
795
+ inline fn damage(battle: anytype, player: anytype, options: anytype) !u8 {
796
+ const roll = if (options.calc.overridden(player, .damage)) |val|
797
+ val
798
+ else roll: {
799
+ if (showdown) break :roll battle.rng.range(u8, 217, 256);
800
+ while (true) {
801
+ const r = std.math.rotr(u8, battle.rng.next(), 1);
802
+ if (r >= 217) break :roll r;
803
+ }
804
+ };
805
+
806
+ assert(roll >= 217 and roll <= 255);
807
+ try options.chance.damage(player, roll);
808
+ return roll;
809
+ }
810
+
811
+ inline fn hit(battle: anytype, player: Player, accuracy: u8, options: anytype) !bool {
812
+ const ok = if (options.calc.overridden(player, .hit)) |val|
813
+ val == .true
814
+ else if (showdown)
815
+ battle.rng.chance(u8, accuracy, 256)
816
+ else
817
+ battle.rng.next() < accuracy;
818
+
819
+ try options.chance.hit(player, ok, accuracy);
820
+ return ok;
821
+ }
822
+
823
+ const METRONOME = init: {
824
+ var num = 0;
825
+ var moves: [238]Move = undefined;
826
+ for (1..Move.size) |i| {
827
+ if (Move.get(@enumFromInt(i)).flags.metronome) {
828
+ moves[num] = @enumFromInt(i);
829
+ num += 1;
830
+ }
831
+ }
832
+ assert(num == moves.len);
833
+ break :init moves;
834
+ };
835
+ };
836
+
837
+ test "RNG agreement" {
838
+ if (!showdown) return;
839
+ var expected: [256]u32 = undefined;
840
+ for (0..expected.len) |i| {
841
+ expected[i] = @intCast(i * 0x1000000);
842
+ }
843
+
844
+ var spe = rng.FixedRNG(2, expected.len){ .rolls = expected };
845
+ var qkc = rng.FixedRNG(2, expected.len){ .rolls = expected };
846
+
847
+ for (0..expected.len) |i| {
848
+ try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1);
849
+ try expectEqual(qkc.chance(u8, 60, 256), i < 60);
850
+ }
851
+ }
852
+
853
+ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 {
854
+ var n: u8 = 0;
855
+ switch (request) {
856
+ .Pass => {
857
+ out[n] = .{};
858
+ n += 1;
859
+ },
860
+ .Switch => {
861
+ const side = battle.side(player);
862
+ var slot: u4 = 2;
863
+ while (slot <= 6) : (slot += 1) {
864
+ const id = side.order[slot - 1];
865
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
866
+ out[n] = .{ .type = .Switch, .data = slot };
867
+ n += 1;
868
+ }
869
+ if (n == 0) {
870
+ out[n] = .{};
871
+ n += 1;
872
+ }
873
+ },
874
+ .Move => {
875
+ const side = battle.side(player);
876
+
877
+ var active = &side.active;
878
+ const stored = side.stored();
879
+
880
+ // While players are not given any input options on the cartridge in these cases,
881
+ // Pokémon Showdown instead produces a list with a single move that must be chosen.
882
+ //
883
+ // Given that no input is allowed on the cartridge 'Pass' seems like it would be logical
884
+ // here when not in compatibility mode, but the engine needs to be able to differentiate
885
+ // between passing while waiting for an opponent's forced switch after fainting and
886
+ // passing due to being forced into using a move. Instead of introducing another option
887
+ // we simply repurpose Move with no move slot, even though pedantically this is not
888
+ // strictly correct as the player would not have been presented the option to move or
889
+ // switch at all.
890
+ if (isForced(active)) {
891
+ out[n] = .{ .type = .Move, .data = @intFromBool(showdown) };
892
+ n += 1;
893
+ return n;
894
+ }
895
+
896
+ var slot: u4 = 2;
897
+ while (!active.volatiles.trapped and slot <= 6) : (slot += 1) {
898
+ const id = side.order[slot - 1];
899
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
900
+ out[n] = .{ .type = .Switch, .data = slot };
901
+ n += 1;
902
+ }
903
+
904
+ const limited = active.volatiles.Bide or active.volatiles.bind > 0;
905
+ // On the cartridge, all of these happen after "FIGHT" (indicating you are not
906
+ // switching) but before you are allowed to select a move. Pokémon Showdown instead
907
+ // either disables all other moves in the case of limited or requires you to select a
908
+ // move normally if sleeping/frozen/bound.
909
+ if (!showdown and (limited or
910
+ Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP)))
911
+ {
912
+ out[n] = .{ .type = .Move, .data = 0 };
913
+ n += 1;
914
+ return n;
915
+ }
916
+
917
+ slot = 1;
918
+ // Pokémon Showdown handles Bide and Binding moves by checking if the move in question
919
+ // is present in the Pokémon's moveset (which means moves called via Metronome / Mirror
920
+ // Move will not result in forcing the subsequent use unless the user also had the
921
+ // proc-ed move in their moveset) and disabling all other moves.
922
+ if (limited) {
923
+ assert(showdown);
924
+ assert(side.last_selected_move != .None);
925
+ while (slot <= 4) : (slot += 1) {
926
+ const m = active.moves[slot - 1];
927
+ if (m.id == .None) break;
928
+ if (m.id == if (active.volatiles.Bide) .Bide else side.last_selected_move) {
929
+ // Pokémon Showdown displays Struggle if limited to Bide but unable to pick
930
+ const struggle =
931
+ m.id == .Bide and (m.pp == 0 or active.volatiles.disabled_move == slot);
932
+ const s = if (struggle) 0 else slot;
933
+ out[n] = .{ .type = .Move, .data = s };
934
+ n += 1;
935
+ return n;
936
+ }
937
+ }
938
+ }
939
+
940
+ const before = n;
941
+ slot = 1;
942
+ while (slot <= 4) : (slot += 1) {
943
+ const m = active.moves[slot - 1];
944
+ if (m.id == .None) break;
945
+ if (m.pp == 0) continue;
946
+ if (active.volatiles.disabled_move == slot) continue;
947
+ out[n] = .{ .type = .Move, .data = slot };
948
+ n += 1;
949
+ }
950
+ // Struggle (Pokémon Showdown would use 'move 1' here)
951
+ if (n == before) {
952
+ out[n] = .{ .type = .Move, .data = 0 };
953
+ n += 1;
954
+ }
955
+ },
956
+ }
957
+ return n;
958
+ }