Improve WIP move-checking integration

This commit is contained in:
Joel Therrien 2023-08-13 17:02:13 -07:00
parent a496b15710
commit deedc1aee4
2 changed files with 77 additions and 5 deletions

View file

@ -9,6 +9,19 @@ use crate::game::Game;
#[wasm_bindgen]
pub struct GameWasm(Game);
#[derive(Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
pub enum ResponseType {
OK,
ERR,
}
#[derive(Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
pub struct MyResult<E> {
response_type: ResponseType,
value: E,
}
#[derive(Deserialize, Tsify, Copy, Clone)]
#[tsify(from_wasm_abi)]
@ -70,11 +83,55 @@ impl GameWasm {
}
}
board_instance.receive_play(played_letters)?;
match board_instance.receive_play(played_letters) {
Err(e) => {
return Ok(serde_wasm_bindgen::to_value(
&MyResult {
response_type: ResponseType::ERR,
value: e
}).unwrap());
},
Ok(_) => {}
}
let result = board_instance.calculate_scores(self.0.get_dictionary())?;
#[derive(Debug, Serialize, Deserialize, Tsify)]
#[tsify(from_wasm_abi)]
struct WordResult {
word: String,
score: u32,
}
Ok(serde_wasm_bindgen::to_value(&&result.1).unwrap())
let result = board_instance.calculate_scores(self.0.get_dictionary());
let result = match result {
Ok(x) => {
let words: Vec<WordResult> = x.0.iter()
.map(|(word, score)| {
WordResult {
word: word.to_string(),
score: *score
}
})
.collect();
//let total_score = x.1;
serde_wasm_bindgen::to_value(
&MyResult {
response_type: ResponseType::OK,
value: words
}).unwrap()
},
Err(e) => {
serde_wasm_bindgen::to_value(
&MyResult {
response_type: ResponseType::ERR,
value: e
}).unwrap()
}
};
Ok(result)
}
}

View file

@ -1,5 +1,5 @@
import * as React from "react";
import {GameWasm, Letter as LetterData, PlayedTile, Tray} from "word_grid";
import {GameWasm, Letter as LetterData, MyResult, PlayedTile, Tray, WordResult} from "word_grid";
import {createRoot} from "react-dom/client";
import {Children, useMemo, useReducer, useState} from "react";
@ -141,8 +141,23 @@ export function Game(props: {wasm: GameWasm}) {
return null;
});
const result = props.wasm.receive_play(playedTiles, false);
const result: MyResult<Array<WordResult> | string> = props.wasm.receive_play(playedTiles, false);
console.log({result});
if(result.response_type === "ERR") {
alert(result.value);
} else {
let total_points = 0;
for (let word_result of (result.value as Array<WordResult>)) {
total_points += word_result.score;
}
alert(`You would score ${total_points} points.`);
}
}}>Check Submission</button>
</>;