|
| 1 | +//! Shared helpers for mapping Mjai messages to a legal `Action`. |
| 2 | +//! |
| 3 | +//! Used by both `Observation::select_action_from_mjai` (4P) and |
| 4 | +//! `Observation3P::select_action_from_mjai` (3P). |
| 5 | +
|
| 6 | +use pyo3::prelude::*; |
| 7 | +use pyo3::types::{PyDict, PyDictMethods}; |
| 8 | + |
| 9 | +use crate::action::{Action, ActionType}; |
| 10 | +use crate::parser::tid_to_mjai; |
| 11 | + |
| 12 | +pub(crate) struct ParsedMjai { |
| 13 | + pub type_str: String, |
| 14 | + pub tile_str: String, |
| 15 | + pub tsumogiri: Option<bool>, |
| 16 | + pub consumed: Option<Vec<String>>, |
| 17 | +} |
| 18 | + |
| 19 | +pub(crate) fn parse_mjai_message(mjai_data: &Bound<'_, PyAny>) -> Option<ParsedMjai> { |
| 20 | + if let Ok(s) = mjai_data.extract::<String>() { |
| 21 | + let v: serde_json::Value = serde_json::from_str(&s).ok()?; |
| 22 | + let type_str = v["type"].as_str()?.to_string(); |
| 23 | + let tile_str = v["pai"].as_str().unwrap_or("").to_string(); |
| 24 | + let tsumogiri = v.get("tsumogiri").and_then(|x| x.as_bool()); |
| 25 | + let consumed = v.get("consumed").and_then(|x| x.as_array()).map(|arr| { |
| 26 | + arr.iter() |
| 27 | + .filter_map(|e| e.as_str().map(|s| s.to_string())) |
| 28 | + .collect::<Vec<_>>() |
| 29 | + }); |
| 30 | + Some(ParsedMjai { |
| 31 | + type_str, |
| 32 | + tile_str, |
| 33 | + tsumogiri, |
| 34 | + consumed, |
| 35 | + }) |
| 36 | + } else if let Ok(dict) = mjai_data.cast::<PyDict>() { |
| 37 | + let type_str: String = dict |
| 38 | + .get_item("type") |
| 39 | + .ok() |
| 40 | + .flatten() |
| 41 | + .and_then(|x| x.extract::<String>().ok()) |
| 42 | + .unwrap_or_default(); |
| 43 | + let tile_str: String = dict |
| 44 | + .get_item("pai") |
| 45 | + .ok() |
| 46 | + .flatten() |
| 47 | + .or_else(|| dict.get_item("tile").ok().flatten()) |
| 48 | + .and_then(|x| x.extract::<String>().ok()) |
| 49 | + .unwrap_or_default(); |
| 50 | + let tsumogiri = dict |
| 51 | + .get_item("tsumogiri") |
| 52 | + .ok() |
| 53 | + .flatten() |
| 54 | + .and_then(|x| x.extract::<bool>().ok()); |
| 55 | + let consumed = dict |
| 56 | + .get_item("consumed") |
| 57 | + .ok() |
| 58 | + .flatten() |
| 59 | + .and_then(|x| x.extract::<Vec<String>>().ok()); |
| 60 | + Some(ParsedMjai { |
| 61 | + type_str, |
| 62 | + tile_str, |
| 63 | + tsumogiri, |
| 64 | + consumed, |
| 65 | + }) |
| 66 | + } else { |
| 67 | + None |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +fn consumed_matches(action_consume: &[u8], expected: &[String]) -> bool { |
| 72 | + if action_consume.len() != expected.len() { |
| 73 | + return false; |
| 74 | + } |
| 75 | + let mut a: Vec<String> = action_consume.iter().map(|&t| tid_to_mjai(t)).collect(); |
| 76 | + let mut b: Vec<String> = expected.to_vec(); |
| 77 | + a.sort(); |
| 78 | + b.sort(); |
| 79 | + a == b |
| 80 | +} |
| 81 | + |
| 82 | +/// Select a matching `Action` from a slice of legal actions for a parsed Mjai |
| 83 | +/// message. |
| 84 | +/// |
| 85 | +/// `three_player` controls whether 3P-only types (`kita`) are recognized; chi |
| 86 | +/// is rejected when set. |
| 87 | +pub(crate) fn select_action<'a>( |
| 88 | + legal_actions: &'a [Action], |
| 89 | + parsed: &ParsedMjai, |
| 90 | + drawn_tile: Option<u8>, |
| 91 | + three_player: bool, |
| 92 | +) -> Option<&'a Action> { |
| 93 | + let atype = parsed.type_str.as_str(); |
| 94 | + |
| 95 | + if atype == "hora" { |
| 96 | + return legal_actions |
| 97 | + .iter() |
| 98 | + .find(|a| matches!(a.action_type, ActionType::Tsumo | ActionType::Ron)); |
| 99 | + } |
| 100 | + |
| 101 | + if atype == "none" { |
| 102 | + return legal_actions |
| 103 | + .iter() |
| 104 | + .find(|a| a.action_type == ActionType::Pass); |
| 105 | + } |
| 106 | + |
| 107 | + let target_type = match atype { |
| 108 | + "dahai" => Some(ActionType::Discard), |
| 109 | + "chi" if !three_player => Some(ActionType::Chi), |
| 110 | + "pon" => Some(ActionType::Pon), |
| 111 | + "kakan" => Some(ActionType::Kakan), |
| 112 | + "daiminkan" => Some(ActionType::Daiminkan), |
| 113 | + "ankan" => Some(ActionType::Ankan), |
| 114 | + "kita" if three_player => Some(ActionType::Kita), |
| 115 | + "reach" => Some(ActionType::Riichi), |
| 116 | + "ryukyoku" => Some(ActionType::KyushuKyuhai), |
| 117 | + _ => None, |
| 118 | + }; |
| 119 | + |
| 120 | + let tt = target_type?; |
| 121 | + |
| 122 | + // Special-case Discard: filter by mjai pai (or any Discard if pai is |
| 123 | + // omitted) then disambiguate via tsumogiri. |
| 124 | + // |
| 125 | + // NOTE: An mjai `dahai` message without a `pai` field is malformed per |
| 126 | + // the protocol, but we still return a non-empty Action (the first |
| 127 | + // legal Discard) instead of `None` to preserve backward compatibility |
| 128 | + // with the previous implementation; bailing out here would silently |
| 129 | + // break callers that rely on the old lenient behavior. |
| 130 | + if tt == ActionType::Discard { |
| 131 | + let candidates: Vec<&Action> = legal_actions |
| 132 | + .iter() |
| 133 | + .filter(|a| { |
| 134 | + a.action_type == ActionType::Discard |
| 135 | + && (parsed.tile_str.is_empty() |
| 136 | + || a.tile.is_some_and(|t| tid_to_mjai(t) == parsed.tile_str)) |
| 137 | + }) |
| 138 | + .collect(); |
| 139 | + |
| 140 | + if candidates.is_empty() { |
| 141 | + return None; |
| 142 | + } |
| 143 | + |
| 144 | + if let (Some(tsumogiri), Some(drawn)) = (parsed.tsumogiri, drawn_tile) { |
| 145 | + let preferred = candidates.iter().find(|a| { |
| 146 | + let is_drawn = a.tile == Some(drawn); |
| 147 | + if tsumogiri { is_drawn } else { !is_drawn } |
| 148 | + }); |
| 149 | + if let Some(a) = preferred { |
| 150 | + return Some(*a); |
| 151 | + } |
| 152 | + } |
| 153 | + |
| 154 | + return Some(candidates[0]); |
| 155 | + } |
| 156 | + |
| 157 | + legal_actions.iter().find(|a| { |
| 158 | + if a.action_type != tt { |
| 159 | + return false; |
| 160 | + } |
| 161 | + |
| 162 | + if let Some(consumed) = parsed.consumed.as_ref() { |
| 163 | + if !consumed_matches(&a.consume_tiles, consumed) { |
| 164 | + return false; |
| 165 | + } |
| 166 | + // If pai is also given, double-check tile match for actions that |
| 167 | + // carry a meaningful tile (chi/pon/daiminkan/kakan). |
| 168 | + if !parsed.tile_str.is_empty() |
| 169 | + && matches!( |
| 170 | + tt, |
| 171 | + ActionType::Chi | ActionType::Pon | ActionType::Daiminkan | ActionType::Kakan |
| 172 | + ) |
| 173 | + { |
| 174 | + if let Some(t) = a.tile { |
| 175 | + if tid_to_mjai(t) != parsed.tile_str { |
| 176 | + return false; |
| 177 | + } |
| 178 | + } else { |
| 179 | + return false; |
| 180 | + } |
| 181 | + } |
| 182 | + return true; |
| 183 | + } |
| 184 | + |
| 185 | + // No consumed field: fall back to pai-based match. |
| 186 | + if !parsed.tile_str.is_empty() { |
| 187 | + if let Some(t) = a.tile { |
| 188 | + return tid_to_mjai(t) == parsed.tile_str; |
| 189 | + } |
| 190 | + return false; |
| 191 | + } |
| 192 | + true |
| 193 | + }) |
| 194 | +} |
0 commit comments