import { createAction } from "@reduxjs/toolkit" ; import { take , select , put } from "@redux-saga/core/effects" ; import { getPiece , PlayerActions } from "@creature-chess/gamemode" ; import { BoardState , BoardSelectors } from "@shoki/board" ; import { PieceModel } from "@creature-chess/models" ; import { AppState } from "../../../store" ; import { clearSelectedPiece } from "../../ui/actions" ; import { UIActions } from "../../ui" ; import { getLocationForPiece } from "../getLocationForPiece" ; export type PlayerClickPieceAction = ReturnType < typeof playerClickPieceAction > ; export const playerClickPieceAction = createAction < { pieceId : string ; } > ( "playerClickPieceAction" ) ; export const clickPieceSaga = function * ( ) { while ( true ) { const action = yield take ( playerClickPieceAction . toString ( ) ) ; const { pieceId } = action . payload ; const board = yield select ( ( state ) => state . game . board ) ; const bench = yield select ( ( state ) => state . game . bench ) ; const piece = BoardSelectors . getPiece ( board , pieceId ) || BoardSelectors . getPiece ( bench , pieceId ) || null ; if ( ! piece ) { continue ; } const pieceLocation = getLocationForPiece ( pieceId , board , bench ) ; const selectedPiece = yield select ( ( state ) => state . game . ui . selectedPieceId ? getPiece ( state . game , state . game . ui . selectedPieceId ) : null ) ; if ( selectedPiece ) { const selectedPieceLocation = getLocationForPiece ( selectedPiece . id , board , bench ) ; if ( ! selectedPieceLocation || ! pieceLocation ) { continue ; } yield put ( PlayerActions . swapPiecePlayerAction ( { pieceAId : selectedPiece . id , pieceALocation : selectedPieceLocation , pieceBId : pieceId , pieceBLocation : pieceLocation } ) ) ; yield put ( clearSelectedPiece ( ) ) ; } else { yield put ( UIActions . selectPiece ( pieceId ) ) ; } } } ;