initial o-x-rust implementation complete
This commit is contained in:
parent
53ba27bd11
commit
124e5c0f7f
|
@ -25,7 +25,7 @@ dependencies = [
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "o-x-rust"
|
name = "o-x-rust"
|
||||||
version = "0.0.2"
|
version = "0.0.3"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
|
@ -4,7 +4,7 @@ description = "Naughts and crosses WASM algorithms"
|
||||||
repository = "https://git.koval.net/cyclane/game-algorithms/src/branch/main/wasm/o-x-rust"
|
repository = "https://git.koval.net/cyclane/game-algorithms/src/branch/main/wasm/o-x-rust"
|
||||||
license = "GNU GPLv3"
|
license = "GNU GPLv3"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
version = "0.0.2"
|
version = "0.0.3"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
|
|
|
@ -1,6 +1,58 @@
|
||||||
use wasm_bindgen::prelude::wasm_bindgen;
|
use wasm_bindgen::prelude::wasm_bindgen;
|
||||||
|
|
||||||
#[wasm_bindgen]
|
#[wasm_bindgen]
|
||||||
pub fn add(a: usize, b: usize) -> usize {
|
pub fn find_winner(board: &[u8]) -> u8 {
|
||||||
a + b
|
for i in 0..3 {
|
||||||
|
let h = i*3;
|
||||||
|
if board[h] == board[h + 1] && board[h + 1] == board[h + 2] {
|
||||||
|
return board[h];
|
||||||
|
}
|
||||||
|
if board[i] == board[i + 3] && board[i + 3] == board[i + 6] {
|
||||||
|
return board[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if board[0] == board[4] && board[4] == board[8] {
|
||||||
|
return board[0];
|
||||||
|
}
|
||||||
|
if board[2] == board[4] && board[4] == board[6] {
|
||||||
|
return board[2];
|
||||||
|
}
|
||||||
|
0
|
||||||
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn count_empty(board: &[u8]) -> usize {
|
||||||
|
board.iter().filter(|&n| *n == 0).count()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn get_turn(me: u8, other: u8, first: bool, empty: usize) -> u8 {
|
||||||
|
if empty % 2 == if first { 1 } else { 0 } {
|
||||||
|
me
|
||||||
|
} else {
|
||||||
|
other
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[wasm_bindgen]
|
||||||
|
pub fn get_score(me: u8, other: u8, first: bool, board: &[u8]) -> i32 {
|
||||||
|
let winner = find_winner(board);
|
||||||
|
if winner != 0 {
|
||||||
|
return if winner == me { 1 } else { -1 };
|
||||||
|
}
|
||||||
|
let empty = count_empty(board);
|
||||||
|
if empty == 0 {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
let mut score = 0;
|
||||||
|
for i in 0..9 {
|
||||||
|
if board[i] != 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let copy = &mut [0u8; 9];
|
||||||
|
copy.copy_from_slice(board);
|
||||||
|
copy[i] = get_turn(me, other, first, empty);
|
||||||
|
score += get_score(me, other, first, copy);
|
||||||
|
}
|
||||||
|
score
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue