@nodots-llc/backgammon-core
v4.6.3
Published
Core game logic for Nodots Backgammon
Downloads
215
Maintainers
Readme
@nodots-llc/backgammon-core
Core game logic implementation for the nodots-backgammon project. This library handles all the game mechanics, move validation, and state management for a backgammon game.
Overview
The library implements the standard rules of backgammon, including:
- Board initialization and state management
- Move validation and execution
- Support for doubles
- Bar entry and re-entry
- Bearing off
- Pip count tracking
Installation
npm i @nodots-llc/backgammon-coreQuick Start
import { Game } from '@nodots-llc/backgammon-core'
// Create a new game (robot vs human)
let game = Game.createNewGame(
{ userId: 'robot-1', isRobot: true },
{ userId: 'human-1', isRobot: false }
)
// Determine starting player and roll into moving state
game = Game.rollForStart(game)
game = Game.roll(game)
// Execute a complete robot turn (moves + auto confirm)
game = await Game.executeRobotTurn(game)Note: Game.executeRobotTurn uses a native analyzer under the hood. Ensure a working node-gyp toolchain (Node 18+, Python 3, C/C++ build tools) is available on your system.
Development Setup
- Clone the repository:
git clone https://github.com/nodots/core.git
cd core- Install dependencies:
npm install- Run tests:
npm testProject Structure
src/Board/- Board state management and move validationChecker/- Checker (piece) logic and stateCube/- Doubling cube implementationDice/- Dice rolling and validationGame/- Core game state and flow managementMove/- Move types and validationMoveKinds/- Different types of moves (PointToPoint, BearOff, Reenter)
Play/- Play state and turn managementPlayer/- Player state and management
Key Concepts
Board Representation
The board is represented with points numbered 1-24, with two different counting directions:
- Clockwise: Points 1-24 counting clockwise from black's home board
- Counterclockwise: Points 1-24 counting counterclockwise from white's home board
Move Types
- Point to Point: Regular moves between points
- Bear Off: Moving checkers off the board from the home board
- Reenter: Moving checkers from the bar back onto the board
Doubles Handling
When a player rolls doubles:
- They get 4 moves of the same value
- Moves can be used by different checkers or the same checker multiple times
- All valid moves must be used if possible
Improved Move Generation (vNEXT)
- The core library now always generates valid moves for all dice rolls, including doubles.
- Move generation fully analyzes the board state and dice, ensuring all possible moves are found for the player, including when rolling doubles (4 moves).
- If no valid moves are possible for a die, a 'no-move' entry is generated for that die slot.
- This ensures compliance with backgammon rules and prevents the game from getting stuck on doubles or blocked positions.
API Examples
// Initialize a new board
const board = Board.initialize()
// Get possible moves for a player
const possibleMoves = Board.getPossibleMoves(board, player, dieValue)
// Execute a move
const newBoard = Board.moveChecker(board, origin, destination, direction)
// Initialize a play with dice roll
const play = Play.initialize(board, player)Logging
The backgammon-core package includes comprehensive logging capabilities for debugging game logic and monitoring game state changes. All logs are prefixed with [Core] for easy identification.
Logger Configuration
import {
logger,
setLogLevel,
setConsoleEnabled,
setIncludeCallerInfo,
type LogLevel,
} from '@nodots-llc/backgammon-core'
// Set log level (debug, info, warn, error)
setLogLevel('debug')
// Disable console output (useful when using external logging)
setConsoleEnabled(false)
// Enable/disable caller information in logs
setIncludeCallerInfo(true)Log Levels
- debug: Detailed debugging information
- info: General information about game state changes
- warn: Warning messages for potential issues
- error: Error messages for game logic failures
Usage Examples
import { logger, debug, info, warn, error } from '@nodots-llc/backgammon-core'
// Log game state changes
logger.info('[Game] Game state changed:', {
fromState: previousState,
toState: newState,
gameId: game.id,
})
// Log move validation
logger.info('[Move] Validating move:', {
fromPoint: move.from,
toPoint: move.to,
checkerId: move.checkerId,
})
// Log warnings
logger.warn('[Move] Invalid move attempted:', {
reason: validationError,
move: move,
})
// Log errors
logger.error('[Core] Game logic error:', {
error: error.message,
gameId: game.id,
context: 'move validation',
})Log Output Format
Logs follow this format:
[Core] [2024-01-15T10:30:45.123Z] [INFO] Game state changed | Called from: updateGameState (gameEngine.ts:45)
[Core] [2024-01-15T10:30:46.456Z] [WARN] Invalid move attempted | Called from: validateMove (moveValidator.ts:123)
[Core] [2024-01-15T10:30:47.789Z] [ERROR] Game logic error | Called from: processMove (gameEngine.ts:67)Environment Configuration
For production environments, you may want to configure logging based on the environment:
import { setLogLevel, setConsoleEnabled } from '@nodots-llc/backgammon-core'
// Configure based on environment
if (process.env.NODE_ENV === 'production') {
setLogLevel('warn') // Only show warnings and errors in production
} else {
setLogLevel('debug') // Show all logs in development
}
// Optionally disable console if using external logging
if (process.env.DISABLE_CORE_LOGGING === 'true') {
setConsoleEnabled(false)
}Logged Events
The logger tracks various game events:
- Game State Changes: State transitions, turn changes, game completion
- Move Operations: Move validation, execution, and completion
- Dice Rolling: Roll results and available moves
- Rule Validation: Move legality checks and rule violations
- Error Handling: Game logic errors and exception handling
- Board Operations: Checker movements and board state changes
Testing
The project uses Jest for testing. Tests are located in __tests__ directories next to the code they test.
Coverage
The test coverage report provides the following metrics:
- Statements: Percentage of statements in the code that have been executed.
- Branches: Percentage of branches (e.g., if/else statements) that have been taken.
- Functions: Percentage of functions that have been called.
- Lines: Percentage of lines of code that have been executed.
Run tests:
npm testRun tests with coverage:
npm test -- --coverageContributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for your changes
- Run the test suite
- Create a pull request
License
MIT License
Copyright (c) 2025 Ken Riley [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Quick Start
import { Game } from '@nodots-llc/backgammon-core'
let game = Game.createNewGame(
{ userId: 'robot-1', isRobot: true },
{ userId: 'human-1', isRobot: false }
)
game = Game.rollForStart(game)
game = Game.roll(game)
game = await Game.executeRobotTurn(game)If npm is failing in your environment
If npm exits with the message:
Exit prior to config file resolving
cause
call config.load() before reading valuesthat indicates a global npm/Node preloader on your machine, not a problem in this package. As a workaround, use the Node-based runners included here (they bypass npm and clear NODE_OPTIONS):
Build without npm:
node scripts/run-build.js- or
make build
Run simulators without npm:
node scripts/run-simulate.js [maxTurns]node scripts/run-simulate-multiple.js [numGames]- or
make simulate,make simulate-multi
