Home > Back-end >  Checkmate function based on no library - reactjs
Checkmate function based on no library - reactjs

Time:04-29

I have tried to figure out a function or algorithm with no use of library

so far I have a function for when there is a check, but can't wrap my head around the checkmate function... I know I'm supposed to look for all the possible moves, but can't really make it work

    getKingPosition(squares, player) {
        return squares.reduce((acc, current, i) =>
            acc || //King may be the only one, if we had found it, returned his position
            ((current //current square mustn't be a null
                && (current.getPlayer() === player)) //we are looking for aspecical king
                && (current instanceof King)
                && i), // returned position if all conditions are completed
            null)
    }

    isCheckForPlayer(squares, player) {
        const opponent = player === 1 ? 2 : 1
        const playerKingPosition = this.getKingPosition(squares, player)
        const canPieceKillPlayerKing = (piece, i) => piece.isMovePossible(playerKingPosition, i, squares)
        return (
            squares.reduce((acc, current, index) =>
            acc ||
            (current &&
                (current.getPlayer() === opponent) &&
                canPieceKillPlayerKing(current, index)
                && true),
            false) 
        )
            
    }

    isCheckmate(isCheckForPlayer, isMovePossible){
        const KingUnabletoMove = this.getKingPosition(squares, player)
        const CheckMate = 
    }

I have started on the function above, but currently a bit clueless..

below is the code for, blocking the possibility of a potential move made because there is a check

       if (isMovePossible) {
                if (squares[i] !== null) {
                    if (squares[i].player === 1) {
                        whitepiecestaken.push(squares[i]);
                    }
                    else {
                        blackpiecestaken.push(squares[i]);
                    }
                }

                squares[i] = squares[this.state.sourceSelection];
                squares[this.state.sourceSelection] = null;

                const isCheckMe = this.isCheckForPlayer(squares, this.state.player)

                if (isCheckMe) {
                    this.setState(oldState => ({
                        status: "Wrong selection. Choose Valid source and destination again. Now you have a check!",
                        sourceSelection: -1,
                    }))
                } else {
                    let player = this.state.player === 1 ? 2 : 1;
                    let turn = this.state.turn === 'white' ? 'black' : 'white';

                    this.setState(oldState => ({
                        sourceSelection: -1,
                        squares,
                        whitepiecestaken: [...oldState.whitepiecestaken, ...whitepiecestaken],
                        blackpiecestaken: [...oldState.blackpiecestaken, ...blackpiecestaken],
                        player,
                        status: '',
                        turn
                    }));
                }
            }
            else {
                this.setState({
                    status: "Wrong selection. Choose valid source and destination again.",
                    sourceSelection: -1,
                });
            }
        }
    }

Also included the kings ability to move below

import Piece from './piece.js';
import { isSameDiagonal, isSameRow } from '../helpers';

export default class King extends Piece {
    constructor(player) {
        super(player, (player === 1 ? 
            "https://upload.wikimedia.org/wikipedia/commons/4/42/Chess_klt45.svg" :
            "https://upload.wikimedia.org/wikipedia/commons/f/f0/Chess_kdt45.svg"
            ));
    }

    isMovePossible(src, dest) {
        return ((src - 9 === dest && isSameDiagonal(src, dest)) ||
        src - 8 === dest ||
        (src - 7 === dest && isSameDiagonal(src, dest)) ||
        (src   1 === dest && isSameRow(src, dest)) ||
        (src   9 === dest && isSameDiagonal(src, dest)) ||
        src   8 === dest ||
        (src   7 === dest && isSameDiagonal(src, dest)) ||
        (src - 1 === dest && isSameRow(src, dest)))
    }

    /**
     * always returns empty array because of one step
     * @return {[]}
     */

    getSrcToDestPath(src, dest) {
        return [];
    }
}

Hope someone can help me

CodePudding user response:

If you have a function for check, and functions to retrieve all moves then it is very simple. The basic steps:

  1. Check if current player is in check.
  2. Check if there are any legal moves to play.
  3. If player is in check and has no legal moves, then it is checkmate (stalemate if no legal moves but not in check).

CodePudding user response:

Board representation is paramount when considering a chess engine (or other related board games), specifically to simplify move generation. Generally the choices are...

  • bitboards (an advanced technique) or
  • a single dimensional array with a border around the board.

Based on the isMovePossible function, it appears you are already using a single dimensional array, but you will find it easier if you include a border around the board, as it will greatly simplify and speed bounds checking when generating moves.

Usually in chess engines that employ a bordered board, the single dimensional array is interpreted as a 10 x 12 array that represents the squares, pieces, and the border. More specifically, see an earlier answer of mine that exemplifies bordered boards, in addition to the genesis of move generation.

Couple of notes about the referenced answer...

  • The code snippet makes use of a 12 x 12 bordered board, although one can make use of a 10 x 12 bordered board and still accommodate the border checking for Knight moves.
  • Special pawn moves (such as two squares from the starting square, en passant captures, and pawn promotion) will require special logic beyond what was presented in the code snippet.
  • The very bottom portion of the code snippet shows the technique for move generation for a single piece, which of course when applied to all of the opponents pieces, will assist in assessing checkmate...

Employing a bordered board in conjunction with an array of move offsets will simplify your endeavor...

  • Related