use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::Arc; use crate::static_data::MoveData; /// A learned move is the data attached to a Pokemon for a move it has learned. It has information /// such as the remaining amount of users, how it has been learned, etc. #[derive(Debug)] #[cfg_attr(feature = "wasm", derive(unique_type_id_derive::UniqueTypeId))] pub struct LearnedMove { /// The immutable move information of the move. move_data: Arc, /// The maximal power points for this move. max_pp: u8, /// The amount of remaining power points. If this is 0, we can not use the move anymore. remaining_pp: AtomicU8, /// The way the move was learned. learn_method: MoveLearnMethod, } /// The different ways a move can be learned. #[derive(Copy, Clone, Debug, Default)] #[repr(u8)] pub enum MoveLearnMethod { /// We do not know the learn method. #[default] Unknown = 0, /// The move was learned through level up. Level = 1, } impl LearnedMove { /// Instantiate a new learned move. pub fn new(move_data: &Arc, learn_method: MoveLearnMethod) -> Self { Self { move_data: move_data.clone(), max_pp: move_data.base_usages(), remaining_pp: AtomicU8::new(move_data.base_usages()), learn_method, } } /// The immutable move information of the move. pub fn move_data(&self) -> &Arc { &self.move_data } /// The maximal power points for this move. pub fn max_pp(&self) -> u8 { self.max_pp } /// The amount of remaining power points. If this is 0, we can not use the move anymore. pub fn remaining_pp(&self) -> u8 { self.remaining_pp.load(Ordering::Relaxed) } /// The way the move was learned. pub fn learn_method(&self) -> MoveLearnMethod { self.learn_method } /// Try and reduce the PP by a certain amount. If the amount is higher than the current uses, /// return false. Otherwise, reduce the PP, and return true. pub fn try_use(&self, amount: u8) -> bool { let res = self.remaining_pp.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| { if amount > x { None } else { Some(x - amount) } }); res.is_ok() } /// Set the remaining PP to the max amount of PP. pub fn restore_all_uses(&self) { self.remaining_pp.store(self.max_pp, Ordering::SeqCst); } /// Restore the remaining PP by a certain amount. Will prevent it from going above max PP. pub fn restore_uses(&self, mut uses: u8) { self.remaining_pp .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |x| { if x + uses > self.max_pp { uses = self.max_pp - x; } Some(x) }) .unwrap(); } }