mykatas/rust/tests/6_bishop.rs

52 lines
1.6 KiB
Rust

// 8 |_|#|_|#|_|#|_|#|
// 7 |#|_|#|_|#|_|#|_|
// 6 |_|#|_|#|_|#|_|#|
// 5 |#|_|#|_|#|_|#|_|
// 4 |_|#|_|#|_|#|_|#|
// 3 |#|_|#|_|#|_|#|_|
// 2 |_|#|_|#|_|#|_|#|
// 1 |#|_|#|_|#|_|#|_|
// a b c d e f g h
fn bishop(start_pos: &str, end_pos: &str, num_moves: u8) -> bool {
let (x1, y1) = get_coords(start_pos);
let (x2, y2) = get_coords(end_pos);
let is_same_position = start_pos == end_pos;
let is_same_color = (x1 + y1) % 2 == (x2 + y2) % 2;
let is_same_line = (x1 - x2).abs() == (y1 - y2).abs();
match num_moves {
0 => is_same_position,
1 => is_same_line,
_ => is_same_color,
}
}
fn get_coords(pos: &str) -> (i8, i8) {
let mut chars = pos.chars();
let x = chars.next().unwrap() as i8 - ('a' as i8);
let y = chars.next().unwrap() as i8 - ('1' as i8);
(x, y)
}
#[test]
fn test_basic() {
assert_eq!(bishop("a1", "b4", 2), true);
assert_eq!(bishop("a1", "b4", 2), true);
assert_eq!(bishop("a1", "b5", 5), false);
assert_eq!(bishop("f1", "f1", 0), true);
assert_eq!(bishop("e6", "a1", 2), false);
assert_eq!(bishop("h2", "a2", 1), false);
assert_eq!(bishop("d1", "a3", 1), false);
assert_eq!(bishop("b2", "a4", 2), false);
assert_eq!(bishop("d7", "a5", 0), false);
assert_eq!(bishop("e7", "a6", 2), false);
assert_eq!(bishop("d1", "a7", 1), false);
assert_eq!(bishop("c6", "a8", 2), true);
assert_eq!(bishop("d7", "b1", 1), false);
assert_eq!(bishop("e5", "b2", 2), true);
assert_eq!(bishop("c7", "b3", 0), false);
assert_eq!(bishop("b4", "b4", 1), true);
assert_eq!(bishop("h5", "b5", 1), false);
}