'use strict' ; import type { CoreState , EnemyAi } from '../components/Game/Game.jsx' ; type Seen = { well : number [ ] ; pieceIds : string [ ] ; } ; type HatetrisAiState = Array < Seen > ; const worstPieces = 'SZOILJT' . split ( '' ) ; export const hatetrisAi = ( currentCoreState , currentAiState , getNextCoreStates ) : [ string , HatetrisAiState ] => { if ( currentAiState === undefined ) { currentAiState = [ ] ; } const prevIndex = currentAiState . findIndex ( ( { well } ) => well . every ( ( row , y ) => row === currentCoreState . well [ y ] ) ) ; const evaluations = worstPieces . map ( ( pieceId , pieceRanking ) => ( { pieceId , alreadyGenerated : prevIndex === - 1 ? 0 : currentAiState [ prevIndex ] . pieceIds . includes ( pieceId ) ? 1 : 0 , highestPeak : Math . max ( ... getNextCoreStates ( currentCoreState , pieceId ) . map ( nextCoreState => { const rating = nextCoreState . well . findIndex ( ( row ) => row !== 0 ) ; return rating === - 1 ? nextCoreState . well . length : rating ; } ) ) , pieceRanking } ) ) ; evaluations . sort ( ( a , b ) => ( a . alreadyGenerated - b . alreadyGenerated ) || ( a . highestPeak - b . highestPeak ) || ( a . pieceRanking - b . pieceRanking ) ) ; const pieceId = evaluations [ 0 ] . pieceId ; return [ pieceId , prevIndex === - 1 ? [ ... currentAiState , { well : currentCoreState . well , pieceIds : [ pieceId ] } ] : currentAiState [ prevIndex ] . pieceIds . includes ( pieceId ) ? currentAiState : [ ... currentAiState . slice ( 0 , prevIndex ) , { ... currentAiState [ prevIndex ] , pieceIds : [ ... currentAiState [ prevIndex ] . pieceIds , pieceId ] } , ... currentAiState . slice ( prevIndex + 1 ) ] ] ; } ;