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
//! An action.
use std::fmt;
use crate::{direction::Direction, error::ParseActionError};
/// Represents an action.
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
pub enum Action {
/// Move action in a specified direction.
Move(Direction),
/// Push action in a specified direction.
Push(Direction),
}
impl Action {
/// Returns the direction associated with the action.
///
/// # Examples
///
/// ```
/// use soukoban::direction::Direction;
/// use soukoban::Action;
///
/// let action = Action::Move(Direction::Up);
/// assert_eq!(action.direction(), Direction::Up);
/// ```
pub fn direction(&self) -> Direction {
match *self {
Action::Move(direction) => direction,
Action::Push(direction) => direction,
}
}
/// Checks if the action is a move action.
///
/// # Examples
///
/// ```
/// use soukoban::direction::Direction;
/// use soukoban::Action;
///
/// let action = Action::Move(Direction::Up);
/// assert!(action.is_move());
/// ```
pub fn is_move(&self) -> bool {
matches!(&self, Action::Move(_))
}
/// Checks if the action is a push action.
///
/// # Examples
///
/// ```
/// use soukoban::direction::Direction;
/// use soukoban::Action;
///
/// let action = Action::Push(Direction::Up);
/// assert!(action.is_push());
/// ```
pub fn is_push(&self) -> bool {
matches!(&self, Action::Push(_))
}
}
impl TryFrom<char> for Action {
type Error = ParseActionError;
fn try_from(char: char) -> Result<Self, ParseActionError> {
let direction = match char.to_ascii_lowercase() {
'u' => Direction::Up,
'd' => Direction::Down,
'l' => Direction::Left,
'r' => Direction::Right,
_ => return Err(ParseActionError::InvalidCharacter(char)),
};
if char.is_ascii_uppercase() {
Ok(Action::Push(direction))
} else {
Ok(Action::Move(direction))
}
}
}
impl From<Action> for char {
fn from(action: Action) -> Self {
let char = match action.direction() {
Direction::Up => 'u',
Direction::Down => 'd',
Direction::Left => 'l',
Direction::Right => 'r',
};
if action.is_push() {
char.to_ascii_uppercase()
} else {
char
}
}
}
impl fmt::Display for Action {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", Into::<char>::into(*self))
}
}