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

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,13 +20,18 @@ const Result = common.Result;
20
20
 
21
21
  const showdown = pkmn.options.showdown;
22
22
 
23
+ const Activate = protocol.Activate;
24
+ const Cant = protocol.Cant;
23
25
  const Damage = protocol.Damage;
26
+ const End = protocol.End;
24
27
  const Heal = protocol.Heal;
28
+ const Start = protocol.Start;
25
29
 
26
30
  const Gen12 = rng.Gen12;
27
31
 
28
32
  const ActivePokemon = data.ActivePokemon;
29
33
  const Effectiveness = data.Effectiveness;
34
+ const Item = data.Item;
30
35
  const Move = data.Move;
31
36
  const MoveSlot = data.MoveSlot;
32
37
  const Pokemon = data.Pokemon;
@@ -34,21 +39,1448 @@ const Side = data.Side;
34
39
  const Species = data.Species;
35
40
  const Stats = data.Stats;
36
41
  const Status = data.Status;
42
+ const Type = data.Type;
43
+ const Types = data.Types;
44
+ const Volatiles = data.Volatiles;
45
+
46
+ // zig fmt: off
47
+ const STAT_BOOSTS = &[_][2]u8{
48
+ .{ 25, 100 }, // -6
49
+ .{ 28, 100 }, // -5
50
+ .{ 33, 100 }, // -4
51
+ .{ 40, 100 }, // -3
52
+ .{ 50, 100 }, // -2
53
+ .{ 66, 100 }, // -1
54
+ .{ 1, 1 }, // 0
55
+ .{ 15, 10 }, // +1
56
+ .{ 2, 1 }, // +2
57
+ .{ 25, 10 }, // +3
58
+ .{ 3, 1 }, // +4
59
+ .{ 35, 10 }, // +5
60
+ .{ 4, 1 }, // +6
61
+ };
62
+
63
+ const ACCURACY_BOOSTS = &[_][2]u8{
64
+ .{ 33, 100 }, // -6
65
+ .{ 36, 100 }, // -5
66
+ .{ 43, 100 }, // -4
67
+ .{ 50, 100 }, // -3
68
+ .{ 60, 100 }, // -2
69
+ .{ 75, 100 }, // -1
70
+ .{ 1, 1 }, // 0
71
+ .{ 133, 100 }, // +1
72
+ .{ 166, 100 }, // +2
73
+ .{ 2, 1 }, // +3
74
+ .{ 233, 100 }, // +4
75
+ .{ 133, 50 }, // +5
76
+ .{ 3, 1 }, // +6
77
+ };
78
+
79
+ const CRITICAL_HITS = &[_]u8{
80
+ 256 / 15, // 0
81
+ 256 / 8, // +1
82
+ 256 / 4, // +2
83
+ 256 / 3, // +3
84
+ 256 / 2, // +4
85
+ };
86
+ // zig fmt: on
87
+
88
+ const MAX_STAT_VALUE = 999;
89
+
90
+ const DISTRIBUTION = [_]u3{ 2, 2, 2, 3, 3, 3, 4, 5 };
37
91
 
38
92
  pub fn update(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Result {
93
+ assert(c1.type != .Pass or c2.type != .Pass or battle.turn == 0);
94
+ if (battle.turn == 0) return start(battle, options);
95
+
96
+ if (try turnOrder(battle, c1, c2, options) == .P1) {
97
+ if (try doTurn(battle, .P1, c1, .P2, c2, options)) |r| return r;
98
+ } else {
99
+ if (try doTurn(battle, .P2, c2, .P1, c1, options)) |r| return r;
100
+ }
101
+
102
+ return endTurn(battle, options);
103
+ }
104
+
105
+ fn start(battle: anytype, options: anytype) !Result {
106
+ const p1 = battle.side(.P1);
107
+ const p2 = battle.side(.P2);
108
+
109
+ var p1_slot = findFirstAlive(p1);
110
+ assert(!showdown or p1_slot == 1);
111
+ if (p1_slot == 0) return if (findFirstAlive(p2) == 0) Result.Tie else Result.Lose;
112
+
113
+ var p2_slot = findFirstAlive(p2);
114
+ assert(!showdown or p2_slot == 1);
115
+ if (p2_slot == 0) return Result.Win;
116
+
117
+ try switchIn(battle, .P1, p1_slot, true, options);
118
+ try switchIn(battle, .P2, p2_slot, true, options);
119
+
120
+ return endTurn(battle, options);
121
+ }
122
+
123
+ fn findFirstAlive(side: *const Side) u8 {
124
+ for (side.pokemon, 0..) |pokemon, i| if (pokemon.hp > 0) return side.pokemon[i].position;
125
+ return 0;
126
+ }
127
+
128
+ fn selectMove(battle: anytype, player: Player, choice: Choice) void {
129
+ if (choice.type == .Pass) return; // FIXME BATON PASS
130
+
131
+ var side = battle.side(player);
132
+ var volatiles = &side.active.volatiles;
133
+
134
+ // pre-battle menu
135
+ const forced = forced: {
136
+ if (volatiles.Recharging) break :forced true;
137
+ // Pokémon Showdown removes Flinch at the end-of-turn in its residual handler
138
+ if (!showdown) {
139
+ volatiles.Flinch = false;
140
+ battle.foe(player).active.volatiles.Flinch = false;
141
+ }
142
+ break :forced (volatiles.Thrashing or volatiles.Charging or volatiles.Rollout);
143
+ };
144
+
145
+ // battle menu
146
+ if (choice.type == .Switch) return;
147
+ assert(choice.type == .Move and (!forced or choice.data == @intFromBool(showdown)));
148
+
149
+ done: {
150
+ if (forced) break :done;
151
+ // pre-move select
152
+ if (volatiles.Encore) {
153
+ // TODO wCurPlayerMove = side.lastMove(true);
154
+ // assert(wCurPlayerMove != .None);
155
+ volatiles.Bide = false; // FIXME wPlayerCharging vs. SUBSTATUS_BIDE?
156
+ const effect = Move.get(.Pound).effect; // TODO
157
+ if (effect != .FuryCutter) volatiles.fury_cutter = false;
158
+ if (effect != .Rage) {
159
+ volatiles.Rage = false;
160
+ volatiles.rage = 0;
161
+ }
162
+ if (effect != .Protect and effect != .Endure) volatiles.protect = 0;
163
+ return;
164
+ }
165
+ if (volatiles.Bide) break :done;
166
+ // move select
167
+ if (choice.data == 0) {
168
+ const struggle = ok: {
169
+ for (side.active.moves, 0..) |move, i| {
170
+ if (move.pp > 0 and volatiles.disabled_move != i + 1) break :ok false;
171
+ }
172
+ break :ok true;
173
+ };
174
+ assert(struggle);
175
+ // TODO wCurPlayerMove = .Struggle;
176
+ } else {
177
+ assert(showdown or side.active.volatiles.disabled_move != choice.data);
178
+ const move = side.active.move(choice.data);
179
+ // You cannot *select* a move with 0 PP
180
+ assert(move.pp != 0);
181
+ // TODO wCurPlayerMove = move.id;
182
+ // battle.lastMove(player).index = @intCast(c.data);
183
+ }
184
+ }
185
+
186
+ volatiles.Rage = false;
187
+ volatiles.rage = 0;
188
+ volatiles.fury_cutter = 0;
189
+ volatiles.protect = 0;
190
+ }
191
+
192
+ fn switchIn(battle: anytype, player: Player, slot: u8, initial: bool, options: anytype) !void {
193
+ var side = battle.side(player);
194
+ var foe = battle.foe(player);
195
+
196
+ var active = &side.active;
197
+ const incoming = side.get(slot);
198
+
199
+ assert(incoming.hp != 0);
200
+ assert(slot != 1 or initial);
201
+
202
+ const out = side.pokemon[0].position;
203
+ side.pokemon[0].position = side.pokemon[slot - 1].position;
204
+ side.pokemon[slot - 1].position = out;
205
+
206
+ side.last_used_move = .None;
207
+ foe.active.volatiles.dirty = true;
208
+
209
+ active.volatiles = .{};
210
+ active.stats = incoming.stats;
211
+ active.moves = incoming.moves;
212
+ active.boosts = .{};
213
+ active.types = incoming.types;
214
+ active.species = incoming.species;
215
+
216
+ statusModify(incoming.status, &active.stats);
217
+
218
+ try options.log.switched(battle.active(player), incoming);
219
+ options.chance.switched(player, side.pokemon[0].position, out);
220
+
221
+ if (side.conditions.Spikes and !active.types.includes(.Flying)) {
222
+ incoming.hp -|= @max(incoming.stats.hp / 8, 1);
223
+ try options.log.damage(battle.active(player), incoming, .Spikes);
224
+ }
225
+ }
226
+
227
+ fn turnOrder(battle: anytype, c1: Choice, c2: Choice, options: anytype) !Player {
228
+ assert(c1.type != .Pass or c2.type != .Pass);
229
+
230
+ if (c1.type == .Pass) return .P2;
231
+ if (c2.type == .Pass) return .P1;
232
+
233
+ // Pokémon Showdown always rolls for Quick Claw every turn, even if no Pokémon hold Quick Claw
234
+ // TODO: add to pending and only commit roll on Pokémon Showdown if roll is used
235
+ const qkc = showdown and try Rolls.quickClaw(battle, .P1, options);
236
+
237
+ if ((c1.type == .Switch) != (c2.type == .Switch)) return if (c1.type == .Switch) .P1 else .P2;
238
+
239
+ // https://www.smogon.com/forums/threads/adv-switch-priority.3622189/
240
+ // > In Gen 1 it's irrelevant [which player switches first] because switches happen instantly on
241
+ // > your own screen without waiting for the other player's choice (and their choice will appear
242
+ // > to happen first for them too, unless they attacked in which case your switch happens first)
243
+ // A cartridge-compatible implemention must not advance the RNG so we simply default to P1
244
+ const double_switch = c1.type == .Switch and c2.type == .Switch;
245
+ if (!showdown and double_switch) return .P1;
246
+
247
+ const m1 = .Pound; // TODO battle.side(.P1).last_selected_move;
248
+ const m2 = .Pound; // TODO battle.side(.P2).last_selected_move;
249
+ if (!showdown or !double_switch) {
250
+ const pri1 = Move.get(m1).priority;
251
+ const pri2 = Move.get(m2).priority;
252
+ if (pri1 != pri2) return if (pri1 > pri2) .P1 else .P2;
253
+
254
+ const qkc1 = battle.side(.P1).stored().item == .QuickClaw;
255
+ const qkc2 = battle.side(.P2).stored().item == .QuickClaw;
256
+ if (!showdown and qkc1 and qkc2) {
257
+ // If both Pokémon have Quick Claw the cartridge checks them in order and exits early if
258
+ // the first one procs, meaning the host has a slightly higher chance of going first
259
+ if (try Rolls.quickClaw(battle, .P1, options)) return .P1;
260
+ if (try Rolls.quickClaw(battle, .P2, options)) return .P2;
261
+ } else if (qkc1) {
262
+ const proc = if (showdown) qkc else try Rolls.quickClaw(battle, .P1, options);
263
+ if (proc) return .P1;
264
+ } else if (qkc2) {
265
+ const proc = if (showdown) qkc else try Rolls.quickClaw(battle, .P2, options);
266
+ if (proc) return .P2;
267
+ }
268
+ }
269
+
270
+ const spe1 = battle.side(.P1).active.stats.spe;
271
+ const spe2 = battle.side(.P2).active.stats.spe;
272
+ if (spe1 == spe2) {
273
+ // Pokémon Showdown's beforeTurnCallback shenanigans
274
+ if (showdown and !double_switch and hasCallback(m1) and hasCallback(m2)) {
275
+ battle.rng.advance(1);
276
+ }
277
+
278
+ const p1 = try Rolls.speedTie(battle, options);
279
+ if (!showdown) return if (p1) .P1 else .P2;
280
+
281
+ // Pokémon Showdown's "lockedmove" volatile's onBeforeTurn uses BattleQueue#changeAction,
282
+ // meaning that if a side is locked into a thrashing move and wins the speed tie, it
283
+ // actually uses its priority to simply insert its actual changed action into the queue,
284
+ // causing it to then execute *after* the side which should go second...
285
+ const t1 = battle.side(.P1).active.volatiles.Thrashing;
286
+ const t2 = battle.side(.P2).active.volatiles.Thrashing;
287
+ // If *both* sides are thrashing it really should be another speed tie, but we've patched
288
+ // that out and enforce host ordering of events, so P1 just goes first regardless of who
289
+ // won the original coin flip
290
+ if (t1 and t2) return .P1;
291
+ return if (p1) if (t1 and !t2) .P2 else .P1 else if (t2 and !t1) .P1 else .P2;
292
+ }
293
+
294
+ return if (spe1 > spe2) .P1 else .P2;
295
+ }
296
+
297
+ fn hasCallback(m: Move) bool {
298
+ return switch (m) {
299
+ .Counter, .MirrorCoat, .Pursuit => true,
300
+ else => false,
301
+ };
302
+ }
303
+
304
+ fn doTurn(
305
+ battle: anytype,
306
+ player: Player,
307
+ player_choice: Choice,
308
+ foe_player: Player,
309
+ foe_choice: Choice,
310
+ options: anytype,
311
+ ) !?Result {
312
+ assert(player_choice.type != .Pass);
313
+
314
+ const volatiles = &battle.side(player).active.volatiles;
315
+ const foe_volatiles = &battle.foe(player).active.volatiles;
316
+
317
+ volatiles.DestinyBond = false;
318
+ if (try executeMove(battle, player, player_choice, options)) |r| return r;
319
+ foe_volatiles.Protect = false;
320
+ foe_volatiles.Endure = false;
321
+ foe_volatiles.DestinyBond = false;
322
+
323
+ // foe_volatiles.DestinyBond = false;
324
+ if (try executeMove(battle, foe_player, foe_choice, options)) |r| return r;
325
+ volatiles.Protect = false;
326
+ volatiles.Endure = false;
327
+ volatiles.DestinyBond = false;
328
+
329
+ return null;
330
+ }
331
+
332
+ fn executeMove(battle: anytype, player: Player, choice: Choice, options: anytype) !?Result {
333
+ if (choice.type == .Switch) {
334
+ try switchIn(battle, player, choice.data, false, options);
335
+ return null;
336
+ }
337
+
338
+ assert(choice.type == .Move);
339
+ var mslot: u4 = @intCast(choice.data);
340
+
341
+ // const move = Move.get(side.last_selected_move);
342
+
343
+ // CheckTurn
344
+
345
+ return doMove(battle, player, options, mslot);
346
+ }
347
+
348
+ fn beforeMove(battle: anytype, player: Player, options: anytype) !bool {
349
+ var log = options.log;
350
+ var side = battle.side(player);
351
+ // const foe = battle.foe(player);
352
+ var active = &side.active;
353
+ var stored = side.stored();
354
+ const ident = battle.active(player);
355
+ var volatiles = &active.volatiles;
356
+
357
+ const move = Move.Pound; // TODO
358
+
359
+ if (volatiles.Recharging) {
360
+ volatiles.Recharging = false;
361
+ cantMove(volatiles);
362
+ try log.cant(ident, .Recharge);
363
+ return false;
364
+ }
365
+
366
+ if (Status.is(stored.status, .SLP)) slp: {
367
+ const before = stored.status;
368
+ // Even if the EXT bit is set this will still correctly modify the sleep duration
369
+ // if (options.calc.modify(player, .sleep)) |extend| {
370
+ // if (!extend) stored.status = 0;
371
+ // } else {
372
+ stored.status -= 1;
373
+ // }
374
+
375
+ const duration = Status.duration(stored.status);
376
+ if (!Status.is(stored.status, .EXT)) {
377
+ try options.chance.sleep(player, duration);
378
+ }
379
+
380
+ if (duration == 0) {
381
+ try log.curestatus(ident, before, .Message);
382
+ stored.status = 0; // clears EXT if present
383
+ cantMove(volatiles);
384
+ volatiles.Nightmare = false;
385
+ } else {
386
+ try log.cant(ident, .Sleep);
387
+ if (move == .Snore or move == .SleepTalk) break :slp;
388
+ cantMove(volatiles);
389
+ return false;
390
+ }
391
+ }
392
+
393
+ if (Status.is(stored.status, .FRZ) and !(move == .FlameWheel or move == .SacredFire)) {
394
+ cantMove(volatiles);
395
+ try log.cant(ident, .Freeze);
396
+ return false;
397
+ }
398
+
399
+ if (volatiles.Flinch) {
400
+ // Pokémon Showdown doesn't clear Flinch until its imaginary "residual" phase, meaning
401
+ // Pokémon can sometimes flinch multiple times from the same original hit
402
+ // if (!showdown) volatiles.Flinch = false;
403
+ volatiles.Flinch = false;
404
+ cantMove(volatiles);
405
+ try log.cant(ident, .Flinch);
406
+ return false;
407
+ }
408
+
409
+ if (volatiles.disabled_duration > 0) {
410
+ // if (options.calc.modify(player, .disable)) |extend| {
411
+ // if (!extend) volatiles.disabled_duration = 0;
412
+ // } else {
413
+ volatiles.disabled_duration -= 1;
414
+ // }
415
+ try options.chance.disable(player, volatiles.disabled_duration);
416
+
417
+ if (volatiles.disabled_duration == 0) {
418
+ volatiles.disabled_move = 0;
419
+ try log.end(ident, .Disable);
420
+ }
421
+ }
422
+
423
+ if (volatiles.Confusion) {
424
+ assert(volatiles.confusion > 0);
425
+
426
+ // if (options.calc.modify(player, .confusion)) |extend| {
427
+ // if (!extend) volatiles.confusion = 0;
428
+ // } else {
429
+ volatiles.confusion -= 1;
430
+ // }
431
+ try options.chance.confusion(player, volatiles.confusion);
432
+
433
+ if (volatiles.confusion == 0) {
434
+ volatiles.Confusion = false;
435
+ try log.end(ident, .Confusion);
436
+ } else {
437
+ try log.activate(ident, .Confusion);
438
+
439
+ if (try Rolls.confused(battle, player, options)) {
440
+ volatiles.BeatUp = false;
441
+ volatiles.Flinch = false;
442
+ cantMove(volatiles);
443
+
444
+ // TODO HitConfusion
445
+
446
+ return false;
447
+ }
448
+ }
449
+ }
450
+
451
+ if (volatiles.Attract) {
452
+ try log.atrract(ident, .Attract);
453
+
454
+ if (try Rolls.attract(battle, player, options)) {
455
+ cantMove(volatiles);
456
+ try log.cant(ident, .Attract);
457
+ return false;
458
+ }
459
+ }
460
+
461
+ if (side.active.volatiles.disabled_move != 0) {
462
+ // A Pokémon that transforms after being disabled may end up with less move slots
463
+ const m = side.active.moves[side.active.volatiles.disabled_move - 1].id;
464
+ if (m != .None and m == move) {
465
+ side.active.volatiles.Charging = false;
466
+ cantMove(volatiles);
467
+ try options.log.disabled(ident, move);
468
+ return false;
469
+ }
470
+ }
471
+
472
+ if (Status.is(stored.status, .PAR) and try Rolls.paralyzed(battle, player, options)) {
473
+ cantMove(volatiles);
474
+ try log.cant(ident, .Paralysis);
475
+ return false;
476
+ }
477
+
478
+ return true;
479
+ }
480
+
481
+ fn cantMove(volatiles: *Volatiles) void {
482
+ volatiles.Bide = false;
483
+ volatiles.Thrashing = false;
484
+ volatiles.Charging = false;
485
+ volatiles.Underground = false;
486
+ volatiles.Flying = false;
487
+ volatiles.Rollout = false;
488
+
489
+ volatiles.fury_cutter = 0;
490
+ }
491
+
492
+ fn canMove(battle: anytype, player: Player, options: anytype) !bool {
39
493
  _ = battle;
40
- _ = c1;
41
- _ = c2;
494
+ _ = player;
42
495
  _ = options;
496
+ return false;
497
+ }
43
498
 
44
- return Result.Default;
499
+ fn decrementPP(side: *Side, mslot: u4) void {
500
+ var active = &side.active;
501
+ const volatiles = &active.volatiles;
502
+
503
+ // TODO assert(side.last_selected_move != .Struggle);
504
+ assert(!volatiles.Charging and !volatiles.BeatUp and !volatiles.Thrashing and !volatiles.Bide);
505
+
506
+ assert(active.move(mslot).pp > 0);
507
+ active.move(mslot).pp = @as(u6, @intCast(active.move(mslot).pp)) -% 1;
508
+ if (volatiles.Transform) return;
509
+
510
+ // FIXME mimic
511
+
512
+ assert(side.stored().move(mslot).pp > 0);
513
+ side.stored().move(mslot).pp = @as(u6, @intCast(side.stored().move(mslot).pp)) -% 1;
514
+ assert(active.move(mslot).pp == side.stored().move(mslot).pp);
45
515
  }
46
516
 
47
- pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 {
517
+ fn doMove(battle: anytype, player: Player, options: anytype, mslot: u4) !?Result {
518
+ _ = options;
519
+ var side = battle.side(player);
520
+ const move = Move.get(.Teleport); // side.last_selected_move
521
+ switch (move.effect) {
522
+ .Teleport => {
523
+ // side.useMove();
524
+ decrementPP(side, mslot);
525
+ },
526
+ else => @panic("TODO"),
527
+ }
528
+ return null;
529
+ }
530
+
531
+ fn checkCriticalHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !bool {
532
+ if (move.bp == 0) return false;
533
+
534
+ const side = battle.side(player);
535
+ const pokemon = side.stored();
536
+
537
+ var stage: u8 =
538
+ if ((pokemon.species == .Chansey and pokemon.item == .LuckyPunch) or
539
+ (pokemon.species == .Farfetchd and pokemon.item == .Stick)) 2 else 0;
540
+ if (stage == 0) {
541
+ if (side.active.volatiles.FocusEnergy) stage += 1;
542
+ if (move.effect.isHighCritical()) stage += 2;
543
+ if (pokemon.item == .ScopeLens) stage += 1;
544
+ }
545
+ assert(stage <= 4);
546
+
547
+ return Rolls.criticalHit(battle, player, CRITICAL_HITS[stage], options);
548
+ }
549
+
550
+ fn calcDamage(
551
+ battle: anytype,
552
+ player: Player,
553
+ target_player: Player,
554
+ m: ?Move.Data,
555
+ crit: bool,
556
+ ) u16 {
48
557
  _ = battle;
49
558
  _ = player;
50
- _ = request;
51
- _ = out;
52
-
559
+ _ = target_player;
560
+ _ = m;
561
+ _ = crit;
53
562
  return 0;
54
563
  }
564
+
565
+ const FORESIGHT: Types = .{ .type1 = .Normal, .type2 = .Fighting };
566
+
567
+ fn adjustDamage(battle: anytype, player: Player, m: Move, damage: u16, effectiveness: *u16) u16 {
568
+ if (m == .Struggle) return;
569
+
570
+ const side = battle.side(player);
571
+ const foe = battle.foe(player);
572
+ const types = foe.active.types;
573
+ const move = Move.get(side.m);
574
+
575
+ var d = damage;
576
+ if ((move.type == .Water and battle.field.weather == .Rain) or
577
+ (move.type == .Fire and battle.field.weather == .Sun))
578
+ {
579
+ d = d *% @intFromEnum(Effectiveness.Super) / 10;
580
+ } else if ((move.type == .Water and battle.field.weather == .Sun) or
581
+ ((move.type == .Fire or m == .SolarBeam) and battle.field.weather == .Rain))
582
+ {
583
+ d = d *% @intFromEnum(Effectiveness.Resisted) / 10;
584
+ }
585
+
586
+ if (side.active.types.includes(move.type)) d +%= d / 2;
587
+
588
+ const neutral = @intFromEnum(Effectiveness.Neutral);
589
+ const foresight = foe.active.volatiles.Foresight and FORESIGHT.includes(move.type);
590
+ const eff1: u16 = if (foresight and types.type1 == .Ghost)
591
+ 10
592
+ else
593
+ @intFromEnum(move.type.effectiveness(types.type1));
594
+ const eff2: u16 = if (foresight and types.type2 == .Ghost)
595
+ 10
596
+ else
597
+ @intFromEnum(move.type.effectiveness(types.type2));
598
+
599
+ // Type effectiveness matchup precedence only matters with (NVE, SE)
600
+ if (!showdown and (eff1 + eff2) == Effectiveness.mismatch and
601
+ Type.precedence(move.type, types.type1) > Type.precedence(move.type, types.type2))
602
+ {
603
+ assert(eff2 != neutral);
604
+ d = d *% eff2 / 10;
605
+ assert(types.type1 != types.type2);
606
+ assert(eff1 != neutral);
607
+ d = d *% eff1 / 10;
608
+ } else {
609
+ if (eff1 != neutral) d = d *% eff1 / 10;
610
+ if (types.type1 != types.type2 and eff2 != neutral) d = d *% eff2 / 10;
611
+ }
612
+
613
+ effectiveness.* = if (types.type1 == types.type2) eff1 * neutral else eff1 * eff2;
614
+ return d;
615
+ }
616
+
617
+ fn randomizeDamage(battle: anytype, player: Player, damage: u16, options: anytype) !u16 {
618
+ if (damage <= 1) return;
619
+ const random = try Rolls.damage(battle, player, options);
620
+ options.calc.base(player.foe(), damage);
621
+ damage = @intCast(@as(u32, damage) *% random / 255);
622
+ options.calc.final(player.foe(), damage);
623
+ return damage;
624
+ }
625
+
626
+ fn applyDamage(
627
+ battle: anytype,
628
+ player: Player,
629
+ options: anytype,
630
+ ) !bool {
631
+ _ = battle;
632
+ _ = player;
633
+ _ = options;
634
+ return false;
635
+ }
636
+
637
+ fn checkHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !bool {
638
+ if (moveHit(battle, player, move, options)) return true;
639
+
640
+ // try options.chance.commit(player, .miss);
641
+ try options.log.lastmiss();
642
+ try options.log.miss(battle.active(player));
643
+
644
+ return false;
645
+ }
646
+
647
+ // TODO: set damage = 0 if missed and not (High) Jump Kick
648
+ fn moveHit(
649
+ battle: anytype,
650
+ player: Player,
651
+ move: Move.Data,
652
+ options: anytype,
653
+ ) !bool {
654
+ const side = battle.side(player);
655
+ const foe = battle.foe(player);
656
+
657
+ if (move.effect == .DreamEater and !Status.is(foe.stored().status, .SLP)) return false;
658
+ if (foe.active.volatiles.Protect) return false;
659
+ const drain = move.effect == .DrainHP or move.effect == .DreamEater;
660
+ if (drain and foe.active.volatiles.Substitute) return false;
661
+ if (side.active.volatiles.LockOn) {
662
+ return !(foe.active.volatiles.Flying and move.extra.undeground);
663
+ }
664
+ assert(!(foe.active.volatiles.Flying and foe.active.volatiles.Underground));
665
+ if (foe.active.volatiles.Flying) {
666
+ if (!move.extra.flying) return false;
667
+ } else if (foe.active.volatiles.Underground) {
668
+ if (!move.extra.underground) return false;
669
+ }
670
+ if (move.effect == .Thunder and battle.field.weather == .Rain) return true;
671
+ if (move.effect == .AlwaysHit) return true;
672
+
673
+ var accuracy: u16 = move.accuracy;
674
+ if (foe.active.boosts.evasion <= side.active.boosts.accuracy or
675
+ !foe.active.volatiles.Foresight)
676
+ {
677
+ var boost = ACCURACY_BOOSTS[@as(u4, @intCast(@as(i8, side.active.boosts.accuracy) + 6))];
678
+ accuracy = accuracy * boost[0] / boost[1];
679
+ boost = ACCURACY_BOOSTS[@as(u4, @intCast(@as(i8, -foe.active.boosts.evasion) + 6))];
680
+ accuracy = accuracy * boost[0] / boost[1];
681
+ accuracy = @min(255, @max(1, accuracy));
682
+ }
683
+
684
+ if (foe.stored().item == .BrightPowder) {
685
+ accuracy -|= 20;
686
+ }
687
+
688
+ // The accuracy roll is skipped entirely if maxed
689
+ if (accuracy == 255) return true;
690
+ return !try Rolls.hit(battle, player, @intCast(accuracy), options);
691
+ }
692
+
693
+ fn checkFaint(
694
+ battle: anytype,
695
+ player: Player,
696
+ options: anytype,
697
+ ) @TypeOf(options.log).Error!?Result {
698
+ _ = battle;
699
+ _ = player;
700
+ return null;
701
+ }
702
+
703
+ fn faint(battle: anytype, player: Player, done: bool, options: anytype) !?Result {
704
+ _ = battle;
705
+ _ = player;
706
+ _ = done;
707
+ _ = options;
708
+ return null;
709
+ }
710
+
711
+ fn handleResidual(battle: anytype, player: Player, options: anytype) !void {
712
+ var side = battle.side(player);
713
+ var stored = side.stored();
714
+ const ident = battle.active(player);
715
+ var volatiles = &side.active.volatiles;
716
+
717
+ // TODO if (stored.hp == 0) return;
718
+ assert(stored.hp > 0);
719
+
720
+ const brn = Status.is(stored.status, .BRN);
721
+ if (brn or Status.is(stored.status, .PSN)) {
722
+ var damage: u16 = undefined;
723
+ if (volatiles.Toxic) {
724
+ volatiles.toxic += 1;
725
+ damage = @max(stored.stats.hp / 16, 1) * volatiles.toxic;
726
+ } else {
727
+ damage = @max(stored.stats.hp / 8, 1);
728
+ }
729
+
730
+ stored.hp -|= damage;
731
+ // Pokémon Showdown uses damageOf here but its not relevant in Generation II
732
+ try options.log.damage(ident, stored, if (brn) Damage.Burn else Damage.Poison);
733
+ if (stored.hp == 0) return;
734
+ }
735
+
736
+ if (volatiles.LeechSeed) {
737
+ var foe = battle.foe(player);
738
+ var foe_stored = foe.stored();
739
+ const foe_ident = battle.active(player.foe());
740
+
741
+ // if (foe_stored.hp == 0) {
742
+ // assert(showdown);
743
+ // return;
744
+ // }
745
+
746
+ const damage = @max(stored.stats.hp / 8, 1);
747
+ stored.hp -|= damage;
748
+ // As above, Pokémon Showdown uses damageOf but its not relevant
749
+ try options.log.damage(ident, stored, .LeechSeed);
750
+
751
+ const before = foe_stored.hp;
752
+ foe_stored.hp = @min(foe_stored.hp + damage, foe_stored.stats.hp);
753
+ // Pokémon Showdown uses the less specific heal here instead of drain... because reasons?
754
+ if (foe_stored.hp > before) try options.log.heal(foe_ident, foe_stored, .Silent);
755
+ if (stored.hp == 0) return;
756
+ }
757
+
758
+ if (volatiles.Nightmare) {
759
+ stored.hp -= @max(stored.stats.hp / 4, 1);
760
+ // ibid
761
+ try options.log.damage(ident, stored, Damage.Nightmare);
762
+ if (stored.hp == 0) return;
763
+ }
764
+
765
+ if (volatiles.Curse) {
766
+ stored.hp -= @max(stored.stats.hp / 4, 1);
767
+ // ibid
768
+ try options.log.damage(ident, stored, Damage.Curse);
769
+ if (stored.hp == 0) return;
770
+ }
771
+ }
772
+
773
+ fn betweenTurns(battle: anytype, mslot: u4, options: anytype) !void {
774
+ const players = std.enums.values(Player);
775
+
776
+ // TODO checkFaintThen(p1, p2);
777
+
778
+ // Future Sight
779
+ inline for (players) |player| {
780
+ var side = battle.side(player);
781
+ var future_sight = &side.conditions.future_sight;
782
+
783
+ if (future_sight.count > 0) {
784
+ future_sight.count -= 1;
785
+ assert(future_sight.count != 0);
786
+ if (future_sight.count == 1) {
787
+ try options.log.end(battle.active(player), .FutureSight);
788
+ // TODO doMove
789
+ }
790
+ }
791
+ }
792
+ // TODO checkFaintThen(p1, p2);
793
+
794
+ // Weather
795
+ if (battle.field.weather != .None) {
796
+ assert(battle.field.weather_duration > 0);
797
+ battle.field.weather_duration -= 1;
798
+
799
+ if (battle.field.weather_duration == 0) {
800
+ battle.field.weather = .None;
801
+ try options.log.weather(battle.field.weather, .None);
802
+ } else {
803
+ try options.log.weather(battle.field.weather, .Upkeep);
804
+ if (battle.field.weather == .Sandstorm) {
805
+ inline for (players) |player| {
806
+ var side = battle.side(player);
807
+ const active = side.active;
808
+ if (!(active.volatiles.underground or active.types.sandstormImmune())) {
809
+ side.stored().hp -|= @max(side.stored().stats.hp / 8, 1);
810
+ try options.log.damage(battle.active(player), side.stored(), .Sandstorm);
811
+ }
812
+ }
813
+ // TODO checkFaintThen(p1, p2);
814
+ }
815
+ }
816
+ }
817
+
818
+ // Binding
819
+ inline for (players) |player| {
820
+ var side = battle.side(player);
821
+ var volatiles = &side.active.volatiles;
822
+
823
+ if (volatiles.bind > 0 and !volatiles.Substitute) {
824
+ volatiles.bind -= 1;
825
+ if (volatiles.bind == 0) {
826
+ const reason = @intFromEnum(End.Bind) + volatiles.bind_reason - 1;
827
+ try options.log.end(battle.active(player), @enumFromInt(reason));
828
+ } else {
829
+ var reason = @intFromEnum(Activate.Bind) + volatiles.bind_reason - 1;
830
+ try options.log.activate(battle.active(player), @enumFromInt(reason));
831
+
832
+ reason = @intFromEnum(Activate.Damage) + volatiles.bind_reason - 1;
833
+ side.stored().hp -|= @max(side.stored().stats.hp / 16, 1);
834
+ try options.log.damage(battle.active(player), side.stored(), reason);
835
+ }
836
+ }
837
+ }
838
+ // TODO checkFaintThen(p1, p2);
839
+
840
+ // Perish Song
841
+ inline for (players) |player| {
842
+ var side = battle.side(player);
843
+ var volatiles = &side.active.volatiles;
844
+
845
+ if (volatiles.PerishSong) {
846
+ assert(volatiles.perish_song > 0);
847
+ volatiles.perish_song -= 1;
848
+
849
+ assert(volatiles.perish_song < 3);
850
+ const reason = @intFromEnum(Start.PerishSong0) + volatiles.perish_song;
851
+ try options.log.start(battle.active(player), reason);
852
+
853
+ if (volatiles.perish_song == 0) {
854
+ volatiles.PerishSong = false;
855
+ side.stored().hp = 0;
856
+ }
857
+ }
858
+ }
859
+ // TODO checkFaintThen(p1, p2);
860
+
861
+ // Leftovers
862
+ inline for (players) |player| {
863
+ var stored = battle.side(player).stored();
864
+
865
+ if (stored.item == .Leftovers) {
866
+ const before = stored.hp;
867
+ stored.hp = @min(stored.hp + @max(stored.stats.hp / 16, 1), stored.stats.hp);
868
+ if (stored.hp > before) try options.log.heal(battle.active(player), stored, .Leftovers);
869
+ }
870
+ }
871
+
872
+ // Mystery Berry
873
+ inline for (players) |player| {
874
+ var stored = battle.side(player).stored();
875
+
876
+ if (stored.item == .MysteryBerry) {
877
+ // TODO stored and active moves, transform, etc
878
+ }
879
+ }
880
+
881
+ // Defrost
882
+ inline for (players) |player| {
883
+ var side = battle.side(player);
884
+
885
+ if (Status.is(side.stored().status, .FRZ) and
886
+ !side.active.volatiles.frozen and
887
+ try Rolls.defrost(battle, player, options))
888
+ {
889
+ try options.log.curestatus(battle.active(player), side.stored().status, .Message);
890
+ side.stored().status = 0;
891
+ }
892
+ }
893
+
894
+ // Side Conditions
895
+ if (showdown) {
896
+ inline for (players) |player| {
897
+ updateSideCondition(battle, player, "Reflect", "reflect");
898
+ }
899
+ inline for (players) |player| {
900
+ updateSideCondition(battle, player, "LightScreen", "light_screen");
901
+ }
902
+ inline for (players) |player| {
903
+ updateSideCondition(battle, player, "Safeguard", "safeguard");
904
+ }
905
+ } else {
906
+ inline for (players) |player| {
907
+ updateSideCondition(battle, player, "Safeguard", "safeguard");
908
+ }
909
+
910
+ inline for (players) |player| {
911
+ updateSideCondition(battle, player, "LightScreen", "light_screen");
912
+ updateSideCondition(battle, player, "Reflect", "reflect");
913
+ }
914
+ }
915
+
916
+ // Healing items
917
+ inline for (players) |player| {
918
+ var side = battle.side(player);
919
+ var stored = side.stored();
920
+ const ident = battle.active(player);
921
+
922
+ const num = @intFromEnum(stored.item);
923
+ if (num > @intFromEnum(Item.Berry)) {
924
+ if (num <= @intFromEnum(Item.GoldBerry)) {
925
+ const proc = if (showdown)
926
+ stored.hp <= stored.stats.hp
927
+ else
928
+ stored.hp < stored.stats.hp;
929
+ if (proc) {
930
+ assert(stored.hp != 0);
931
+ try options.log.enditem(ident, stored.item, .Eat);
932
+ stored.item = .None;
933
+
934
+ const offset = num - @intFromEnum(Item.Berry);
935
+ assert(offset < 3);
936
+ stored.hp = @min(stored.hp + ((offset + 1) * 10), stored.stats.hp);
937
+ const reason: Heal = @enumFromInt(@intFromEnum(Heal.Berry) + offset);
938
+ try options.log.heal(ident, stored, reason);
939
+ }
940
+ } else if (num < @intFromEnum(Item.BitterBerry)) {
941
+ const proc = if (stored.item == .MiracleBerry)
942
+ Status.any(stored.status)
943
+ else
944
+ Status.is(stored.status, @enumFromInt(num - @intFromEnum(Item.MintBerry) + 2));
945
+
946
+ if (proc) {
947
+ assert(Status.any(stored.status));
948
+ try options.log.enditem(ident, stored.item, .Eat);
949
+ stored.item = .None;
950
+
951
+ // FIXME wtf?
952
+ // side.active.volatiles.Toxic = false;
953
+ // side.active.volatiles.NightMare = false;
954
+ if (stored.item == .MiracleBerry) {
955
+ side.active.volatiles.Confusion = false;
956
+ try options.log.end(ident, .Confusion);
957
+ }
958
+ stored.status = 0;
959
+
960
+ // FIXME recalc stats
961
+
962
+ try options.log.curestatus(ident, stored.status, .Message);
963
+ }
964
+ } else if (num == @intFromEnum(Item.BitterBerry)) {
965
+ if (side.active.volatiles.Confusion) {
966
+ try options.log.enditem(ident, stored.item, .Eat);
967
+ stored.item = .None;
968
+
969
+ side.active.volatiles.Confusion = false;
970
+ try options.log.end(ident, .Confusion);
971
+ }
972
+ }
973
+ }
974
+ }
975
+
976
+ // Encore
977
+ inline for (players) |player| {
978
+ var side = battle.side(player);
979
+ var volatiles = &side.active.volatiles;
980
+
981
+ if (volatiles.Encore) {
982
+ assert(volatiles.encore > 0);
983
+ volatiles.encore -= 1;
984
+
985
+ if (volatiles.encore == 0 or side.active.moves(mslot).pp == 0) {
986
+ volatiles.Encore = false;
987
+ try options.log.end(battle.active(player), .Encore);
988
+ }
989
+ }
990
+ }
991
+ }
992
+
993
+ inline fn updateSideCondition(
994
+ battle: anytype,
995
+ player: Player,
996
+ comptime key: []const u8,
997
+ comptime value: []const u8,
998
+ options: anytype,
999
+ ) !void {
1000
+ var side = battle.side(player);
1001
+ if (@field(side.conditions, key)) {
1002
+ assert(@field(side.conditions, value) > 0);
1003
+ @field(side.conditions, value) -= 1;
1004
+
1005
+ if (@field(side.conditions, value) == 0) {
1006
+ @field(side.conditions, key) = false;
1007
+ try options.log.sideend(battle.active(player), @field(protocol.Side, key));
1008
+ }
1009
+ }
1010
+ }
1011
+
1012
+ fn endTurn(battle: anytype, options: anytype) @TypeOf(options.log).Error!Result {
1013
+ battle.turn += 1;
1014
+
1015
+ if (showdown and battle.turn >= 1000) {
1016
+ try options.log.tie();
1017
+ return Result.Tie;
1018
+ } else if (battle.turn >= 65535) {
1019
+ return Result.Error;
1020
+ }
1021
+
1022
+ try options.log.turn(battle.turn);
1023
+
1024
+ return Result.Default;
1025
+ }
1026
+
1027
+ pub const Effects = struct {
1028
+ fn protect(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
1029
+ var side = battle.side(player);
1030
+ var volatiles = &side.active.volatiles;
1031
+
1032
+ // TODO or if we didn't go first
1033
+ if (volatiles.Substitute) return try options.log.fail(battle.active(player), .None);
1034
+
1035
+ // TODO
1036
+
1037
+ if (move.effect == .Endure) {
1038
+ volatiles.Endure = true;
1039
+ } else {
1040
+ volatiles.Protect = true;
1041
+ }
1042
+ try options.log.singleturn(battle.active(player), move.id);
1043
+ }
1044
+ };
1045
+
1046
+ fn statusModify(status: u8, stats: *Stats(u16)) void {
1047
+ if (Status.is(status, .PAR)) {
1048
+ stats.spe = @max(stats.spe / 4, 1);
1049
+ } else if (Status.is(status, .BRN)) {
1050
+ stats.atk = @max(stats.atk / 2, 1);
1051
+ }
1052
+ }
1053
+
1054
+ inline fn isForced(active: anytype) bool {
1055
+ return active.volatiles.Recharging or active.volatiles.Rage or
1056
+ active.volatiles.Thrashing or active.volatiles.Charging or
1057
+ active.volatiles.Rollout;
1058
+ }
1059
+
1060
+ pub const Rolls = struct {
1061
+ inline fn speedTie(battle: anytype, options: anytype) !bool {
1062
+ const p1 = if (options.calc.overridden(.P1, .speed_tie)) |player|
1063
+ player == .P1
1064
+ else if (showdown)
1065
+ battle.rng.range(u8, 0, 2) == 0
1066
+ else
1067
+ battle.rng.next() < Gen12.percent(50) + 1;
1068
+
1069
+ try options.chance.speedTie(p1);
1070
+ return p1;
1071
+ }
1072
+
1073
+ inline fn quickClaw(battle: anytype, player: Player, options: anytype) !bool {
1074
+ const qkc = if (options.calc.overridden(player, .quick_claw)) |val|
1075
+ val == .true
1076
+ else if (showdown)
1077
+ battle.rng.chance(u8, 60, 256)
1078
+ else
1079
+ battle.rng.next() < 60;
1080
+
1081
+ try options.chance.quickClaw(player, qkc);
1082
+ return qkc;
1083
+ }
1084
+
1085
+ inline fn hit(battle: anytype, player: Player, accuracy: u8, options: anytype) !bool {
1086
+ const ok = if (options.calc.overridden(player, .hit)) |val|
1087
+ val == .true
1088
+ else if (showdown)
1089
+ battle.rng.chance(u8, accuracy, 256)
1090
+ else
1091
+ battle.rng.next() < accuracy;
1092
+
1093
+ try options.chance.hit(player, ok, accuracy);
1094
+ return ok;
1095
+ }
1096
+
1097
+ inline fn criticalHit(battle: anytype, player: Player, rate: u8, options: anytype) !bool {
1098
+ const crit = if (options.calc.overridden(player, .critical_hit)) |val|
1099
+ val == .true
1100
+ else if (showdown)
1101
+ battle.rng.chance(u8, rate, 256)
1102
+ else
1103
+ battle.rng.next() < rate;
1104
+
1105
+ try options.chance.criticalHit(player, crit, rate);
1106
+ return crit;
1107
+ }
1108
+
1109
+ inline fn damage(battle: anytype, player: anytype, options: anytype) !u8 {
1110
+ const roll = if (options.calc.overridden(player, .damage)) |val|
1111
+ val
1112
+ else roll: {
1113
+ if (showdown) break :roll battle.rng.range(u8, 217, 256);
1114
+ while (true) {
1115
+ const r = std.math.rotr(u8, battle.rng.next(), 1);
1116
+ if (r >= 217) break :roll r;
1117
+ }
1118
+ };
1119
+
1120
+ assert(roll >= 217 and roll <= 255);
1121
+ try options.chance.damage(player, roll);
1122
+ return roll;
1123
+ }
1124
+
1125
+ inline fn confused(battle: anytype, player: Player, options: anytype) !bool {
1126
+ const cfz = if (options.calc.overridden(player, .confused)) |val|
1127
+ val == .true
1128
+ else if (showdown)
1129
+ !battle.rng.chance(u8, 128, 256)
1130
+ else
1131
+ battle.rng.next() >= Gen12.percent(50) + 1;
1132
+
1133
+ try options.chance.confused(player, cfz);
1134
+ return cfz;
1135
+ }
1136
+
1137
+ inline fn attract(battle: anytype, player: Player, options: anytype) !bool {
1138
+ const cant = if (options.calc.overridden(player, .attract)) |val|
1139
+ val == .true
1140
+ else if (showdown)
1141
+ battle.rng.chance(u8, 1, 2)
1142
+ else
1143
+ battle.rng.next() > Gen12.percent(50) + 1;
1144
+
1145
+ try options.chance.attract(player, cant);
1146
+ return cant;
1147
+ }
1148
+
1149
+ inline fn paralyzed(battle: anytype, player: Player, options: anytype) !bool {
1150
+ const par = if (options.calc.overridden(player, .paralyzed)) |val|
1151
+ val == .true
1152
+ else if (showdown)
1153
+ battle.rng.chance(u8, 63, 256)
1154
+ else
1155
+ battle.rng.next() < Gen12.percent(25);
1156
+
1157
+ try options.chance.paralyzed(player, par);
1158
+ return par;
1159
+ }
1160
+
1161
+ inline fn defrost(battle: anytype, player: Player, options: anytype) !bool {
1162
+ const thaw = if (options.calc.overridden(player, .defrost)) |val|
1163
+ val == .true
1164
+ else if (showdown)
1165
+ battle.rng.chance(u8, 25, 256)
1166
+ else
1167
+ battle.rng.next() < Gen12.percent(10);
1168
+
1169
+ try options.chance.defrost(player, thaw);
1170
+ return thaw;
1171
+ }
1172
+
1173
+ inline fn secondaryChance(battle: anytype, player: Player, rate: u8, options: anytype) !bool {
1174
+ // GLITCH: 100% secondary chance will still fail 1/256 of the time
1175
+ const proc = if (options.calc.overridden(player, .secondary_chance)) |val|
1176
+ val == .true
1177
+ else if (showdown)
1178
+ battle.rng.chance(u8, rate, 256)
1179
+ else
1180
+ battle.rng.next() < rate;
1181
+
1182
+ try options.chance.secondaryChance(player, proc, rate);
1183
+ return proc;
1184
+ }
1185
+
1186
+ inline fn focusBand(battle: anytype, player: Player, options: anytype) !bool {
1187
+ // FIXME
1188
+ const proc = if (options.calc.overridden(player, .focus_band)) |val|
1189
+ val == .true
1190
+ else if (showdown)
1191
+ battle.rng.chance(u8, 30, 256)
1192
+ else
1193
+ battle.rng.next() <= 30;
1194
+
1195
+ try options.chance.focusBand(player, proc);
1196
+ return proc;
1197
+ }
1198
+
1199
+ inline fn psywave(battle: anytype, player: Player, max: u8, options: anytype) !u8 {
1200
+ const power = if (options.calc.overridden(player, .psywave)) |val|
1201
+ val - 1
1202
+ else if (showdown)
1203
+ battle.rng.range(u8, 0, max)
1204
+ else power: {
1205
+ while (true) {
1206
+ const r = battle.rng.next();
1207
+ if (r < max) break :power r;
1208
+ }
1209
+ };
1210
+
1211
+ assert(power < max);
1212
+ try options.chance.psywave(player, power, max);
1213
+ return power;
1214
+ }
1215
+
1216
+ inline fn sleepDuration(battle: anytype, player: Player, options: anytype) u3 {
1217
+ // FIXME
1218
+ const duration: u3 = if (options.calc.overridden(player, .duration)) |val|
1219
+ @intCast(val)
1220
+ else if (showdown)
1221
+ @intCast(battle.rng.range(u8, 1, 8))
1222
+ else duration: {
1223
+ while (true) {
1224
+ const r = battle.rng.next() & 7;
1225
+ if (r != 0) break :duration @intCast(r);
1226
+ }
1227
+ };
1228
+
1229
+ assert(duration >= 1 and duration <= 7);
1230
+ options.chance.duration(.sleep, player, player.foe(), duration);
1231
+ return duration;
1232
+ }
1233
+
1234
+ inline fn triAttack(battle: anytype, player: Player, options: anytype) !u8 {
1235
+ const which: TriAttack = if (options.calc.overridden(player, .tri_attack)) |val|
1236
+ val
1237
+ else if (showdown)
1238
+ @enumFromInt(battle.rng.range(u8, 0, 2))
1239
+ else
1240
+ // FIXME swap the upper 4 bits in register r8 and the lower 4 ones.
1241
+ @enumFromInt((battle.rng.next() & 3) - 1);
1242
+
1243
+ try options.chance.triAttack(player, which);
1244
+ return which.status();
1245
+ }
1246
+
1247
+ inline fn present(battle: anytype, player: Player, options: anytype) !u8 {
1248
+ const power = if (options.calc.overridden(player, .present)) |val|
1249
+ val * 40
1250
+ else if (showdown) power: {
1251
+ const r = battle.rng.range(u8, 0, 10);
1252
+ if (r < 2) break :power 0;
1253
+ if (r < 6) break :power 40;
1254
+ if (r < 9) break :power 80;
1255
+ break :power 120;
1256
+ } else power: {
1257
+ const r = battle.rng.next();
1258
+ if (r <= Gen12.percent(40)) break :power 40;
1259
+ if (r <= Gen12.percent(70) + 1) break :power 80;
1260
+ if (r <= Gen12.percent(80)) break :power 120;
1261
+ break :power 0;
1262
+ };
1263
+ try options.chance.present(player, power);
1264
+ return power;
1265
+ }
1266
+
1267
+ inline fn spite(battle: anytype, player: Player, options: anytype) !u8 {
1268
+ const pp = if (options.calc.overridden(player, .spite)) |val|
1269
+ val
1270
+ else if (showdown)
1271
+ battle.rng.range(u8, 2, 6)
1272
+ else
1273
+ (battle.rng.next() & 3) + 2;
1274
+
1275
+ try options.chance.spite(player, pp);
1276
+ return pp;
1277
+ }
1278
+
1279
+ const CONVERSION2: [Type.size]Type = [_]Type{.{}} ** Type.size;
1280
+
1281
+ inline fn conversion2(battle: anytype, player: Player, mtype: Type, options: anytype) !Type {
1282
+ assert(mtype != .@"???");
1283
+ const ty = if (options.calc.overridden(player, .conversion2)) |val|
1284
+ val
1285
+ else if (showdown) ty: {
1286
+ var i: u8 = 0;
1287
+ for (Type.SHOWDOWN) |t| {
1288
+ if (@intFromEnum(mtype.effectiveness(t)) < @intFromEnum(Effectiveness.Neutral)) {
1289
+ CONVERSION2[i] = t;
1290
+ i += 1;
1291
+ }
1292
+ }
1293
+ assert(i > 0 and i <= CONVERSION2.len);
1294
+ break :ty CONVERSION2[battle.rng.range(u8, 0, i)];
1295
+ } else ty: {
1296
+ while (true) {
1297
+ // FIXME MASK bits
1298
+ const r = battle.rng.next();
1299
+ if (r == 6) continue; // BIRD
1300
+ if (r > 9 and r < 20) continue; // UNUSED_TYPES
1301
+ if (r > 27) continue; // TYPES_END
1302
+
1303
+ const t = Types.conversion2(r);
1304
+ if (@intFromEnum(mtype.effectiveness(t)) < @intFromEnum(Effectiveness.Neutral)) {
1305
+ break :ty t;
1306
+ }
1307
+ }
1308
+ };
1309
+
1310
+ try options.chance.conversion2(player, ty);
1311
+ return ty;
1312
+ }
1313
+
1314
+ // TODO thrashingDuration
1315
+ // TODO confusionDuraiton (from thrash vs. from move)
1316
+ // TODO forceSwitch
1317
+ // TODO tripleKick
1318
+ // TODO kingsRock
1319
+ // TODO bindingDuration
1320
+ // TODO bideDuration
1321
+ // TODO conversion moveSlot
1322
+ // TODO disable duration
1323
+ // TODO encore duration
1324
+ // TODO magnitude
1325
+ // TODO metronome
1326
+ // TODO protect
1327
+ // TODO sleeptalk move slot
1328
+
1329
+ const METRONOME = init: {
1330
+ var num = 0;
1331
+ var moves: [238]Move = undefined;
1332
+ for (1..Move.size) |i| {
1333
+ if (Move.get(@enumFromInt(i)).extra.metronome) {
1334
+ moves[num] = @enumFromInt(i);
1335
+ num += 1;
1336
+ }
1337
+ }
1338
+ assert(num == moves.len);
1339
+ break :init moves;
1340
+ };
1341
+ };
1342
+
1343
+ pub const TriAttack = enum(u2) {
1344
+ PAR,
1345
+ FRZ,
1346
+ BRN,
1347
+
1348
+ pub inline fn status(self: TriAttack) u8 {
1349
+ return Status.init(@enumFromInt(6 - @as(u8, @intFromEnum(self))));
1350
+ }
1351
+ };
1352
+
1353
+ test TriAttack {
1354
+ try expectEqual(Status.init(.PAR), TriAttack.PAR.status());
1355
+ try expectEqual(Status.init(.FRZ), TriAttack.FRZ.status());
1356
+ try expectEqual(Status.init(.BRN), TriAttack.BRN.status());
1357
+ }
1358
+
1359
+ test "RNG agreement" {
1360
+ if (!showdown) return;
1361
+ var expected: [256]u32 = undefined;
1362
+ for (0..expected.len) |i| {
1363
+ expected[i] = @intCast(i * 0x1000000);
1364
+ }
1365
+
1366
+ var spe: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1367
+ var qkc: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1368
+ var cfz: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1369
+ var atr: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1370
+ var frz: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1371
+
1372
+ for (0..expected.len) |i| {
1373
+ try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1);
1374
+ try expectEqual(qkc.chance(u8, 60, 256), i < 60);
1375
+ try expectEqual(!cfz.chance(u8, 128, 256), i >= Gen12.percent(50) + 1);
1376
+ try expectEqual(atr.chance(u8, 1, 2), i < Gen12.percent(50) + 1);
1377
+ try expectEqual(frz.chance(u8, 25, 256), i < Gen12.percent(10));
1378
+ }
1379
+ }
1380
+
1381
+ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 {
1382
+ var n: u8 = 0;
1383
+ switch (request) {
1384
+ .Pass => {
1385
+ out[n] = .{};
1386
+ n += 1;
1387
+ },
1388
+ .Switch => {
1389
+ const side = battle.side(player);
1390
+ var slot: u4 = 2;
1391
+ while (slot <= 6) : (slot += 1) {
1392
+ const id = side.order[slot - 1];
1393
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
1394
+ out[n] = .{ .type = .Switch, .data = slot };
1395
+ n += 1;
1396
+ }
1397
+ if (n == 0) {
1398
+ out[n] = .{};
1399
+ n += 1;
1400
+ }
1401
+ },
1402
+ .Move => {
1403
+ const side = battle.side(player);
1404
+
1405
+ var active = &side.active;
1406
+ const stored = side.stored();
1407
+
1408
+ // While players are not given any input options on the cartridge in these cases,
1409
+ // Pokémon Showdown instead produces a list with a single move that must be chosen.
1410
+ //
1411
+ // Given that no input is allowed on the cartridge 'Pass' seems like it would be logical
1412
+ // here when not in compatibility mode, but the engine needs to be able to differentiate
1413
+ // between passing while waiting for an opponent's forced switch after fainting and
1414
+ // passing due to being forced into using a move. Instead of introducing another option
1415
+ // we simply repurpose Move with no move slot, even though pedantically this is not
1416
+ // strictly correct as the player would not have been presented the option to move or
1417
+ // switch at all.
1418
+ if (isForced(active)) {
1419
+ out[n] = .{ .type = .Move, .data = @intFromBool(showdown) };
1420
+ n += 1;
1421
+ return n;
1422
+ }
1423
+
1424
+ var slot: u4 = 2;
1425
+ while (!active.volatiles.trapped and slot <= 6) : (slot += 1) {
1426
+ const id = side.order[slot - 1];
1427
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
1428
+ out[n] = .{ .type = .Switch, .data = slot };
1429
+ n += 1;
1430
+ }
1431
+
1432
+ const limited = active.volatiles.Bide or active.volatiles.bind > 0;
1433
+ // On the cartridge, all of these happen after "FIGHT" (indicating you are not
1434
+ // switching) but before you are allowed to select a move. Pokémon Showdown instead
1435
+ // either disables all other moves in the case of limited or requires you to select a
1436
+ // move normally if sleeping/frozen/bound.
1437
+ if (!showdown and (limited or
1438
+ Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP)))
1439
+ {
1440
+ out[n] = .{ .type = .Move, .data = 0 };
1441
+ n += 1;
1442
+ return n;
1443
+ }
1444
+
1445
+ slot = 1;
1446
+ // Pokémon Showdown handles Bide and Binding moves by checking if the move in question
1447
+ // is present in the Pokémon's moveset (which means moves called via Metronome / Mirror
1448
+ // Move will not result in forcing the subsequent use unless the user also had the
1449
+ // proc-ed move in their moveset) and disabling all other moves.
1450
+ if (limited) {
1451
+ assert(showdown);
1452
+ assert(side.last_selected_move != .None);
1453
+ while (slot <= 4) : (slot += 1) {
1454
+ const m = active.moves[slot - 1];
1455
+ if (m.id == .None) break;
1456
+ if (m.id == if (active.volatiles.Bide) .Bide else side.last_selected_move) {
1457
+ // Pokémon Showdown displays Struggle if limited to Bide but unable to pick
1458
+ const struggle =
1459
+ m.id == .Bide and (m.pp == 0 or active.volatiles.disabled_move == slot);
1460
+ const s = if (struggle) 0 else slot;
1461
+ out[n] = .{ .type = .Move, .data = s };
1462
+ n += 1;
1463
+ return n;
1464
+ }
1465
+ }
1466
+ }
1467
+
1468
+ const before = n;
1469
+ slot = 1;
1470
+ while (slot <= 4) : (slot += 1) {
1471
+ const m = active.moves[slot - 1];
1472
+ if (m.id == .None) break;
1473
+ if (m.pp == 0) continue;
1474
+ if (active.volatiles.disabled_move == slot) continue;
1475
+ out[n] = .{ .type = .Move, .data = slot };
1476
+ n += 1;
1477
+ }
1478
+ // Struggle (Pokémon Showdown would use 'move 1' here)
1479
+ if (n == before) {
1480
+ out[n] = .{ .type = .Move, .data = 0 };
1481
+ n += 1;
1482
+ }
1483
+ },
1484
+ }
1485
+ return n;
1486
+ }