diff options
Diffstat (limited to 'rust/queen-attack/src/lib.rs')
| -rw-r--r-- | rust/queen-attack/src/lib.rs | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/rust/queen-attack/src/lib.rs b/rust/queen-attack/src/lib.rs new file mode 100644 index 0000000..cbdc2c7 --- /dev/null +++ b/rust/queen-attack/src/lib.rs | |||
| @@ -0,0 +1,36 @@ | |||
| 1 | #[derive(Debug)] | ||
| 2 | pub struct ChessPosition { | ||
| 3 | rank: i32, | ||
| 4 | file: i32, | ||
| 5 | } | ||
| 6 | |||
| 7 | #[derive(Debug)] | ||
| 8 | pub struct Queen { | ||
| 9 | pos: ChessPosition, | ||
| 10 | } | ||
| 11 | |||
| 12 | fn in_range<T: Ord>(n: T, min: T, max: T) -> bool { | ||
| 13 | min <= n && n < max | ||
| 14 | } | ||
| 15 | |||
| 16 | impl ChessPosition { | ||
| 17 | pub fn new(rank: i32, file: i32) -> Option<Self> { | ||
| 18 | if in_range(rank, 0, 8) && in_range(file, 0, 8) { | ||
| 19 | Some(ChessPosition { rank, file }) | ||
| 20 | } else { | ||
| 21 | None | ||
| 22 | } | ||
| 23 | } | ||
| 24 | } | ||
| 25 | |||
| 26 | impl Queen { | ||
| 27 | pub fn new(pos: ChessPosition) -> Self { | ||
| 28 | Queen { pos } | ||
| 29 | } | ||
| 30 | |||
| 31 | pub fn can_attack(&self, other: &Queen) -> bool { | ||
| 32 | self.pos.file == other.pos.file | ||
| 33 | || self.pos.rank == other.pos.rank | ||
| 34 | || (self.pos.rank - other.pos.rank).abs() == (self.pos.file - other.pos.file).abs() | ||
| 35 | } | ||
| 36 | } | ||
