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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
|
use std::fmt::{self, Display, Formatter};
use rand::prelude::ThreadRng;
use rand::Rng;
pub const NUM_STATS: usize = 7;
pub const STATS: [&str; NUM_STATS] = [
"charisma",
"constitution",
"dexterity",
"health",
"intelligence",
"strength",
"wisdom",
];
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Stats
{
values: [u8; NUM_STATS],
}
impl Stats
{
pub const fn from_values(values: [u8; NUM_STATS]) -> Self { Self { values } }
fn roll_initial_value(rng: &mut ThreadRng) -> u8
{
let mut v = 0;
for _ in 0..3 {
v += rng.gen_range(1..=6);
}
v
}
pub fn roll_initial() -> Self
{
let mut rng = rand::thread_rng();
let mut values = [0; NUM_STATS];
for v in &mut values {
*v = Self::roll_initial_value(&mut rng);
}
Self { values }
}
pub fn swap(&mut self, val1: &str, val2: &str) -> bool
{
unimplemented!();
}
pub fn get(&self, attribute: &str) -> Option<u8>
{
match STATS.binary_search(&attribute) {
Ok(pos) => Some(self.values[pos]),
Err(_) => None,
}
}
pub fn get_mut(&mut self, attribute: &str) -> Option<&mut u8>
{
match STATS.binary_search(&attribute) {
Ok(pos) => Some(self.values.get_mut(pos).unwrap()),
Err(_) => None,
}
}
}
impl Display for Stats
{
fn fmt(&self, fmt: &mut Formatter) -> Result<(), fmt::Error>
{
writeln!(fmt, "[")?;
for i in 0..NUM_STATS {
writeln!(fmt, " {} = {}", STATS[i], self.values[i])?;
}
writeln!(fmt, "]")?;
Ok(())
}
}
#[cfg(test)]
mod tests
{
use super::*;
fn test_stats() -> Stats { Stats::from_values([1, 2, 3, 4, 5, 6, 7]) }
#[test]
fn swap_same_argument()
{
let mut stats = test_stats();
assert_eq!(stats.get("intelligence"), Some(5));
assert!(stats.swap("intelligence", "intelligence"));
assert_eq!(stats.get("intelligence"), Some(5));
assert_eq!(stats.get("wisdom"), Some(7));
assert!(stats.swap("wisdom", "wisdom"));
assert_eq!(stats.get("wisdom"), Some(7));
}
#[test]
fn swap_invalid_argument()
{
let mut stats = test_stats();
assert!(!stats.swap("", "intelligence"));
assert_eq!(stats, test_stats());
assert!(!stats.swap("intelligence", ""));
assert_eq!(stats, test_stats());
assert!(!stats.swap("aoeu", "aoeu"));
assert_eq!(stats, test_stats());
assert!(!stats.swap("", ""));
assert_eq!(stats, test_stats());
}
}
|