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
37
use super::*;
use rand::{thread_rng, Rng};
#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
pub struct Die {
pub sides: usize,
}
impl Die {
pub fn new(sides: usize) -> Self {
Self { sides }
}
pub fn roll(self) -> usize {
thread_rng().gen_range(1, self.sides as usize)
}
}
impl Default for Die {
fn default() -> Self {
Self::new(6)
}
}
impl std::fmt::Display for Die {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self.sides)
}
}
impl FromStr for Die {
type Err = std::num::ParseIntError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Die::new(s.parse::<usize>()?))
}
}