azalea_core/
difficulty.rs1use std::{
2 fmt::{Debug, Error, Formatter},
3 io::{Cursor, Write},
4};
5
6use azalea_buf::{AzaleaRead, AzaleaWrite, BufReadError};
7
8#[derive(Hash, Clone, Copy, Debug, PartialEq, Eq)]
9pub enum Difficulty {
10 PEACEFUL = 0,
11 EASY = 1,
12 NORMAL = 2,
13 HARD = 3,
14}
15
16pub enum Err {
17 InvalidDifficulty(String),
18}
19
20impl Debug for Err {
21 fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
22 match self {
23 Err::InvalidDifficulty(s) => write!(f, "Invalid difficulty: {s}"),
24 }
25 }
26}
27
28impl Difficulty {
29 pub fn name(&self) -> &'static str {
30 match self {
31 Difficulty::PEACEFUL => "peaceful",
32 Difficulty::EASY => "easy",
33 Difficulty::NORMAL => "normal",
34 Difficulty::HARD => "hard",
35 }
36 }
37
38 pub fn from_name(name: &str) -> Result<Difficulty, Err> {
39 match name {
40 "peaceful" => Ok(Difficulty::PEACEFUL),
41 "easy" => Ok(Difficulty::EASY),
42 "normal" => Ok(Difficulty::NORMAL),
43 "hard" => Ok(Difficulty::HARD),
44 _ => Err(Err::InvalidDifficulty(name.to_string())),
45 }
46 }
47
48 pub fn by_id(id: u8) -> Difficulty {
49 match id % 4 {
50 0 => Difficulty::PEACEFUL,
51 1 => Difficulty::EASY,
52 2 => Difficulty::NORMAL,
53 3 => Difficulty::HARD,
54 _ => panic!("Unknown difficulty id: {id}"),
56 }
57 }
58
59 pub fn id(&self) -> u8 {
60 match self {
61 Difficulty::PEACEFUL => 0,
62 Difficulty::EASY => 1,
63 Difficulty::NORMAL => 2,
64 Difficulty::HARD => 3,
65 }
66 }
67}
68
69impl AzaleaRead for Difficulty {
70 fn azalea_read(buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
71 Ok(Difficulty::by_id(u8::azalea_read(buf)?))
72 }
73}
74
75impl AzaleaWrite for Difficulty {
76 fn azalea_write(&self, buf: &mut impl Write) -> Result<(), std::io::Error> {
77 u8::azalea_write(&self.id(), buf)
78 }
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84
85 #[test]
86 fn test_difficulty_from_name() {
87 assert_eq!(
88 Difficulty::PEACEFUL,
89 Difficulty::from_name("peaceful").unwrap()
90 );
91 assert_eq!(Difficulty::EASY, Difficulty::from_name("easy").unwrap());
92 assert_eq!(Difficulty::NORMAL, Difficulty::from_name("normal").unwrap());
93 assert_eq!(Difficulty::HARD, Difficulty::from_name("hard").unwrap());
94 assert!(Difficulty::from_name("invalid").is_err());
95 }
96
97 #[test]
98 fn test_difficulty_id() {
99 assert_eq!(0, Difficulty::PEACEFUL.id());
100 assert_eq!(1, Difficulty::EASY.id());
101 assert_eq!(2, Difficulty::NORMAL.id());
102 assert_eq!(3, Difficulty::HARD.id());
103 }
104
105 #[test]
106 fn test_difficulty_name() {
107 assert_eq!("peaceful", Difficulty::PEACEFUL.name());
108 assert_eq!("easy", Difficulty::EASY.name());
109 assert_eq!("normal", Difficulty::NORMAL.name());
110 assert_eq!("hard", Difficulty::HARD.name());
111 }
112}