DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 7d5486e5144305656353cbfcdfd8a177c99cb88b deck-builder/client/src/game_status/parser.rs -rw-r--r-- 13.1 KiB
7d5486e5Jonni Liljamo feat(client): advanced roll action, log configs 1 year, 4 months ago
                                                                                
cd13a21d skye
c5909cd0 skye
c5909cd0 skye
c5909cd0 skye
c5909cd0 skye
89bbb3e7 skye
c5909cd0 skye
89bbb3e7 skye
c5909cd0 skye
c5909cd0 skye
89bbb3e7 skye
c5909cd0 skye
c5909cd0 skye
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
/*
 * This file is part of laurelin_client
 * Copyright (C) 2023 Jonni Liljamo <jonni@liljamo.com>
 *
 * Licensed under GPL-3.0-only.
 * See LICENSE for licensing information.
 */

use std::collections::HashMap;

use fastrand::Rng;

use crate::{
    api::game::{Action, Command, Game},
    game_status::SupplyPile,
    util::action_to_log,
};

use super::{GameStatus, LogEntry, LogSection, PlayerState, PlayerStatus};

/// funny unsafe wrapper
fn get_invoker_target_next<'a>(
    players: &'a mut HashMap<String, PlayerStatus>,
    invoker: &String,
    target: &String,
) -> (&'a mut PlayerStatus, &'a mut PlayerStatus, String) {
    unsafe {
        // NOTE: soo... I don't really know the consequences of possibly
        // having two mutable references to the same value, but I guess
        // I'll find out!
        // in many instances where people wanted multiple mutable references
        // to Vec or HashMap values, they only gave one in wrappers like this,
        // if the wanted values were the same.
        // e.g. returning (V, None), if the keys were the same.

        let invoker_ref: *mut PlayerStatus = players.get_mut(invoker).unwrap() as *mut _;
        let target_ref: *mut PlayerStatus = players.get_mut(target).unwrap() as *mut _;

        let next_turn_n: usize = if ((*invoker_ref).turn_n + 1) > (players.len() - 1) {
            0
        } else {
            (*invoker_ref).turn_n + 1
        };

        let next_player = players
            .iter()
            .find(|np| np.1.turn_n == next_turn_n)
            .unwrap();

        (&mut *invoker_ref, &mut *target_ref, next_player.0.clone())
    }
}

pub fn parse(game: &Game) -> Result<GameStatus, ()> {
    let mut game_status = GameStatus {
        log: vec![],
        actions: game.actions.as_ref().unwrap().to_vec(),
        supply_piles: vec![],
        players: HashMap::new(),
    };

    game_status.players.insert(
        game.host_id.clone(),
        PlayerStatus {
            turn_n: 0,
            display_name: game.host.as_ref().unwrap().username.clone(),
            state: PlayerState::Idle,
            plays: 0,
            buys: 0,
            currency: 0,
            vp: 2,
            hand: vec![],
            deck: vec![],
            discard: vec![],
        },
    );

    game_status.players.insert(
        game.guest_id.clone(),
        PlayerStatus {
            turn_n: 1,
            display_name: game.guest.as_ref().unwrap().username.clone(),
            state: PlayerState::Idle,
            plays: 0,
            buys: 0,
            currency: 0,
            vp: 2,
            hand: vec![],
            deck: vec![],
            discard: vec![],
        },
    );

    for action in game_status.actions.clone() {
        parse_action(&action, game, &mut game_status);
    }

    Ok(game_status)
}

macro_rules! current_seed {
    ($action:ident) => {
        Some($action.seed.parse::<u64>().unwrap())
    };
}

fn parse_action(action: &Action, game: &Game, game_status: &mut GameStatus) {
    game_status.log.push(action_to_log(action, game_status));

    // invoker: the one who invoked the action
    // target: the one who the action affects, may also be the invoker, e.g. draw
    let (invoker, target, next_player_uuid) =
        get_invoker_target_next(&mut game_status.players, &action.invoker, &action.target);

    let Some(action_pos) = game_status.actions.iter().position(|a| *a == action.clone()) else {
        panic!("Action was not found in game_status.actions!");
    };

    match &action.command {
        Command::InitSupplyPile { card, amount } => {
            let pile = SupplyPile {
                card: card.clone(),
                amount: *amount,
            };

            game_status.supply_piles.push(pile);
        }
        Command::TakeFromPile { index, for_cost } => {
            // index should be within range
            assert!(*index <= game_status.supply_piles.len());
            let pile = &mut game_status
                .supply_piles
                .get_mut(*index)
                .unwrap_or_else(|| unreachable!());

            // pile should not be empty
            assert!(pile.amount > 0);

            // player should have buys
            assert!(target.buys > 0);

            // player should have enough
            assert!(*for_cost <= target.currency);

            pile.amount -= 1;
            target.buys -= 1;
            target.currency -= for_cost;

            target.discard.push(pile.card.clone());
        }
        Command::PlayCard { index } => {
            // index should be within range
            assert!(*index <= target.hand.len());

            // player should have plays
            assert!(target.plays > 0);
            target.plays -= 1;

            let card = target.hand.remove(*index);
            if card.to_be_trashed {
                // marked for trash, let it fall into oblivion
            } else {
                // discard normally
                target.discard.push(card.clone());
            }

            for card_action in &card.actions {
                let action = &Action::new(
                    &game.id,
                    &action.invoker,
                    if card_action.target_self {
                        &action.invoker
                    } else {
                        &next_player_uuid
                    },
                    &card_action.command,
                    current_seed!(action),
                );
                game_status.actions.insert(action_pos + 1, action.clone());

                parse_action(action, game, game_status);
            }
        }
        Command::Draw { amount } => {
            for _ in 0..*amount {
                if target.deck.is_empty() {
                    shuffle_discard_to_deck(target, action.seed.parse::<u64>().unwrap());
                }

                // NOTE: deck *might* still be empty, if discard was empty too
                if !target.deck.is_empty() {
                    target
                        .hand
                        .push(target.deck.pop().unwrap_or_else(|| unreachable!()));
                }
            }
        }
        Command::Discard { index } => {
            // index should be within range
            assert!(*index <= target.hand.len());
            target.discard.push(target.hand.remove(*index));
        }
        Command::EndTurn {} => {
            // NOTE: target will be the next player

            // set player to idle
            invoker.state = PlayerState::Idle;

            // clear stats
            invoker.currency = 0;
            invoker.plays = 0;
            invoker.buys = 0;

            let start_turn_action = Action::new(
                &game.id,
                &action.invoker,
                &action.target,
                &Command::StartTurn {},
                current_seed!(action),
            );
            game_status
                .actions
                .insert(action_pos + 1, start_turn_action.clone());

            parse_action(&start_turn_action, game, game_status);
        }
        Command::StartTurn {} => {
            // set the target to the play phase
            target.state = PlayerState::PlayPhase;

            // give a play and a buy at the start
            target.plays = 1;
            target.buys = 1;

            let draw_action = Action::new(
                &game.id,
                &action.target,
                &action.target,
                &Command::Draw { amount: 2 },
                current_seed!(action),
            );
            game_status
                .actions
                .insert(action_pos + 1, draw_action.clone());

            parse_action(&draw_action, game, game_status);
        }
        Command::ChangePlayerState { state } => {
            target.state = *state;
        }
        Command::RollForAdvanced { amount, sides, pairs } => {
            let mut results: Vec<usize> = Vec::with_capacity(*amount);
            for _ in 0..*amount {
                let result = Rng::with_seed(action.seed.parse::<u64>().unwrap()).usize(1..=*sides);

                let mut last = 0;
                for (pos, res) in pairs {
                    if (last..=*pos).contains(&result) {
                        // TODO: check res.target_self, and select another
                        // player as target if false.
                        let action = Action::new(
                            &game.id,
                            &action.target,
                            &action.target,
                            &res.command,
                            current_seed!(action),
                        );
                        game_status
                            .actions
                            .insert(action_pos + 1, action.clone());

                        parse_action(&action, game, game_status);
                    }
                    last = *pos;
                }

                results.push(result);
            }

            /*
            if *amount == 1 {
                game_status
                    .log
                    .push(LogEntry::from_sections([LogSection::bold(
                        &results.first().unwrap().to_string(),
                    )]));
            } else {
                game_status
                    .log
                    .push(LogEntry::from_sections([LogSection::bold(&format!(
                        "   {} = {}",
                        results
                            .iter()
                            .map(ToString::to_string)
                            .collect::<Vec<String>>()
                            .join(" "),
                        results.iter().sum::<usize>(),
                    ))]));
            }
            */
        }
        Command::GiveCurrency { amount } => {
            target.currency += amount;
        }
        Command::RollForCurrency { amount, sides } => {
            let mut results: Vec<usize> = Vec::with_capacity(*amount);
            for _ in 0..*amount {
                let result = Rng::with_seed(action.seed.parse::<u64>().unwrap()).usize(1..=*sides);
                target.currency += result;

                results.push(result);
            }

            if *amount == 1 {
                game_status
                    .log
                    .push(LogEntry::from_sections([LogSection::bold(
                        &results.first().unwrap().to_string(),
                    )]));
            } else {
                game_status
                    .log
                    .push(LogEntry::from_sections([LogSection::bold(&format!(
                        "   {} = {}",
                        results
                            .iter()
                            .map(ToString::to_string)
                            .collect::<Vec<String>>()
                            .join(" "),
                        results.iter().sum::<usize>(),
                    ))]));
            }
        }
        Command::GivePlays { amount } => {
            target.plays += amount;
        }
        Command::RollForPlays { amount, sides } => {
            let mut results: Vec<usize> = Vec::with_capacity(*amount);
            for _ in 0..*amount {
                let result = Rng::with_seed(action.seed.parse::<u64>().unwrap()).usize(1..=*sides);
                target.plays += result;

                results.push(result);
            }

            if *amount == 1 {
                game_status
                    .log
                    .push(LogEntry::from_sections([LogSection::bold(
                        &results.first().unwrap().to_string(),
                    )]));
            } else {
                game_status
                    .log
                    .push(LogEntry::from_sections([LogSection::bold(&format!(
                        "   {} = {}",
                        results
                            .iter()
                            .map(ToString::to_string)
                            .collect::<Vec<String>>()
                            .join(" "),
                        results.iter().sum::<usize>(),
                    ))]));
            }
        }
        Command::GiveBuys { amount } => {
            target.buys += amount;
        }
        Command::GiveVP { amount } => {
            target.vp += amount;
        }
        Command::RemoveVP { amount } => {
            target.vp -= amount;
        }
        Command::MarkCardInDeckToBeTrashed { index } => {
            if target.deck.is_empty() {
                return;
            }
            match index {
                Some(index) => {
                    target.deck.get_mut(*index).unwrap().to_be_trashed = true;
                }
                None => {
                    let deck_len = target.deck.len();
                    target
                        .deck
                        .get_mut(
                            Rng::with_seed(action.seed.parse::<u64>().unwrap()).usize(0..deck_len),
                        )
                        .unwrap()
                        .to_be_trashed = true;
                }
            }
        }
        #[allow(unreachable_patterns)]
        _ => todo!(),
    }
}

fn shuffle_discard_to_deck(target: &mut PlayerStatus, seed: u64) {
    let cards = target.discard.to_vec();
    target.discard.clear();

    target.deck = cards;

    let rng = Rng::with_seed(seed);
    rng.shuffle(&mut target.deck);
}