Skip to content

Instantly share code, notes, and snippets.

@cazala
Created July 25, 2018 15:20
Show Gist options
  • Save cazala/3fcb19ed0c1a85832da3d3ff6f971e31 to your computer and use it in GitHub Desktop.
Save cazala/3fcb19ed0c1a85832da3d3ff6f971e31 to your computer and use it in GitHub Desktop.
// src/modules/middleware/analysis-middleware.js
import {
   addPiece,
   removePiece,
   checkSquare,
+  initSquares
 } from '../../modules/squares/actions'
 import {
   wasKingCastle,
   wasQueenCastle,
   getSquaresOfPiece
 } from '../../chess/analysis'
 import engine, { isKingInCheck } from '../../chess/engine'
+import { checkmate } from '../match/actions'

 export default store => next => action => {
   switch (action.type) {
   // ...
       if (isKingInCheck(board, !isWhite)) {
         next(checkSquare(getSquaresOfPiece(isWhite ? 'k' : 'K', board)[0]))
         next(checkSquare(action.toSquare))
+        const squares = store.getState().squares
+        const squaresWithPiecesFromPlayerInCheck = squares.filter(
+          square =>
+            square.pieceId !== '_' &&
+            (isWhite ? square.color === 'piece_black' : 'piece_white')
+        )
+        const amountOfValidMoves = squaresWithPiecesFromPlayerInCheck.reduce(
+          (moves, square) =>
+            moves + engine(squares)(square.pieceId)(square.id).length,
+          0
+        )
+        if (amountOfValidMoves === 0) {
+          if (store.getState().match.status === 'started') {
+            next(checkmate())
+            setTimeout(() => next(initSquares()), 10000)
+          }
+        }
       }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment