DEVELOPMENT ENVIRONMENT

~liljamo/deck-builder

ref: 0c4f861d4867c926ef1e031d211dc01fe8b6f68b deck-builder/client/src/plugins/async_tasks/parse_game_status.rs -rw-r--r-- 2.1 KiB
0c4f861dJonni Liljamo Merge branch 'master' into dev 1 year, 7 months ago
                                                                                
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
/*
 * 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 crate::{
    api::game::Game,
    game_status::GameStatus,
    plugins::{game::GameData, FinishedRefreshGameEvent},
};

use bevy::{
    prelude::*,
    tasks::{AsyncComputeTaskPool, Task},
};
use futures_lite::future;

use super::GameEndCallEvent;

#[derive(Component)]
pub struct ParseGameStatus(Task<GameStatus>);

#[derive(Clone)]
pub struct ParseGameStatusEvent {
    pub game: Game,
}

pub fn start_call(mut commands: Commands, mut start_ev_r: EventReader<ParseGameStatusEvent>) {
    for ev in start_ev_r.iter() {
        let thread_pool = AsyncComputeTaskPool::get();
        let ev = ev.clone();
        let task = thread_pool.spawn(async move { GameStatus::new(&ev.game) });
        commands.spawn(ParseGameStatus(task));
    }
}

pub fn handle_call(
    mut commands: Commands,
    mut tasks: Query<(Entity, &mut ParseGameStatus)>,
    mut game_data: ResMut<GameData>,
    mut eg_ev_w: EventWriter<GameEndCallEvent>,
    mut frg_ev_w: EventWriter<FinishedRefreshGameEvent>,
) {
    if let Ok((entity, mut task)) = tasks.get_single_mut() {
        if let Some(response) = future::block_on(future::poll_once(&mut task.0)) {
            game_data.game_status = Some(response);
            game_data.locked = false;

            // NOTE: checking for end conditions
            let mut empty_piles = 0;
            for pile in &game_data.game_status.as_ref().unwrap().supply_piles {
                if pile.amount == 0 {
                    empty_piles += 1;
                }
            }
            if empty_piles >= 2 {
                // end me daddy
                eg_ev_w.send(GameEndCallEvent {
                    game_id: game_data.game.as_ref().unwrap().id.clone(),
                });
            } else {
                // dont end me daddy
                frg_ev_w.send(FinishedRefreshGameEvent);
            }

            // remove the task
            commands.entity(entity).remove::<ParseGameStatus>();
            commands.entity(entity).despawn_recursive();
        }
    }
}