splitting major logic into library, lots of wasm guards

This commit is contained in:
Andy Pack 2024-02-01 17:51:05 +00:00
parent f4f89e5519
commit a47d6b4320
Signed by: sarsoo
GPG Key ID: A55BA3536A5E0ED7
35 changed files with 609 additions and 249 deletions

2
.gitignore vendored
View File

@ -1,4 +1,4 @@
/target
**/target
**/*.rs.bk
bin/
pkg/

94
Cargo.lock generated
View File

@ -4,9 +4,9 @@ version = 3
[[package]]
name = "bumpalo"
version = "3.13.0"
version = "3.14.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1"
checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec"
[[package]]
name = "cfg-if"
@ -26,9 +26,17 @@ dependencies = [
[[package]]
name = "draught"
version = "0.1.0"
dependencies = [
"draughtlib",
]
[[package]]
name = "draught_web"
version = "1.0.1"
dependencies = [
"console_error_panic_hook",
"draughtlib",
"getrandom",
"indextree",
"rand",
@ -37,11 +45,20 @@ dependencies = [
"web-sys",
]
[[package]]
name = "draughtlib"
version = "0.1.0"
dependencies = [
"indextree",
"rand",
"wasm-bindgen",
]
[[package]]
name = "getrandom"
version = "0.2.10"
version = "0.2.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427"
checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5"
dependencies = [
"cfg-if",
"js-sys",
@ -58,30 +75,30 @@ checksum = "c40411d0e5c63ef1323c3d09ce5ec6d84d71531e18daed0743fccea279d7deb6"
[[package]]
name = "js-sys"
version = "0.3.64"
version = "0.3.67"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a"
checksum = "9a1d36f1235bc969acba30b7f5990b864423a6068a10f7c90ae8f0112e3a59d1"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.147"
version = "0.2.153"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd"
[[package]]
name = "log"
version = "0.4.19"
version = "0.4.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
[[package]]
name = "once_cell"
version = "1.18.0"
version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
[[package]]
name = "ppv-lite86"
@ -91,18 +108,18 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "proc-macro2"
version = "1.0.66"
version = "1.0.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9"
checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.32"
version = "1.0.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50f3b39ccfb720540debaa0164757101c08ecb8d326b15358ce76a62c7e85965"
checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef"
dependencies = [
"proc-macro2",
]
@ -145,9 +162,9 @@ checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
[[package]]
name = "syn"
version = "2.0.28"
version = "2.0.48"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04361975b3f5e348b2189d8dc55bc942f278b2d482a6a0365de5bdd62d351567"
checksum = "0f3531638e407dfc0814761abb7c00a5b54992b849452a0646b7f65c9f770f3f"
dependencies = [
"proc-macro2",
"quote",
@ -156,9 +173,9 @@ dependencies = [
[[package]]
name = "unicode-ident"
version = "1.0.11"
version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
[[package]]
name = "wasi"
@ -168,9 +185,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
version = "0.2.87"
version = "0.2.90"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342"
checksum = "b1223296a201415c7fad14792dbefaace9bd52b62d33453ade1c5b5f07555406"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
@ -178,9 +195,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.87"
version = "0.2.90"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd"
checksum = "fcdc935b63408d58a32f8cc9738a0bffd8f05cc7c002086c6ef20b7312ad9dcd"
dependencies = [
"bumpalo",
"log",
@ -193,9 +210,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.37"
version = "0.4.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03"
checksum = "bde2032aeb86bdfaecc8b261eef3cba735cc426c1f3a3416d1e0791be95fc461"
dependencies = [
"cfg-if",
"js-sys",
@ -205,9 +222,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.87"
version = "0.2.90"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d"
checksum = "3e4c238561b2d428924c49815533a8b9121c664599558a5d9ec51f8a1740a999"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
@ -215,9 +232,9 @@ dependencies = [
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.87"
version = "0.2.90"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b"
checksum = "bae1abb6806dc1ad9e560ed242107c0f6c84335f1749dd4e8ddb012ebd5e25a7"
dependencies = [
"proc-macro2",
"quote",
@ -228,15 +245,15 @@ dependencies = [
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.87"
version = "0.2.90"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1"
checksum = "4d91413b1c31d7539ba5ef2451af3f0b833a005eb27a631cec32bc0635a8602b"
[[package]]
name = "wasm-bindgen-test"
version = "0.3.37"
version = "0.3.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e6e302a7ea94f83a6d09e78e7dc7d9ca7b186bc2829c24a22d0753efd680671"
checksum = "139bd73305d50e1c1c4333210c0db43d989395b64a237bd35c10ef3832a7f70c"
dependencies = [
"console_error_panic_hook",
"js-sys",
@ -248,19 +265,20 @@ dependencies = [
[[package]]
name = "wasm-bindgen-test-macro"
version = "0.3.37"
version = "0.3.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecb993dd8c836930ed130e020e77d9b2e65dd0fbab1b67c790b0f5d80b11a575"
checksum = "70072aebfe5da66d2716002c729a14e4aec4da0e23cc2ea66323dac541c93928"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "web-sys"
version = "0.3.64"
version = "0.3.67"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b"
checksum = "58cd2333b6e0be7a39605f0e255892fd7418a682d8da8fe042fe25128794d2ed"
dependencies = [
"js-sys",
"wasm-bindgen",

View File

@ -1,54 +1,8 @@
[package]
name = "draught"
version = "1.0.1"
authors = ["aj <andrewjpack@gmail.com>"]
edition = "2018"
repository = "https://github.com/Sarsoo/draught"
[lib]
crate-type = ["cdylib", "rlib"]
[features]
default = ["console_error_panic_hook"]
debug_logs = [] # log extra stuff to the web console
time_ex = [] # allow time profiling in computer
[dependencies]
wasm-bindgen = "0.2.87"
indextree = "4.6.0"
rand = {version = "0.8.5"}
getrandom = {version = "*", features = ["js"]}
# rand = {version = "0.8"}
# getrandom = { version = "0.2", features = ["js"] }
# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = "0.1.7", optional = true }
[dependencies.web-sys]
version = "0.3.45"
features = [
"console",
'CanvasRenderingContext2d',
'Document',
'Element',
'HtmlCanvasElement',
'Window',
]
[dev-dependencies]
wasm-bindgen-test = "0.3.37"
[profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"
# [package.metadata.wasm-pack.profile.release]
# wasm-opt = false
[workspace]
resolver = "2"
members = [
"draught",
"draughtlib",
"draught_web",
]

9
draught/Cargo.toml Normal file
View File

@ -0,0 +1,9 @@
[package]
name = "draught"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
draughtlib = {path = "../draughtlib"}

3
draught/src/main.rs Normal file
View File

@ -0,0 +1,3 @@
fn main() {
}

267
draught_web/Cargo.lock generated Normal file
View File

@ -0,0 +1,267 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "bumpalo"
version = "3.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a3e2c3daef883ecc1b5d58c15adae93470a91d425f3532ba1695849656af3fc1"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "console_error_panic_hook"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc"
dependencies = [
"cfg-if",
"wasm-bindgen",
]
[[package]]
name = "draught"
version = "1.0.1"
dependencies = [
"console_error_panic_hook",
"getrandom",
"indextree",
"rand",
"wasm-bindgen",
"wasm-bindgen-test",
"web-sys",
]
[[package]]
name = "getrandom"
version = "0.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "be4136b2a15dd319360be1c07d9933517ccf0be8f16bf62a3bee4f0d618df427"
dependencies = [
"cfg-if",
"js-sys",
"libc",
"wasi",
"wasm-bindgen",
]
[[package]]
name = "indextree"
version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c40411d0e5c63ef1323c3d09ce5ec6d84d71531e18daed0743fccea279d7deb6"
[[package]]
name = "js-sys"
version = "0.3.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5f195fe497f702db0f318b07fdd68edb16955aed830df8363d837542f8f935a"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "libc"
version = "0.2.147"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3"
[[package]]
name = "log"
version = "0.4.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b06a4cde4c0f271a446782e3eff8de789548ce57dbc8eca9292c27f4a42004b4"
[[package]]
name = "once_cell"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "ppv-lite86"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
[[package]]
name = "proc-macro2"
version = "1.0.66"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50f3b39ccfb720540debaa0164757101c08ecb8d326b15358ce76a62c7e85965"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
"getrandom",
]
[[package]]
name = "scoped-tls"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
[[package]]
name = "syn"
version = "2.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04361975b3f5e348b2189d8dc55bc942f278b2d482a6a0365de5bdd62d351567"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "unicode-ident"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c"
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd"
dependencies = [
"bumpalo",
"log",
"once_cell",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-futures"
version = "0.4.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c02dbc21516f9f1f04f187958890d7e6026df8d16540b7ad9492bc34a67cea03"
dependencies = [
"cfg-if",
"js-sys",
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.87"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1"
[[package]]
name = "wasm-bindgen-test"
version = "0.3.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e6e302a7ea94f83a6d09e78e7dc7d9ca7b186bc2829c24a22d0753efd680671"
dependencies = [
"console_error_panic_hook",
"js-sys",
"scoped-tls",
"wasm-bindgen",
"wasm-bindgen-futures",
"wasm-bindgen-test-macro",
]
[[package]]
name = "wasm-bindgen-test-macro"
version = "0.3.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecb993dd8c836930ed130e020e77d9b2e65dd0fbab1b67c790b0f5d80b11a575"
dependencies = [
"proc-macro2",
"quote",
]
[[package]]
name = "web-sys"
version = "0.3.64"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b85cbef8c220a6abc02aefd892dfc0fc23afb1c6a426316ec33253a3877249b"
dependencies = [
"js-sys",
"wasm-bindgen",
]

51
draught_web/Cargo.toml Normal file
View File

@ -0,0 +1,51 @@
[package]
name = "draught_web"
version = "1.0.1"
authors = ["Sarsoo <andy@sarsoo.xyz>"]
edition = "2018"
repository = "https://github.com/Sarsoo/draught"
[lib]
crate-type = ["cdylib", "rlib"]
[features]
default = ["console_error_panic_hook"]
debug_logs = [] # log extra stuff to the web console
time_ex = [] # allow time profiling in computer
[dependencies]
draughtlib = {path = "../draughtlib"}
wasm-bindgen = "0.2.87"
indextree = "4.6.0"
rand = {version = "0.8.5"}
getrandom = {version = "*", features = ["js"]}
# The `console_error_panic_hook` crate provides better debugging of panics by
# logging them with `console.error`. This is great for development, but requires
# all the `std::fmt` and `std::panicking` infrastructure, so isn't great for
# code size when deploying.
console_error_panic_hook = { version = "0.1.7", optional = true }
[dependencies.web-sys]
version = "0.3.45"
features = [
"console",
'CanvasRenderingContext2d',
'Document',
'Element',
'HtmlCanvasElement',
'Window',
]
[dev-dependencies]
wasm-bindgen-test = "0.3.37"
[profile.release]
# Tell `rustc` to optimize for small code size.
opt-level = "s"
# [package.metadata.wasm-pack.profile.release]
# wasm-opt = false

View File

Before

Width:  |  Height:  |  Size: 66 KiB

After

Width:  |  Height:  |  Size: 66 KiB

View File

@ -2,31 +2,28 @@
//!
//! An implementation of checkers/draughts in Rust WebAssembly with a minimax AI player
pub mod board;
pub mod utils;
pub mod game;
pub mod paint;
pub mod comp;
extern crate wasm_bindgen;
use wasm_bindgen::prelude::*;
pub use board::Board;
pub use game::Game;
pub use comp::Computer;
pub use draughtlib::board::Board;
pub use draughtlib::game::Game;
pub use draughtlib::comp::Computer;
pub use paint::Painter;
/// Wrap the [`web_sys`] access to the browser console in a macro for easy logging
#[macro_export]
macro_rules! log {
( $( $t:tt )* ) => {
web_sys::console::log_1(&format!( $( $t )* ).into());
web_sys::console::log_1(&format!( $( $t )* ).into())
}
}
#[macro_export]
macro_rules! log_error {
( $( $t:tt )* ) => {
web_sys::console::error_1(&format!( $( $t )* ).into());
web_sys::console::error_1(&format!( $( $t )* ).into())
}
}

View File

@ -10,11 +10,12 @@ use web_sys::CanvasRenderingContext2d;
use std::f64;
use crate::log;
use crate::board::{Board, BrdIdx};
use crate::board::iter::PieceIterator;
use draughtlib::board::{Board, BrdIdx};
use draughtlib::board::iter::PieceIterator;
use crate::board::enums::Team::*;
use crate::board::enums::Strength::*;
use draughtlib::board::enums::Team::*;
use draughtlib::board::enums::Strength::*;
use draughtlib::game::Game;
/// Default hex colour value for white square background
const WHITE_SQUARE: &str = "#FFFFFF";
@ -83,11 +84,6 @@ pub struct Painter {
}
impl Painter {
/// Set selected piece by board index
pub fn set_selected(&mut self, idx: &Option<BrdIdx>) {
self.selected_idx = *idx;
}
/// Get a canvas by element ID
fn get_canvas(canvas_id: &str) -> HtmlCanvasElement {
// JS WINDOW
@ -136,11 +132,11 @@ impl Painter {
}
}
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl Painter {
/// Default constructor which queries for canvas by ID
#[wasm_bindgen(constructor)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))]
pub fn new(width: u32, height: u32, canvas_id: &str) -> Painter {
let canvas = Painter::get_canvas(canvas_id);
@ -209,6 +205,16 @@ impl Painter {
}
}
/// Set selected piece by board index
pub fn set_selected(&mut self, idx: &BrdIdx) {
self.selected_idx = Option::Some(*idx);
}
/// Clear selected piece by board index
pub fn clear_selected(&mut self) {
self.selected_idx = None;
}
/// Set new square outline colour value
pub fn set_square_outline(&mut self, value: JsValue) {
self.square_outline = value;
@ -247,6 +253,11 @@ impl Painter {
ans
}
pub fn draw_current(&self, game: &Game)
{
self.draw(game.current_board());
}
/// Draw a board onto the canvas
pub fn draw(&self, board: &Board) {

View File

@ -79,8 +79,9 @@ canvas.addEventListener("click", (event) => {
function start_game() {
game = new Game(BOARD_WIDTH, BOARD_HEIGHT, PIECE_ROWS, Team.Black, SEARCH_DEPTH);
painter = new Painter(CANVAS_WIDTH, CANVAS_HEIGHT, "game-canvas");
game.set_painter(painter);
game.draw();
// game.set_painter(painter);
// game.draw();
painter.draw_current(game);
clearInterval(wonTimeout);
updateTeamText();
@ -107,8 +108,10 @@ function process_canvas_click(cell_coord) {
clicks.push(cell_coord);
current_state = GameState.HUMAN_TURN.FROM_SELECTED;
game.set_selected(cell_coord);
game.draw();
painter.set_selected(cell_coord);
// game.draw();
painter.draw_current(game);
break;
// second click of a move
@ -179,7 +182,9 @@ function process_canvas_click(cell_coord) {
}
game.clear_selected();
game.draw();
painter.clear_selected();
// game.draw();
painter.draw_current(game);
clicks = [];
current_state = GameState.HUMAN_TURN.THINKING;

View File

@ -19,7 +19,8 @@
}
},
"../pkg": {
"version": "1.0.0"
"name": "draught_web",
"version": "1.0.1"
},
"node_modules/@discoveryjs/json-ext": {
"version": "0.5.7",
@ -1409,9 +1410,9 @@
}
},
"node_modules/follow-redirects": {
"version": "1.15.2",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz",
"integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==",
"version": "1.15.5",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.5.tgz",
"integrity": "sha512-vSFWUON1B+yAw1VN4xMfxgn5fTUiaOzAJCKBwIIgT/+7CuGy9+r+5gITvP62j3RmaD5Ph65UaERdOSRGUzZtgw==",
"dev": true,
"funding": [
{

13
draughtlib/Cargo.toml Normal file
View File

@ -0,0 +1,13 @@
[package]
name = "draughtlib"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
indextree = "4.6.0"
rand = "0.8.5"
[target.'cfg(target_arch = "wasm32")'.dependencies]
wasm-bindgen = "0.2.87"

View File

@ -1,10 +1,12 @@
#[cfg(target_arch = "wasm32")]
extern crate wasm_bindgen;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
use std::fmt::{Display};
/// Move/Jump, for use in Move
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MoveType {
@ -13,7 +15,7 @@ pub enum MoveType {
}
/// Black/White
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Team {
@ -41,7 +43,7 @@ impl Display for Team {
}
/// Man/King
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Strength {
@ -50,7 +52,7 @@ pub enum Strength {
}
/// Model board square as Empty/Occupied/Unplayable
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SquareState {
@ -70,7 +72,7 @@ impl Display for SquareState {
}
/// Possible outcomes of trying to move
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[repr(u8)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Moveable {

View File

@ -105,13 +105,16 @@ pub mod tests {
use super::*;
use crate::board::enums::SquareState;
use crate::board::Piece;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::*;
// use crate::log;
#[cfg(target_arch = "wasm32")]
wasm_bindgen_test_configure!(run_in_browser);
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn index_iterator() {
let board = Board::new(2, 2, Team::Black);
let iter = RowIndexIterator::new(&board);
@ -122,7 +125,8 @@ pub mod tests {
], collected);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn square_iterator() {
let board = Board::new(2, 2, Team::Black);
let iter = RowSquareIterator::new(&board);
@ -139,7 +143,8 @@ pub mod tests {
], collected);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn piece_iterator_one_piece() {
let idx = 2;
@ -158,7 +163,8 @@ pub mod tests {
assert_eq!(collected[0], (idx, board.cell(idx)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn piece_iterator_multiple_pieces() {
let mut board = Board::new(4, 4, Team::Black);

View File

@ -14,9 +14,11 @@ use iter::*;
use std::fmt::{Display, Write};
use std::option::Option;
use crate::log;
// use draught_web::log;
#[cfg(target_arch = "wasm32")]
extern crate wasm_bindgen;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
/// Standard width of a checkers board is 8 squares
@ -25,16 +27,16 @@ pub const STD_WIDTH: usize = 8;
pub const STD_HEIGHT: usize = 8;
/// Game piece given by its team and strength (normal or kinged)
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Piece {
pub team: Team,
pub strength: Strength
}
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl Piece {
#[wasm_bindgen(constructor)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))]
pub fn new(team: Team, strength: Strength) -> Piece {
Piece {
team, strength
@ -72,7 +74,7 @@ impl<T: Clone + Copy> Direction<T> {
}
/// Board squares given by a state and a possible occupying game piece
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Square {
/// Game piece if square is occupied
@ -81,10 +83,10 @@ pub struct Square {
pub state: SquareState
}
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl Square {
/// Standard constructor function to form square from state and occupant
#[wasm_bindgen(constructor)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))]
pub fn new(state: SquareState, occupant: Option<Piece>) -> Square{
Square {
occupant,
@ -118,16 +120,16 @@ impl Square {
}
/// Rank 2 tensor index to identify a board square by row and column
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BrdIdx {
pub row: usize,
pub col: usize
}
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl BrdIdx {
#[wasm_bindgen(constructor)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))]
pub fn from(row: usize, col: usize) -> BrdIdx {
BrdIdx{
row, col
@ -150,7 +152,7 @@ impl Display for BrdIdx {
///////////////
/// Single state of a checkers board
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Board {
/// 1D backing array of board squares for the 2D game board
@ -386,7 +388,7 @@ impl Board {
// BOUND FUNCS
///////////////////
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl Board {
/// Get a copy of a board square by 1D array index
pub fn cell(&self, idx: usize) -> Square {
@ -731,7 +733,7 @@ impl Board {
// BOUND TYPE FUNCS
/////////////////////////
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl Board {
/// Unwrap the jumpee piece from the square and [`Board::check_jumpee_team`] with [`Moveable`] response
pub fn validate_jumpee(jumpee: Square, from_occ: Piece) -> Moveable {
@ -771,7 +773,7 @@ impl Board {
}
/// Initialise a game board without game pieces
#[wasm_bindgen(constructor)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))]
pub fn new(width: usize, height: usize, current_turn: Team) -> Board {
let total_cells = width * height;
@ -826,7 +828,7 @@ impl Board {
}
impl Display for Board {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut string = String::new();
for i in 0..self.height {
@ -839,7 +841,7 @@ impl Display for Board {
Unplayable => write!(string, ". "),
};
if let Err(err) = result {
log!("Error printing cell state, ({}, {}), {}", i, j, err);
// log!("Error printing cell state, ({}, {}), {}", i, j, err);
}
}
string.push('\n');

View File

@ -1,7 +1,9 @@
use super::*;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::*;
// use crate::log;
#[cfg(target_arch = "wasm32")]
wasm_bindgen_test_configure!(run_in_browser);
@ -11,19 +13,22 @@ wasm_bindgen_test_configure!(run_in_browser);
// log!("{}", board);
// }
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn create() {
let _ = Board::new(STD_WIDTH, STD_HEIGHT, Black);
assert!(true);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn std_num_cells() {
let board = Board::new(8, 8, Black);
assert_eq!(64, board.num_cells());
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn idx_diffs() {
let from = BrdIdx::from(1, 1);
let to = BrdIdx::from(2, 2);
@ -38,7 +43,8 @@ fn idx_diffs() {
assert_eq!(Board::idx_diffs(from, to), (-5, 10));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn set_cell() {
let idx = 1;
@ -53,25 +59,28 @@ fn set_cell() {
// INDEXING
//////////////
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn cell_index_top_left() {
let board = Board::new(8, 8, Black);
assert_eq!(0, board.cell_index(0, 0));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn cell_index_central() {
let board = Board::new(8, 8, Black);
assert_eq!(9, board.cell_index(1, 1));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn cell_index_central_2() {
let board = Board::new(8, 8, Black);
assert_eq!(17, board.cell_index(2, 1));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn board_index() {
let board = Board::new(8, 8, Black);
@ -87,13 +96,15 @@ fn board_index() {
// SQUARE STATE
///////////////////
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn first_square_unplayable() {
let board = Board::new(8, 8, Black);
assert_eq!(Unplayable, board.cell_state(board.cell_index(0, 0)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn first_square_row_5_unplayable() {
let board = Board::new(8, 8, Black);
assert_eq!(Empty, board.cell_state(board.cell_index(5, 0)));
@ -103,7 +114,8 @@ fn first_square_row_5_unplayable() {
// DIAGNOAL INDICES
//////////////////////
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn moveable_indices_unplayable() {
let board = Board::new(8, 8, Black);
assert_eq!(None, board.adjacent_indices(BrdIdx::from(7, 7)));
@ -111,43 +123,50 @@ fn moveable_indices_unplayable() {
assert_eq!(None, board.adjacent_indices(BrdIdx::from(1, 1)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn moveable_indices_central() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![1, 3, 17, 19]), board.adjacent_indices(BrdIdx::from(1, 2)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn moveable_indices_top_row() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![8, 10]), board.adjacent_indices(BrdIdx::from(0, 1)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn moveable_indices_left_column() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![1, 17]), board.adjacent_indices(BrdIdx::from(1, 0)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn moveable_indices_bottom_row() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![49, 51]), board.adjacent_indices(BrdIdx::from(7, 2)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn moveable_indices_right_column() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![14, 30]), board.adjacent_indices(BrdIdx::from(2, 7)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn moveable_indices_top_right() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![14]), board.adjacent_indices(BrdIdx::from(0, 7)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn moveable_indices_bottom_left() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![49]), board.adjacent_indices(BrdIdx::from(7, 0)));
@ -157,7 +176,8 @@ fn moveable_indices_bottom_left() {
// JUMPABLE INDICES
//////////////////////
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn jumpable_indices_unplayable() {
let board = Board::new(8, 8, Black);
assert_eq!(None, board.jumpable_indices(BrdIdx::from(7, 7)));
@ -165,61 +185,71 @@ fn jumpable_indices_unplayable() {
assert_eq!(None, board.jumpable_indices(BrdIdx::from(1, 1)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn jumpable_indices() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![24, 28]), board.jumpable_indices(BrdIdx::from(1, 2)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn jumpable_indices_central() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![10, 14, 42, 46]), board.jumpable_indices(BrdIdx::from(3, 4)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn jumpable_indices_top_row() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![19]), board.jumpable_indices(BrdIdx::from(0, 1)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn jumpable_indices_left_column() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![26]), board.jumpable_indices(BrdIdx::from(1, 0)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn jumpable_indices_bottom_row() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![40, 44]), board.jumpable_indices(BrdIdx::from(7, 2)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn jumpable_indices_right_column() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![5, 37]), board.jumpable_indices(BrdIdx::from(2, 7)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn jumpable_indices_top_right() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![21]), board.jumpable_indices(BrdIdx::from(0, 7)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn jumpable_indices_bottom_left() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![42]), board.jumpable_indices(BrdIdx::from(7, 0)));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn black_adjacent_indices() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![1, 3]), board.player_adjacent_indices(BrdIdx::from(1, 2), Black));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn white_adjacent_indices() {
let board = Board::new(8, 8, Black);
assert_eq!(Some(vec![17, 19]), board.player_adjacent_indices(BrdIdx::from(1, 2), White));
@ -228,8 +258,9 @@ fn white_adjacent_indices() {
////////////////
// JUMPEE
////////////////
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn check_jumpee_opposing_teams() {
let from = Piece::new(Black, Man);
let jumpee = Piece::new(White, Man);
@ -240,7 +271,8 @@ fn check_jumpee_opposing_teams() {
assert_eq!(Board::check_jumpee_team(from, jumpee), true);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn check_jumpee_same_teams() {
let from = Piece::new(Black, Man);
let jumpee = Piece::new(Black, Man);
@ -251,7 +283,8 @@ fn check_jumpee_same_teams() {
assert_eq!(Board::check_jumpee_team(from, jumpee), false);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn check_validate_jumpee_opposing_teams() {
let jumpee_square = Square::pc(White, Man);
let from_piece = Piece::new(Black, Man);
@ -264,7 +297,8 @@ fn check_validate_jumpee_opposing_teams() {
assert_eq!(Board::validate_jumpee(jumpee_square, from_piece), Moveable::Allowed);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn check_validate_jumpee_same_teams() {
let jumpee_square = Square::pc(White, Man);
let from_piece = Piece::new(White, Man);
@ -281,7 +315,8 @@ fn check_validate_jumpee_same_teams() {
// SCORE
/////////////////
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn score() {
//////////////////////////////////
let board = Board::new(8, 8, Black);
@ -310,7 +345,8 @@ fn score() {
// MOVE VALIDATION
///////////////////////
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn validate_man_move_team_directions() {
// WHITE NEEDS INCREASING IDX
@ -347,7 +383,8 @@ fn validate_man_move_team_directions() {
assert_eq!(Moveable::IllegalTrajectory, board.validate_man_move(from, to, piece));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn validate_man_move_weird_trajectories() {
// WHITE NEEDS INCREASING IDX
@ -384,7 +421,8 @@ fn validate_man_move_weird_trajectories() {
assert_eq!(Moveable::IllegalTrajectory, board.validate_man_move(from, to, piece));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn can_move() {
// WHITE NEEDS INCREASING IDX
@ -444,7 +482,8 @@ fn can_move() {
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn can_move_jump() {
// WHITE NEEDS INCREASING IDX

View File

@ -5,11 +5,12 @@ use indextree::{Arena, Node, NodeId, NodeEdge};
use rand::prelude::*;
use rand::seq::SliceRandom;
#[cfg(target_arch = "wasm32")]
extern crate wasm_bindgen;
// use wasm_bindgen::prelude::*;
use crate::log;
use crate::log_error;
// use draught_web::log;
// use draught_web::log_error;
use crate::board::{Board, BrdIdx};
use crate::board::enums::{MoveType, Moveable, Team};
@ -387,7 +388,7 @@ impl Computer {
// weird error, no child nodes have same score as root node
// this is odd because the root nodes score is either the max or min of it's children
if possible_perfect_moves.len() == 0 {
log_error!("No next moves matched the score of the root node, picking randomly instead");
// log_error!("No next moves matched the score of the root node, picking randomly instead");
ret = Some(Computer::random_choice(&tree, possible_moves, &mut rng));
}

View File

@ -1,5 +1,6 @@
use super::*;
// use wasm_bindgen::prelude::*;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::*;
use crate::board::Square;
@ -8,6 +9,7 @@ use crate::board::enums::Strength::*;
// use Team::*;
#[cfg(target_arch = "wasm32")]
wasm_bindgen_test_configure!(run_in_browser);
// #[wasm_bindgen_test]
@ -19,7 +21,8 @@ wasm_bindgen_test_configure!(run_in_browser);
// assert_eq!(comp.tree.count(), 1);
// }
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn available_moves() {
// . W .
// _ . _
@ -42,7 +45,8 @@ fn available_moves() {
assert!(moves.into_iter().all(|m| m.mv_type == MoveType::Move));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn available_moves_jumps() {
// . W . _
// _ . B .
@ -68,7 +72,8 @@ fn available_moves_jumps() {
assert!(moves[1].mv_type == MoveType::Jump);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn available_moves_std_brd() {
let brd = Board::init_game(Board::new(8, 8, White), 3);
let comp = Computer::new(3, White, 0.5);
@ -84,7 +89,8 @@ fn available_moves_std_brd() {
assert!(moves.into_iter().all(|m| m.mv_type == MoveType::Move));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn expand_node() {
let brd = Board::init_game(Board::new(8, 8, White), 3);
let mut comp = Computer::new(3, White, 0.5);
@ -103,7 +109,8 @@ fn expand_node() {
assert_eq!(children.len(), 7);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn expand_layer() {
let brd = Board::init_game(Board::new(8, 8, White), 3);
let mut comp = Computer::new(3, White, 0.5);
@ -120,7 +127,8 @@ fn expand_layer() {
assert_eq!(tree.count(), 49 + 7 + 1);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn leaf_nodes() {
let brd = Board::init_game(Board::new(8, 8, White), 3);
let mut comp = Computer::new(3, White, 0.5);
@ -136,7 +144,8 @@ fn leaf_nodes() {
assert_eq!(comp.get_leaf_nodes(&mut tree, id).len(), moves.len() + moves2.len() - 1);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn best_scores() {
let brd = Board::new(1, 1, White);
assert_eq!(Computer::best_score(&brd, vec!(-5, -1, 2, 3, 4)), -5);
@ -145,7 +154,8 @@ fn best_scores() {
assert_eq!(Computer::best_score(&brd, vec!(-1, 2, 3, 4)), 4);
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn insert_scores_all_take() {
// . _ . _ .
// W . W . W
@ -188,7 +198,8 @@ fn insert_scores_all_take() {
assert_eq!(children_scores, vec!(-3, -3, -3, -3));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn insert_scores_one_take() {
// . _ . _ .
// W . _ . W
@ -234,7 +245,8 @@ fn insert_scores_one_take() {
}
#[cfg(feature = "time_ex")]
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn tree_depth() {
let depth = 1;
@ -275,7 +287,7 @@ fn time_get_move(depth: usize) {
web_sys::console::time_end_with_label("tree_timer");
}
// #[wasm_bindgen_test]
// #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
// fn tree_get_move() {
// let mut brd = Board::new(5, 4, White);
// brd.set_cell(brd.cell_idx(BrdIdx::from(1, 2)), Square::pc(White, Man));
@ -290,7 +302,7 @@ fn time_get_move(depth: usize) {
// // log!("{:?}", comp.get_move(brd).unwrap());
// }
// #[wasm_bindgen_test]
// #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
// fn tree_get_move() {
// let mut brd = Board::new(5, 5, White);
// brd.set_cell(brd.cell_idx(BrdIdx::from(1, 2)), Square::pc(White, Man));

View File

@ -2,14 +2,16 @@
use crate::board::Board;
#[cfg(target_arch = "wasm32")]
extern crate wasm_bindgen;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen::prelude::*;
use crate::log;
// use draught_web::log;
use crate::board::{Square, BrdIdx};
use crate::board::enums::{SquareState, Moveable, Team};
use crate::paint::Painter;
// use draught_web::paint::Painter;
use crate::comp::Computer;
use Team::*;
@ -20,13 +22,12 @@ use std::fmt::{Display};
#[cfg(test)] pub mod tests;
/// Root-level structure for managing the game as a collection of board states
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
#[derive(Debug)]
pub struct Game {
current: Board,
selected_piece: Option<BrdIdx>,
previous_boards: Vec<Board>,
painter: Option<Painter>,
search_depth: usize,
pub last_node_count: usize,
pub perfect_chance: f64,
@ -44,7 +45,7 @@ impl Game {
}
}
#[wasm_bindgen]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
impl Game {
/// Get pointer to current board's squares
pub fn current_board_cells(&self) -> *const Square {
@ -110,10 +111,6 @@ impl Game {
}
self.selected_piece = Some(*idx);
match &mut self.painter {
Some(p) => p.set_selected(&Some(*idx)),
None => {},
}
}
/// Set proportion of perfect moves from AI
@ -124,10 +121,6 @@ impl Game {
/// Clear currently selected piece
pub fn clear_selected(&mut self) {
self.selected_piece = None;
match &mut self.painter {
Some(p) => p.set_selected(&None),
None => {},
}
}
/// Attempt to make a move given a source and destination index
@ -146,7 +139,7 @@ impl Game {
}
} else {
log!("Unable to make move, {:?}", able);
// log!("Unable to make move, {:?}", able);
}
able
@ -176,7 +169,7 @@ impl Game {
}
/// Get new game without board renderer
#[wasm_bindgen(constructor)]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))]
pub fn new(width: usize, height: usize, piece_rows: usize, first_turn: Team, search_depth: usize) -> Game {
Game {
current: Board::init_game(
@ -184,43 +177,12 @@ impl Game {
),
selected_piece: None,
previous_boards: Vec::with_capacity(10),
painter: None,
search_depth,
last_node_count: 0,
perfect_chance: 0.5,
}
}
/// Get a new game with canvas ID and dimensions
pub fn new_with_canvas(width: usize, height: usize, piece_rows: usize, first_turn: Team, search_depth: usize, canvas_id: &str, canvas_width: u32, canvas_height: u32) -> Game {
Game {
current: Board::init_game(
Board::new(width, height, first_turn), piece_rows,
),
selected_piece: None,
previous_boards: Vec::with_capacity(10),
painter: Some(
Painter::new(canvas_width, canvas_height, canvas_id)
),
search_depth,
last_node_count: 0,
perfect_chance: 0.5,
}
}
/// Set painter for rendering boards
pub fn set_painter(&mut self, value: Painter) {
self.painter = Some(value);
}
/// Draw current board using painter if exists
pub fn draw(&self) {
match &self.painter {
Some(p) => p.draw(&self.current),
None => log!("No painter to draw board with")
}
}
/// Create computer, get move from current board and update current board
pub fn ai_move(&mut self) {
@ -233,7 +195,7 @@ impl Game {
match new_brd {
Some(brd) => self.push_new_board(brd),
None => {
log!("No possible moves, re-pushing current board");
// log!("No possible moves, re-pushing current board");
let mut new_brd = self.current.clone();
new_brd.current_turn = new_brd.current_turn.opponent();

View File

@ -1,7 +1,9 @@
use super::*;
#[cfg(target_arch = "wasm32")]
use wasm_bindgen_test::*;
// use crate::log;
#[cfg(target_arch = "wasm32")]
wasm_bindgen_test_configure!(run_in_browser);
// use crate::board::{Piece};
@ -9,7 +11,8 @@ use crate::board::enums::Strength::*;
// use crate::board::enums::Team::*;
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn make_move() {
let mut game = Game::new(8, 8, 3, Black, 3);
// log!("{}", game);
@ -37,7 +40,8 @@ fn make_move() {
// log!("{}", game.previous_board(0));
}
#[wasm_bindgen_test]
#[cfg_attr(target_arch = "wasm32", wasm_bindgen_test)]
#[cfg_attr(not(target_arch = "wasm32"), test)]
fn make_jump() {
let mut game = Game::new(8, 8, 3, Black, 3);
// log!("{}", game);

3
draughtlib/src/lib.rs Normal file
View File

@ -0,0 +1,3 @@
pub mod board;
pub mod game;
pub mod comp;