Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IPVGO: Add optional board state argument to the go analysis functions #1716

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion markdown/bitburner.goanalysis.getchains.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,24 @@

Returns an ID for each point. All points that share an ID are part of the same network (or "chain"). Empty points are also given chain IDs to represent continuous empty space. Dead nodes are given the value `null.`

Takes an optional boardState argument; by default uses the current board state.

The data from getChains() can be used with the data from getBoardState() to see which player (or empty) each chain is

For example, a 5x5 board might look like this. There is a large chain \#1 on the left side, smaller chains 2 and 3 on the right, and a large chain 0 taking up the center of the board. <pre lang="javascript"> \[ \[ 0,0,0,3,4\], \[ 1,0,0,3,3\], \[ 1,1,0,0,0\], \[null,1,0,2,2\], \[null,1,0,2,5\], \] </pre>

**Signature:**

```typescript
getChains(): (number | null)[][];
getChains(boardState?: string[]): (number | null)[][];
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| boardState | string\[\] | _(Optional)_ |

**Returns:**

(number \| null)\[\]\[\]
Expand Down
13 changes: 11 additions & 2 deletions markdown/bitburner.goanalysis.getcontrolledemptynodes.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

## GoAnalysis.getControlledEmptyNodes() method

Returns 'X', 'O', or '?' for each empty point to indicate which player controls that empty point. If no single player fully encircles the empty space, it is shown as contested with '?'. "\#" are dead nodes that are not part of the subnet.
Returns 'X' for black, 'O' for white, or '?' for each empty point to indicate which player controls that empty point. If no single player fully encircles the empty space, it is shown as contested with '?'. "\#" are dead nodes that are not part of the subnet.

Takes an optional boardState argument; by default uses the current board state.

Filled points of any color are indicated with '.'

Expand All @@ -13,8 +15,15 @@ In this example, white encircles some space in the top-left, black encircles som
**Signature:**

```typescript
getControlledEmptyNodes(): string[];
getControlledEmptyNodes(boardState?: string[]): string[];
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| boardState | string\[\] | _(Optional)_ |

**Returns:**

string\[\]
Expand Down
11 changes: 10 additions & 1 deletion markdown/bitburner.goanalysis.getliberties.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@

Returns a number for each point, representing how many open nodes its network/chain is connected to. Empty nodes and dead nodes are shown as -1 liberties.

Takes an optional boardState argument; by default uses the current board state.

For example, a 5x5 board might look like this. The chain in the top-left touches 5 total empty nodes, and the one in the center touches four. The group in the bottom-right only has one liberty; it is in danger of being captured! <pre lang="javascript"> \[ \[-1, 5,-1,-1, 2\], \[ 5, 5,-1,-1,-1\], \[-1,-1, 4,-1,-1\], \[ 3,-1,-1, 3, 1\], \[ 3,-1,-1, 3, 1\], \] </pre>

**Signature:**

```typescript
getLiberties(): number[][];
getLiberties(boardState?: string[]): number[][];
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| boardState | string\[\] | _(Optional)_ |

**Returns:**

number\[\]\[\]
Expand Down
14 changes: 12 additions & 2 deletions markdown/bitburner.goanalysis.getvalidmoves.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,29 @@

## GoAnalysis.getValidMoves() method

Shows if each point on the board is a valid move for the player.
Shows if each point on the board is a valid move for the player. By default, analyzes the current board state. Takes an optional boardState (and an optional prior-move boardState, if desired) to analyze a custom board.

The true/false validity of each move can be retrieved via the X and Y coordinates of the move. `const validMoves = ns.go.analysis.getValidMoves();`

`const moveIsValid = validMoves[x][y];`

Note that the \[0\]\[0\] point is shown on the bottom-left on the visual board (as is traditional), and each string represents a vertical column on the board. In other words, the printed example above can be understood to be rotated 90 degrees clockwise compared to the board UI as shown in the IPvGO subnet tab.

Also note that, when given a custom board state, only one prior move can be analyzed. This means that the superko rules (no duplicate board states in the full game history) is not supported; you will have to implement your own analysis for that.

**Signature:**

```typescript
getValidMoves(): boolean[][];
getValidMoves(boardState?: string[], priorBoardState?: string[]): boolean[][];
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| boardState | string\[\] | _(Optional)_ |
| priorBoardState | string\[\] | _(Optional)_ |

**Returns:**

boolean\[\]\[\]
Expand Down
8 changes: 4 additions & 4 deletions markdown/bitburner.goanalysis.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ export interface GoAnalysis

| Method | Description |
| --- | --- |
| [getChains()](./bitburner.goanalysis.getchains.md) | <p>Returns an ID for each point. All points that share an ID are part of the same network (or "chain"). Empty points are also given chain IDs to represent continuous empty space. Dead nodes are given the value <code>null.</code></p><p>The data from getChains() can be used with the data from getBoardState() to see which player (or empty) each chain is</p><p>For example, a 5x5 board might look like this. There is a large chain \#1 on the left side, smaller chains 2 and 3 on the right, and a large chain 0 taking up the center of the board. <pre lang="javascript"> \[ \[ 0,0,0,3,4\], \[ 1,0,0,3,3\], \[ 1,1,0,0,0\], \[null,1,0,2,2\], \[null,1,0,2,5\], \] </pre></p> |
| [getControlledEmptyNodes()](./bitburner.goanalysis.getcontrolledemptynodes.md) | <p>Returns 'X', 'O', or '?' for each empty point to indicate which player controls that empty point. If no single player fully encircles the empty space, it is shown as contested with '?'. "\#" are dead nodes that are not part of the subnet.</p><p>Filled points of any color are indicated with '.'</p><p>In this example, white encircles some space in the top-left, black encircles some in the top-right, and between their routers is contested space in the center: <pre lang="javascript"> \[ "OO..?", "OO.?.", "O.?.X", ".?.XX", "?..X\#", \] </pre></p> |
| [getLiberties()](./bitburner.goanalysis.getliberties.md) | <p>Returns a number for each point, representing how many open nodes its network/chain is connected to. Empty nodes and dead nodes are shown as -1 liberties.</p><p>For example, a 5x5 board might look like this. The chain in the top-left touches 5 total empty nodes, and the one in the center touches four. The group in the bottom-right only has one liberty; it is in danger of being captured! <pre lang="javascript"> \[ \[-1, 5,-1,-1, 2\], \[ 5, 5,-1,-1,-1\], \[-1,-1, 4,-1,-1\], \[ 3,-1,-1, 3, 1\], \[ 3,-1,-1, 3, 1\], \] </pre></p> |
| [getChains(boardState)](./bitburner.goanalysis.getchains.md) | <p>Returns an ID for each point. All points that share an ID are part of the same network (or "chain"). Empty points are also given chain IDs to represent continuous empty space. Dead nodes are given the value <code>null.</code></p><p>Takes an optional boardState argument; by default uses the current board state.</p><p>The data from getChains() can be used with the data from getBoardState() to see which player (or empty) each chain is</p><p>For example, a 5x5 board might look like this. There is a large chain \#1 on the left side, smaller chains 2 and 3 on the right, and a large chain 0 taking up the center of the board. <pre lang="javascript"> \[ \[ 0,0,0,3,4\], \[ 1,0,0,3,3\], \[ 1,1,0,0,0\], \[null,1,0,2,2\], \[null,1,0,2,5\], \] </pre></p> |
| [getControlledEmptyNodes(boardState)](./bitburner.goanalysis.getcontrolledemptynodes.md) | <p>Returns 'X' for black, 'O' for white, or '?' for each empty point to indicate which player controls that empty point. If no single player fully encircles the empty space, it is shown as contested with '?'. "\#" are dead nodes that are not part of the subnet.</p><p>Takes an optional boardState argument; by default uses the current board state.</p><p>Filled points of any color are indicated with '.'</p><p>In this example, white encircles some space in the top-left, black encircles some in the top-right, and between their routers is contested space in the center: <pre lang="javascript"> \[ "OO..?", "OO.?.", "O.?.X", ".?.XX", "?..X\#", \] </pre></p> |
| [getLiberties(boardState)](./bitburner.goanalysis.getliberties.md) | <p>Returns a number for each point, representing how many open nodes its network/chain is connected to. Empty nodes and dead nodes are shown as -1 liberties.</p><p>Takes an optional boardState argument; by default uses the current board state.</p><p>For example, a 5x5 board might look like this. The chain in the top-left touches 5 total empty nodes, and the one in the center touches four. The group in the bottom-right only has one liberty; it is in danger of being captured! <pre lang="javascript"> \[ \[-1, 5,-1,-1, 2\], \[ 5, 5,-1,-1,-1\], \[-1,-1, 4,-1,-1\], \[ 3,-1,-1, 3, 1\], \[ 3,-1,-1, 3, 1\], \] </pre></p> |
| [getStats()](./bitburner.goanalysis.getstats.md) | <p>Displays the game history, captured nodes, and gained bonuses for each opponent you have played against.</p><p>The details are keyed by opponent name, in this structure:</p><p><pre lang="javascript"> { <OpponentName>: { wins: number, losses: number, winStreak: number, highestWinStreak: number, favor: number, bonusPercent: number, bonusDescription: string, } } </pre></p> |
| [getValidMoves()](./bitburner.goanalysis.getvalidmoves.md) | <p>Shows if each point on the board is a valid move for the player.</p><p>The true/false validity of each move can be retrieved via the X and Y coordinates of the move. <code>const validMoves = ns.go.analysis.getValidMoves();</code></p><p><code>const moveIsValid = validMoves[x][y];</code></p><p>Note that the \[0\]\[0\] point is shown on the bottom-left on the visual board (as is traditional), and each string represents a vertical column on the board. In other words, the printed example above can be understood to be rotated 90 degrees clockwise compared to the board UI as shown in the IPvGO subnet tab.</p> |
| [getValidMoves(boardState, priorBoardState)](./bitburner.goanalysis.getvalidmoves.md) | <p>Shows if each point on the board is a valid move for the player. By default, analyzes the current board state. Takes an optional boardState (and an optional prior-move boardState, if desired) to analyze a custom board.</p><p>The true/false validity of each move can be retrieved via the X and Y coordinates of the move. <code>const validMoves = ns.go.analysis.getValidMoves();</code></p><p><code>const moveIsValid = validMoves[x][y];</code></p><p>Note that the \[0\]\[0\] point is shown on the bottom-left on the visual board (as is traditional), and each string represents a vertical column on the board. In other words, the printed example above can be understood to be rotated 90 degrees clockwise compared to the board UI as shown in the IPvGO subnet tab.</p><p>Also note that, when given a custom board state, only one prior move can be analyzed. This means that the superko rules (no duplicate board states in the full game history) is not supported; you will have to implement your own analysis for that.</p> |

10 changes: 10 additions & 0 deletions src/Go/boardAnalysis/boardAnalysis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -645,6 +645,16 @@ export function boardFromSimpleBoard(simpleBoard: SimpleBoard): Board {
);
}

/**
* Creates a Board object from the given simpleBoard string array
* Also updates the board object with the analytics (liberties/chains) from the simple board
*/
export const updatedBoardFromSimpleBoard = (simpleBoard: SimpleBoard): Board => {
const board = boardFromSimpleBoard(simpleBoard);
updateChains(board);
ficocelliguy marked this conversation as resolved.
Show resolved Hide resolved
return board;
};

export function boardStateFromSimpleBoard(
simpleBoard: SimpleBoard,
ai = GoOpponent.Daedalus,
Expand Down
35 changes: 31 additions & 4 deletions src/Go/boardState/boardState.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import type { Board, BoardState, Move, Neighbor, PointState } from "../Types";
import { Board, BoardState, Move, Neighbor, PointState, SimpleBoard } from "../Types";

import { GoOpponent, GoColor, GoValidity } from "@enums";
import { GoColor, GoOpponent, GoValidity } from "@enums";
import { bitverseBoardShape } from "../Constants";
import { getExpansionMoveArray } from "../boardAnalysis/goAI";
import {
boardFromSimpleBoard,
boardStringFromBoard,
evaluateIfMoveIsValid,
findAllCapturedChains,
findLibertiesForChain,
getAllChains,
boardFromSimpleBoard,
boardStringFromBoard,
updatedBoardFromSimpleBoard,
} from "../boardAnalysis/boardAnalysis";
import { endGoGame } from "../boardAnalysis/scoring";
import { addObstacles, resetCoordinates, rotate90Degrees } from "./offlineNodes";
Expand Down Expand Up @@ -59,6 +60,32 @@ export function getNewBoardState(
return newBoardState;
}

/**
* Generates a new BoardState object from a given SimpleBoard string array, and an optional prior move board state
*/
export function getNewBoardStateFromSimpleBoard(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You only use this once, I think it makes more sense to just do this where you use it instead of exporting a new function.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I played around with this, but after the other changes it is fairly large, and also the "where you use it" is now inside the netscript implementation. Keeping this as a contained utility function here alongside similar ones ended up being cleaner.

simpleBoard: SimpleBoard,
priorSimpleBoard?: SimpleBoard,
ai: GoOpponent = GoOpponent.Netburners,
): BoardState {
const newState = getNewBoardState(simpleBoard.length, ai, false, updatedBoardFromSimpleBoard(simpleBoard));
if (priorSimpleBoard) {
newState.previousBoards.push(priorSimpleBoard.join(""));

// Identify the previous player based on the difference in pieces
const priorWhitePieces = priorSimpleBoard.join("").match(/O/g)?.length ?? 0;
const priorBlackPieces = priorSimpleBoard.join("").match(/X/g)?.length ?? 0;
const currentWhitePieces = simpleBoard.join("").match(/O/g)?.length ?? 0;
const currentBlackPieces = simpleBoard.join("").match(/X/g)?.length ?? 0;
if (priorWhitePieces - priorBlackPieces > currentWhitePieces - currentBlackPieces) {
newState.previousPlayer = GoColor.black;
}
}

updateCaptures(newState.board, newState.previousPlayer ?? GoColor.white);
return newState;
}

/**
* Determines how many starting pieces the opponent has on the board
*/
Expand Down
89 changes: 79 additions & 10 deletions src/Go/effects/netscriptGoImplementation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { Play, SimpleBoard, SimpleOpponentStats } from "../Types";
import { Board, BoardState, Play, SimpleBoard, SimpleOpponentStats } from "../Types";

import { Player } from "@player";
import { AugmentationName, GoColor, GoOpponent, GoPlayType, GoValidity } from "@enums";
import { Go, GoEvents } from "../Go";
import { getNewBoardState, makeMove, passTurn, updateCaptures, updateChains } from "../boardState/boardState";
import {
getNewBoardState,
getNewBoardStateFromSimpleBoard,
makeMove,
passTurn,
updateCaptures,
updateChains,
} from "../boardState/boardState";
import { makeAIMove, resetAI } from "../boardAnalysis/goAI";
import {
evaluateIfMoveIsValid,
Expand Down Expand Up @@ -150,8 +157,8 @@ export async function getOpponentNextMove(logOpponentMove = true, logger: (s: st
/**
* Returns a grid of booleans indicating if the coordinates at that location are a valid move for the player (black pieces)
*/
export function getValidMoves() {
const boardState = Go.currentGame;
export function getValidMoves(_boardState?: BoardState) {
const boardState = _boardState || Go.currentGame;
// Map the board matrix into true/false values
return boardState.board.map((column, x) =>
column.reduce((validityArray: boolean[], point, y) => {
Expand All @@ -165,10 +172,11 @@ export function getValidMoves() {
/**
* Returns a grid with an ID for each contiguous chain of same-state nodes (excluding dead/offline nodes)
*/
export function getChains() {
export function getChains(_board?: Board) {
const board = _board || Go.currentGame.board;
const chains: string[] = [];
// Turn the internal chain IDs into nice consecutive numbers for display to the player
return Go.currentGame.board.map((column) =>
return board.map((column) =>
column.reduce((chainIdArray: (number | null)[], point) => {
if (!point) {
chainIdArray.push(null);
Expand All @@ -186,8 +194,9 @@ export function getChains() {
/**
* Returns a grid of numbers representing the number of open-node connections each player-owned chain has.
*/
export function getLiberties() {
return Go.currentGame.board.map((column) =>
export function getLiberties(_board?: Board) {
const board = _board || Go.currentGame.board;
return board.map((column) =>
column.reduce((libertyArray: number[], point) => {
libertyArray.push(point?.liberties?.length || -1);
return libertyArray;
Expand All @@ -198,8 +207,8 @@ export function getLiberties() {
/**
* Returns a grid indicating which player, if any, controls the empty nodes by fully encircling it with their routers
*/
export function getControlledEmptyNodes() {
const board = Go.currentGame.board;
export function getControlledEmptyNodes(_board?: Board) {
const board = _board || Go.currentGame.board;
const controlled = getControlledSpace(board);
return controlled.map((column, x: number) =>
column.reduce((ownedPoints: string, owner: GoColor, y: number) => {
Expand Down Expand Up @@ -322,6 +331,66 @@ export function getStats() {
return statDetails;
}

const boardValidity = {
valid: "",
badShape: "Invalid boardState: Board must be a square",
badType: "Invalid boardState: Board must be an array of strings",
badSize: "Invalid boardState: Board must be 5, 7, 9, 13, or 19 in size",
badCharacters:
'Invalid board state: unknown characters found. "X" represents black pieces, "O" white, "." empty points, and "#" offline nodes.',
failedToCreateBoard: "Invalid board state: Failed to create board",
} as const;

/**
* Validate the given SimpleBoard and prior board state (if present) and turn it into a full BoardState with updated analytics
*/
export function validateBoardState(
error: (s: string) => void,
_boardState?: unknown,
_priorBoardState?: unknown,
): BoardState | undefined {
const simpleBoard = getSimpleBoardFromUnknown(error, _boardState);
const priorSimpleBoard = getSimpleBoardFromUnknown(error, _priorBoardState);

if (!_boardState || !simpleBoard) {
return undefined;
}

try {
return getNewBoardStateFromSimpleBoard(simpleBoard, priorSimpleBoard);
} catch (e) {
error(boardValidity.failedToCreateBoard);
}
}

/**
* Check that the given boardState is a valid SimpleBoard, and return it if it is.
*/
function getSimpleBoardFromUnknown(error: (arg0: string) => void, _boardState: unknown): SimpleBoard | undefined {
if (!_boardState) {
return undefined;
}
if (!Array.isArray(_boardState)) {
error(boardValidity.badType);
}
if ((_boardState as unknown[]).find((row) => typeof row !== "string")) {
error(boardValidity.badType);
}

const boardState = _boardState as string[];

if (boardState.find((row) => row.length !== boardState.length)) {
error(boardValidity.badShape);
}
if (![5, 7, 9, 13, 19].includes(boardState.length)) {
error(boardValidity.badSize);
}
if (boardState.find((row) => row.match(/[^XO#.]/))) {
error(boardValidity.badCharacters);
}
return boardState as SimpleBoard;
}

/** Validate singularity access by throwing an error if the player does not have access. */
export function checkCheatApiAccess(error: (s: string) => void): void {
const hasSourceFile = Player.activeSourceFileLvl(14) > 1;
Expand Down
Loading