game_features/unlock.rs
1use crate::{StatCondition, UseMode};
2use std::collections::HashMap;
3use std::hash::Hash;
4
5/// An unlockable element.
6/// It can be unlocked to access the inner value if all conditions are met:
7/// - `StatCondition`s
8/// - Item Conditions
9/// - Dependant unlockables were previously unlocked.
10#[derive(Debug, Clone, Serialize, Deserialize, new, Builder)]
11pub struct Unlockable<U, K, S, I> {
12 /// The key of this unlockable.
13 pub id: U,
14 /// The thing we want to unlock access to.
15 pub inner: K,
16 /// Whether we unlocked it or not.
17 pub is_unlocked: bool,
18 /// The stat conditions required to unlock this element.
19 #[new(default)]
20 pub unlock_stat_conditions: Vec<StatCondition<S>>,
21 /// The item conditions required to unlock this element.
22 #[new(default)]
23 pub unlock_item_conditions: Vec<(I, usize, UseMode)>,
24 /// A list of other unlockables upon which this one depends.
25 /// If Unlockable B depends on A, then A must be unlocked before B can be unlocked.
26 #[new(default)]
27 pub unlock_dependencies: Vec<U>,
28}
29
30impl<U, K, S, I> Unlockable<U, K, S, I> {
31 /// Returns Some with the inner value if is_unlocked = true.
32 /// Otherwise returns None
33 pub fn try_get(&self) -> Option<&K> {
34 if self.is_unlocked {
35 Some(&self.inner)
36 } else {
37 None
38 }
39 }
40
41 /// Returns Some with the inner value if is_unlocked = true.
42 /// Otherwise returns None
43 pub fn try_get_mut(&mut self) -> Option<&mut K> {
44 if self.is_unlocked {
45 Some(&mut self.inner)
46 } else {
47 None
48 }
49 }
50
51 /// Returns the inner value without checking the lock.
52 pub fn get(&self) -> &K {
53 &self.inner
54 }
55
56 /// Returns the inner value without checking the lock.
57 pub fn get_mut(&mut self) -> &mut K {
58 &mut self.inner
59 }
60
61 /// Inserts a new value without changing the lock.
62 /// Returns the previous inner value.
63 pub fn set(&mut self, new: K) {
64 self.inner = new;
65 }
66
67 /// Locks the inner value.
68 pub fn lock(&mut self) {
69 self.is_unlocked = true;
70 }
71
72 /// Unlocks the inner value.
73 pub fn unlock(&mut self) {
74 self.is_unlocked = false;
75 }
76
77 /// Verifies if the inner value is locked.
78 pub fn is_unlocked(&self) -> bool {
79 self.is_unlocked
80 }
81}
82
83/// A structure holding all unlockables.
84#[derive(Debug, Clone, Default, Serialize, Deserialize, new)]
85pub struct Unlockables<U: Hash + Eq, K, S, I> {
86 /// The unlockables we are holding.
87 pub unlockables: HashMap<U, Unlockable<U, K, S, I>>,
88}
89// TODO impl to try unlock and to try unlock recursively.