tetro-tui 3.2.2

A terminal-based but modern tetromino-stacking game that is very customizable and cross-platform.
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
use std::{
    io::{self, Write},
    num::NonZeroU32,
    time::Duration,
};

use crossterm::{
    cursor::MoveTo,
    event::{
        self, Event, KeyCode, KeyEvent,
        KeyEventKind::{Press, Repeat},
        KeyModifiers,
    },
    style::{Print, PrintStyledContent, Stylize},
    terminal::{Clear, ClearType},
    QueueableCommand,
};
use falling_tetromino_engine::{
    DelayParameters, ExtDuration, ExtNonNegF64, Game, GameLimits, InGameTime, Stat,
};

use crate::{
    fmt_helpers::{fmt_duration, fmt_hertz, fmt_player_input, BoolAsOnOff},
    game_modding::{self, Combo},
    game_mode_presets::GameModePreset,
    game_renderers::{Renderer, TetroTUIRenderer},
    game_restoration::{GameRestorationData, RawInputHistory},
    tui_menus::{title_bar, Menu, MenuUpdate},
    tui_settings::{GameModePreferences, GameplaySettings},
    Application, GameMetaData, GameSave,
};

impl<T: Write> Application<T> {
    pub fn run_menu_new_game(&mut self) -> io::Result<MenuUpdate> {
        let mut selected = 0usize;
        let mut customization_selected = 0usize;

        let lowerbound_cheese = NonZeroU32::new(10).unwrap();
        let lowerbound_combo = NonZeroU32::new(10).unwrap();

        let d_time = Duration::from_secs(5);
        let d_score = 10;
        let d_pieces = 1;
        let d_lines = 1;

        let d_fall_delay: ExtDuration = Duration::from_millis(10).into();
        let mult_fall_delay: ExtNonNegF64 = ExtNonNegF64::new(10.0).unwrap();
        let lowerbound_fall_delay: ExtDuration = Duration::from_secs_f64(1e-9).into();
        let upperbound_fall_delay: ExtDuration = Duration::from_secs_f64(100.0).into();

        loop {
            // First part: rendering the menu.
            let w_main = Self::W_MAIN.into();
            let (x_main, y_main) = Self::viewport_offset();
            let y_selection = Self::H_MAIN / 5;

            let game_modes = self.available_base_game_modes();

            let game_save_available = if !self.game_saves.slots.is_empty() {
                1
            } else {
                0
            };
            let idx_cheese = 3;
            let idx_combo = 4;
            let idx_custom = game_modes.len();
            let opt_idx_game_save =
                (!self.game_saves.slots.is_empty()).then_some(game_modes.len() + 1);

            // Normal presets + 2 spaces if game_save option available + custom preset.
            let selection_len = game_modes.len() + game_save_available + 1;
            // There are four columns for the custom stat selection.
            let customization_selection_size = 4;
            selected %= selection_len;
            customization_selected %= customization_selection_size;
            // Render menu title.
            self.term
                .queue(Clear(ClearType::All))?
                .queue(MoveTo(x_main, y_main + y_selection))?
                .queue(PrintStyledContent(
                    format!("{:^w_main$}", "+ Start New Game +").bold(),
                ))?
                .queue(MoveTo(x_main, y_main + y_selection + 2))?
                .queue(Print(format!("{:^w_main$}", title_bar(&self.settings))))?;
            // Render normal and special game modes.
            for (
                i,
                GameModePreset {
                    title,
                    description,
                    stat_and_order_desc: _,
                    build: _,
                },
            ) in game_modes.iter().enumerate()
            {
                self.term
                    .queue(MoveTo(
                        x_main,
                        y_main + y_selection + 4 + u16::try_from(i).unwrap(),
                    ))?
                    .queue(Print(format!(
                        "{:^w_main$}",
                        if i == selected {
                            format!(">> {title}: {description} <<")
                        } else {
                            title.to_string()
                        }
                    )))?;
            }
            // Render custom mode option.
            self.term
                .queue(MoveTo(
                    x_main,
                    y_main + y_selection + 3 + u16::try_from(game_modes.len() + 2).unwrap(),
                ))?
                .queue(Print(format!(
                    "{:^w_main$}",
                    if selected == idx_custom {
                        format!(
                            "{:<42}",
                            format!(
                                "{} Custom: [Del]=reset{}{}",
                                if customization_selected == 0 {
                                    ">>"
                                } else {
                                    " |"
                                },
                                if self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .seed
                                    .is_some()
                                {
                                    " *seed"
                                } else {
                                    ""
                                },
                                if self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .start_board
                                    .is_some()
                                {
                                    " *board"
                                } else {
                                    ""
                                },
                            ),
                        )
                    } else {
                        "Custom".to_owned()
                    }
                )))?;
            // Render custom mode stuff.
            if selected == idx_custom {
                let stats_strs = [
                    format!(
                        "| Initial fall delay = {:?}s (Gravity: {})",
                        self.settings
                            .game_mode_preferences
                            .custom_config
                            .fall_params
                            .base_delay()
                            .as_secs_ennf64()
                            .get(),
                        fmt_hertz(
                            self.settings
                                .game_mode_preferences
                                .custom_config
                                .fall_params
                                .base_delay()
                                .as_hertz()
                        ),
                    ),
                    format!(
                        "| Progressive gravity = {}",
                        (!self
                            .settings
                            .game_mode_preferences
                            .custom_config
                            .fall_params
                            .is_constant())
                        .on_off()
                    ),
                    format!(
                        "| Limit = {:?} [→]",
                        self.settings
                            .game_mode_preferences
                            .custom_config
                            .win_condition
                    ),
                ];
                for (j, stat_str) in stats_strs.into_iter().enumerate() {
                    self.term
                        .queue(MoveTo(
                            x_main + 16 + 4 * u16::try_from(j).unwrap(),
                            y_main
                                + y_selection
                                + 3
                                + u16::try_from(1 + j + game_modes.len() + 2).unwrap(),
                        ))?
                        .queue(Print(if j + 1 == customization_selected {
                            format!(
                                ">{stat_str}{}",
                                if customization_selected != 3
                                    || self
                                        .settings
                                        .game_mode_preferences
                                        .custom_config
                                        .win_condition
                                        .is_some()
                                {
                                    " [↓|↑]"
                                } else {
                                    ""
                                }
                            )
                        } else {
                            stat_str
                        }))?;
                }
            }

            // Render load game save option.
            if let Some(GameSave {
                game_meta_data,
                game_restoration_data: GameRestorationData { input_history, .. },
                inputs_to_load,
            }) = &self.game_saves.get()
            {
                let load_title = &game_meta_data.title;
                let load_offset_max = input_history.inputs.len();
                self.term
                    .queue(MoveTo(
                        x_main,
                        y_main + y_selection + 4 + u16::try_from(game_modes.len() + 1).unwrap() + if selected == idx_custom { 5 } else { 2 },
                    ))?
                    .queue(Print(format!(
                        "{:^w_main$}",
                        if Some(selected) == opt_idx_game_save {
                            if *inputs_to_load == 0 {
                                format!(">> Load {load_title} from beginning [Del] <<")
                            } else {
                                let (load_time, load_input) = input_history.inputs[(inputs_to_load - 1) % input_history.inputs.len()];
                                let load_time = fmt_duration(load_time);
                                let load_input = fmt_player_input(load_input, self.settings.tui_style().buttonsglyphs);
                                format!(">> Load {load_title} from input {inputs_to_load}/{load_offset_max} ({load_input} @ {load_time}) [Del] <<")
                            }
                        } else {
                            format!("Game save ({load_title})")
                        },
                    )))?;
            }

            self.term.flush()?;
            // Wait for new input.
            let mut immediately_start_new_game = false;
            match event::read()? {
                // Quit app.
                Event::Key(KeyEvent {
                    code: KeyCode::Char('c' | 'C'),
                    modifiers: KeyModifiers::CONTROL,
                    kind: Press | Repeat,
                    state: _,
                }) => break Ok(MenuUpdate::Push(Menu::Quit)),

                // Exit menu.
                Event::Key(KeyEvent {
                    code: KeyCode::Esc | KeyCode::Char('q' | 'Q') | KeyCode::Backspace,
                    kind: Press,
                    ..
                }) => break Ok(MenuUpdate::Pop),

                // Try select mode.
                Event::Key(KeyEvent {
                    code: KeyCode::Enter | KeyCode::Char('e' | 'E'),
                    kind: Press,
                    modifiers,
                    ..
                }) => {
                    if modifiers.contains(KeyModifiers::ALT) {
                        if let Some(GameSave {
                            game_meta_data,
                            game_restoration_data,
                            inputs_to_load: _,
                        }) = &self.game_saves.slots.get(self.game_saves.selected)
                        {
                            let replay_length = if let Some((time, _)) =
                                game_restoration_data.input_history.inputs.last()
                            {
                                *time
                            } else {
                                Duration::ZERO
                            };
                            break Ok(MenuUpdate::Push(Menu::ReplayGame {
                                game_restoration_data: Box::new(game_restoration_data.clone()),
                                game_meta_data: game_meta_data.clone(),
                                replay_length,
                                game_renderer: Box::new(TetroTUIRenderer::with_number(
                                    self.temp_data.renderer_used,
                                )),
                            }));
                        }
                    }
                    immediately_start_new_game = true;
                }

                // Move selector up or increase stat.
                Event::Key(KeyEvent {
                    code: KeyCode::Up | KeyCode::Char('k' | 'K'),
                    kind: Press | Repeat,
                    modifiers,
                    ..
                }) => {
                    if customization_selected > 0 {
                        match customization_selected {
                            1 => {
                                // Increase custom fall delay.
                                let base_delay = self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params
                                    .base_delay();

                                let new_base_delay = if base_delay.is_zero() {
                                    // Bootstrap from zero to baseline.
                                    if modifiers.contains(KeyModifiers::ALT) {
                                        lowerbound_fall_delay
                                    } else {
                                        d_fall_delay
                                    }
                                } else if base_delay.is_infinite() {
                                    // Already at max.
                                    base_delay
                                } else {
                                    // Naïvely increase first.
                                    let new_base_delay = if modifiers.contains(KeyModifiers::ALT) {
                                        base_delay.mul_ennf64(mult_fall_delay)
                                    } else {
                                        base_delay + d_fall_delay
                                    };
                                    // Manually cap.
                                    if new_base_delay > upperbound_fall_delay {
                                        ExtDuration::Infinite
                                    } else {
                                        new_base_delay
                                    }
                                };

                                // Adjust lock curve to either be decreasing or infinite as well.
                                self.settings
                                    .game_mode_preferences
                                    .custom_config
                                    .lock_params = if new_base_delay.is_infinite() {
                                    DelayParameters::constant(ExtDuration::Infinite)
                                } else {
                                    DelayParameters::standard_lock()
                                };

                                // Get previous fall lowerbound.
                                let lowerbound = self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params
                                    .lowerbound();

                                self.settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params = self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params
                                    .with_bounds(new_base_delay, lowerbound)
                                    .unwrap_or_else(DelayParameters::standard_fall);
                                // Normally lowerbound is 0, can only enter this if config was modified.
                            }
                            2 => {
                                // Toggle decreasing fall/lock delay.
                                let (ftemp, ltemp) = if self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params
                                    .is_constant()
                                {
                                    (
                                        DelayParameters::standard_fall(),
                                        DelayParameters::standard_lock(),
                                    )
                                } else {
                                    // Note delay args don't matter, we're interested in constant factor and subtrahend coefficients not the delay.
                                    (
                                        DelayParameters::constant(Default::default()),
                                        DelayParameters::constant(Default::default()),
                                    )
                                };
                                self.settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params = self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params
                                    .with_coefficients(ftemp.factor(), ftemp.subtrahend())
                                    .unwrap();
                                self.settings
                                    .game_mode_preferences
                                    .custom_config
                                    .lock_params = self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .lock_params
                                    .with_coefficients(ltemp.factor(), ltemp.subtrahend())
                                    .unwrap();
                            }
                            3 => {
                                match self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .win_condition
                                {
                                    Some(Stat::TimeElapsed(ref mut t)) => {
                                        *t += d_time;
                                    }
                                    Some(Stat::PiecesLocked(ref mut p)) => {
                                        *p += d_pieces;
                                    }
                                    Some(Stat::LinesCleared(ref mut l)) => {
                                        *l += d_lines;
                                    }
                                    Some(Stat::PointsScored(ref mut s)) => {
                                        *s += d_score;
                                    }
                                    None => {}
                                };
                            }
                            _ => unreachable!(),
                        }
                    } else {
                        selected += selection_len - 1;
                    }
                }

                // Move selector down or decrease stat.
                Event::Key(KeyEvent {
                    code: KeyCode::Down | KeyCode::Char('j' | 'J'),
                    kind: Press | Repeat,
                    modifiers,
                    ..
                }) => {
                    // Selected custom stat; decrease it.
                    if customization_selected > 0 {
                        match customization_selected {
                            1 => {
                                // Increase custom fall delay.
                                let base_delay = self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params
                                    .base_delay();

                                let new_base_delay = if base_delay.is_zero() {
                                    // Already at zero, leave it.
                                    base_delay
                                } else if base_delay.is_infinite() {
                                    // Bootstrap(?) it down from infinity to upper bound.
                                    upperbound_fall_delay
                                } else {
                                    // Naïvely decrease first.
                                    let new_base_delay = if modifiers.contains(KeyModifiers::ALT) {
                                        base_delay.div_ennf64(mult_fall_delay)
                                    } else {
                                        base_delay.saturating_sub(d_fall_delay)
                                    };
                                    // Manually cap.
                                    if new_base_delay < lowerbound_fall_delay {
                                        ExtDuration::ZERO
                                    } else {
                                        new_base_delay
                                    }
                                };

                                // Adjust lock curve to either be decreasing or infinite as well.
                                self.settings
                                    .game_mode_preferences
                                    .custom_config
                                    .lock_params = if new_base_delay.is_infinite() {
                                    DelayParameters::constant(ExtDuration::Infinite)
                                } else {
                                    DelayParameters::standard_lock()
                                };

                                let lowerbound = self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params
                                    .lowerbound();

                                self.settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params = self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params
                                    .with_bounds(new_base_delay, lowerbound)
                                    .unwrap_or_else(DelayParameters::standard_fall);
                                // Normally lowerbound is 0, can only enter this if config was modified.
                            }
                            2 => {
                                // Toggle decreasing fall/lock delay.
                                let (ftemp, ltemp) = if self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params
                                    .is_constant()
                                {
                                    (
                                        DelayParameters::standard_fall(),
                                        DelayParameters::standard_lock(),
                                    )
                                } else {
                                    // Note delay args don't matter, we're interested in constant factor and subtrahend coefficients not the delay.
                                    (
                                        DelayParameters::constant(Default::default()),
                                        DelayParameters::constant(Default::default()),
                                    )
                                };
                                self.settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params = self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .fall_params
                                    .with_coefficients(ftemp.factor(), ftemp.subtrahend())
                                    .unwrap();
                                self.settings
                                    .game_mode_preferences
                                    .custom_config
                                    .lock_params = self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .lock_params
                                    .with_coefficients(ltemp.factor(), ltemp.subtrahend())
                                    .unwrap();
                            }
                            3 => {
                                match self
                                    .settings
                                    .game_mode_preferences
                                    .custom_config
                                    .win_condition
                                {
                                    Some(Stat::TimeElapsed(ref mut t)) => {
                                        *t = t.saturating_sub(d_time);
                                    }
                                    Some(Stat::PiecesLocked(ref mut p)) => {
                                        *p = p.saturating_sub(d_pieces);
                                    }
                                    Some(Stat::LinesCleared(ref mut l)) => {
                                        *l = l.saturating_sub(d_lines);
                                    }
                                    Some(Stat::PointsScored(ref mut s)) => {
                                        *s = s.saturating_sub(d_score);
                                    }
                                    None => {}
                                };
                            }
                            _ => unreachable!(),
                        }
                    // Move gamemode selector
                    } else {
                        selected += 1;
                    }
                }

                // Move selector left (select stat).
                Event::Key(KeyEvent {
                    code: KeyCode::Left | KeyCode::Char('h' | 'H'),
                    kind: Press | Repeat,
                    modifiers,
                    ..
                }) => {
                    if selected == idx_custom && customization_selected > 0 {
                        customization_selected += customization_selection_size - 1
                    } else if selected == idx_cheese {
                        if let Some(limit) = self.settings.game_mode_preferences.cheese_config.limit
                        {
                            self.settings.game_mode_preferences.cheese_config.limit =
                                if limit > lowerbound_cheese {
                                    NonZeroU32::try_from(limit.get() - 1).ok()
                                } else {
                                    None
                                };
                        }
                    } else if selected == idx_combo {
                        if modifiers.contains(KeyModifiers::ALT) {
                            let new_layout_idx = if let Some(i) =
                                Combo::LAYOUTS.iter().position(|lay| {
                                    *lay == self
                                        .settings
                                        .game_mode_preferences
                                        .combo_config
                                        .start_layout
                                }) {
                                let layout_cnt = Combo::LAYOUTS.len();
                                (i + layout_cnt - 1) % layout_cnt
                            } else {
                                0
                            };
                            self.settings
                                .game_mode_preferences
                                .combo_config
                                .start_layout = Combo::LAYOUTS[new_layout_idx];
                        } else if let Some(limit) =
                            self.settings.game_mode_preferences.combo_config.limit
                        {
                            self.settings.game_mode_preferences.combo_config.limit =
                                if limit > lowerbound_combo {
                                    NonZeroU32::try_from(limit.get() - 1).ok()
                                } else {
                                    None
                                };
                        }
                    } else if Some(selected) == opt_idx_game_save {
                        if let Some(GameSave {
                            game_restoration_data: GameRestorationData { input_history, .. },
                            inputs_to_load,
                            ..
                        }) = self.game_saves.get_mut()
                        {
                            *inputs_to_load += input_history.inputs.len()
                                * if modifiers.contains(KeyModifiers::ALT) {
                                    20
                                } else {
                                    1
                                };
                            *inputs_to_load %= input_history.inputs.len() + 1;
                        }
                    }
                }

                // Reload from savefile.
                Event::Key(KeyEvent {
                    code: KeyCode::Char('l' | 'L'),
                    modifiers,
                    kind: Press | Repeat,
                    ..
                }) if { modifiers.contains(KeyModifiers::CONTROL.union(KeyModifiers::ALT)) } => {
                    self.temp_data.loadfile_result = self.savefile_load();
                }

                // Store to savefile.
                Event::Key(KeyEvent {
                    code: KeyCode::Char('s' | 'S'),
                    modifiers,
                    kind: Press | Repeat,
                    ..
                }) if { modifiers.contains(KeyModifiers::CONTROL.union(KeyModifiers::ALT)) } => {
                    self.temp_data.storefile_result = self.savefile_store();
                }

                // Move selector right (select stat).
                Event::Key(KeyEvent {
                    code: KeyCode::Right | KeyCode::Char('l' | 'L'),
                    kind: Press | Repeat,
                    modifiers,
                    ..
                }) => {
                    // If custom gamemode selected, allow incrementing stat selection.
                    if selected == idx_custom {
                        // If reached last stat, cycle through stats for limit.
                        if customization_selected == customization_selection_size - 1 {
                            self.settings
                                .game_mode_preferences
                                .custom_config
                                .win_condition = match self
                                .settings
                                .game_mode_preferences
                                .custom_config
                                .win_condition
                            {
                                Some(Stat::TimeElapsed(_)) => Some(Stat::PointsScored(200)),
                                Some(Stat::PointsScored(_)) => Some(Stat::PiecesLocked(100)),
                                Some(Stat::PiecesLocked(_)) => Some(Stat::LinesCleared(40)),
                                Some(Stat::LinesCleared(_)) => None,
                                None => Some(Stat::TimeElapsed(Duration::from_secs(300))),
                            };
                        } else {
                            customization_selected += 1
                        }
                    } else if selected == idx_cheese {
                        self.settings.game_mode_preferences.cheese_config.limit =
                            if let Some(limit) =
                                self.settings.game_mode_preferences.cheese_config.limit
                            {
                                limit.checked_add(1)
                            } else {
                                Some(lowerbound_cheese)
                            };
                    } else if selected == idx_combo {
                        if modifiers.contains(KeyModifiers::ALT) {
                            let new_layout_idx = if let Some(i) =
                                Combo::LAYOUTS.iter().position(|lay| {
                                    *lay == self
                                        .settings
                                        .game_mode_preferences
                                        .combo_config
                                        .start_layout
                                }) {
                                let layout_cnt = Combo::LAYOUTS.len();
                                (i + 1) % layout_cnt
                            } else {
                                0
                            };
                            self.settings
                                .game_mode_preferences
                                .combo_config
                                .start_layout = Combo::LAYOUTS[new_layout_idx];
                        } else {
                            self.settings.game_mode_preferences.combo_config.limit =
                                if let Some(limit) =
                                    self.settings.game_mode_preferences.combo_config.limit
                                {
                                    limit.checked_add(1)
                                } else {
                                    Some(lowerbound_combo)
                                };
                        }
                    } else if Some(selected) == opt_idx_game_save {
                        if let Some(GameSave {
                            game_restoration_data: GameRestorationData { input_history, .. },
                            inputs_to_load,
                            ..
                        }) = self.game_saves.get_mut()
                        {
                            *inputs_to_load += if modifiers.contains(KeyModifiers::ALT) {
                                20
                            } else {
                                1
                            };
                            *inputs_to_load %= input_history.inputs.len() + 1;
                        }
                    }
                }

                // Load first input for game save.
                Event::Key(KeyEvent {
                    code: KeyCode::Home,
                    kind: Press | Repeat,
                    ..
                }) => {
                    if Some(selected) == opt_idx_game_save {
                        if let Some(GameSave { inputs_to_load, .. }) = self.game_saves.get_mut() {
                            *inputs_to_load = 0;
                        }
                    }
                }

                // Load last input for game save.
                Event::Key(KeyEvent {
                    code: KeyCode::End,
                    kind: Press | Repeat,
                    ..
                }) => {
                    if Some(selected) == opt_idx_game_save {
                        if let Some(GameSave {
                            game_restoration_data: GameRestorationData { input_history, .. },
                            inputs_to_load,
                            ..
                        }) = self.game_saves.get_mut()
                        {
                            *inputs_to_load = input_history.inputs.len();
                        }
                    }
                }

                // Move selector right (select stat).
                Event::Key(KeyEvent {
                    code: KeyCode::Delete | KeyCode::Char('d' | 'D'),
                    kind: Press | Repeat,
                    modifiers,
                    ..
                }) => {
                    if selected == idx_custom {
                        self.settings.game_mode_preferences.custom_config.seed = None;
                        self.settings
                            .game_mode_preferences
                            .custom_config
                            .start_board = None;
                        self.settings
                            .game_mode_preferences
                            .custom_config
                            .fall_params = DelayParameters::standard_fall();
                        self.settings
                            .game_mode_preferences
                            .custom_config
                            .lock_params = DelayParameters::standard_lock();
                        self.settings
                            .game_mode_preferences
                            .custom_config
                            .win_condition = None;
                    } else if selected == idx_cheese {
                        self.settings.game_mode_preferences.cheese_config.limit =
                            GameModePreferences::default().cheese_config.limit;
                    } else if selected == idx_combo {
                        if modifiers.contains(KeyModifiers::ALT) {
                            self.settings
                                .game_mode_preferences
                                .combo_config
                                .start_layout = Combo::LAYOUTS[0];
                        } else {
                            self.settings.game_mode_preferences.combo_config.limit =
                                GameModePreferences::default().combo_config.limit;
                        }
                    } else if Some(selected) == opt_idx_game_save {
                        self.game_saves.slots.remove(self.game_saves.selected);
                        self.game_saves.selected = 0;
                    }
                }

                Event::Key(KeyEvent {
                    code: KeyCode::Char(c @ '0'..='9'),
                    kind: Press | Repeat,
                    ..
                }) => {
                    let n = c.to_digit(10).unwrap() as usize;
                    if n <= selection_len {
                        selected = if n == 0 { 10 - 1 } else { n - 1 };
                        immediately_start_new_game = true;
                    }
                }

                // Secret - This unlocks things.
                Event::Key(KeyEvent {
                    code: KeyCode::Char('u' | 'U'),
                    modifiers: KeyModifiers::CONTROL,
                    kind: Press | Repeat,
                    ..
                }) => {
                    self.settings.game_mode_preferences.master_mode_unlocked = true;
                    self.settings
                        .game_mode_preferences
                        .experimental_mode_unlocked = true;
                }

                // Other event: don't care.
                _ => {}
            }

            if immediately_start_new_game {
                let game_menu = self.create_game_menu(selected);
                self.statistics.new_games_started += 1;

                break Ok(MenuUpdate::Push(game_menu));
            }
        }
    }

    pub fn available_base_game_modes(&self) -> Vec<GameModePreset> {
        let mut game_modes = vec![
            GameModePreset::swift(),
            GameModePreset::classic(),
            GameModePreset::puzzle(),
            GameModePreset::cheese(
                self.settings.game_mode_preferences.cheese_config,
                self.settings
                    .game_mode_preferences
                    .cheese_fall_and_lock_delays,
            ),
            GameModePreset::combo(self.settings.game_mode_preferences.combo_config),
        ];

        if self.settings.game_mode_preferences.master_mode_unlocked {
            game_modes.insert(2, GameModePreset::master());
        }

        if self
            .settings
            .game_mode_preferences
            .experimental_mode_unlocked
        {
            game_modes.push(GameModePreset::ascent())
        }

        game_modes
    }

    pub fn create_game_menu(&self, selection: usize) -> Menu {
        let game_modes = self.available_base_game_modes();

        let GameplaySettings {
            rotsys,
            tetgen,
            preview: prev,
            das,
            arr,
            sdf,
            lcd,
            are,
            initsys,
            dtapfinesse: _,
        } = *self.settings.gameplay();

        let mut builder = Game::builder();

        builder
            .rotation_system(rotsys)
            .tetromino_generator(tetgen)
            .generate_piece_preview(prev)
            .delayed_auto_shift(das)
            .auto_repeat_rate(arr)
            .soft_drop_factor(sdf)
            .line_clear_duration(lcd)
            .spawn_delay(are)
            .allow_spawn_manipulation(initsys);

        let (game_meta_data, mut game, raw_input_history) = if selection < game_modes.len() {
            // Build one of the selected game modes.
            let GameModePreset {
                title,
                description: _,
                stat_and_order_desc,
                build,
            } = &game_modes[selection];

            let preset_game = build(&builder);

            let preset_game_meta_data = GameMetaData {
                datetime: chrono::Utc::now().format("%Y-%m-%d_%H:%M").to_string(),
                title: title.to_owned(),
                stat_and_desc_order: *stat_and_order_desc,
            };

            let blank_input_history = RawInputHistory::default();

            (preset_game_meta_data, preset_game, blank_input_history)
        } else if selection == game_modes.len() + 1 && self.game_saves.get().is_some() {
            // Load saved game.
            // SAFETY: `self.game_saves.get().is_some()`.
            let GameSave {
                game_meta_data,
                game_restoration_data,
                inputs_to_load,
            } = &self.game_saves.get().unwrap();

            let restored_game = game_restoration_data.restore(*inputs_to_load);

            let mut restored_game_meta_data = game_meta_data.clone();
            // Mark restored game as such.
            restored_game_meta_data.title.push('\'');

            let restored_input_history = game_restoration_data
                .input_history
                .inputs
                .iter()
                .take(*inputs_to_load)
                .copied()
                .collect::<Vec<_>>()
                .into();

            (
                restored_game_meta_data,
                restored_game,
                restored_input_history,
            )
        } else {
            // Build custom game.
            let n = &self.settings.game_mode_preferences;

            builder
                .fall_delay_params(n.custom_config.fall_params)
                .lock_delay_params(n.custom_config.lock_params)
                .game_limits(match n.custom_config.win_condition {
                    Some(stat) => GameLimits::single(stat, true),
                    None => GameLimits::new(),
                });

            // Optionally load custom seed.
            if let Some(seed) = n.custom_config.seed {
                builder.seed(seed);
            }

            // Optionally load custom board.
            let new_custom_game = if let Some(encoded_board) = &n.custom_config.start_board {
                game_modding::StartBoard::build(&builder, encoded_board.clone())
            // Otherwise just build a normal custom game.
            } else {
                builder.build()
            };

            let title = match n.custom_config.win_condition {
                Some(stat) => match stat {
                    Stat::TimeElapsed(duration) => format!("Time-{}s", duration.as_secs()),
                    Stat::PiecesLocked(p) => format!("Pieces-{p}"),
                    Stat::LinesCleared(l) => format!("Lines-{l}"),
                    Stat::PointsScored(s) => format!("Score-{s}"),
                },
                None => "Limitless".to_owned(),
            };

            let custom_game_meta_data = GameMetaData {
                datetime: chrono::Utc::now().format("%Y-%m-%d_%H:%M").to_string(),
                title,
                stat_and_desc_order: (Stat::PointsScored(0), false),
            };
            let blank_input_history = RawInputHistory::default();
            (
                /*success or just fallback?: selection == game_modes.len(),*/
                custom_game_meta_data,
                new_custom_game,
                blank_input_history,
            )
        };
        // FIXME: Unused code: modifier addition.
        // game.modifiers.push(game_mode_presets::game_modifiers::print_fall_delay::modifier());
        // game.modifiers.push(game_mode_presets::game_modifiers::misc_modifiers::print_recency_tet_gen_stats::modifier());
        // game.modifiers.push(falling_tetromino_engine::Modifier { descriptor: "always_clear_board".to_owned(), mod_function: Box::new(|_c, _i, s, _m, _f| { s.board = Default::default(); })});

        let mut game_renderer = TetroTUIRenderer::with_number(self.temp_data.renderer_used);

        // We do an initial update, which allows a piece to spawn and queue to get generated.
        // We do this so the renderer does not render a first frame when game is in its raw start state.
        if game.state().time.is_zero() {
            match game.update(InGameTime::ZERO, None) {
                Ok(msgs) => game_renderer.update_feed(msgs, &self.settings),
                // ?? but i didn't even do anything yet
                Err(_update_game_error) => {}
            }
        }

        Menu::PlayGame {
            game: game.into(),
            raw_input_history,
            game_meta_data,
            game_renderer: game_renderer.into(),
            selection_id_for_game_retry: Some(selection),
        }
    }
}