Spaces:
Running
Running
File size: 2,061 Bytes
88d4171 |
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 |
use wasm_bindgen::prelude::*;
use crate::core::models::{GameState, CardDatabase};
use crate::core::mcts::{SearchHorizon, EvalMode};
#[wasm_bindgen]
pub struct WasmEngine {
state: GameState,
db: CardDatabase,
}
#[wasm_bindgen]
impl WasmEngine {
#[wasm_bindgen(constructor)]
pub fn new(card_db_json: &str) -> Result<WasmEngine, JsError> {
let db = CardDatabase::from_json(card_db_json)
.map_err(|e| JsError::new(&format!("Failed to parse card DB: {}", e)))?;
Ok(WasmEngine {
state: GameState::default(),
db,
})
}
pub fn init_game(&mut self,
p0_deck: Vec<u32>,
p1_deck: Vec<u32>,
p0_energy: Vec<u32>,
p1_energy: Vec<u32>,
p0_lives: Vec<u32>,
p1_lives: Vec<u32>,
seed: Option<u64>
) {
self.state.initialize_game_with_seed(
p0_deck.into_iter().map(|x| x as u16).collect(),
p1_deck.into_iter().map(|x| x as u16).collect(),
p0_energy.into_iter().map(|x| x as u16).collect(),
p1_energy.into_iter().map(|x| x as u16).collect(),
p0_lives.into_iter().map(|x| x as u16).collect(),
p1_lives.into_iter().map(|x| x as u16).collect(),
seed
);
}
pub fn step(&mut self, action_id: i32) -> Result<(), JsError> {
self.state.step(&self.db, action_id)
.map_err(|e| JsError::new(&e.to_string()))
}
pub fn get_state_json(&self) -> Result<String, JsError> {
serde_json::to_string(&self.state)
.map_err(|e| JsError::new(&e.to_string()))
}
pub fn get_legal_actions(&mut self) -> Vec<i32> {
self.state.get_legal_action_ids(&self.db)
}
pub fn ai_suggest(&mut self, sims: usize) -> Result<i32, JsError> {
let suggestions = self.state.get_mcts_suggestions(&self.db, sims, SearchHorizon::GameEnd, EvalMode::Normal);
if let Some((action, _, _)) = suggestions.first() {
Ok(*action)
} else {
Ok(0)
}
}
}
|