mastermind/
peg.rs

1use rand::{self, Rng};
2use color::{self, Color};
3use std::cmp;
4use std::fmt;
5
6#[derive(Clone)]
7pub struct Peg {
8    color: Color,
9    found: bool,
10}
11
12impl Peg {
13    pub fn new(color: Color) -> Peg {
14        Peg {
15            color,
16            found: false,
17        }
18    }
19
20    pub fn new_random() -> Peg {
21        Peg {
22            color: Color::new(rand::thread_rng().gen_range(0, color::NUM_COLORS)),
23            found: false,
24        }
25    }
26
27    pub fn color(&self) -> Color {
28        self.color.clone()
29    }
30
31    pub fn found(&self) -> bool {
32        self.found
33    }
34
35    pub fn find(&mut self) {
36        self.found = true;
37    }
38}
39
40impl cmp::PartialEq for Peg {
41    fn eq(&self, other: &Peg) -> bool {
42        self.color == other.color
43    }
44}
45
46impl fmt::Debug for Peg {
47    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
48        write!(f, "{}, {}", self.color, self.found)
49    }
50}
51
52impl fmt::Display for Peg {
53    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
54        write!(f, "{}", self.color)
55    }
56}
57
58impl Into<Peg> for char {
59    fn into(self) -> Peg {
60        use Color::*;
61        match self.to_lowercase().to_string().as_ref() {
62            "r" => Peg::new(Red),
63            "o" => Peg::new(Orange),
64            "y" => Peg::new(Yellow),
65            "g" => Peg::new(Green),
66            "l" => Peg::new(Blue),
67            "i" => Peg::new(Indigo),
68            "p" => Peg::new(Purple),
69            "b" => Peg::new(Black),
70            "w" => Peg::new(White),
71            _ => Peg::new(Black),
72        }
73    }
74}
75
76pub fn convert(guess: String) -> Vec<Peg> {
77    let mut converted: Vec<Peg> = Vec::new();
78    for c in guess.chars() {
79        converted.push(c.into());
80    }
81    converted
82}