Skip to main content

azalea_core/
game_type.rs

1use std::io::{self, Cursor, Write};
2
3use azalea_buf::{AzBuf, AzBufVar, BufReadError, BufReadErrorRepr};
4use tracing::debug;
5
6/// A Minecraft gamemode, like survival or creative.
7///
8/// When this is used as a component, it is only present for local players. For
9/// non-local players, their gamemode must be looked up in the tab list.
10#[cfg_attr(feature = "bevy_ecs", derive(bevy_ecs::component::Component))]
11#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
12pub enum GameMode {
13    #[default]
14    Survival,
15    Creative,
16    Adventure,
17    Spectator,
18}
19
20impl GameMode {
21    pub fn to_id(&self) -> u8 {
22        match self {
23            GameMode::Survival => 0,
24            GameMode::Creative => 1,
25            GameMode::Adventure => 2,
26            GameMode::Spectator => 3,
27        }
28    }
29
30    /// Get the ID of the game mode, but return -1 if the game type is invalid.
31    pub fn to_optional_id<T: Into<Option<GameMode>>>(game_type: T) -> i8 {
32        match game_type.into() {
33            Some(game_type) => game_type.to_id() as i8,
34            None => -1,
35        }
36    }
37
38    pub fn from_id(id: u8) -> Option<GameMode> {
39        Some(match id {
40            0 => GameMode::Survival,
41            1 => GameMode::Creative,
42            2 => GameMode::Adventure,
43            3 => GameMode::Spectator,
44            _ => return None,
45        })
46    }
47
48    pub fn from_optional_id(id: i8) -> Option<OptionalGameType> {
49        Some(
50            match id {
51                -1 => None,
52                id => Some(GameMode::from_id(id as u8)?),
53            }
54            .into(),
55        )
56    }
57
58    /// The translation key for the short display name for the gamemode, like
59    /// "Survival".
60    ///
61    /// ```
62    /// # use azalea_core::game_type::GameMode;
63    /// # use azalea_chat::component::translatable::TranslatableComponent;
64    /// assert_eq!(
65    ///     TranslatableComponent::new(GameMode::Survival.short_name_key(), vec![]).to_string(),
66    ///     "Survival"
67    /// );
68    /// ```
69    pub fn short_name_key(&self) -> String {
70        format!("selectWorld.gameMode.{}", self.name())
71    }
72
73    /// The translation key for the long display name for the gamemode, like
74    /// "Survival Mode".
75    /// ```
76    /// # use azalea_core::game_type::GameMode;
77    /// # use azalea_chat::component::translatable::TranslatableComponent;
78    /// assert_eq!(
79    ///     TranslatableComponent::new(GameMode::Survival.long_name_key(), vec![]).to_string(),
80    ///     "Survival Mode"
81    /// );
82    /// ```
83    pub fn long_name_key(&self) -> String {
84        format!("gameMode.{}", self.name())
85    }
86
87    pub fn from_name(name: &str) -> GameMode {
88        match name {
89            "survival" => GameMode::Survival,
90            "creative" => GameMode::Creative,
91            "adventure" => GameMode::Adventure,
92            "spectator" => GameMode::Spectator,
93            _ => panic!("Unknown game type name: {name}"),
94        }
95    }
96
97    /// The internal name for the game mode, like "survival".
98    pub fn name(&self) -> &'static str {
99        match self {
100            GameMode::Survival => "survival",
101            GameMode::Creative => "creative",
102            GameMode::Adventure => "adventure",
103            GameMode::Spectator => "spectator",
104        }
105    }
106}
107
108impl GameMode {
109    /// Whether the player can't interact with blocks while in this game mode.
110    ///
111    /// Returns true if you're in adventure or spectator.
112    pub fn is_block_placing_restricted(&self) -> bool {
113        matches!(self, GameMode::Adventure | GameMode::Spectator)
114    }
115}
116
117impl AzBuf for GameMode {
118    fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
119        let id = u32::azalea_read_var(ctx, buf)?;
120        let id = id.try_into().unwrap_or_else(|_| {
121            debug!("Unknown game mode id {id}, defaulting to survival");
122            0
123        });
124        Ok(GameMode::from_id(id).unwrap_or_else(|| {
125            debug!("Unknown game mode id {id}, defaulting to survival");
126            GameMode::Survival
127        }))
128    }
129    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
130        u8::azalea_write(&self.to_id(), ctx, buf)
131    }
132}
133
134/// Rust doesn't let us `impl AzBuf for Option<GameType>` so we have to
135/// make a new type :(
136#[derive(Clone, Copy, Debug, Hash, PartialEq)]
137pub struct OptionalGameType(pub Option<GameMode>);
138
139impl From<Option<GameMode>> for OptionalGameType {
140    fn from(game_type: Option<GameMode>) -> Self {
141        OptionalGameType(game_type)
142    }
143}
144
145impl From<OptionalGameType> for Option<GameMode> {
146    fn from(optional_game_type: OptionalGameType) -> Self {
147        optional_game_type.0
148    }
149}
150
151impl AzBuf for OptionalGameType {
152    fn azalea_read(ctx: azalea_buf::Ctx, buf: &mut Cursor<&[u8]>) -> Result<Self, BufReadError> {
153        let id = i8::azalea_read(ctx, buf)?;
154        GameMode::from_optional_id(id)
155            .ok_or(BufReadErrorRepr::UnexpectedEnumVariant { id: id as i32 }.into())
156    }
157    fn azalea_write(&self, ctx: azalea_buf::Ctx, buf: &mut impl Write) -> io::Result<()> {
158        GameMode::to_optional_id(*self).azalea_write(ctx, buf)
159    }
160}