Generate random chess position: Difference between revisions

m
Line 554:
</pre>
=={{header|Haskell}}==
Uses System.Random library: https://hackage.haskell.org/package/random-1.1/docs/System-Random.html
 
Module RandomChess
<lang haskell>{-# LANGUAGE LambdaCase, TupleSections #-}
Line 563 ⟶ 561:
, placePawns
, placeRemaining
, boardSort
, 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
let (rankx, gen2) = randomf gen1
put (currentState { generator = gen2 })
pure x
 
randomPos :: State BoardState Pos
randomPos = do
currentStateboardState <- getgets board
num <- randomState (randomR (1, 8))
let gen1 = generator currentState
letchr (num,<- gen2) =randomState (randomR (1'a', 8'h')) gen1
let (chr, gen3) = randomR ('a', 'h') gen2
put (currentState {generator = gen3})
let pos = (chr, num)
if isPosOccupied pos (board currentState)boardState then
randomPos
else
Line 702 ⟶ 705:
 
randomPiece :: State BoardState Square
randomPiece = ChessPiece <$> randomState random <*> randomState random
randomPiece = do
currentState <- get
let gen1 = generator currentState
let (rank, gen2) = random gen1
let (color, gen3) = random gen2
put (currentState {generator = gen3})
pure $ ChessPiece rank color
 
placeKings :: State BoardState ()
Line 723 ⟶ 720:
 
placePawns :: State BoardState ()
placePawns = dorandomState (randomR (1, 16)) >>= go
currentState <- get
let gen1 = generator currentState
let (totalPawns, gen2) = randomR (1, 16) gen1
put currentState { generator = gen2 }
go totalPawns
where
go :: Int -> State BoardState ()
Line 734 ⟶ 726:
go n = do
currentState <- get
let gen1 = generator currentState
pos <- randomPos
let (color, gen2)<- =randomState random gen1
put currentState { generator = gen2 }
let pawn = ChessPiece Pawn color
let currentBoard = board currentState
Line 754 ⟶ 744:
 
placeRemaining :: State BoardState ()
placeRemaining = do
letrandomState (n, gen2) = randomR (5, sum $ fmap snd remaining)) gen1>>= go remaining
currentState <- get
let gen1 = generator currentState
let (n, gen2) = randomR (5, sum $ fmap snd remaining) gen1
put currentState { generator = gen2 }
go remaining n
where
remaining = filter (\case
Anonymous user