pinch-points 0.9.0

A fast, kid-friendly crab-routing game: route streams of crabs into your sandcastle before time runs out
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
//! Gameplay tracking: fold the SimEvent stream and round/puzzle
//! outcomes into the lifetime stats, and pop unlock toasts.

use super::save::save;
use super::ui::spawn_toast;
use super::{ACHIEVEMENTS, PuzzleAttempt, RoundScratch, StagesRun, Stats, Unlocked, Unsaved};
use crate::app::net::Online;
use crate::app::settings::GameSettings;
use crate::app::sim_events::SimEvent;
use crate::app::{Controllers, SeatController};
use crate::sim::CrabKind;
use bevy::prelude::*;

/// The seat whose deeds count: this peer's own online, else seat 0, and
/// only when a person here is playing it, never the AI or a bot.
///
/// Online it is read off the round's controllers, which hold this peer's
/// seat as its only `Local` one (`online_controllers`), rather than off
/// the session: the controllers are this round's until the next board is
/// built, and the session can be the next round's already, taken up off
/// the wire with the seats re-dealt (`take_the_next_round`).
fn local_seat(online: &Online, controllers: &Controllers) -> Option<u8> {
    let local = |seat: usize| controllers.0[seat] == SeatController::Local;
    // Watching someone else's match earns nothing: no seat is this peer's.
    let seat = match &online.0 {
        Some(_) => (0..controllers.0.len()).find(|&seat| local(seat))?,
        None => 0,
    };
    local(seat).then_some(seat as u8)
}

/// What every system that can earn a trophy needs: the record it adds to,
/// the shelf of what is already earned, and the words to say so in. The
/// toast rings its own chime as it shows (`update_toasts`).
#[derive(bevy::ecs::system::SystemParam)]
pub struct Trophies<'w> {
    pub stats: ResMut<'w, Stats>,
    unlocked: ResMut<'w, Unlocked>,
    pub settings: Res<'w, GameSettings>,
    unsaved: ResMut<'w, Unsaved>,
}

impl Trophies<'_> {
    /// Unlock whatever the stats now earn, with a toast and a chime each,
    /// and save both: once, after the caller's own changes, because a save
    /// is a sync to disk on the frame thread.
    pub fn credit(&mut self, commands: &mut Commands) {
        self.unlock(commands);
        self.save();
    }

    /// The same for a change made in the middle of a round, which is
    /// written out only when it earned something: see [`Unsaved`].
    pub fn tally(&mut self, commands: &mut Commands) {
        if self.unlock(commands) {
            self.save();
        } else {
            self.unsaved.0 = true;
        }
    }

    /// Whether anything new was unlocked.
    fn unlock(&mut self, commands: &mut Commands) -> bool {
        unlock_new(commands, &self.stats, &mut self.unlocked, &self.settings)
    }

    fn save(&mut self) {
        save(&mut self.stats, &mut self.unlocked);
        self.unsaved.0 = false;
    }
}

/// The round on the board and what this machine saw of it.
#[derive(bevy::ecs::system::SystemParam)]
pub struct RoundSeen<'w> {
    sim: Res<'w, crate::app::Sim>,
    tally: Res<'w, crate::app::awards::RoundTally>,
}

impl RoundSeen<'_> {
    /// Whether the round's deeds are this player's to be credited for: it
    /// was played here from its first tick, by the rule the results card's
    /// awards go by ([`RoundTally::covers`](crate::app::awards::RoundTally::covers)).
    /// A round resumed from a pasted code began somewhere else, and its
    /// first half (the raids on this castle among it) was never counted
    /// here: counted, it was a dry win on every paste, and a round counted
    /// as often as it was pasted.
    fn whole(&self) -> bool {
        self.tally.covers(&self.sim.0)
    }
}

/// Whether the deeds on the board are this player's to count as they
/// happen: a puzzle's always, a versus round's by [`RoundSeen::whole`],
/// the rule its end goes by. A round resumed from a pasted code counts
/// none: the same code pasted again was the same golden crab banked
/// again, for every trophy that counts them.
#[derive(bevy::ecs::system::SystemParam)]
pub struct DeedsCount<'w> {
    screen: Res<'w, State<crate::app::Screen>>,
    round: RoundSeen<'w>,
}

impl DeedsCount<'_> {
    fn here(&self) -> bool {
        *self.screen.get() != crate::app::Screen::Versus || self.round.whole()
    }
}

/// Fold the sim event stream into the lifetime stats.
pub fn track_events(
    mut commands: Commands,
    mut events: MessageReader<SimEvent>,
    online: Res<Online>,
    controllers: Res<Controllers>,
    counted: DeedsCount,
    mut trophies: Trophies,
    mut scratch: ResMut<RoundScratch>,
) {
    let seat = local_seat(&online, &controllers).filter(|_| counted.here());
    let Some(seat) = seat else {
        for _ in events.read() {}
        return;
    };
    let mut changed = false;
    for event in events.read() {
        match event {
            SimEvent::CrabBanked { owner, kind, .. } if *owner == seat => {
                trophies.stats.banked += 1;
                scratch.banked += 1;
                // Molts and sparkling crabs count where they start what the
                // trophy names (`LureStarted`, `TideEventFired`), because
                // not every one banked does: never in a lure's quiet spell
                // or the wheel's cooldown, and never by Monopoly's sweep.
                match kind {
                    CrabKind::Golden => trophies.stats.golden += 1,
                    CrabKind::Giant => trophies.stats.giants += 1,
                    CrabKind::Common
                    | CrabKind::Juvenile
                    | CrabKind::Molting
                    | CrabKind::Sparkling => {}
                }
                changed = true;
            }
            // The roulette trophy wants variety, so remember *which* events
            // have come up rather than how many. Any seat's sparkling crab
            // spins a wheel everyone plays under, so it says "see", where
            // the count of wheels this seat spun says "spin".
            SimEvent::TideEventFired { event, by } => {
                trophies.stats.events_seen |= 1 << event.index();
                if *by == Some(seat) {
                    trophies.stats.events += 1;
                }
                changed = true;
            }
            SimEvent::LureStarted { owner } if *owner == seat => {
                trophies.stats.lures += 1;
                changed = true;
            }
            SimEvent::CrabEaten { .. } => {
                trophies.stats.gulls_fed += 1;
                changed = true;
            }
            SimEvent::CastleRaided { owner, .. } if *owner == seat => {
                trophies.stats.raids_taken += 1;
                scratch.raids += 1;
                changed = true;
            }
            SimEvent::CrabBanked { .. }
            | SimEvent::LureStarted { .. }
            | SimEvent::CastleRaided { .. }
            | SimEvent::CrabSpawned { .. }
            | SimEvent::GullIncoming { .. }
            | SimEvent::GullArrived
            | SimEvent::GullTookOff
            | SimEvent::GullLanded { .. }
            | SimEvent::GullShooed { .. }
            | SimEvent::GullFlewOff { .. }
            | SimEvent::GoldenCalled { .. }
            | SimEvent::SignpostPlaced { .. }
            | SimEvent::SignpostRemoved { .. }
            | SimEvent::SignpostEvicted { .. }
            | SimEvent::TierUp { .. }
            | SimEvent::SurgeStarted
            | SimEvent::WheelLocked { .. }
            | SimEvent::LureRefused { .. }
            | SimEvent::GoldenOut { .. }
            | SimEvent::RoundEnded => {}
        }
    }
    if changed {
        trophies.tally(&mut commands);
    }
}

/// What a finished round was worth to the local seat, and how it was won.
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
pub(super) struct RoundOutcome {
    pub won: bool,
    /// The round was played against a live opponent over the wire.
    pub online: bool,
    /// This round also decided a series, and the local seat took it.
    pub series: bool,
    /// Which chair the local player sat in, for the trophy that wants the
    /// whole table rather than four wins from the same seat.
    pub seat: u8,
    /// This board played the round to its last tick, so the round scratch
    /// holds all of it: a dry win is claimed on nothing less.
    pub saw_the_end: bool,
}

/// Count a daily round played on `day`'s beach, scoring `score`.
///
/// The day is the one the round was seeded for, handed in rather than read
/// off the clock here: the round ends minutes after it began, and those
/// minutes can cross midnight.
fn credit_daily(stats: &mut Stats, day: u32, score: u32) {
    if stats.daily_day != day {
        // A day's daily played for the first time: that day's best starts
        // over, and the habit counter ticks.
        stats.daily_day = day;
        stats.daily_best = 0;
        stats.daily_days += 1;
    }
    stats.daily_best = stats.daily_best.max(score);
    // And the all-time mark, which is what a trophy can hang on:
    // `daily_best` starts over at midnight and would take the trophy's
    // progress bar back down with it.
    stats.daily_record = stats.daily_record.max(stats.daily_best);
}

/// Tally a finished round for the local seat and clear the round scratch.
///
/// A win with no raid taken is the Dry Castle trophy: the raid counter has
/// to be read before it is cleared, and cleared whatever the result. The
/// round's banked count is the same shape, read for the best-round record
/// and then reset either way.
fn credit_round(stats: &mut Stats, scratch: &mut RoundScratch, outcome: RoundOutcome) {
    stats.best_round = stats.best_round.max(scratch.banked);
    if outcome.won {
        stats.wins += 1;
        if scratch.raids == 0 && outcome.saw_the_end {
            stats.dry_wins += 1;
        }
        if outcome.online {
            stats.online_wins += 1;
        }
        // One bit per chair. `checked_shl` rather than a shift: the seat
        // comes from a session the wire agreed on, and a byte only has
        // eight bits to give.
        stats.seats_won |= 1u8.checked_shl(u32::from(outcome.seat)).unwrap_or(0);
        if outcome.series {
            stats.series_wins += 1;
        }
    }
    *scratch = RoundScratch::default();
}

/// Count a round played, at a table of `seats`: the round itself, the
/// busiest table, and a hosted one.
fn credit_table(stats: &mut Stats, seats: u8, online: &Online) {
    stats.rounds += 1;
    // The busiest table this seat has ever sat at. Seats, not peers: an AI
    // seat still fills a chair and still has a castle to raid.
    stats.crowd = stats.crowd.max(u32::from(seats));
    if online
        .0
        .as_ref()
        .is_some_and(crate::app::net::OnlineSession::is_host)
    {
        stats.hosted += 1;
    }
}

/// A versus round just ended: count it, the win, and the dry-castle win.
pub fn record_round(
    mut commands: Commands,
    round: RoundSeen,
    seating: crate::app::seating::Seating,
    scoring: crate::app::teams::Scoring,
    tournament: Res<crate::app::tournament::Tournament>,
    mut trophies: Trophies,
    mut scratch: ResMut<RoundScratch>,
) {
    let crate::app::seating::Seating {
        seats,
        online,
        controllers,
        ..
    } = seating;
    if !round.whole() {
        *scratch = RoundScratch::default();
        return;
    }
    let Some(seat) = local_seat(&online, &controllers) else {
        return;
    };
    let scores = round.sim.0.scores();
    if scoring.local.daily.active {
        // The day the round was seeded for, not the day it ended on: a
        // round that crosses midnight is yesterday's beach.
        credit_daily(
            &mut trophies.stats,
            scoring.local.daily.day,
            scores[usize::from(seat)],
        );
    }
    let mode = scoring.mode(seats.0);
    let won = scoring.leaders(scores, seats.0)[usize::from(seat)];
    credit_played(
        &mut commands,
        &mut trophies,
        &mut scratch,
        seats.0,
        &online,
        RoundOutcome {
            won,
            online: online.0.is_some(),
            // `record_series_round` runs first, so the series verdict is in.
            // Asked by mode, because a series won in teams is won by every
            // seat on the team - and a per-seat search would find nobody.
            series: tournament.is_decided()
                && tournament
                    .winner(mode, seats.0)
                    .is_some_and(|champion| champion.claims(seat, mode)),
            seat,
            saw_the_end: true,
        },
    );
}

/// Credit a round this machine's seat played at a table of `seats`: the
/// table ([`credit_table`]), the round's `outcome`, and whatever the two
/// unlock.
fn credit_played(
    commands: &mut Commands,
    trophies: &mut Trophies,
    scratch: &mut RoundScratch,
    seats: u8,
    online: &Online,
    outcome: RoundOutcome,
) {
    credit_table(&mut trophies.stats, seats, online);
    credit_round(&mut trophies.stats, scratch, outcome);
    trophies.credit(commands);
}

/// A joiner walked on to the next round before its own board had
/// finished (`follow_the_called_round`): count the round it played, which
/// never reaches the results card [`record_round`] runs on.
///
/// Who won is the host's word, carried in its call
/// ([`Invitation::crowned`](crate::app::net::Invitation::crowned)): the
/// frames this board was missing were never coming, and a bank or a raid
/// in them could still have decided the round. A dry win is not claimed
/// for the same reason, since a raid in those frames went uncounted. Not
/// part of a series' last round, which no call follows.
pub fn record_called_round(
    mut commands: Commands,
    round: RoundSeen,
    seating: crate::app::seating::Seating,
    mut trophies: Trophies,
    mut scratch: ResMut<RoundScratch>,
) {
    let crate::app::seating::Seating {
        seats,
        online,
        controllers,
        ..
    } = seating;
    if !crate::app::session::walked_on(&round.sim.0, &online) || !round.whole() {
        return;
    }
    let (Some(seat), Some(session)) = (local_seat(&online, &controllers), online.0.as_ref()) else {
        return;
    };
    credit_played(
        &mut commands,
        &mut trophies,
        &mut scratch,
        seats.0,
        &online,
        RoundOutcome {
            won: crate::transport::is_crowned(session.crowned, seat),
            online: true,
            series: false,
            seat,
            saw_the_end: false,
        },
    );
}

/// Persist on leaving a play screen so a mid-round quit loses nothing.
pub fn save_now(
    mut stats: ResMut<Stats>,
    mut unlocked: ResMut<Unlocked>,
    mut unsaved: ResMut<Unsaved>,
) {
    save(&mut stats, &mut unlocked);
    unsaved.0 = false;
}

/// Persist what a round has not written yet when the game is closed in
/// the middle of one: quit from the pause card, or the window closed. The
/// screen is never left then, so [`save_now`] does not run.
pub fn save_on_exit(
    mut exits: MessageReader<AppExit>,
    mut stats: ResMut<Stats>,
    mut unlocked: ResMut<Unlocked>,
    mut unsaved: ResMut<Unsaved>,
) {
    if exits.read().count() > 0 && unsaved.0 {
        save(&mut stats, &mut unlocked);
        unsaved.0 = false;
    }
}

/// A level was saved out of the editor: one trophy for building a beach of
/// your own. Its own system rather than a line in the editor, so the editor
/// stays ignorant of achievements.
pub fn record_level_built(
    mut commands: Commands,
    mut saved: MessageReader<crate::app::LevelSaved>,
    mut trophies: Trophies,
) {
    let built = saved.read().count() as u32;
    if built == 0 {
        return;
    }
    trophies.stats.levels_built += built;
    trophies.credit(&mut commands);
}

/// Fresh round: the scratch starts over.
pub fn reset_round_scratch(mut scratch: ResMut<RoundScratch>) {
    *scratch = RoundScratch::default();
}

/// A puzzle was solved.
///
/// Ordered after `progress::record_cleared` so the stage just finished is
/// already counted: the last stage of a campaign is the one this would
/// otherwise miss, and the one the trophy is for. Only the built-in stages
/// count, so saving a level in the editor does not unfinish the campaign.
pub fn record_puzzle(
    mut commands: Commands,
    progress: Res<crate::app::progress::Progress>,
    campaign: Res<crate::app::Campaign>,
    mut attempt: ResMut<PuzzleAttempt>,
    mut trophies: Trophies,
) {
    // A solve is a solve, and the trophies over this one say "solve 100
    // puzzles": re-solving a stage is one of those.
    trophies.stats.puzzles += 1;
    // Read before the campaign sweep below, which is about the whole list
    // rather than this stage.
    credit_stage(
        &mut trophies.stats,
        &mut attempt,
        campaign.current().posts,
        campaign.place().section == crate::app::campaign::Section::Custom,
    );
    // The Tide Pool's own stages: the co-op ladder beside it is for two,
    // and finishing the campaign alone cannot wait on a friend.
    let shipped = campaign.section(crate::app::campaign::Section::TidePool);
    let builtins = &campaign.levels[shipped];
    if !builtins.is_empty() && builtins.iter().all(|level| progress.level_cleared(level)) {
        trophies.stats.campaign_done = 1;
    }
    trophies.credit(&mut commands);
}

/// How a stage was cleared, not merely that it was, and only on a stage
/// that was still unbeaten when the attempt began: these three say
/// "stages", and a stage already in the book is not another one.
///
/// The clear puts the stage in the book, so the attempt stops being
/// unbeaten here, and a restart, which keeps the attempt (same stage, same
/// name), must not set it again: win, R, win again is one stage, not two.
///
/// A spare signpost counts only on a player's own level (`own`, the stage
/// list's section of them): the trophy says "a new stage of yours", and a
/// shipped stage that grants a post it does not need, the tutorial's, is
/// scenery rather than a feat.
fn credit_stage(stats: &mut Stats, attempt: &mut PuzzleAttempt, posts: u8, own: bool) {
    if !std::mem::replace(&mut attempt.unbeaten, false) {
        return;
    }
    if own && attempt.layout.len() < usize::from(posts) {
        stats.under_par += 1;
    }
    if posts >= DEEP_POSTS {
        stats.deep_solves += 1;
    }
    if attempt.retries == 0 && attempt.first_run {
        stats.clean_solves += 1;
    }
}

/// The signpost grant that marks the deep end of the campaign. The late
/// stages hand out five; nothing earlier does.
const DEEP_POSTS: u8 = 5;

/// Count the reloads of the stage in play, so the first-try trophy can tell
/// a clean solve from a solve on the ninth go.
///
/// The first load of a stage is not a retry, which is what the name check
/// is for: entering a stage sends the same message that restarting it does,
/// and only the stage it names tells them apart.
pub fn track_puzzle_attempt(
    mut loads: MessageReader<crate::app::LoadLevel>,
    campaign: Res<crate::app::Campaign>,
    progress: Res<crate::app::progress::Progress>,
    mut attempt: ResMut<PuzzleAttempt>,
) {
    let mut loads = loads.read().count() as u32;
    if loads == 0 {
        return;
    }
    let name = &campaign.current().name;
    if attempt.stage != *name {
        // Read here rather than at the clear, which is the moment it stops
        // being true: the stage trophies ask what this attempt walked up
        // to, not what it left behind.
        attempt.unbeaten = !progress.level_cleared(campaign.current());
        attempt.stage = name.clone();
        attempt.retries = 0;
        attempt.layout.clear();
        loads -= 1;
    }
    attempt.retries += loads;
}

/// A run begins: note what it was given to work with (see
/// `PuzzleAttempt::layout`).
pub fn note_posts_spent(
    sim: Res<crate::app::Sim>,
    campaign: Res<crate::app::Campaign>,
    mut attempt: ResMut<PuzzleAttempt>,
    mut ran: ResMut<StagesRun>,
) {
    attempt.first_run = ran.0.insert(campaign.current().name.clone());
    attempt.layout = sim
        .0
        .tiles()
        .filter_map(|(x, y, _)| {
            let post = sim.0.signpost_at(x, y)?;
            Some((x, y, post.dir, post.owner))
        })
        .collect();
}

/// Entering the puzzle screen starts a fresh attempt: coming back to a
/// stage later is a new go at it, not a continuation of the last one.
pub fn reset_puzzle_attempt(mut attempt: ResMut<PuzzleAttempt>) {
    *attempt = PuzzleAttempt::default();
}

/// A level went out as a share code, or came in as one. Its own system for
/// the reason [`record_level_built`] is one: the editor writes a message
/// and knows nothing about what reads it.
pub fn record_codes(
    mut commands: Commands,
    mut shared: MessageReader<crate::app::CodeShared>,
    mut taken: MessageReader<crate::app::CodeTaken>,
    mut trophies: Trophies,
) {
    let out = shared.read().count() as u32;
    let inn = taken.read().count() as u32;
    if out == 0 && inn == 0 {
        return;
    }
    trophies.stats.codes_shared += out;
    trophies.stats.codes_taken += inn;
    trophies.credit(&mut commands);
}

fn unlock_new(
    commands: &mut Commands,
    stats: &Stats,
    unlocked: &mut Unlocked,
    settings: &GameSettings,
) -> bool {
    let tr = settings.tr();
    let mut any = false;
    for (index, achievement) in ACHIEVEMENTS.iter().enumerate() {
        // `insert` says whether the id was new, so no `contains` before
        // it. The threshold goes first: it is a compare, cheaper than
        // hashing the id, and it keeps the set out of it entirely.
        if !achievement.met(stats) || !unlocked.0.insert(achievement.id) {
            continue;
        }
        any = true;
        spawn_toast(commands, tr.ach_names[index], tr.ach_descs[index]);
    }
    // Saved by the caller, once: every one of them writes the stats it just
    // changed anyway, and a save is a sync to disk on the frame thread.
    // Saving here as well cost two per unlock and three for a double.
    any
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::audio::Muted;
    use bevy::ecs::system::RunSystemOnce;

    fn win() -> RoundOutcome {
        RoundOutcome {
            won: true,
            saw_the_end: true,
            ..RoundOutcome::default()
        }
    }

    fn scratch(raids: u32, banked: u32) -> RoundScratch {
        RoundScratch { raids, banked }
    }

    /// A world `track_events` and `save_on_exit` can run in, with every
    /// trophy already earned or none of them.
    ///
    /// The record on disk starts empty too: a save merges with it, and a
    /// test that builds a second world would have counted the first's
    /// round as well.
    fn tracking(all_unlocked: bool) -> App {
        let _ = std::fs::remove_file(crate::app::achievements::save_path());
        let mut app = App::new();
        app.add_message::<SimEvent>();
        app.add_message::<AppExit>();
        app.init_resource::<Stats>();
        app.init_resource::<RoundScratch>();
        app.init_resource::<Unsaved>();
        app.init_resource::<GameSettings>();
        app.init_resource::<Muted>();
        app.init_resource::<Online>();
        app.init_resource::<Controllers>();
        app.insert_resource(State::new(crate::app::Screen::Puzzle));
        app.insert_resource(crate::app::Sim(crate::sim::Board::new(5, 5, 0)));
        app.init_resource::<crate::app::awards::RoundTally>();
        let mut unlocked = Unlocked::default();
        if all_unlocked {
            unlocked.0.extend(ACHIEVEMENTS.iter().map(|a| a.id));
        }
        app.insert_resource(unlocked);
        app
    }

    fn eaten(app: &mut App) {
        app.world_mut()
            .write_message(SimEvent::CrabEaten { pos: Vec2::ZERO });
        let _ = app.world_mut().run_system_once(track_events);
    }

    /// A crab eaten in the middle of a round is counted and not written:
    /// a save is a sync to disk on the frame thread, and a busy beach
    /// stuttered with one for every crab. It waits for the game to close.
    #[test]
    fn a_change_mid_round_is_kept_until_the_game_closes() {
        let mut app = tracking(true);
        eaten(&mut app);
        assert_eq!(app.world().resource::<Stats>().gulls_fed, 1, "counted");
        assert!(app.world().resource::<Unsaved>().0, "and not written yet");
        // Closing the game writes it.
        app.world_mut().write_message(AppExit::Success);
        let _ = app.world_mut().run_system_once(save_on_exit);
        assert!(
            !app.world().resource::<Unsaved>().0,
            "written on the way out"
        );
    }

    /// One that earns a trophy is written at once, so an unlock the player
    /// was just shown is never lost.
    #[test]
    fn a_change_that_earns_a_trophy_is_written_at_once() {
        let mut app = tracking(false);
        // The first crab home earns the first trophy there is.
        app.world_mut().write_message(SimEvent::CrabBanked {
            id: 0,
            owner: 0,
            pos: Vec2::ZERO,
            keep: Vec2::ZERO,
            points: 1,
            kind: CrabKind::Common,
            handed: crate::sim::Handedness::Right,
        });
        let _ = app.world_mut().run_system_once(track_events);
        assert!(!app.world().resource::<Unlocked>().0.is_empty(), "unlocked");
        assert!(!app.world().resource::<Unsaved>().0, "and written");
    }

    /// Winning untouched earns the dry-castle trophy; winning after a raid
    /// does not; and either way the round's raid count starts over.
    #[test]
    fn a_dry_win_needs_an_unraided_castle() {
        let mut stats = Stats::default();
        let mut round = RoundScratch::default();
        credit_round(&mut stats, &mut round, win());
        assert_eq!((stats.wins, stats.dry_wins), (1, 1));

        let mut round = scratch(2, 0);
        credit_round(&mut stats, &mut round, win());
        assert_eq!((stats.wins, stats.dry_wins), (2, 1), "raided: no trophy");
        assert_eq!(round.raids, 0, "the scratch resets");

        // A loss counts neither, and still clears the scratch.
        let mut round = scratch(5, 0);
        credit_round(&mut stats, &mut round, RoundOutcome::default());
        assert_eq!((stats.wins, stats.dry_wins), (2, 1));
        assert_eq!(round.raids, 0);
    }

    /// The best-round record is the high-water mark of a scratch counter,
    /// so it has to be read before the reset and survive a losing round.
    #[test]
    fn the_best_round_is_a_high_water_mark() {
        let mut stats = Stats::default();
        let mut round = scratch(0, 30);
        credit_round(&mut stats, &mut round, RoundOutcome::default());
        assert_eq!(stats.best_round, 30, "a losing round still counts");
        assert_eq!(round.banked, 0);

        credit_round(&mut stats, &mut scratch(0, 12), win());
        assert_eq!(stats.best_round, 30, "a worse round does not lower it");

        credit_round(&mut stats, &mut scratch(0, 51), win());
        assert_eq!(stats.best_round, 51);
    }

    /// The stage trophies count stages and say so: "clear 10 stages first
    /// try". They used to count clears, so ten goes at stage one were ten
    /// stages, and fell to the easiest stage in the campaign played over
    /// and over.
    #[test]
    fn a_stage_already_beaten_is_not_another_stage() {
        use crate::app::progress::Progress;
        use crate::app::{Campaign, LoadLevel};
        let mut levels = crate::sim::campaign_levels();
        levels.truncate(2);
        let first = levels[0].name.clone();
        let mut app = App::new();
        app.add_message::<LoadLevel>();
        app.init_resource::<PuzzleAttempt>();
        app.init_resource::<Progress>();
        app.insert_resource(Campaign::tide_pool_of(levels));
        app.add_systems(Update, track_puzzle_attempt);
        let load = |app: &mut App| {
            app.world_mut()
                .write_message(LoadLevel { keep_posts: false });
            app.update();
        };
        let unbeaten = |app: &App| app.world().resource::<PuzzleAttempt>().unbeaten;

        load(&mut app);
        assert!(unbeaten(&app), "nothing cleared yet");

        // Clear it, leave, and come back: the same stage, no longer a new one.
        app.world_mut().resource_mut::<Progress>().mark(&first);
        let _ = app.world_mut().run_system_once(reset_puzzle_attempt);
        load(&mut app);
        assert!(!unbeaten(&app), "a stage already in the book");

        // The one behind it is still its own stage.
        app.world_mut().resource_mut::<Campaign>().index = 1;
        load(&mut app);
        assert!(unbeaten(&app), "a stage never played");
    }

    /// Win a stage, restart it with R, win it again: the restart is the
    /// same attempt on the same stage, and the second clear is not another
    /// stage for the stage trophies.
    #[test]
    fn a_stage_won_twice_through_a_restart_counts_once() {
        use crate::app::{Campaign, LoadLevel};
        let mut levels = crate::sim::campaign_levels();
        let deep = levels
            .iter()
            .position(|level| level.posts >= DEEP_POSTS)
            .expect("a deep stage");
        let posts = levels[deep].posts;
        levels.truncate(deep + 1);
        let mut app = App::new();
        app.add_message::<LoadLevel>();
        app.init_resource::<PuzzleAttempt>();
        app.init_resource::<crate::app::progress::Progress>();
        app.insert_resource(Campaign {
            index: deep,
            ..Campaign::tide_pool_of(levels)
        });
        app.add_systems(Update, track_puzzle_attempt);
        let load = |app: &mut App, keep_posts: bool| {
            app.world_mut().write_message(LoadLevel { keep_posts });
            app.update();
        };
        let mut stats = Stats::default();
        let mut clear = |app: &mut App| {
            let mut attempt = app.world_mut().resource_mut::<PuzzleAttempt>();
            // One signpost: well under any deep stage's grant.
            attempt.layout = vec![(0, 0, crate::sim::Direction::Up, 0)];
            attempt.first_run = true;
            credit_stage(&mut stats, &mut attempt, posts, true);
        };

        load(&mut app, false);
        clear(&mut app);
        // R on the result card: the same stage, posts kept.
        load(&mut app, true);
        clear(&mut app);
        assert_eq!(
            (stats.under_par, stats.deep_solves, stats.clean_solves),
            (1, 1, 1),
            "one stage, counted once"
        );
    }

    /// A spare signpost counts on a player's own level and never on a
    /// shipped stage: Welcome Ashore's crab walks home with its post still
    /// in hand, and clearing it so is no trophy. The same level filed
    /// behind the shipped list as the player's own is.
    #[test]
    fn spare_signposts_count_only_on_a_players_own_level() {
        use crate::app::Campaign;
        use crate::app::progress::Progress;
        let mut levels = crate::sim::campaign_levels();
        levels.truncate(1);
        assert_eq!(levels[0].name, "Welcome Ashore");
        assert!(levels[0].posts > 0, "it grants a post");
        levels.push(levels[0].clone());
        let mut app = tracking(true);
        app.init_resource::<Progress>();
        app.insert_resource(Campaign {
            levels,
            index: 0,
            builtins: 1,
            coop: 0,
        });
        let spare = |app: &mut App, index: usize| {
            app.world_mut().resource_mut::<Campaign>().index = index;
            app.insert_resource(PuzzleAttempt {
                unbeaten: true,
                ..PuzzleAttempt::default()
            });
            let _ = app.world_mut().run_system_once(record_puzzle);
            app.world().resource::<Stats>().under_par
        };
        assert_eq!(spare(&mut app, 0), 0, "a shipped stage is not one of yours");
        assert_eq!(spare(&mut app, 1), 1, "a level of the player's own is");
    }

    /// Entering a stage sends the same message that restarting it does, so
    /// the first-try trophy hangs entirely on telling them apart. Backwards
    /// either way it is worthless: it would go to everybody, or to nobody.
    #[test]
    fn the_first_load_of_a_stage_is_not_a_retry() {
        use crate::app::{Campaign, LoadLevel};
        let mut levels = crate::sim::campaign_levels();
        levels.truncate(2);
        let mut app = App::new();
        app.add_message::<LoadLevel>();
        app.init_resource::<PuzzleAttempt>();
        app.init_resource::<crate::app::progress::Progress>();
        app.insert_resource(Campaign::tide_pool_of(levels));
        app.add_systems(Update, track_puzzle_attempt);
        let load = |app: &mut App| {
            app.world_mut()
                .write_message(LoadLevel { keep_posts: false });
            app.update();
        };
        let retries = |app: &App| app.world().resource::<PuzzleAttempt>().retries;

        load(&mut app);
        assert_eq!(retries(&app), 0, "arriving at a stage is not a retry");
        load(&mut app);
        load(&mut app);
        assert_eq!(retries(&app), 2, "two restarts");

        // The next stage is a fresh attempt, not a continuation.
        app.world_mut().resource_mut::<Campaign>().index = 1;
        load(&mut app);
        assert_eq!(retries(&app), 0);
        load(&mut app);
        assert_eq!(retries(&app), 1);

        // And coming back to a stage already played starts over, which is
        // what entering the screen clears the name for.
        let _ = app.world_mut().run_system_once(reset_puzzle_attempt);
        app.world_mut().resource_mut::<Campaign>().index = 0;
        load(&mut app);
        assert_eq!(retries(&app), 0, "a second visit is a fresh attempt");
    }

    /// A stage lost, left for the stage list and come back to: entering the
    /// screen starts a fresh attempt, but not a fresh first run, so the
    /// clear is not "first try".
    #[test]
    fn a_stage_left_and_come_back_to_is_not_a_first_try() {
        use crate::app::Campaign;
        let mut levels = crate::sim::campaign_levels();
        levels.truncate(2);
        let mut app = App::new();
        app.init_resource::<PuzzleAttempt>();
        app.init_resource::<StagesRun>();
        app.insert_resource(crate::app::Sim(crate::sim::Board::new(3, 3, 1)));
        app.insert_resource(Campaign::tide_pool_of(levels));
        let run = |app: &mut App| {
            let _ = app.world_mut().run_system_once(note_posts_spent);
            app.world().resource::<PuzzleAttempt>().first_run
        };
        assert!(run(&mut app), "the first go at a stage");
        let _ = app.world_mut().run_system_once(reset_puzzle_attempt);
        assert!(!run(&mut app), "back after leaving: a second go");
        app.world_mut().resource_mut::<Campaign>().index = 1;
        assert!(run(&mut app), "another stage's first");
    }

    /// The whole-table trophy wants four different chairs, so four wins
    /// from seat 0 light one bit and losing a seat lights none.
    #[test]
    fn the_seat_bitmask_counts_chairs_not_wins() {
        let mut stats = Stats::default();
        for _ in 0..4 {
            credit_round(&mut stats, &mut RoundScratch::default(), win());
        }
        assert_eq!(stats.wins, 4);
        assert_eq!(stats.seats_won, 0b0001, "four wins, one chair");

        for seat in 1..4 {
            credit_round(
                &mut stats,
                &mut RoundScratch::default(),
                RoundOutcome { seat, ..win() },
            );
        }
        assert_eq!(stats.seats_won.count_ones(), 4, "four of the six chairs");

        // A loss lights nothing, whatever chair it was in.
        credit_round(
            &mut stats,
            &mut RoundScratch::default(),
            RoundOutcome {
                seat: 5,
                ..RoundOutcome::default()
            },
        );
        assert_eq!(stats.seats_won.count_ones(), 4);
    }

    /// Online and series wins only count when the round was won, and only
    /// under the circumstances that earned them.
    #[test]
    fn online_and_series_wins_need_the_win() {
        let mut stats = Stats::default();
        // Losing an online series decider earns nothing.
        credit_round(
            &mut stats,
            &mut RoundScratch::default(),
            RoundOutcome {
                won: false,
                online: true,
                series: true,
                seat: 0,
                saw_the_end: true,
            },
        );
        assert_eq!((stats.online_wins, stats.series_wins), (0, 0));

        credit_round(
            &mut stats,
            &mut RoundScratch::default(),
            RoundOutcome {
                won: true,
                online: true,
                series: true,
                seat: 0,
                saw_the_end: true,
            },
        );
        assert_eq!((stats.online_wins, stats.series_wins), (1, 1));

        // A plain local win moves neither.
        credit_round(&mut stats, &mut RoundScratch::default(), win());
        assert_eq!((stats.online_wins, stats.series_wins), (1, 1));
        assert_eq!(stats.wins, 2);
    }

    /// A round played here from its first tick is counted when it ends;
    /// one resumed from a pasted code is not, nor is its dry win: the
    /// raids before the paste were never seen here, and the same code
    /// pasted again was the same round counted again.
    #[test]
    fn a_pasted_round_earns_no_round_stats() {
        use crate::app::awards::{Reading, RoundTally};
        use crate::sim::{MAX_PLAYERS, PlayerAction, generate_arena};
        let idle = [PlayerAction::None; MAX_PLAYERS];
        let ended = |resumed: bool| {
            let mut app = tracking(false);
            app.init_resource::<crate::app::Daily>();
            app.init_resource::<crate::app::tournament::Tournament>();
            app.init_resource::<crate::app::Playback>();
            app.init_resource::<crate::app::SeatNames>();
            app.insert_resource(crate::app::Seats(2));
            let mut board = generate_arena(7, 2, 12, 9);
            let mut tally = RoundTally::default();
            for tick in 0..40 {
                let before = Reading::of(&board);
                board.tick(&idle);
                // Pasted at tick 20: everything before it was played
                // somewhere else.
                if !resumed || tick >= 20 {
                    tally.observe(before, &board, &idle);
                }
            }
            board.set_score(0, 9);
            app.insert_resource(crate::app::Sim(board));
            app.insert_resource(tally);
            let _ = app.world_mut().run_system_once(record_round);
            let stats = app.world().resource::<Stats>();
            (stats.rounds, stats.wins, stats.dry_wins)
        };
        assert_eq!(ended(false), (1, 1, 1), "played whole, an unraided win");
        assert_eq!(ended(true), (0, 0, 0), "pasted half way");
    }

    /// A versus round resumed from a pasted code counts no deeds as they
    /// happen either, by the rule its end goes by: a code pasted again
    /// was the same crabs counted again. One played whole counts them.
    #[test]
    fn a_pasted_round_counts_no_deeds() {
        use crate::app::awards::{Reading, RoundTally};
        use crate::sim::{MAX_PLAYERS, PlayerAction, generate_arena};
        let idle = [PlayerAction::None; MAX_PLAYERS];
        let fed = |resumed: bool| {
            let mut app = tracking(false);
            app.insert_resource(State::new(crate::app::Screen::Versus));
            let mut board = generate_arena(7, 2, 12, 9);
            let mut tally = RoundTally::default();
            for tick in 0..40 {
                let before = Reading::of(&board);
                board.tick(&idle);
                if !resumed || tick >= 20 {
                    tally.observe(before, &board, &idle);
                }
            }
            app.insert_resource(crate::app::Sim(board));
            app.insert_resource(tally);
            eaten(&mut app);
            app.world().resource::<Stats>().gulls_fed
        };
        assert_eq!(fed(false), 1, "played whole");
        assert_eq!(fed(true), 0, "pasted half way");
    }

    /// A joiner walked on to the next round a frame short of the tide
    /// never sees its results card: the round it played is counted all
    /// the same, won or lost as the host's card crowned it, without a dry
    /// win it cannot vouch for. A board that did finish is left to the
    /// card, which counts it once.
    #[test]
    fn a_round_walked_on_from_is_counted_on_the_hosts_word() {
        use crate::app::awards::{Reading, RoundTally};
        use crate::sim::{MAX_PLAYERS, PlayerAction, generate_arena};
        use crate::transport::{MatchTerms, UdpTransport};
        let idle = [PlayerAction::None; MAX_PLAYERS];
        let walked_on = |crowned: u8, finished: bool| {
            let mut app = tracking(false);
            app.init_resource::<crate::app::Playback>();
            app.init_resource::<crate::app::SeatNames>();
            app.insert_resource(crate::app::Seats(2));
            // This peer played seat 1; the call has re-dealt it seat 2 of
            // the next round already, which is not the seat to count.
            let mut controllers = Controllers([SeatController::Remote; MAX_PLAYERS]);
            controllers.0[1] = SeatController::Local;
            app.insert_resource(controllers);
            let mut joiner = crate::app::net::OnlineSession::new(
                UdpTransport::host(0).expect("socket"),
                crate::sim::Lockstep::new(2, vec![0, 1, 2], crate::sim::DEFAULT_DELAY),
                2,
                MatchTerms::default(),
            );
            joiner.next_round = true;
            joiner.crowned = crowned;
            app.insert_resource(Online(Some(joiner)));
            let mut board = generate_arena(7, 2, 12, 9);
            let mut tally = RoundTally::default();
            let ticks = if finished { u64::MAX } else { 40 };
            while board.ticks() < ticks && !board.round_over() {
                let before = Reading::of(&board);
                board.tick(&idle);
                tally.observe(before, &board, &idle);
            }
            app.insert_resource(crate::app::Sim(board));
            app.insert_resource(tally);
            let _ = app.world_mut().run_system_once(record_called_round);
            let stats = app.world().resource::<Stats>();
            (stats.rounds, stats.wins, stats.dry_wins, stats.online_wins)
        };
        assert_eq!(walked_on(0b10, false), (1, 1, 0, 1), "seat 1 crowned");
        assert_eq!(walked_on(0b01, false), (1, 0, 0, 0), "seat 0 crowned");
        assert_eq!(walked_on(0b10, true), (0, 0, 0, 0), "the card's to count");
    }

    /// A daily is counted under the day it was seeded for. A round begun
    /// before midnight and finished after it is yesterday's beach, and
    /// counting it under the new day started today's best on a score made
    /// somewhere else.
    #[test]
    fn a_daily_counts_on_the_day_it_was_seeded_for() {
        let mut stats = Stats::default();
        credit_daily(&mut stats, 100, 12);
        assert_eq!(
            (stats.daily_day, stats.daily_best, stats.daily_days),
            (100, 12, 1)
        );
        // Another round on day 100's beach, ending after midnight: still
        // day 100, the same day's best, no second day on the habit counter.
        credit_daily(&mut stats, 100, 30);
        assert_eq!(
            (stats.daily_day, stats.daily_best, stats.daily_days),
            (100, 30, 1)
        );
        // Day 101's own beach starts its best over and counts a new day,
        // and the all-time record keeps the higher mark.
        credit_daily(&mut stats, 101, 5);
        assert_eq!(
            (stats.daily_day, stats.daily_best, stats.daily_days),
            (101, 5, 2)
        );
        assert_eq!(stats.daily_record, 30);
    }
}