Skip to content

Commit

Permalink
add color methods
Browse files Browse the repository at this point in the history
  • Loading branch information
scottbedard committed Jul 21, 2024
1 parent 80ba795 commit 7d0341b
Show file tree
Hide file tree
Showing 10 changed files with 154 additions and 16 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,30 @@ createHexchessInitial()
// { board: { ... }, enPassant, turn, fullmove, halfmove }
```

#### `getColor`

Get the color of a piece.

```ts
import { getColor } from '@bedard/hexchess'

getColor('p') // 'b'
getColor('P') // 'w'
getColor('?') // null
```

#### `getPositionColor`

Get color of a piece by board position.

```ts
import { getPositionColor } from '@bedard/hexchess'

getPositionColor(hexchess, 'f5') // 'w'
getPositionColor(hexchess, 'f6') // null
getPositionColor(hexchess, 'f7') // 'b'
```

#### `getTargets`

Find all legal moves from a position and return the resulting array of `Notation` objects.
Expand Down
25 changes: 19 additions & 6 deletions pkg/hexchess.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,19 @@ export function parseNotation(str: string): Notation;
* @returns {string}
*/
export function stringifyHexchess(hexchess: Hexchess): string;
/**
* Get piece color
* @param {string} val
* @returns {any}
*/
export function getPieceColor(val: string): any;
/**
* Find piece color at board position
* @param {Hexchess} hexchess
* @param {Position} position
* @returns {any}
*/
export function getPositionColor(hexchess: Hexchess, position: Position): any;
export interface Board {
a1: Piece | null;
a2: Piece | null;
Expand Down Expand Up @@ -139,18 +152,18 @@ export interface Hexchess {
turn: Color;
}

export type PromotionPiece = "n" | "b" | "r" | "q";

export type Piece = "P" | "N" | "B" | "R" | "Q" | "K" | "p" | "n" | "b" | "r" | "q" | "k";

export type Color = "w" | "b";

export interface Notation {
from: Position;
promotion: PromotionPiece | null;
to: Position;
}

export type PromotionPiece = "n" | "b" | "r" | "q";

export type Piece = "P" | "N" | "B" | "R" | "Q" | "K" | "p" | "n" | "b" | "r" | "q" | "k";

export type Color = "w" | "b";


export function getTargets(hexchess: Hexchess, position: Position): Notation[];

Expand Down
41 changes: 34 additions & 7 deletions pkg/hexchess_bg.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ function passStringToWasm0(arg, malloc, realloc) {
const ret = encodeString(arg, view);

offset += ret.written;
ptr = realloc(ptr, len, offset, 1) >>> 0;
}

WASM_VECTOR_LEN = offset;
Expand Down Expand Up @@ -197,6 +198,32 @@ export function stringifyHexchess(hexchess) {
}
}

function _assertChar(c) {
if (typeof(c) === 'number' && (c >= 0x110000 || (c >= 0xD800 && c < 0xE000))) throw new Error(`expected a valid Unicode scalar value, found ${c}`);
}
/**
* Get piece color
* @param {string} val
* @returns {any}
*/
export function getPieceColor(val) {
const char0 = val.codePointAt(0);
_assertChar(char0);
const ret = wasm.getPieceColor(char0);
return takeObject(ret);
}

/**
* Find piece color at board position
* @param {Hexchess} hexchess
* @param {Position} position
* @returns {any}
*/
export function getPositionColor(hexchess, position) {
const ret = wasm.getPositionColor(addHeapObject(hexchess), addHeapObject(position));
return takeObject(ret);
}

/**
* Find target moves from a position, regardless of turn color
* @param {Hexchess} hexchess
Expand All @@ -216,11 +243,6 @@ function handleError(f, args) {
}
}

export function __wbindgen_is_undefined(arg0) {
const ret = getObject(arg0) === undefined;
return ret;
};

export function __wbindgen_object_clone_ref(arg0) {
const ret = getObject(arg0);
return addHeapObject(ret);
Expand All @@ -230,6 +252,11 @@ export function __wbindgen_object_drop_ref(arg0) {
takeObject(arg0);
};

export function __wbindgen_is_undefined(arg0) {
const ret = getObject(arg0) === undefined;
return ret;
};

export function __wbg_new_abda76e883ba8a5f() {
const ret = new Error();
return addHeapObject(ret);
Expand Down Expand Up @@ -264,12 +291,12 @@ export function __wbindgen_string_get(arg0, arg1) {
getInt32Memory0()[arg0 / 4 + 0] = ptr1;
};

export function __wbg_parse_06816e879d29d4df() { return handleError(function (arg0, arg1) {
export function __wbg_parse_66d1801634e099ac() { return handleError(function (arg0, arg1) {
const ret = JSON.parse(getStringFromWasm0(arg0, arg1));
return addHeapObject(ret);
}, arguments) };

export function __wbg_stringify_daa6661e90c04140() { return handleError(function (arg0) {
export function __wbg_stringify_8887fe74e1c50d81() { return handleError(function (arg0) {
const ret = JSON.stringify(getObject(arg0));
return addHeapObject(ret);
}, arguments) };
Expand Down
Binary file modified pkg/hexchess_bg.wasm
Binary file not shown.
2 changes: 2 additions & 0 deletions pkg/hexchess_bg.wasm.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ export function createHexchessInitial(): number;
export function parseHexchess(a: number, b: number): number;
export function parseNotation(a: number, b: number): number;
export function stringifyHexchess(a: number, b: number): void;
export function getPieceColor(a: number): number;
export function getPositionColor(a: number, b: number): number;
export function getTargets(a: number, b: number): number;
export function __wbindgen_malloc(a: number, b: number): number;
export function __wbindgen_realloc(a: number, b: number, c: number, d: number): number;
Expand Down
5 changes: 2 additions & 3 deletions pkg/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "@bedard/hexchess",
"name": "hexchess",
"version": "0.1.0",
"license": "MIT",
"repository": {
Expand All @@ -17,6 +17,5 @@
"sideEffects": [
"./hexchess.js",
"./snippets/*"
],
"main": "hexchess.js"
]
}
28 changes: 28 additions & 0 deletions src/game/hexchess.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,13 @@ impl Hexchess {
})
}

pub fn color(&self, position: Position) -> Option<Color> {
match self.board.get(position) {
None => None,
Some(piece) => Some(piece.color()),
}
}

pub fn initial() -> Self {
Hexchess {
board: Board::initial(),
Expand Down Expand Up @@ -540,4 +547,25 @@ mod tests {

assert_eq!(Err(Failure::InvalidBoard), hexchess);
}

#[test]
fn test_color() {
let hexchess = Hexchess::initial();

assert_eq!(None, hexchess.color(Position::A1));

assert_eq!(Some(Color::White), hexchess.color(Position::B1)); // P
assert_eq!(Some(Color::White), hexchess.color(Position::C1)); // R
assert_eq!(Some(Color::White), hexchess.color(Position::D1)); // N
assert_eq!(Some(Color::White), hexchess.color(Position::E1)); // Q
assert_eq!(Some(Color::White), hexchess.color(Position::F1)); // B
assert_eq!(Some(Color::White), hexchess.color(Position::G1)); // K

assert_eq!(Some(Color::Black), hexchess.color(Position::B7)); // p
assert_eq!(Some(Color::Black), hexchess.color(Position::C8)); // r
assert_eq!(Some(Color::Black), hexchess.color(Position::D9)); // n
assert_eq!(Some(Color::Black), hexchess.color(Position::E10)); // q
assert_eq!(Some(Color::Black), hexchess.color(Position::F11)); // b
assert_eq!(Some(Color::Black), hexchess.color(Position::G10)); // k
}
}
19 changes: 19 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ pub mod game;
use crate::game::board::Position;
use crate::game::hexchess::Hexchess;
use crate::game::notation::Notation;
use crate::game::piece::Piece;
use tsify::JsValueSerdeExt;
use wasm_bindgen::prelude::*;

Expand Down Expand Up @@ -63,6 +64,24 @@ pub fn stringify_hexchess(hexchess: Hexchess) -> String {
hexchess.to_string()
}

/// Get piece color
#[wasm_bindgen(js_name = getPieceColor)]
pub fn get_piece_color(val: char) -> JsValue {
set_panic_hook();

match Piece::from_char(val) {
Ok(piece) => JsValue::from_serde(&piece.color()).unwrap(),
Err(_) => JsValue::NULL,
}
}

/// Find piece color at board position
#[wasm_bindgen(js_name = getPositionColor)]
pub fn get_position_color(hexchess: Hexchess, position: Position) -> JsValue {
set_panic_hook();
JsValue::from_serde(&hexchess.color(position)).unwrap()
}

/// Find target moves from a position, regardless of turn color
#[wasm_bindgen(js_name = getTargets, skip_typescript)]
pub fn get_targets(hexchess: Hexchess, position: Position) -> JsValue {
Expand Down
3 changes: 3 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ export default defineConfig({
wasm(),
topLevelAwait()
],
resolve: {
mainFields: ['module']
},
test: {
typecheck: {
enabled: true,
Expand Down
23 changes: 23 additions & 0 deletions vitest/color.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {
createHexchessInitial,
getPieceColor,
getPositionColor,
} from '@bedard/hexchess'

import { describe, expect, it } from 'vitest'

describe('color', () => {
it('getColor', () => {
expect(getPieceColor('p')).toBe('b')
expect(getPieceColor('P')).toBe('w')
expect(getPieceColor('?')).toBe(null)
})

it('getPositionColor', () => {
const hexchess = createHexchessInitial()

expect(getPositionColor(hexchess, 'f5')).toBe('w')
expect(getPositionColor(hexchess, 'f6')).toBe(null)
expect(getPositionColor(hexchess, 'f7')).toBe('b')
})
})

0 comments on commit 7d0341b

Please sign in to comment.