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

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,1155 @@ 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) !bool {
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 false;
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 false;
386
+ }
387
+ }
388
+
389
+ if (Status.is(stored.status, .FRZ) and !(move == .FlameWheel or move == .SacredFire)) {
390
+ cantMove(volatiles);
391
+ try log.cant(ident, .Freeze);
392
+ return false;
393
+ }
394
+
395
+ if (volatiles.Flinch) {
396
+ // Pokémon Showdown doesn't clear Flinch until its imaginary "residual" phase, meaning
397
+ // Pokémon can sometimes flinch multiple times from the same original hit
398
+ // if (!showdown) volatiles.Flinch = false;
399
+ volatiles.Flinch = false;
400
+ cantMove(volatiles);
401
+ try log.cant(ident, .Flinch);
402
+ return false;
403
+ }
404
+
405
+ if (volatiles.disabled_duration > 0) {
406
+ // if (options.calc.modify(player, .disable)) |extend| {
407
+ // if (!extend) volatiles.disabled_duration = 0;
408
+ // } else {
409
+ volatiles.disabled_duration -= 1;
410
+ // }
411
+ try options.chance.disable(player, volatiles.disabled_duration);
412
+
413
+ if (volatiles.disabled_duration == 0) {
414
+ volatiles.disabled_move = 0;
415
+ try log.end(ident, .Disable);
416
+ }
417
+ }
418
+
419
+ if (volatiles.Confusion) {
420
+ assert(volatiles.confusion > 0);
421
+
422
+ // if (options.calc.modify(player, .confusion)) |extend| {
423
+ // if (!extend) volatiles.confusion = 0;
424
+ // } else {
425
+ volatiles.confusion -= 1;
426
+ // }
427
+ try options.chance.confusion(player, volatiles.confusion);
428
+
429
+ if (volatiles.confusion == 0) {
430
+ volatiles.Confusion = false;
431
+ try log.end(ident, .Confusion);
432
+ } else {
433
+ try log.activate(ident, .Confusion);
434
+
435
+ if (try Rolls.confused(battle, player, options)) {
436
+ volatiles.BeatUp = false;
437
+ volatiles.Flinch = false;
438
+ cantMove(volatiles);
439
+
440
+ // TODO HitConfusion
441
+
442
+ return false;
443
+ }
444
+ }
445
+ }
446
+
447
+ if (volatiles.Attract) {
448
+ try log.atrract(ident, .Attract);
449
+
450
+ if (try Rolls.attract(battle, player, options)) {
451
+ cantMove(volatiles);
452
+ try log.cant(ident, .Attract);
453
+ return false;
454
+ }
455
+ }
456
+
457
+ if (side.active.volatiles.disabled_move != 0) {
458
+ // A Pokémon that transforms after being disabled may end up with less move slots
459
+ const m = side.active.moves[side.active.volatiles.disabled_move - 1].id;
460
+ if (m != .None and m == move) {
461
+ side.active.volatiles.Charging = false;
462
+ cantMove(volatiles);
463
+ try options.log.disabled(ident, move);
464
+ return false;
465
+ }
466
+ }
467
+
468
+ if (Status.is(stored.status, .PAR) and try Rolls.paralyzed(battle, player, options)) {
469
+ cantMove(volatiles);
470
+ try log.cant(ident, .Paralysis);
471
+ return false;
472
+ }
473
+
474
+ return true;
475
+ }
476
+
477
+ fn cantMove(volatiles: *Volatiles) void {
478
+ volatiles.Bide = false;
479
+ volatiles.Thrashing = false;
480
+ volatiles.Charging = false;
481
+ volatiles.Underground = false;
482
+ volatiles.Flying = false;
483
+ volatiles.Rollout = false;
484
+
485
+ volatiles.fury_cutter = 0;
486
+ }
487
+
488
+ fn canMove(battle: anytype, player: Player, options: anytype) !bool {
39
489
  _ = battle;
40
- _ = c1;
41
- _ = c2;
490
+ _ = player;
42
491
  _ = options;
492
+ return false;
493
+ }
43
494
 
44
- return Result.Default;
495
+ fn decrementPP(side: *Side, mslot: u4) void {
496
+ var active = &side.active;
497
+ const volatiles = &active.volatiles;
498
+
499
+ // TODO assert(side.last_selected_move != .Struggle);
500
+ assert(!volatiles.Charging and !volatiles.BeatUp and !volatiles.Thrashing and !volatiles.Bide);
501
+
502
+ assert(active.move(mslot).pp > 0);
503
+ active.move(mslot).pp = @as(u6, @intCast(active.move(mslot).pp)) -% 1;
504
+ if (volatiles.Transform) return;
505
+
506
+ // FIXME mimic
507
+
508
+ assert(side.stored().move(mslot).pp > 0);
509
+ side.stored().move(mslot).pp = @as(u6, @intCast(side.stored().move(mslot).pp)) -% 1;
510
+ assert(active.move(mslot).pp == side.stored().move(mslot).pp);
45
511
  }
46
512
 
47
- pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 {
513
+ fn doMove(battle: anytype, player: Player, options: anytype, mslot: u4) !?Result {
514
+ _ = options;
515
+ var side = battle.side(player);
516
+ const move = Move.get(.Teleport); // side.last_selected_move
517
+ switch (move.effect) {
518
+ .Teleport => {
519
+ // side.useMove();
520
+ decrementPP(side, mslot);
521
+ },
522
+ else => @panic("TODO"),
523
+ }
524
+ return null;
525
+ }
526
+
527
+ fn checkCriticalHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !bool {
528
+ if (move.bp == 0) return false;
529
+
530
+ const side = battle.side(player);
531
+ const pokemon = side.stored();
532
+
533
+ var stage: u8 =
534
+ if ((pokemon.species == .Chansey and pokemon.item == .LuckyPunch) or
535
+ (pokemon.species == .Farfetchd and pokemon.item == .Stick)) 2 else 0;
536
+ if (stage == 0) {
537
+ if (side.active.volatiles.FocusEnergy) stage += 1;
538
+ if (move.effect.isHighCritical()) stage += 2;
539
+ if (pokemon.item == .ScopeLens) stage += 1;
540
+ }
541
+ assert(stage <= 4);
542
+
543
+ return Rolls.criticalHit(battle, player, CRITICAL_HITS[stage], options);
544
+ }
545
+
546
+ fn calcDamage(
547
+ battle: anytype,
548
+ player: Player,
549
+ target_player: Player,
550
+ m: ?Move.Data,
551
+ crit: bool,
552
+ ) u16 {
48
553
  _ = battle;
49
554
  _ = player;
50
- _ = request;
51
- _ = out;
52
-
555
+ _ = target_player;
556
+ _ = m;
557
+ _ = crit;
53
558
  return 0;
54
559
  }
560
+ const FORESIGHT: Types = .{ .type1 = .Normal, .type2 = .Fighting };
561
+
562
+ fn adjustDamage(battle: anytype, player: Player, m: Move, damage: u16, effectiveness: *u16) u16 {
563
+ if (m == .Struggle) return;
564
+
565
+ const side = battle.side(player);
566
+ const foe = battle.foe(player);
567
+ const types = foe.active.types;
568
+ const move = Move.get(side.m);
569
+
570
+ var d = damage;
571
+ if ((move.type == .Water and battle.field.weather == .Rain) or
572
+ (move.type == .Fire and battle.field.weather == .Sun))
573
+ {
574
+ d = d *% @intFromEnum(Effectiveness.Super) / 10;
575
+ } else if ((move.type == .Water and battle.field.weather == .Sun) or
576
+ ((move.type == .Fire or m == .SolarBeam) and battle.field.weather == .Rain))
577
+ {
578
+ d = d *% @intFromEnum(Effectiveness.Resisted) / 10;
579
+ }
580
+
581
+ if (side.active.types.includes(move.type)) d +%= d / 2;
582
+
583
+ const neutral = @intFromEnum(Effectiveness.Neutral);
584
+ const foresight = foe.active.volatiles.Foresight and FORESIGHT.includes(move.type);
585
+ const eff1: u16 = if (foresight and types.type1 == .Ghost)
586
+ 10
587
+ else
588
+ @intFromEnum(move.type.effectiveness(types.type1));
589
+ const eff2: u16 = if (foresight and types.type2 == .Ghost)
590
+ 10
591
+ else
592
+ @intFromEnum(move.type.effectiveness(types.type2));
593
+
594
+ // Type effectiveness matchup precedence only matters with (NVE, SE)
595
+ if (!showdown and (eff1 + eff2) == Effectiveness.mismatch and
596
+ Type.precedence(move.type, types.type1) > Type.precedence(move.type, types.type2))
597
+ {
598
+ assert(eff2 != neutral);
599
+ d = d *% eff2 / 10;
600
+ assert(types.type1 != types.type2);
601
+ assert(eff1 != neutral);
602
+ d = d *% eff1 / 10;
603
+ } else {
604
+ if (eff1 != neutral) d = d *% eff1 / 10;
605
+ if (types.type1 != types.type2 and eff2 != neutral) d = d *% eff2 / 10;
606
+ }
607
+
608
+ effectiveness.* = if (types.type1 == types.type2) eff1 * neutral else eff1 * eff2;
609
+ return d;
610
+ }
611
+
612
+ fn randomizeDamage(battle: anytype, player: Player, damage: u16, options: anytype) !u16 {
613
+ if (damage <= 1) return;
614
+ const random = try Rolls.damage(battle, player, options);
615
+ options.calc.base(player.foe(), damage);
616
+ damage = @intCast(@as(u32, damage) *% random / 255);
617
+ options.calc.final(player.foe(), damage);
618
+ return damage;
619
+ }
620
+
621
+ fn applyDamage(
622
+ battle: anytype,
623
+ player: Player,
624
+ options: anytype,
625
+ ) !bool {
626
+ _ = battle;
627
+ _ = player;
628
+ _ = options;
629
+ return false;
630
+ }
631
+
632
+ fn checkHit(battle: anytype, player: Player, move: Move.Data, options: anytype) !bool {
633
+ if (moveHit(battle, player, move, options)) return true;
634
+
635
+ // try options.chance.commit(player, .miss);
636
+ try options.log.lastmiss();
637
+ try options.log.miss(battle.active(player));
638
+
639
+ return false;
640
+ }
641
+
642
+ // TODO: set damage = 0 if missed and not (High) Jump Kick
643
+ fn moveHit(
644
+ battle: anytype,
645
+ player: Player,
646
+ move: Move.Data,
647
+ options: anytype,
648
+ ) !bool {
649
+ const side = battle.side(player);
650
+ const foe = battle.foe(player);
651
+
652
+ if (move.effect == .DreamEater and !Status.is(foe.stored().status, .SLP)) return false;
653
+ if (foe.active.volatiles.Protect) return false;
654
+ const drain = move.effect == .DrainHP or move.effect == .DreamEater;
655
+ if (drain and foe.active.volatiles.Substitute) return false;
656
+ if (side.active.volatiles.LockOn) {
657
+ return !(foe.active.volatiles.Flying and move.flags.undeground);
658
+ }
659
+ assert(!(foe.active.volatiles.Flying and foe.active.volatiles.Underground));
660
+ if (foe.active.volatiles.Flying) {
661
+ if (!move.flags.flying) return false;
662
+ } else if (foe.active.volatiles.Underground) {
663
+ if (!move.flags.underground) return false;
664
+ }
665
+ if (move.effect == .Thunder and battle.field.weather == .Rain) return true;
666
+ if (move.effect == .AlwaysHit) return true;
667
+
668
+ var accuracy: u16 = move.accuracy;
669
+ if (foe.active.boosts.evasion <= side.active.boosts.accuracy or
670
+ !foe.active.volatiles.Foresight)
671
+ {
672
+ var boost = ACCURACY_BOOSTS[@as(u4, @intCast(@as(i8, side.active.boosts.accuracy) + 6))];
673
+ accuracy = accuracy * boost[0] / boost[1];
674
+ boost = ACCURACY_BOOSTS[@as(u4, @intCast(@as(i8, -foe.active.boosts.evasion) + 6))];
675
+ accuracy = accuracy * boost[0] / boost[1];
676
+ accuracy = @min(255, @max(1, accuracy));
677
+ }
678
+
679
+ if (foe.stored().item == .BrightPowder) {
680
+ accuracy = @min(0, accuracy -% 20);
681
+ }
682
+
683
+ // The accuracy roll is skipped entirely if maxed
684
+ if (accuracy == 255) return true;
685
+ return !try Rolls.hit(battle, player, @intCast(accuracy), options);
686
+ }
687
+
688
+ fn checkFaint(
689
+ battle: anytype,
690
+ player: Player,
691
+ options: anytype,
692
+ ) @TypeOf(options.log).Error!?Result {
693
+ _ = battle;
694
+ _ = player;
695
+ return null;
696
+ }
697
+
698
+ fn faint(battle: anytype, player: Player, done: bool, options: anytype) !?Result {
699
+ _ = battle;
700
+ _ = player;
701
+ _ = done;
702
+ _ = options;
703
+ return null;
704
+ }
705
+
706
+ fn handleResidual(battle: anytype, player: Player, options: anytype) !void {
707
+ var side = battle.side(player);
708
+ var stored = side.stored();
709
+ const ident = battle.active(player);
710
+ var volatiles = &side.active.volatiles;
711
+
712
+ // TODO if (stored.hp == 0) return;
713
+ assert(stored.hp > 0);
714
+
715
+ const brn = Status.is(stored.status, .BRN);
716
+ if (brn or Status.is(stored.status, .PSN)) {
717
+ var damage: u16 = undefined;
718
+ if (volatiles.Toxic) {
719
+ volatiles.toxic += 1;
720
+ damage = @max(stored.stats.hp / 16, 1) * volatiles.toxic;
721
+ } else {
722
+ damage = @max(stored.stats.hp / 8, 1);
723
+ }
724
+ damage = @min(damage, stored.hp);
725
+
726
+ if (!showdown or damage > 0) {
727
+ stored.hp -= damage;
728
+ // Pokémon Showdown uses damageOf here but its not relevant in Generation II
729
+ try options.log.damage(ident, stored, if (brn) Damage.Burn else Damage.Poison);
730
+ if (stored.hp == 0) return;
731
+ }
732
+ }
733
+
734
+ if (volatiles.LeechSeed) {
735
+ var foe = battle.foe(player);
736
+ var foe_stored = foe.stored();
737
+ const foe_ident = battle.active(player.foe());
738
+
739
+ // if (foe_stored.hp == 0) {
740
+ // assert(showdown);
741
+ // return;
742
+ // }
743
+
744
+ const damage = @min(@max(stored.stats.hp / 8, 1), stored.hp);
745
+ stored.hp -= damage;
746
+ // As above, Pokémon Showdown uses damageOf but its not relevant
747
+ if (damage > 0) try options.log.damage(ident, stored, .LeechSeed);
748
+
749
+ const before = foe_stored.hp;
750
+ foe_stored.hp = @min(foe_stored.hp + damage, foe_stored.stats.hp);
751
+ // Pokémon Showdown uses the less specific heal here instead of drain... because reasons?
752
+ if (foe_stored.hp > before) try options.log.heal(foe_ident, foe_stored, .Silent);
753
+ if (stored.hp == 0) return;
754
+ }
755
+
756
+ if (volatiles.Nightmare) {
757
+ const damage = @min(@max(stored.stats.hp / 4, 1), stored.hp);
758
+ if (!showdown or damage > 0) {
759
+ stored.hp -= damage;
760
+ // ibid
761
+ try options.log.damage(ident, stored, Damage.Nightmare);
762
+ if (stored.hp == 0) return;
763
+ }
764
+ }
765
+
766
+ if (volatiles.Curse) {
767
+ const damage = @min(@max(stored.stats.hp / 4, 1), stored.hp);
768
+ if (!showdown or damage > 0) {
769
+ stored.hp -= damage;
770
+ // ibid
771
+ try options.log.damage(ident, stored, Damage.Curse);
772
+ if (stored.hp == 0) return;
773
+ }
774
+ }
775
+ }
776
+
777
+ fn betweenTurn(battle: anytype, mslot: u4, options: anytype) !void {
778
+ const players = std.enums.values(Player);
779
+
780
+ // TODO checkFaintThen(p1, p2);
781
+
782
+ // Future Sight
783
+ inline for (players) |player| {
784
+ var side = battle.side(player);
785
+ if (side.conditions.future_sight.count > 0) {
786
+ side.conditions.future_sight.count -= 1;
787
+ assert(side.conditions.future_sight.count != 0);
788
+ if (side.conditions.future_sight.count == 1) {
789
+ try options.log.end(battle.active(player), .FutureSight);
790
+ // TODO doMove
791
+
792
+ }
793
+ }
794
+ }
795
+ // TODO checkFaintThen(p1, p2);
796
+
797
+ // Weather
798
+ inline for (players) |player| {
799
+ var side = battle.side(player);
800
+ _ = side; // TODO
801
+
802
+ }
803
+ // TODO checkFaintThen(p1, p2);
804
+
805
+ // Binding
806
+ inline for (players) |player| {
807
+ var side = battle.side(player);
808
+ _ = side; // TODO
809
+
810
+ }
811
+ // TODO checkFaintThen(p1, p2);
812
+
813
+ // Perish Song
814
+ inline for (players) |player| {
815
+ var side = battle.side(player);
816
+ _ = side; // TODO
817
+
818
+ }
819
+ // TODO checkFaintThen(p1, p2);
820
+
821
+ // Leftovers
822
+ inline for (players) |player| {
823
+ var stored = battle.side(player).stored();
824
+ if (stored.item == .Leftovers) {
825
+ const before = stored.hp;
826
+ const heal = @min(@max(stored.stats.hp / 16, 1), stored.hp);
827
+ stored.hp = @min(stored.hp + heal, stored.stats.hp);
828
+ if (stored.hp > before) try options.log.heal(battle.active(player), stored, .Leftovers);
829
+ }
830
+ }
831
+
832
+ // Mystery Berry
833
+ inline for (players) |player| {
834
+ var stored = battle.side(player).stored();
835
+ if (stored.item == .MysteryBerry) {
836
+ // TODO stored and active moves, transform, etc
837
+ }
838
+ }
839
+
840
+ // Defrost
841
+ inline for (players) |player| {
842
+ var side = battle.side(player);
843
+ if (Status.is(side.stored().status, .FRZ) and
844
+ !side.active.volatiles.frozen and
845
+ try Rolls.defrost(battle, player, options))
846
+ {
847
+ try options.log.curestatus(battle.active(player), side.stored().status, .Message);
848
+ side.stored().status = 0;
849
+ }
850
+ }
851
+
852
+ // Safeguard
853
+ inline for (players) |player| {
854
+ var side = battle.side(player);
855
+ if (side.conditions.Safeguard) {
856
+ assert(side.conditions.safeguard > 0);
857
+ side.conditions.safeguard -= 1;
858
+
859
+ if (side.conditions.safeguard == 0) {
860
+ side.conditions.Safeguard = false;
861
+ try options.log.sideend(battle.active(player), .Safeguard);
862
+ }
863
+ }
864
+ }
865
+
866
+ // Reflect / Light Screen
867
+ inline for (players) |player| {
868
+ var side = battle.side(player);
869
+ _ = side; // TODO
870
+ }
871
+
872
+ // Stat boosting items
873
+ inline for (players) |player| {
874
+ var side = battle.side(player);
875
+ _ = side; // TODO
876
+ }
877
+
878
+ // Healing items
879
+ inline for (players) |player| {
880
+ var side = battle.side(player);
881
+ _ = side; // TODO
882
+ }
883
+
884
+ // Encore
885
+ inline for (players) |player| {
886
+ var side = battle.side(player);
887
+ if (side.active.volatiles.Encore) {
888
+ assert(side.active.volatiles.encore > 0);
889
+ side.active.volatiles.encore -= 1;
890
+
891
+ if (side.active.volatiles.encore == 0 or side.active.moves(mslot).pp == 0) {
892
+ side.active.volatiles.Encore = false;
893
+ try options.log.end(battle.active(player), .Encore);
894
+ }
895
+ }
896
+ }
897
+ }
898
+
899
+ fn endTurn(battle: anytype, options: anytype) @TypeOf(options.log).Error!Result {
900
+ battle.turn += 1;
901
+
902
+ if (showdown and battle.turn >= 1000) {
903
+ try options.log.tie();
904
+ return Result.Tie;
905
+ } else if (battle.turn >= 65535) {
906
+ return Result.Error;
907
+ }
908
+
909
+ try options.log.turn(battle.turn);
910
+
911
+ return Result.Default;
912
+ }
913
+
914
+ pub const Effects = struct {
915
+ fn protect(battle: anytype, player: Player, move: Move.Data, options: anytype) !void {
916
+ var side = battle.side(player);
917
+ var volatiles = &side.active.volatiles;
918
+
919
+ // TODO or if we didn't go first
920
+ if (volatiles.Substitute) return try options.log.fail(battle.active(player), .None);
921
+
922
+ // TODO
923
+
924
+ if (move.effect == .Endure) {
925
+ volatiles.Endure = true;
926
+ } else {
927
+ volatiles.Protect = true;
928
+ }
929
+ try options.log.singleturn(battle.active(player), move.id);
930
+ }
931
+ };
932
+
933
+ fn statusModify(status: u8, stats: *Stats(u16)) void {
934
+ if (Status.is(status, .PAR)) {
935
+ stats.spe = @max(stats.spe / 4, 1);
936
+ } else if (Status.is(status, .BRN)) {
937
+ stats.atk = @max(stats.atk / 2, 1);
938
+ }
939
+ }
940
+
941
+ inline fn isForced(active: anytype) bool {
942
+ return active.volatiles.Recharging or active.volatiles.Rage or
943
+ active.volatiles.Thrashing or active.volatiles.Charging or
944
+ active.volatiles.Rollout;
945
+ }
946
+
947
+ pub const Rolls = struct {
948
+ inline fn speedTie(battle: anytype, options: anytype) !bool {
949
+ const p1 = if (options.calc.overridden(.P1, .speed_tie)) |player|
950
+ player == .P1
951
+ else if (showdown)
952
+ battle.rng.range(u8, 0, 2) == 0
953
+ else
954
+ battle.rng.next() < Gen12.percent(50) + 1;
955
+
956
+ try options.chance.speedTie(p1);
957
+ return p1;
958
+ }
959
+
960
+ inline fn quickClaw(battle: anytype, player: Player, options: anytype) !bool {
961
+ const qkc = if (options.calc.overridden(player, .quick_claw)) |val|
962
+ val == .true
963
+ else if (showdown)
964
+ battle.rng.chance(u8, 60, 256)
965
+ else
966
+ battle.rng.next() < 60;
967
+
968
+ try options.chance.quickClaw(player, qkc);
969
+ return qkc;
970
+ }
971
+
972
+ inline fn criticalHit(battle: anytype, player: Player, rate: u8, options: anytype) !bool {
973
+ const crit = if (options.calc.overridden(player, .critical_hit)) |val|
974
+ val == .true
975
+ else if (showdown)
976
+ battle.rng.chance(u8, rate, 256)
977
+ else
978
+ battle.rng.next() < rate;
979
+
980
+ try options.chance.criticalHit(player, crit, rate);
981
+ return crit;
982
+ }
983
+
984
+ inline fn damage(battle: anytype, player: anytype, options: anytype) !u8 {
985
+ const roll = if (options.calc.overridden(player, .damage)) |val|
986
+ val
987
+ else roll: {
988
+ if (showdown) break :roll battle.rng.range(u8, 217, 256);
989
+ while (true) {
990
+ const r = std.math.rotr(u8, battle.rng.next(), 1);
991
+ if (r >= 217) break :roll r;
992
+ }
993
+ };
994
+
995
+ assert(roll >= 217 and roll <= 255);
996
+ try options.chance.damage(player, roll);
997
+ return roll;
998
+ }
999
+
1000
+ inline fn hit(battle: anytype, player: Player, accuracy: u8, options: anytype) !bool {
1001
+ const ok = if (options.calc.overridden(player, .hit)) |val|
1002
+ val == .true
1003
+ else if (showdown)
1004
+ battle.rng.chance(u8, accuracy, 256)
1005
+ else
1006
+ battle.rng.next() < accuracy;
1007
+
1008
+ try options.chance.hit(player, ok, accuracy);
1009
+ return ok;
1010
+ }
1011
+
1012
+ inline fn confused(battle: anytype, player: Player, options: anytype) !bool {
1013
+ const cfz = if (options.calc.overridden(player, .confused)) |val|
1014
+ val == .true
1015
+ else if (showdown)
1016
+ !battle.rng.chance(u8, 128, 256)
1017
+ else
1018
+ battle.rng.next() >= Gen12.percent(50) + 1;
1019
+
1020
+ try options.chance.confused(player, cfz);
1021
+ return cfz;
1022
+ }
1023
+
1024
+ inline fn attract(battle: anytype, player: Player, options: anytype) !bool {
1025
+ const cant = if (options.calc.overridden(player, .attract)) |val|
1026
+ val == .true
1027
+ else if (showdown)
1028
+ battle.rng.chance(u8, 1, 2)
1029
+ else
1030
+ battle.rng.next() > Gen12.percent(50) + 1;
1031
+
1032
+ try options.chance.attract(player, cant);
1033
+ return cant;
1034
+ }
1035
+
1036
+ inline fn defrost(battle: anytype, player: Player, options: anytype) !bool {
1037
+ const thaw = if (options.calc.overridden(player, .defrost)) |val|
1038
+ val == .true
1039
+ else if (showdown)
1040
+ battle.rng.chance(u8, 25, 256)
1041
+ else
1042
+ battle.rng.next() < Gen12.percent(10);
1043
+
1044
+ try options.chance.defrost(player, thaw);
1045
+ return thaw;
1046
+ }
1047
+
1048
+ const METRONOME = init: {
1049
+ var num = 0;
1050
+ var moves: [238]Move = undefined;
1051
+ for (1..Move.size) |i| {
1052
+ if (Move.get(@enumFromInt(i)).flags.metronome) {
1053
+ moves[num] = @enumFromInt(i);
1054
+ num += 1;
1055
+ }
1056
+ }
1057
+ assert(num == moves.len);
1058
+ break :init moves;
1059
+ };
1060
+ };
1061
+
1062
+ test "RNG agreement" {
1063
+ if (!showdown) return;
1064
+ var expected: [256]u32 = undefined;
1065
+ for (0..expected.len) |i| {
1066
+ expected[i] = @intCast(i * 0x1000000);
1067
+ }
1068
+
1069
+ var spe: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1070
+ var qkc: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1071
+ var cfz: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1072
+ var atr: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1073
+ var frz: rng.FixedRNG(2, expected.len) = .{ .rolls = expected };
1074
+
1075
+ for (0..expected.len) |i| {
1076
+ try expectEqual(spe.range(u8, 0, 2) == 0, i < Gen12.percent(50) + 1);
1077
+ try expectEqual(qkc.chance(u8, 60, 256), i < 60);
1078
+ try expectEqual(!cfz.chance(u8, 128, 256), i >= Gen12.percent(50) + 1);
1079
+ try expectEqual(atr.chance(u8, 1, 2), i < Gen12.percent(50) + 1);
1080
+ try expectEqual(frz.chance(u8, 25, 256), i < Gen12.percent(10));
1081
+ }
1082
+ }
1083
+
1084
+ pub fn choices(battle: anytype, player: Player, request: Choice.Type, out: []Choice) u8 {
1085
+ var n: u8 = 0;
1086
+ switch (request) {
1087
+ .Pass => {
1088
+ out[n] = .{};
1089
+ n += 1;
1090
+ },
1091
+ .Switch => {
1092
+ const side = battle.side(player);
1093
+ var slot: u4 = 2;
1094
+ while (slot <= 6) : (slot += 1) {
1095
+ const id = side.order[slot - 1];
1096
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
1097
+ out[n] = .{ .type = .Switch, .data = slot };
1098
+ n += 1;
1099
+ }
1100
+ if (n == 0) {
1101
+ out[n] = .{};
1102
+ n += 1;
1103
+ }
1104
+ },
1105
+ .Move => {
1106
+ const side = battle.side(player);
1107
+
1108
+ var active = &side.active;
1109
+ const stored = side.stored();
1110
+
1111
+ // While players are not given any input options on the cartridge in these cases,
1112
+ // Pokémon Showdown instead produces a list with a single move that must be chosen.
1113
+ //
1114
+ // Given that no input is allowed on the cartridge 'Pass' seems like it would be logical
1115
+ // here when not in compatibility mode, but the engine needs to be able to differentiate
1116
+ // between passing while waiting for an opponent's forced switch after fainting and
1117
+ // passing due to being forced into using a move. Instead of introducing another option
1118
+ // we simply repurpose Move with no move slot, even though pedantically this is not
1119
+ // strictly correct as the player would not have been presented the option to move or
1120
+ // switch at all.
1121
+ if (isForced(active)) {
1122
+ out[n] = .{ .type = .Move, .data = @intFromBool(showdown) };
1123
+ n += 1;
1124
+ return n;
1125
+ }
1126
+
1127
+ var slot: u4 = 2;
1128
+ while (!active.volatiles.trapped and slot <= 6) : (slot += 1) {
1129
+ const id = side.order[slot - 1];
1130
+ if (id == 0 or side.pokemon[id - 1].hp == 0) continue;
1131
+ out[n] = .{ .type = .Switch, .data = slot };
1132
+ n += 1;
1133
+ }
1134
+
1135
+ const limited = active.volatiles.Bide or active.volatiles.bind > 0;
1136
+ // On the cartridge, all of these happen after "FIGHT" (indicating you are not
1137
+ // switching) but before you are allowed to select a move. Pokémon Showdown instead
1138
+ // either disables all other moves in the case of limited or requires you to select a
1139
+ // move normally if sleeping/frozen/bound.
1140
+ if (!showdown and (limited or
1141
+ Status.is(stored.status, .FRZ) or Status.is(stored.status, .SLP)))
1142
+ {
1143
+ out[n] = .{ .type = .Move, .data = 0 };
1144
+ n += 1;
1145
+ return n;
1146
+ }
1147
+
1148
+ slot = 1;
1149
+ // Pokémon Showdown handles Bide and Binding moves by checking if the move in question
1150
+ // is present in the Pokémon's moveset (which means moves called via Metronome / Mirror
1151
+ // Move will not result in forcing the subsequent use unless the user also had the
1152
+ // proc-ed move in their moveset) and disabling all other moves.
1153
+ if (limited) {
1154
+ assert(showdown);
1155
+ assert(side.last_selected_move != .None);
1156
+ while (slot <= 4) : (slot += 1) {
1157
+ const m = active.moves[slot - 1];
1158
+ if (m.id == .None) break;
1159
+ if (m.id == if (active.volatiles.Bide) .Bide else side.last_selected_move) {
1160
+ // Pokémon Showdown displays Struggle if limited to Bide but unable to pick
1161
+ const struggle =
1162
+ m.id == .Bide and (m.pp == 0 or active.volatiles.disabled_move == slot);
1163
+ const s = if (struggle) 0 else slot;
1164
+ out[n] = .{ .type = .Move, .data = s };
1165
+ n += 1;
1166
+ return n;
1167
+ }
1168
+ }
1169
+ }
1170
+
1171
+ const before = n;
1172
+ slot = 1;
1173
+ while (slot <= 4) : (slot += 1) {
1174
+ const m = active.moves[slot - 1];
1175
+ if (m.id == .None) break;
1176
+ if (m.pp == 0) continue;
1177
+ if (active.volatiles.disabled_move == slot) continue;
1178
+ out[n] = .{ .type = .Move, .data = slot };
1179
+ n += 1;
1180
+ }
1181
+ // Struggle (Pokémon Showdown would use 'move 1' here)
1182
+ if (n == before) {
1183
+ out[n] = .{ .type = .Move, .data = 0 };
1184
+ n += 1;
1185
+ }
1186
+ },
1187
+ }
1188
+ return n;
1189
+ }