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
#![allow(unused_imports)]
#![allow(dead_code)]

#[macro_use]
extern crate wasm_bindgen;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;

extern crate oasis_game_core;

use wasm_bindgen::prelude::*;
use oasis_game_core::{Store, Action, GameError};
use std::collections::HashMap;

#[wasm_bindgen]
extern "C" {
    #[wasm_bindgen(js_namespace = console)]
    fn info(s: &str);
}

#[wasm_bindgen]
pub struct Proxy {
    store: Box<dyn Store>
}

#[wasm_bindgen]
impl Proxy {
    pub fn get_move_names(&self) -> JsValue {
        let moves: Vec<String> = self.store.get_move_names()
            .iter()
            .map(|x| String::from(*x))
            .collect();
        JsValue::from_serde(&moves).unwrap()
    }

    pub fn get_state(&self) -> JsValue {
        let state = self.store.get_state();
        let js_value = JsValue::from_serde(&state);
        js_value.unwrap()
    }

    pub fn get_player_id(&self) -> u16 {
        self.store.get_player_id()
    }

    pub fn dispatch(&mut self, action: JsValue) -> Result<(), JsValue> {
        let action: Action = JsValue::into_serde(&action).unwrap();
        self.store.dispatch(action).map_err(|err| JsValue::from_str(&err.to_string()))
    }
}

pub fn create_proxy (store: Box<dyn Store>) -> Proxy {
    Proxy {
        store
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}