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.71k stars 892 forks source link

Promotion callback #136

Open barrust opened 7 years ago

barrust commented 7 years ago

It would be helpful if one could pass a either a value ('q') or a function to the promotion option in move. This would allow for generating the answer to what to promote to when necessary instead of having to default it to something.

jhlywa commented 7 years ago

You must pass the promotion piece when promoting; chess.js doesn't default. You can use one of the following:

var chess = new Chess();

chess.load('8/1P5k/8/8/8/8/8/1K6 w - - 0 1')
chess.move('b8=N')
// -> { color: 'w',  from: 'b7',  to: 'b8',  flags: 'np',  piece: 'p', promotion: 'n',  san: 'b8=N' }

chess.load('8/1P5k/8/8/8/8/8/1K6 w - - 0 1')
chess.move({from: 'b7', to: 'b8', promotion: 'r'});                   
// -> { color: 'w',  from: 'b7',  to: 'b8',  flags: 'np',  piece: 'p', promotion: 'r',  san: 'b8=R' }

chess.load('8/1P5k/8/8/8/8/8/1K6 w - - 0 1');                                                               
chess.move('b7b8=q', {sloppy: true});   
// -> { color: 'w',  from: 'b7',  to: 'b8',  flags: 'np',  piece: 'p', promotion: 'q',  san: 'b8=Q' }          

Does this suffice?

barrust commented 7 years ago

Sorry, I should have been more clear about the term default. I have been using the second version described while making a UI to help teach my kids about chess. What I was thinking would be a great additon, would be something like this:

var chess = new Chess();
chess.load('8/1P5k/8/8/8/8/8/1K6 w - - 0 1')
chess.move({
    from: 'b7', 
    to: 'b8', 
    promotion: function() {
        var promotion_options = ['q', 'r', 'n', 'b'];
        var promotion_val = promotion_options[Math.ceil(Math.random()*promotion_options.length) - 1];
        return promotion_val;  // this is a random promotion but it could also have been more clever...
    }
}); 

Does that make sense? It would allow for the developers of a UI to give the user a choice of promotion pieces after the promotion is signaled.

barrust commented 7 years ago

The random char function is just to show what I meant by not knowing the value before the move is registered. chess.js does not need to support the callback functionality and I am fine if it is decided that it is not within scope.

Thanks for your help and a great library

kwende commented 3 years ago

Yeah, I'm sorry, but @barrust is really right on this. You ought to be able to capture the fact someone is about to promote a piece and choose what piece to promote via a callback. "Why does Chess.js need to run a callback for this?" doesn't understand how people are using the library.