aboutsummaryrefslogtreecommitdiff
path: root/rust/queen-attack/src/lib.rs
blob: cbdc2c7a65a8c63bc8c27dc1f83a5f1dbc9ec201 (plain) (blame)
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
#[derive(Debug)]
pub struct ChessPosition {
    rank: i32,
    file: i32,
}

#[derive(Debug)]
pub struct Queen {
    pos: ChessPosition,
}

fn in_range<T: Ord>(n: T, min: T, max: T) -> bool {
    min <= n && n < max
}

impl ChessPosition {
    pub fn new(rank: i32, file: i32) -> Option<Self> {
        if in_range(rank, 0, 8) && in_range(file, 0, 8) {
            Some(ChessPosition { rank, file })
        } else {
            None
        }
    }
}

impl Queen {
    pub fn new(pos: ChessPosition) -> Self {
        Queen { pos }
    }

    pub fn can_attack(&self, other: &Queen) -> bool {
        self.pos.file == other.pos.file
            || self.pos.rank == other.pos.rank
            || (self.pos.rank - other.pos.rank).abs() == (self.pos.file - other.pos.file).abs()
    }
}