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.68k stars 889 forks source link

[Question]: How to access the various fields in .moves({ verbose: true}) #445

Closed VladimirMishka closed 8 months ago

VladimirMishka commented 8 months ago

Hello, I am an experienced Delphi programmer but totally new to JavaScript/TypeScript and I don't understand the structure of what is returned by .moves({ verbose: true}) and the appropriate JS/TS syntax to retrieve the data from the fields of the list of possible moves. For example, the following simple code lists 50 possible moves from the position given by the FEN string.

import { Chess } from "chess.js" const analysisBoard = new Chess("r1bq1rk1/ppppbppp/4p3/4P3/5Q2/2NB1NP1/PP1P3P/R1B1K2R w KQ - 1 11") console.log(analysisBoard.moves({ verbose: true}))

Move 26 in the list is both a capture and a check [san: "Bxh7+"]

26: (10) {color: "w", piece: "b", from: "d3",...} color: "w" piece: "b" from: "d3" to: "h7" san: "Bxh7+" flags: "c" lan: "d3h7" before: "r1bq1rk1/ppppbppp/4p3/4P3/5Q2/2NB1NP1/PP1P3P/R1B1K2R w KQ - 1 11" after: "r1bq1rk1/ppppbppB/4p3/4P3/5Q2/2N2NP1/PP1P3P/R1B1K2R b KQ - 0 11" captured: "p"

I thought that the structure might be just a list of strings. However, syntax like let MoveStr=analysisBoard.moves[26], isn't getting me anywhere. When I try console.log(MoveStr), it is undefined.

Would someone who is familiar with the structure and the appropriate JS/TS syntax please be so kind as to tell me how I would loop through the available moves, finding any that are checks (i.e., contain the character "+") and/or are captures (either they contain the character "x", or flags: contains "c" or the captured field is present) and then be able to access the data from some of the fields of those moves, for example, "piece:", "from:" and "after:"?

Thank you very much for any help.

VladimirMishka commented 8 months ago

I guessed that the structure is a list/array of objects. This website: https://www.freecodecamp.org/news/javascript-array-of-objects-tutorial-how-to-create-update-and-loop-through-objects-using-js-array-methods/ gave me some sample code that worked, e.g.,

import { Chess } from "chess.js" const analysisBoard = new Chess("r1bq1rk1/ppppbppp/4p3/4P3/5Q2/2NB1NP1/PP1P3P/R1B1K2R w KQ - 1 11") let possibleMoves = analysisBoard.moves({ verbose: true}) let movesThatAreChecks = possibleMoves.filter(possibleMoves => possibleMoves.san.includes("+")) console.log(possibleMoves) console.log(analysisBoard.ascii()) console.log(movesThatAreChecks) console.log(movesThatAreChecks[0].after) console.log(movesThatAreChecks[1].after) let movesThatAreCaptures = possibleMoves.filter(possibleMoves => possibleMoves.san.includes("x")) console.log(movesThatAreCaptures)