sokoban-elements 0.2.1

Parsing and writing Sokoban, Hexoban, Trioban and Octoban file formats.
Documentation
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
mod errors;
mod hexoban_move_characters;
mod octoban_move_characters;
mod parser;
mod sokoban_move_characters;
mod solving_mode;
mod step;
mod trioban_move_characters;

// Generated code - `clippy::all` alone is not enough: the workspace lint table also
// enables pedantic, restriction and nursery lints, none of which are members of `all`.
#[allow(clippy::all, clippy::pedantic, clippy::restriction, clippy::nursery)]
mod grammar;

use std::ops::Index;

pub use errors::{SavedGameSyntaxError, SavedGameSyntaxErrorKind};
use parser::Parser;
pub use solving_mode::SolvingMode;
pub use step::Step;

use crate::Tessellation;

/// Sequence of pusher steps with accompanying metadata (ie. title, author, etc..).
///
/// Besides movement direction, `SavedGame` also represents:
///
/// - forward or reverse [`SolvingMode`]
/// - pusher jumps (in reverse solving mode)
/// - pusher selection steps on boards with multiple pushers (`Multiban`)
///
/// A saved game is tied to the physical board it was recorded against. Mirroring, rotating,
/// resizing, or trimming that board can invalidate movement directions and piece positions. The
/// mismatch is not detected automatically and not enforced anywhere.
/// [`GameBoard`](crate::GameBoard) and [`SavedGame`] are separate structures, and the client is
/// expected to maintain the relationship between them.
///
/// # Examples
///
/// ```rust
/// # use sokoban_elements::*;
/// #
/// # fn main() -> Result<(), SavedGameSyntaxError> {
/// let saved_game = SavedGame::parsed("llRRddsssSSSnNN", Tessellation::Hexoban)?;
/// let saved_game = SavedGame::parsed("nlLNrr", Tessellation::Trioban)?;
///
/// assert_eq!(saved_game[3].direction(), Direction::NorthEast);
/// assert_eq!(saved_game[3], Step::PushOrPull(Direction::NorthEast));
/// # Ok(())
/// # }
/// ```
///
/// # Editing
///
/// `SavedGame` is not editable in a sense where `Step`s can be added, removed, inserted or
/// modified. This is by design. This type is meant for archival purposes, as an input of Sokoban
/// data to writers and as output of Sokoban data readers. Game engines and solvers will need to use
/// their own structures to track movement history. At the end of solving session, they may use
/// `SavedGame` to archive progress of that session.
///
/// # Step counts, and the metrics that are not here
///
/// [`moves_count()`](SavedGame::moves_count()) and [`pushes_count()`](SavedGame::pushes_count())
/// are facts about the step sequence, so they live here.
///
/// The rest of the standard metric set does not. Box lines and box changes need to know *which* box
/// each push moved, and no saved game text format encodes box identity, so they can only be had by
/// replaying the steps against a [`GameBoard`](crate::GameBoard). Replaying a game is playing it
/// and that is out of scope for this crate.
///
/// # Solutions
///
/// Whether a `SavedGame` solves a board, how far it replays on one, and what its
/// [`SolvingMode::Reverse`] solution looks like played forwards are all questions about playing
/// rather than about what is recorded, so again - out of scope for this crate. Nothing here plays,
/// validates or edits a game: game engines and solvers keep their own board state, and are expected
/// to track these as they go rather than replay a `SavedGame` to recover them.
///
/// # Serde
///
/// With the `serde` feature, `SavedGame` is a map whose steps are the same text a `.sok` file would
/// carry:
///
/// ```json
/// {
///   "tessellation": "Sokoban",
///   "moves": "[]LuR",
///   "title": "",
///   "solved_by": "",
///   "notes": "",
///   "current_move_idx": 0
/// }
/// ```
///
/// There is deliberately no `solving_mode` field. [`SolvingMode::Reverse`] is always encoded in the
/// text itself as a leading jump section (`[]` when the game does not open with a jump), so the
/// moves are the single source of truth and no document can declare a mode contradicting its own
/// steps. A `solving_mode` key is rejected rather than silently ignored, as are all other unknown
/// fields.
///
/// Everything except `tessellation` and `moves` may be omitted. `current_move_idx` is special: the
/// parser reads it from a `*` marker inside the moves text, so omitting the field keeps whatever
/// the text says, while providing it overrides that. An empty `moves` string is the empty
/// [`SolvingMode::Forward`] game (an empty reverse game prints as `"[]"`).
///
/// ```rust
/// use sokoban_elements::*;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # #[cfg(feature = "serde")] {
/// let saved_game = SavedGame::parsed("lurd", Tessellation::Sokoban)?;
///
/// let json = serde_json::to_string(&saved_game)?;
/// assert_eq!(serde_json::from_str::<SavedGame>(&json)?, saved_game);
/// # }
/// #     Ok(())
/// # }
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct SavedGame {
    solving_mode: SolvingMode,
    steps:        Vec<Step>,
    tessellation: Tessellation,

    pub title:     String,
    pub solved_by: String,
    pub notes:     String,

    /// Index of currently played move from [`steps()`](Self::steps()).
    ///
    /// This can be found in some sokoban file formats so [`SavedGame`] has a place for it. On the
    /// other hand, [`SavedGame`] doesn't use it in any way, so it doesn't validate it against
    /// [`steps()`](SavedGame::steps()) either. [`SavedGame`] clients are advised to maintain and
    /// validate this value themselves.
    pub current_move_idx: usize,
}

/// Tests if `input` contains only characters that are valid in saved game strings.
///
/// This method doesn't test if `input` is a valid saved game. The only way to do that is
/// to actually [parse](SavedGame::parsed()) it.
pub(crate) fn is_saved_game_line(line: &str) -> bool {
    !line
        .chars()
        .all(|c| c.is_whitespace() || c.is_ascii_digit())
        && line.chars().all(|c| {
            c.is_ascii_digit()
                || c.is_whitespace()
                || Parser::is_move_char(c)
                || Parser::is_push_char(c)
                || Parser::is_saved_game_marker(c)
                || (c == Parser::RLE_EOL)
                || (c == Parser::RLE_GROUP_START)
                || (c == Parser::RLE_GROUP_END)
        })
}

impl SavedGame {
    /// Constructs `SavedGame` from parsed string of moves in context of
    /// [`Tessellation`](crate::Tessellation).
    ///
    /// # Examples
    ///
    /// ```
    /// # use sokoban_elements::*;
    /// #
    /// # fn main() -> Result<(), SavedGameSyntaxError> {
    /// let saved_game: SavedGame = SavedGame::parsed("lurdLurd", Tessellation::Sokoban)?;
    /// #     Ok(())
    /// # }
    /// ```
    ///
    /// # Grammar
    ///
    /// Save game strings use following characters:
    ///
    /// |                     | char                                   |
    /// | ------------------- | -------------------------------------- |
    /// | Move pusher         | 'l', 'u', 'r', 'd', 'w', 'e', 'n', 's' |
    /// | Push/pull box       | 'L', 'U', 'R', 'D', 'W', 'E', 'N', 'S' |
    /// | Begin jump          | '['                                    |
    /// | End jump            | ']'                                    |
    /// | Begin pusher change | '{'                                    |
    /// | End pusher change   | '{'                                    |
    /// | Current position    | '*'                                    |
    ///
    /// Mapping between characters and movement direction depends on
    /// [`Tessellation`](crate::Tessellation) context and is not the same in every
    /// [`Tessellation`](crate::Tessellation). Also, not all [`Tessellation`](crate::Tessellation)s
    /// use all movement characters, so this method may return error if it finds legal movement
    /// character but in wrong game tessellation context. Ie.
    /// [`Sokoban`](crate::Tessellation::Sokoban) will return error for character `'W'`.
    ///
    /// `SavedGame` strings mostly follow [SokobanYASC](https://sourceforge.net/projects/sokobanyasc/)
    /// specification:
    ///
    /// ```sok_file_format
    /// ::::::::::::::::::::::::::: Moves ::::::::::::::::::::::::::
    /// ::                                                        ::
    /// :: Remarks:                                               ::
    /// ::                                                        ::
    /// ::   Moves may be run-length encoded, e.g., "3r4U" means  ::
    /// ::   "rrrUUUU", and "2(3(dr)R)" means "drdrdrRdrdrdrR".   ::
    /// ::   Each line must, however, have at least one proper    ::
    /// ::   non-digit character. Spaces between moves are        ::
    /// ::   allowed.                                             ::
    /// ::                                                        ::
    /// ::   Jumps and pulls: Only in reverse mode saved games    ::
    /// ::   and solutions.                                       ::
    /// ::                                                        ::
    /// ::   Reverse mode saved games and solutions must begin    ::
    /// ::   with a jump, even if it is empty. An example:        ::
    /// ::   "[]U[rr]d".                                          ::
    /// ::                                                        ::
    /// ::   Pusher changes: Only in puzzles with multiple        ::
    /// ::   pushers, e.g., Multiban. Moves inside the braces     ::
    /// ::   depict the relative movement to get from the         ::
    /// ::   currently active pusher to the next active pusher.   ::
    /// ::   At game start, a "{...}" sequence activates the      ::
    /// ::   pusher relative to the top-left pusher. An example:  ::
    /// ::   "{rddd}Urr{uul}uLU". If the top-left pusher is the   ::
    /// ::   first active pusher, then the empty "{}" can be      ::
    /// ::   omitted.                                             ::
    /// ::                                                        ::
    /// ::   The current position is optional and defaults to the ::
    /// ::   position after the last move.                        ::
    /// ::                                                        ::
    /// ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    /// ```
    ///
    /// - [Moves grammar](https://raw.githubusercontent.com/tadams42/sokoban-elements/main/crates/sokoban-elements/doc/img/saved_game_text_grammar.svg)
    /// - [RLE grammar](https://raw.githubusercontent.com/tadams42/sokoban-elements/main/crates/sokoban-elements/doc/img/rle_grammar.svg)
    pub fn parsed(data: &str, tessellation: Tessellation) -> Result<Self, SavedGameSyntaxError> {
        let (steps, is_reverse, current_idx) = Parser::parse(data, tessellation)?;

        Ok(Self {
            steps,
            tessellation,
            solving_mode: if is_reverse {
                SolvingMode::Reverse
            } else {
                SolvingMode::Forward
            },
            current_move_idx: current_idx,
            title: String::new(),
            solved_by: String::new(),
            notes: String::new(),
        })
    }

    /// Constructs new [`SavedGame`] from sequence of [`Step`], validating each of them in context
    /// of given game tessellation.
    ///
    /// - if `data` contains [`Step::Jump`], marks created [`SavedGame`] as [`SolvingMode::Reverse`]
    /// - if `data` doesn't contain [`Step::Jump`] uses value of `solving_mode` argument
    ///
    /// # Examples
    ///
    /// ```
    /// use sokoban_elements::*;
    /// # use std::vec;
    ///
    /// # fn main() -> Result<(), SavedGameSyntaxError> {
    /// let moves = vec![
    ///     Step::Move(Direction::Down),
    ///     Step::PushOrPull(Direction::Down),
    ///     Step::PushOrPull(Direction::Down),
    ///     Step::Jump(Direction::Down),
    ///     Step::Jump(Direction::Down),
    ///     Step::Move(Direction::Down),
    /// ];
    ///
    /// let saved_game: SavedGame =
    ///     SavedGame::from_steps(&moves, Tessellation::Sokoban, Some(SolvingMode::Forward))?;
    ///
    /// assert_eq!(saved_game.solving_mode(), SolvingMode::Reverse);
    /// #     Ok(())
    /// # }
    /// ```
    pub fn from_steps(
        data: &[Step], tessellation: Tessellation, solving_mode: Option<SolvingMode>,
    ) -> Result<Self, SavedGameSyntaxError> {
        let mut is_reverse = false;

        for (idx, step) in data.iter().enumerate() {
            if matches!(step, Step::Jump(_)) {
                is_reverse = true;
            }

            if !tessellation.known_directions().contains(&step.direction()) {
                return Err(SavedGameSyntaxError::new(
                    SavedGameSyntaxErrorKind::InvalidStepDirection {
                        input: *step,
                        tessellation,
                        position: idx,
                    },
                ));
            }
        }

        Ok(Self {
            steps: data.to_vec(),
            tessellation,
            solving_mode: if is_reverse {
                SolvingMode::Reverse
            } else {
                solving_mode.unwrap_or_default()
            },
            current_move_idx: 0,
            title: String::new(),
            solved_by: String::new(),
            notes: String::new(),
        })
    }

    /// Serializes [`steps()`](SavedGame::steps()) into saved game string.
    pub fn printed_steps(&self) -> String {
        Parser::print(&self.steps, self.tessellation, self.solving_mode)
    }

    /// [`SolvingMode`] this [`SavedGame`] was recorded in.
    pub fn solving_mode(&self) -> SolvingMode { self.solving_mode }

    /// [`Tessellation`](crate::Tessellation) this [`SavedGame`] was recorded against.
    pub fn tessellation(&self) -> Tessellation { self.tessellation }

    /// Slice of [`Step`]s in this [`SavedGame`].
    pub fn steps(&self) -> &[Step] { &self.steps }

    /// Total number of steps in this [`SavedGame`].
    pub fn len(&self) -> usize { self.steps.len() }

    /// True if this [`SavedGame`] has no steps.
    pub fn is_empty(&self) -> bool { self.steps.is_empty() }

    /// Total number of [`Step::Move`] steps in this [`SavedGame`].
    pub fn moves_count(&self) -> usize {
        self.steps
            .iter()
            .filter(|s| matches!(s, Step::Move(_)))
            .count()
    }

    /// Total number of [`Step::PushOrPull`] steps in this [`SavedGame`].
    pub fn pushes_count(&self) -> usize {
        self.steps
            .iter()
            .filter(|s| matches!(s, Step::PushOrPull(_)))
            .count()
    }
}

impl Index<usize> for SavedGame {
    type Output = Step;

    fn index(&self, index: usize) -> &Self::Output { &self.steps[index] }
}

#[cfg(feature = "serde")]
mod serde_impl {
    use serde::de::Error as _;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};

    use super::{SavedGame, SolvingMode};
    use crate::Tessellation;

    /// Wire format of [`SavedGame`]: the printed steps plus the metadata that text can't carry.
    #[derive(Serialize, Deserialize)]
    #[serde(rename = "SavedGame", deny_unknown_fields)]
    struct SavedGameRepr {
        tessellation: Tessellation,
        moves:        String,

        #[serde(default)]
        title: String,

        #[serde(default)]
        solved_by: String,

        #[serde(default)]
        notes: String,

        /// `Option` so that an absent field leaves the index the moves text declared with `*`
        /// intact. Serializing always writes `Some`.
        #[serde(default)]
        current_move_idx: Option<usize>,
    }

    impl Serialize for SavedGame {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            SavedGameRepr {
                tessellation:     self.tessellation,
                moves:            self.printed_steps(),
                title:            self.title.clone(),
                solved_by:        self.solved_by.clone(),
                notes:            self.notes.clone(),
                current_move_idx: Some(self.current_move_idx),
            }
            .serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for SavedGame {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let repr = SavedGameRepr::deserialize(deserializer)?;

            let mut retv = if repr.moves.trim().is_empty() {
                // The printer emits "" only for a forward game with no steps, and the saved game
                // grammar requires at least one section, so `parsed("")` would fail. An empty
                // reverse game prints as "[]" and parses normally, so the two stay distinct.
                SavedGame::from_steps(&[], repr.tessellation, Some(SolvingMode::Forward))
                    .map_err(D::Error::custom)?
            } else {
                // Parsing validates every step against the tessellation and recovers the solving
                // mode from the leading jump section.
                SavedGame::parsed(&repr.moves, repr.tessellation).map_err(D::Error::custom)?
            };

            retv.title = repr.title;
            retv.solved_by = repr.solved_by;
            retv.notes = repr.notes;
            if let Some(current_move_idx) = repr.current_move_idx {
                retv.current_move_idx = current_move_idx;
            }

            Ok(retv)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Direction, Tessellation};

    /// How many [`Step::Jump`] steps a game holds.
    ///
    /// Not the count of jump *sequences*.
    fn jump_steps(saved_game: &SavedGame) -> usize {
        saved_game
            .steps()
            .iter()
            .filter(|s| matches!(s, Step::Jump(_)))
            .count()
    }

    #[test]
    fn it_can_be_constructed_from_char_data() -> Result<(), SavedGameSyntaxError> {
        let saved_game: SavedGame = SavedGame::parsed("lurdLURD", Tessellation::Sokoban)?;

        assert_eq!(saved_game.len(), 8);
        assert_eq!(saved_game.moves_count(), 4);
        assert_eq!(saved_game.pushes_count(), 4);
        assert_eq!(jump_steps(&saved_game), 0);

        Ok(())
    }

    #[test]
    fn it_correctly_recognizes_reverse_mode_saved_games_in_char_data()
    -> Result<(), SavedGameSyntaxError> {
        let saved_game: SavedGame = SavedGame::parsed("lurdLURD", Tessellation::Sokoban)?;
        assert_eq!(saved_game.solving_mode(), SolvingMode::Forward);

        // An empty `[]` section is what marks a game as reverse, and it contributes no step of its
        // own - so the marker is not mistaken for a jump anywhere it appears.
        let saved_game: SavedGame = SavedGame::parsed("[]", Tessellation::Sokoban)?;
        assert_eq!(saved_game.solving_mode(), SolvingMode::Reverse);
        assert_eq!(jump_steps(&saved_game), 0);

        let saved_game: SavedGame = SavedGame::parsed("lurd[]", Tessellation::Sokoban)?;
        assert_eq!(saved_game.solving_mode(), SolvingMode::Reverse);
        assert_eq!(jump_steps(&saved_game), 0);

        let saved_game: SavedGame = SavedGame::parsed("l[u]rd[]", Tessellation::Sokoban)?;
        assert_eq!(saved_game.solving_mode(), SolvingMode::Reverse);
        assert_eq!(jump_steps(&saved_game), 1);

        Ok(())
    }

    #[test]
    fn it_can_be_constructed_from_steps() -> Result<(), SavedGameSyntaxError> {
        let moves = vec![
            Step::PushOrPull(Direction::Left),
            Step::Move(Direction::Up),
            Step::PushOrPull(Direction::Right),
            Step::Jump(Direction::Down),
        ];

        let saved_game: SavedGame = SavedGame::from_steps(&moves, Tessellation::Sokoban, None)?;

        assert_eq!(saved_game.moves_count(), 1);
        assert_eq!(saved_game.pushes_count(), 2);
        assert_eq!(jump_steps(&saved_game), 1);

        Ok(())
    }

    #[test]
    fn when_constructed_from_steps_may_use_default_solving_mode() -> Result<(), SavedGameSyntaxError>
    {
        let moves = vec![
            Step::PushOrPull(Direction::Left),
            Step::Move(Direction::Up),
            Step::PushOrPull(Direction::Right),
        ];

        let saved_game: SavedGame = SavedGame::from_steps(&moves, Tessellation::Sokoban, None)?;
        assert_eq!(saved_game.solving_mode, SolvingMode::Forward);

        Ok(())
    }

    #[test]
    fn when_constructed_from_steps_may_use_solving_mode_argument()
    -> Result<(), SavedGameSyntaxError> {
        let moves = vec![
            Step::PushOrPull(Direction::Left),
            Step::Move(Direction::Up),
            Step::PushOrPull(Direction::Right),
        ];

        let saved_game: SavedGame =
            SavedGame::from_steps(&moves, Tessellation::Sokoban, Some(SolvingMode::Reverse))?;
        assert_eq!(saved_game.solving_mode, SolvingMode::Reverse);

        Ok(())
    }

    #[test]
    fn when_constructed_from_steps_may_ignore_solving_mode_argument()
    -> Result<(), SavedGameSyntaxError> {
        let moves = vec![
            Step::PushOrPull(Direction::Left),
            Step::Move(Direction::Up),
            Step::PushOrPull(Direction::Right),
            Step::Jump(Direction::Right),
        ];

        let saved_game: SavedGame =
            SavedGame::from_steps(&moves, Tessellation::Sokoban, Some(SolvingMode::Forward))?;
        assert_eq!(saved_game.solving_mode, SolvingMode::Reverse);

        Ok(())
    }

    #[test]
    fn it_can_convert_steps_to_string() -> Result<(), SavedGameSyntaxError> {
        let saved_game: SavedGame = SavedGame::parsed("lurdllurd", Tessellation::Sokoban)?;
        let converted = saved_game.printed_steps();
        assert_eq!(converted, "lurdllurd");

        let saved_game: SavedGame = SavedGame::parsed("lur{dllu}rd", Tessellation::Sokoban)?;
        let converted = saved_game.printed_steps();
        assert_eq!(converted, "lur{dllu}rd");

        let saved_game: SavedGame = SavedGame::parsed("lur[dllu]rd", Tessellation::Sokoban)?;
        let converted = saved_game.printed_steps();
        assert_eq!(converted, "[]lur[dllu]rd");

        Ok(())
    }

    #[test]
    fn when_converting_steps_to_string_ensures_start_jump_for_reverse_mode_saved_games()
    -> Result<(), SavedGameSyntaxError> {
        let moves = vec![
            Step::PushOrPull(Direction::Left),
            Step::Move(Direction::Up),
            Step::PushOrPull(Direction::Right),
        ];
        let saved_game: SavedGame =
            SavedGame::from_steps(&moves, Tessellation::Sokoban, Some(SolvingMode::Reverse))?;
        let converted = saved_game.printed_steps();
        assert_eq!(converted, "[]LuR");

        let moves = vec![
            Step::Jump(Direction::Left),
            Step::PushOrPull(Direction::Left),
            Step::Move(Direction::Up),
            Step::PushOrPull(Direction::Right),
        ];
        let saved_game: SavedGame =
            SavedGame::from_steps(&moves, Tessellation::Sokoban, Some(SolvingMode::Reverse))?;
        let converted = saved_game.printed_steps();
        assert_eq!(converted, "[l]LuR");

        Ok(())
    }

    #[cfg(feature = "serde")]
    mod serde {
        use std::error::Error;

        use super::*;

        fn round_tripped(saved_game: &SavedGame) -> Result<SavedGame, Box<dyn Error>> {
            let json = serde_json::to_string(saved_game)?;

            Ok(serde_json::from_str::<SavedGame>(&json)?)
        }

        #[test]
        fn it_round_trips_through_json() -> Result<(), Box<dyn Error>> {
            let cases = [
                (Tessellation::Sokoban, "lurdLURD"),
                (Tessellation::Hexoban, "llRRddsssSSSnNN"),
                (Tessellation::Trioban, "nlLNrr"),
                (Tessellation::Octoban, "lurdLURD"),
            ];

            for (tessellation, moves) in cases {
                let saved_game = SavedGame::parsed(moves, tessellation)?;

                assert_eq!(round_tripped(&saved_game)?, saved_game, "{tessellation:?}");
            }

            Ok(())
        }

        /// Pusher selection steps are printed as `{..}` sections and must survive the text form.
        #[test]
        fn it_round_trips_pusher_changes() -> Result<(), Box<dyn Error>> {
            let saved_game = SavedGame::parsed("lur{dllu}rd", Tessellation::Sokoban)?;

            let parsed = round_tripped(&saved_game)?;
            assert_eq!(parsed, saved_game);
            assert_eq!(parsed.printed_steps(), "lur{dllu}rd");

            Ok(())
        }

        #[test]
        fn it_round_trips_reverse_mode_games() -> Result<(), Box<dyn Error>> {
            let saved_game = SavedGame::parsed("[l]LuR", Tessellation::Sokoban)?;
            assert_eq!(saved_game.solving_mode(), SolvingMode::Reverse);

            let parsed = round_tripped(&saved_game)?;
            assert_eq!(parsed, saved_game);
            assert_eq!(parsed.solving_mode(), SolvingMode::Reverse);

            Ok(())
        }

        /// An empty forward game prints as `""` and an empty reverse game as `"[]"`, so the two
        /// stay distinguishable even though the parser rejects the empty string.
        #[test]
        fn when_game_has_no_steps_solving_mode_still_round_trips() -> Result<(), Box<dyn Error>> {
            for solving_mode in [SolvingMode::Forward, SolvingMode::Reverse] {
                let saved_game =
                    SavedGame::from_steps(&[], Tessellation::Sokoban, Some(solving_mode))?;

                let parsed = round_tripped(&saved_game)?;
                assert_eq!(parsed, saved_game);
                assert!(parsed.is_empty());
                assert_eq!(parsed.solving_mode(), solving_mode);
            }

            Ok(())
        }

        #[test]
        fn it_round_trips_metadata() -> Result<(), Box<dyn Error>> {
            let mut saved_game = SavedGame::parsed("lurd", Tessellation::Sokoban)?;
            saved_game.title = "Best attempt".to_string();
            saved_game.solved_by = "Tomislav".to_string();
            saved_game.notes = "Not really solved".to_string();
            saved_game.current_move_idx = 3;

            let parsed = round_tripped(&saved_game)?;

            assert_eq!(parsed.title, "Best attempt");
            assert_eq!(parsed.solved_by, "Tomislav");
            assert_eq!(parsed.notes, "Not really solved");
            assert_eq!(parsed.current_move_idx, 3);

            Ok(())
        }

        #[test]
        fn when_only_moves_are_given_the_rest_defaults() -> Result<(), Box<dyn Error>> {
            let saved_game: SavedGame =
                serde_json::from_str(r#"{"tessellation": "Sokoban", "moves": "lurd"}"#)?;

            assert_eq!(saved_game, SavedGame::parsed("lurd", Tessellation::Sokoban)?);

            Ok(())
        }

        /// `current_move_idx` is also encoded inside the moves text as `*`, so an absent field must
        /// not overwrite what the text says.
        #[test]
        fn when_current_move_idx_is_absent_the_moves_marker_wins() -> Result<(), Box<dyn Error>> {
            let saved_game: SavedGame =
                serde_json::from_str(r#"{"tessellation": "Sokoban", "moves": "lu*rd"}"#)?;

            assert_eq!(saved_game.current_move_idx, 2);
            assert_eq!(saved_game.len(), 4);

            Ok(())
        }

        #[test]
        fn when_current_move_idx_is_given_it_wins() -> Result<(), Box<dyn Error>> {
            let saved_game: SavedGame = serde_json::from_str(
                r#"{"tessellation": "Sokoban", "moves": "lu*rd", "current_move_idx": 0}"#,
            )?;

            assert_eq!(saved_game.current_move_idx, 0);

            Ok(())
        }

        /// Solving mode is derived from the moves text alone, so a document that also declares it
        /// must be rejected rather than silently ignored.
        #[test]
        fn it_rejects_a_solving_mode_field() {
            let result = serde_json::from_str::<SavedGame>(
                r#"{"tessellation": "Sokoban", "moves": "lurd", "solving_mode": "Reverse"}"#,
            );

            assert!(result.is_err());
        }

        #[test]
        fn it_rejects_steps_illegal_for_the_tessellation() {
            let result = serde_json::from_str::<SavedGame>(
                r#"{"tessellation": "Sokoban", "moves": "lurdnw"}"#,
            );

            assert!(result.is_err());
        }
    }
}