Anonymous user
Generate random chess position: Difference between revisions
m
→{{header|Haskell}}
Line 554:
</pre>
=={{header|Haskell}}==
Module RandomChess
<lang haskell>{-# LANGUAGE LambdaCase, TupleSections #-}
Line 563 ⟶ 561:
, placePawns
, placeRemaining
, emptyBoard
, toFen
Line 575 ⟶ 572:
import Control.Monad.State (State, get, gets, put)
import Data.List (find, sortBy)
import System.Random (Random, RandomGen, StdGen, random, randomR)
type Pos = (Char, Int)
Line 688 ⟶ 685:
-- State functions
randomState :: (StdGen -> (a, StdGen)) -> State BoardState a
randomState f = do
currentState <- get▼
let gen1 = generator currentState▼
pure x
randomPos :: State BoardState Pos
randomPos = do
num <- randomState (randomR (1, 8))
▲ let gen1 = generator currentState
let pos = (chr, num)
if isPosOccupied pos
randomPos
else
Line 702 ⟶ 705:
randomPiece :: State BoardState Square
randomPiece = ChessPiece <$> randomState random <*> randomState random
▲ currentState <- get
▲ let (rank, gen2) = random gen1
placeKings :: State BoardState ()
Line 723 ⟶ 720:
placePawns :: State BoardState ()
placePawns =
▲ put currentState { generator = gen2 }
where
go :: Int -> State BoardState ()
Line 734 ⟶ 726:
go n = do
currentState <- get
pos <- randomPos
let pawn = ChessPiece Pawn color
let currentBoard = board currentState
Line 754 ⟶ 744:
placeRemaining :: State BoardState ()
placeRemaining =
▲ let (n, gen2) = randomR (5, sum $ fmap snd remaining) gen1
where
remaining = filter (\case
|