jhlywa / chess.js

A TypeScript chess library for chess move generation/validation, piece placement/movement, and check/checkmate/draw detection
BSD 2-Clause "Simplified" License
3.72k stars 892 forks source link

Feature request: Store list of captured pieces for easy access #291

Open kurtjd opened 3 years ago

kurtjd commented 3 years ago

It would be nice if the engine stored a list of captured pieces for each side and allows an easy API to access them. For example, to display the captured pieces next to the game, the user should be able to do:

let captured_white = game.get_captured_pieces("white")
let captured_black = game.get_captured_pieces("black")

// write display code here

Sure, the user could just keep track themselves after each .move() call if it generates a capture flag however this would not work if the user was loading in some PGN data as they are not calling .move() themselves.

To further clarify, I'm working on a correspondence chess server so the PGN of each game is stored in a database. When the player views the game in the browser, the game and board are loaded from the PGN. Currently the only way to get the captured pieces in this case is to loop over .history() and search for the captured flag.

This proposal seems like a nice quality of life enhancement, however I can understand if you do not want to clutter the API.

I am willing to implement this if deemed a good idea since I have to anyway for my personal project.

kurtjd commented 3 years ago

If this is not accepted as a feature in the API, here's the method I used to solve the issue from outside:

function get_captured_pieces(game, color) {
    const captured = {'p': 0, 'n': 0, 'b': 0, 'r': 0, 'q': 0}

    for (const move of game.history({ verbose: true })) {
        if (move.hasOwnProperty("captured") && move.color !== color[0]) {
            captured[move.captured]++
        }
    }

    return captured
}

In a game where two white pawns and a white rook have been captured:

get_captured_pieces(game, "white")

will return:

{"p":2,"n":0,"b":0,"r":1,"q":0}