web_lib/offscreen_game/
round_validation.rs

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
use mahjong_core::PlayerId;
use serde::Serialize;
use ts_rs::TS;
use wasm_bindgen::prelude::wasm_bindgen;

use super::OffscreenGame;

#[derive(Clone, Serialize, TS)]
#[ts(export)]
pub enum RoundValidationError {
    NoHandMahjong,
}

#[wasm_bindgen]
pub struct IsValidRoundResult {
    pub is_valid: bool,
    error_message: Option<RoundValidationError>,
    #[wasm_bindgen(getter_with_clone)]
    pub winner_player: Option<PlayerId>,
}

#[wasm_bindgen]
impl IsValidRoundResult {
    pub fn error_message_data(&self) -> String {
        serde_json::to_string(&self.error_message).unwrap()
    }
}

#[wasm_bindgen]
impl OffscreenGame {
    pub fn get_is_valid_round(&self) -> IsValidRoundResult {
        let mut hand_with_mahjong: Option<PlayerId> = None;

        for player in self.game.players.iter() {
            let hand = self.game.table.hands.get(&player).unwrap();

            if hand.can_say_mahjong().map_or(false, |_| true) {
                hand_with_mahjong = Some(player.clone());
                break;
            }
        }

        if hand_with_mahjong.is_some() {
            return IsValidRoundResult {
                error_message: None,
                is_valid: true,
                winner_player: hand_with_mahjong,
            };
        }

        IsValidRoundResult {
            error_message: Some(RoundValidationError::NoHandMahjong),
            is_valid: false,
            winner_player: None,
        }
    }
}