1
//! Authors: Maurice Laveaux and Sjef van Loo
2
use core::fmt;
3

            
4
use crate::Priority;
5

            
6
/// The two players in a parity game.
7
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
8
pub enum Player {
9
    Even,
10
    Odd,
11
}
12

            
13
impl Player {
14
    /// Constructs a player from its index. This can be used in algorithms where
15
    /// we have a 2-array, and 0 is Even and 1 is Odd.
16
68000
    pub fn from_index(index: u8) -> Self {
17
68000
        Self::try_from_index(index).unwrap_or_else(|| panic!("Invalid player index {}", index))
18
68000
    }
19

            
20
    /// Constructs a player from its index, returning `None` for any value other
21
    /// than 0 (Even) or 1 (Odd). Use this when the index comes from untrusted
22
    /// input that should be reported as a recoverable error.
23
79004
    pub fn try_from_index(index: u8) -> Option<Self> {
24
79004
        match index {
25
37458
            0 => Some(Player::Even),
26
41546
            1 => Some(Player::Odd),
27
            _ => None,
28
        }
29
79004
    }
30

            
31
    /// Constructs a player from a priority.
32
38767
    pub fn from_priority(priority: Priority) -> Self {
33
38767
        if priority.value().is_multiple_of(2) {
34
17898
            Player::Even
35
        } else {
36
20869
            Player::Odd
37
        }
38
38767
    }
39

            
40
    /// Returns the index of the player, the inverse of [Self::from_index].
41
41494
    pub fn to_index(&self) -> usize {
42
41494
        match self {
43
19587
            Player::Even => 0,
44
21907
            Player::Odd => 1,
45
        }
46
41494
    }
47

            
48
    /// Returns the opponent of the current player.
49
86417
    pub fn opponent(&self) -> Self {
50
86417
        match self {
51
43600
            Player::Even => Player::Odd,
52
42817
            Player::Odd => Player::Even,
53
        }
54
86417
    }
55

            
56
    /// Returns the string representation of the solution for this player.
57
    pub fn solution(&self) -> &'static str {
58
        match self {
59
            Player::Even => "true",
60
            Player::Odd => "false",
61
        }
62
    }
63
}
64

            
65
impl fmt::Display for Player {
66
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67
        match self {
68
            Player::Even => write!(f, "even"),
69
            Player::Odd => write!(f, "odd"),
70
        }
71
    }
72
}