post-push-party 0.1.7

Push code, earn points, throw a party!
Documentation
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use std::collections::{HashMap, HashSet};

use crate::{
    bonus_track::{ALL_TRACKS, Reward},
    game::GameRef,
    pack::{Pack, PackItem},
    party::{ALL_PARTIES, Palette, Party},
    storage::PushHistory,
};

/// measures how quickly the player gains packs automatically based
/// on lifetime points. specifically it's the rate of increase of
/// difference between subsequent break points
///
/// eg. if the value is 25, then the player will get points
/// at: 0  + 1 * 25 = 25
///     25 + 2 * 25 = 75
///     75 + 3 * 25 = 150
///     ... etc
const PACK_ACCRUAL_RATE: u64 = 25;

#[derive(Debug, Clone, PartialEq)]
pub struct State {
    pub party_points: u64,

    pub lifetime_points_earned: u64,

    /// refers to bonus tracks by their identifier string
    pub bonus_tracks: HashMap<String, u32>,

    /// which parties the player has unlocked via the store.
    /// refers to parties by their identifier string
    pub unlocked_parties: HashSet<String>,

    /// which parties have been enabled by the player.
    /// refers to parties by their identifier string
    pub enabled_parties: HashSet<String>,

    /// which palettes the player has unlocked for each party.
    /// refers to parties and palettes by their id strings
    pub unlocked_palettes: HashMap<String, Vec<String>>,

    /// which palette is currently configured for each party.
    /// refers to parties and palettes by their id strings
    pub active_palettes: HashMap<String, PaletteSelection>,

    /// how many packs of each type the player has
    pub packs: HashMap<Pack, u32>,

    /// how many packs have been earned though the points accrual mechanism
    pub lifetime_packs_earned: u64,

    /// how many game tokens the player has
    /// refers to games by their ids
    pub games: HashMap<String, u32>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PaletteSelection {
    Specific(String), // palette name
    Random,
}

impl Default for PaletteSelection {
    fn default() -> Self {
        Self::Specific(Palette::WHITE_ANSI.id().to_string())
    }
}

impl Default for State {
    fn default() -> Self {
        let mut bonus_tracks = HashMap::new();
        bonus_tracks.insert("commit_value".to_string(), 1);

        let mut unlocked_parties = HashSet::new();
        unlocked_parties.insert("base".to_string());

        let white = Palette::WHITE_ANSI.id().to_string();

        Self {
            party_points: 0,
            lifetime_points_earned: 0,
            bonus_tracks,
            enabled_parties: unlocked_parties.clone(),
            unlocked_parties,
            unlocked_palettes: HashMap::from([("base".to_string(), vec![white.clone()])]),
            active_palettes: HashMap::from([(
                "base".to_string(),
                PaletteSelection::Specific(white),
            )]),
            packs: HashMap::new(),
            games: HashMap::new(),
            lifetime_packs_earned: 0,
        }
    }
}

impl State {
    #[expect(clippy::too_many_arguments)]
    pub fn new(
        party_points: u64,
        lifetime_points_earned: u64,
        lifetime_packs_earned: u64,
        bonus_tracks: HashMap<String, u32>,
        unlocked_parties: HashSet<String>,
        enabled_parties: HashSet<String>,
        unlocked_palettes: HashMap<String, Vec<String>>,
        active_palettes: HashMap<String, PaletteSelection>,
        packs: HashMap<Pack, u32>,
        games: HashMap<String, u32>,
    ) -> Self {
        Self {
            party_points,
            lifetime_points_earned,
            bonus_tracks,
            unlocked_parties,
            enabled_parties,
            unlocked_palettes,
            active_palettes,
            packs,
            games,
            lifetime_packs_earned,
        }
    }

    /// if packs were earned as a result of earning these points,
    /// this returns the list of point thresholds that were
    /// crossed. otherwise an empty list
    pub fn earn_points(&mut self, amount: u64) -> Vec<u64> {
        self.party_points += amount;
        self.lifetime_points_earned += amount;

        let mut thresholds = Vec::new();

        // check if we've crossed a threshold for which we should
        // grant packs. the thresholds values are
        //   PACK_ACCRUAL_RATE * (n+1) * (n+2) / 2
        // where n is the number of packs earned in this way so far
        let mut threshold =
            PACK_ACCRUAL_RATE * (self.lifetime_packs_earned + 1) * (self.lifetime_packs_earned + 2)
                / 2;
        while threshold <= self.lifetime_points_earned {
            self.lifetime_packs_earned += 1;
            self.add_pack(Pack::Basic);
            thresholds.push(threshold);

            threshold = PACK_ACCRUAL_RATE
                * (self.lifetime_packs_earned + 1)
                * (self.lifetime_packs_earned + 2)
                / 2
        }

        thresholds
    }

    pub fn bonus_level(&self, id: &str) -> u32 {
        self.bonus_tracks.get(id).copied().unwrap_or(0)
    }

    pub fn set_bonus_level(&mut self, id: &str, level: u32) {
        self.bonus_tracks.insert(id.to_string(), level);
    }

    pub fn points_per_commit(&self) -> u64 {
        let level = self.bonus_level("commit_value");
        if level == 0 {
            return 1;
        }
        // find commit_value track and get reward
        for track in ALL_TRACKS.iter() {
            if track.id() == "commit_value"
                && let Some(Reward::FlatPoints(n)) = track.reward_at_level(level)
            {
                return n;
            }
        }
        1
    }

    pub fn unlocked_parties(&self) -> impl Iterator<Item = &'static dyn Party> + use<'_> {
        ALL_PARTIES
            .iter()
            .copied()
            .filter(|&party| self.is_party_unlocked(party.id()))
    }

    pub fn is_party_unlocked(&self, id: &str) -> bool {
        self.unlocked_parties.contains(id)
    }

    pub fn is_party_enabled(&self, id: &str) -> bool {
        self.unlocked_parties.contains(id) && self.enabled_parties.contains(id)
    }

    pub fn unlock_party(&mut self, id: &str) {
        self.unlocked_parties.insert(id.to_string());
        self.enabled_parties.insert(id.to_string());

        // seed with white palette if no palettes unlocked yet
        if !self.unlocked_palettes.contains_key(id) {
            let white = Palette::WHITE_ANSI.id().to_string();
            self.unlocked_palettes
                .insert(id.to_string(), vec![white.clone()]);
            self.active_palettes
                .insert(id.to_string(), PaletteSelection::Specific(white));
        }
    }

    pub fn toggle_party(&mut self, id: &str) {
        if self.unlocked_parties.contains(id) {
            if self.enabled_parties.contains(id) {
                self.enabled_parties.remove(id);
            } else {
                self.enabled_parties.insert(id.to_string());
            }
        }
    }

    pub fn unlock_palette(&mut self, party_id: &str, palette_name: &str) {
        self.unlocked_palettes
            .entry(party_id.to_string())
            .and_modify(|v| {
                v.push(palette_name.to_string());
            })
            .or_insert(Vec::from([palette_name.to_string()]));
    }

    pub fn is_palette_unlocked(&self, party_id: &str, palette_name: &str) -> bool {
        self.unlocked_palettes
            .get(party_id)
            .is_some_and(|v| v.iter().any(|name| name == palette_name))
    }

    pub fn unlocked_palettes(&self, party_id: &str) -> Option<&Vec<String>> {
        self.unlocked_palettes.get(party_id)
    }

    pub fn selected_palette(&self, party_id: &str) -> Option<&PaletteSelection> {
        self.active_palettes.get(party_id)
    }

    /// the index of the selected palette for the given party.
    /// returns the length of the unlocked palettes list if "random" is selected.
    /// falls back to 0 if state is somehow missing.
    pub fn selected_palette_idx(&self, party_id: &str) -> usize {
        let Some(palettes) = self.unlocked_palettes(party_id) else {
            return 0;
        };
        let Some(selected) = self.selected_palette(party_id) else {
            return 0;
        };
        match selected {
            PaletteSelection::Specific(palette_name) => palettes
                .iter()
                .position(|name| *name == *palette_name)
                .unwrap_or(0),
            PaletteSelection::Random => palettes.len(),
        }
    }

    /// sets the selected palette for a party based on its index in the list of available palettes
    ///
    /// NOTE: if the index is outside of the valid range, the palette selection will be set to "random"
    pub fn set_selected_palette(&mut self, party_id: &str, palette_idx: usize) {
        let palettes = self.unlocked_palettes(party_id);
        let palette_name = palettes.and_then(|palettes| palettes.get(palette_idx));
        let selection = match palette_name {
            Some(name) => PaletteSelection::Specific(name.to_string()),
            None => PaletteSelection::Random,
        };
        self.active_palettes.insert(party_id.to_string(), selection);
    }

    /// adds a pack to the player's inventory
    pub fn add_pack(&mut self, pack: Pack) {
        self.packs.entry(pack).and_modify(|n| *n += 1).or_insert(1);
    }

    /// how many packs of the given type the player has
    pub fn pack_count(&self, pack: &Pack) -> u32 {
        self.packs.get(pack).copied().unwrap_or_default()
    }

    /// how many packs of all types the player has
    pub fn pack_total(&self) -> u32 {
        self.packs.values().sum()
    }

    /// decrements the number of packs of a given type,
    /// invokes the "open" algorithm that determins what's in a pack, then
    /// applies the received items to the player's state
    pub fn open_pack(&mut self, pack: Pack) -> Vec<PackItem> {
        self.packs
            .entry(pack)
            .and_modify(|n| *n = n.saturating_sub(1));

        pack.open(self)
    }

    /// adds a game token to the player's inventory
    pub fn add_game_token(&mut self, game: GameRef) {
        self.games
            .entry(game.id().to_string())
            .and_modify(|n| *n += 1)
            .or_insert(1);
    }

    /// deducts a game token from the player's inventory
    pub fn deduct_game_token(&mut self, game: GameRef) {
        self.games
            .entry(game.id().to_string())
            .and_modify(|n| *n = n.saturating_sub(1));
    }

    /// how many games tokens for the given game the player has
    pub fn game_token_count(&self, game: GameRef) -> u32 {
        self.games.get(game.id()).copied().unwrap_or_default()
    }

    /// how many game tokens the player has across all games
    pub fn game_token_total(&self) -> u32 {
        self.games.values().sum()
    }
}

pub fn points(state: &State) {
    println!("You have {} party points.", state.party_points);
}

pub fn stats(state: &State, history: &PushHistory) {
    if !state.is_party_unlocked("stats") {
        println!("You haven't unlocked the Stats party yet.");
        return;
    }

    let clock = crate::clock::Clock::from_now();
    let push = crate::git::Push::default();
    let breakdown = crate::scoring::PointsBreakdown {
        commits: 0,
        points_per_commit: 0,
        total: 0,
        applied: vec![],
    };

    let ctx =
        crate::party::RenderContext::new(&push, history, &breakdown, state, &clock, Vec::new());
    crate::party::stats::Stats.render(&ctx, &crate::party::Palette::WHITE_ANSI);
}

pub fn dump(state: &State) {
    println!("party_points: {}", state.party_points);
    println!("lifetime_points_earned: {}", state.lifetime_points_earned);
    println!("lifetime_packs_earned: {}", state.lifetime_packs_earned);
    println!("points_per_commit: {}", state.points_per_commit());
    println!("bonus_levels: {:?}", state.bonus_tracks);
    println!("unlocked_parties: {:?}", state.unlocked_parties);
    println!("enabled_parties: {:?}", state.enabled_parties);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn default_state_has_zero_points_or_packs() {
        let state = State::default();
        assert_eq!(state.party_points, 0);
        assert_eq!(state.lifetime_points_earned, 0);
        assert_eq!(state.packs.values().count(), 0)
    }

    #[test]
    fn earn_points_updates_both_balances() {
        let mut state = State::default();
        state.earn_points(100);
        assert_eq!(state.party_points, 100);
        assert_eq!(state.lifetime_points_earned, 100);

        // spend some points
        state.party_points -= 30;
        state.earn_points(50);
        assert_eq!(state.party_points, 120);
        assert_eq!(state.lifetime_points_earned, 150);
    }

    #[test]
    fn default_state_has_commit_value_at_level_one() {
        let state = State::default();
        assert_eq!(state.bonus_level("commit_value"), 1);
    }

    #[test]
    fn default_state_has_one_unlock() {
        let state = State::default();
        assert_eq!(state.unlocked_parties.len(), 1);
        assert_eq!(state.enabled_parties.len(), 1);
    }

    #[test]
    fn bonus_level_returns_zero_for_missing() {
        let state = State::default();
        assert_eq!(state.bonus_level("nonexistent"), 0);
    }

    #[test]
    fn set_bonus_level_works() {
        let mut state = State::default();
        state.set_bonus_level("first_push", 3);
        assert_eq!(state.bonus_level("first_push"), 3);
    }

    #[test]
    fn points_per_commit_uses_commit_value_level() {
        let mut state = State::default();
        assert_eq!(state.points_per_commit(), 1);

        state.set_bonus_level("commit_value", 2);
        assert_eq!(state.points_per_commit(), 2);

        state.set_bonus_level("commit_value", 5);
        assert_eq!(state.points_per_commit(), 5);
    }

    #[test]
    fn unlock_feature_adds_to_both_sets() {
        let mut state = State::default();
        let id = "exclamations";
        state.unlock_party(id);

        assert!(state.is_party_unlocked(id));
        assert!(state.is_party_enabled(id));
    }

    #[test]
    fn toggle_feature_works() {
        let mut state = State::default();
        let id = "exclamations";

        state.unlock_party(id);

        assert!(state.is_party_enabled(id));
        state.toggle_party(id);
        assert!(!state.is_party_enabled(id));
        state.toggle_party(id);
        assert!(state.is_party_enabled(id));
    }

    #[test]
    fn toggle_locked_party_does_nothing() {
        let mut state = State::default();
        let id = "big_text";

        state.toggle_party(id);
        assert!(!state.is_party_enabled(id));
    }

    #[test]
    fn test_add_and_open_pack() {
        let mut state = State::default();
        assert_eq!(state.pack_count(&Pack::Basic), 0);

        state.add_pack(Pack::Basic);
        assert_eq!(state.pack_count(&Pack::Basic), 1);

        // nothing breaks
        state.open_pack(Pack::Basic);
    }

    #[test]
    fn get_packs_based_on_lifetime_points() {
        let mut state = State::default();

        assert_eq!(state.lifetime_packs_earned, 0);
        assert_eq!(state.pack_count(&Pack::Basic), 0);

        // should earn 1 pack
        let thresholds = state.earn_points(PACK_ACCRUAL_RATE);

        assert_eq!(thresholds, vec![PACK_ACCRUAL_RATE]);
        assert_eq!(state.lifetime_packs_earned, 1);
        assert_eq!(state.pack_count(&Pack::Basic), 1);

        // should earn 2 packs at once
        let thresholds = state.earn_points(5 * PACK_ACCRUAL_RATE);

        assert_eq!(
            thresholds,
            vec![3 * PACK_ACCRUAL_RATE, 6 * PACK_ACCRUAL_RATE]
        );
        assert_eq!(state.lifetime_packs_earned, 3);
        assert_eq!(state.pack_count(&Pack::Basic), 3);
    }
}