web_lib/offscreen_game/
round_validation.rs

1use mahjong_core::PlayerId;
2use serde::Serialize;
3use ts_rs::TS;
4use wasm_bindgen::prelude::wasm_bindgen;
5
6use super::OffscreenGame;
7
8#[derive(Clone, Serialize, TS)]
9#[ts(export)]
10pub enum RoundValidationError {
11    NoHandMahjong,
12}
13
14#[wasm_bindgen]
15pub struct IsValidRoundResult {
16    pub is_valid: bool,
17    error_message: Option<RoundValidationError>,
18    #[wasm_bindgen(getter_with_clone)]
19    pub winner_player: Option<PlayerId>,
20}
21
22#[wasm_bindgen]
23impl IsValidRoundResult {
24    pub fn error_message_data(&self) -> String {
25        serde_json::to_string(&self.error_message).unwrap()
26    }
27}
28
29#[wasm_bindgen]
30impl OffscreenGame {
31    pub fn get_is_valid_round(&self) -> IsValidRoundResult {
32        let mut hand_with_mahjong: Option<PlayerId> = None;
33
34        for player in self.game.players.iter() {
35            let hand = self.game.table.hands.get(player).unwrap();
36
37            if hand.can_say_mahjong().is_ok_and(|_| true) {
38                hand_with_mahjong = Some(player.clone());
39                break;
40            }
41        }
42
43        if hand_with_mahjong.is_some() {
44            return IsValidRoundResult {
45                error_message: None,
46                is_valid: true,
47                winner_player: hand_with_mahjong,
48            };
49        }
50
51        IsValidRoundResult {
52            error_message: Some(RoundValidationError::NoHandMahjong),
53            is_valid: false,
54            winner_player: None,
55        }
56    }
57}