{-# LANGUAGE DeriveFoldable, DeriveTraversable, TupleSections #-}
module Game.LambdaHack.Client.AI.Strategy
( Strategy, nullStrategy, liftFrequency
, (.|), reject, (.=>), only, bestVariant, renameStrategy, returN, mapStrategyM
) where
import Prelude ()
import Game.LambdaHack.Common.Prelude
import Control.Applicative
import Data.Int (Int32)
import Game.LambdaHack.Common.Frequency as Frequency
newtype Strategy a = Strategy { runStrategy :: [Frequency a] }
deriving (Show, Foldable, Traversable)
_maxBound32 :: Integer
_maxBound32 = toInteger (maxBound :: Int32)
instance Monad Strategy where
m >>= f = normalizeStrategy $ Strategy
[ toFreq name [
#ifdef WITH_EXPENSIVE_ASSERTIONS
assert (toInteger p * toInteger q <= _maxBound32)
#endif
(p * q, b)
| (p, a) <- runFrequency x
, y <- runStrategy (f a)
, (q, b) <- runFrequency y
]
| x <- runStrategy m
, let name = "Strategy_bind (" <> nameFrequency x <> ")"]
instance Functor Strategy where
fmap f (Strategy fs) = Strategy (map (fmap f) fs)
instance Applicative Strategy where
{-# INLINE pure #-}
pure x = Strategy $ return $! uniformFreq "Strategy_pure" [x]
(<*>) = ap
instance MonadPlus Strategy where
mzero = Strategy []
mplus (Strategy xs) (Strategy ys) = Strategy (xs ++ ys)
instance Alternative Strategy where
(<|>) = mplus
empty = mzero
normalizeStrategy :: Strategy a -> Strategy a
normalizeStrategy (Strategy fs) = Strategy $ filter (not . nullFreq) fs
nullStrategy :: Strategy a -> Bool
nullStrategy strat = null $ runStrategy strat
liftFrequency :: Frequency a -> Strategy a
liftFrequency f = normalizeStrategy $ Strategy $ return f
infixr 2 .|
(.|) :: Strategy a -> Strategy a -> Strategy a
(.|) = mplus
reject :: Strategy a
reject = mzero
infix 3 .=>
(.=>) :: Bool -> Strategy a -> Strategy a
p .=> m | p = m
| otherwise = mzero
only :: (a -> Bool) -> Strategy a -> Strategy a
only p s = normalizeStrategy $ do
x <- s
p x .=> return x
bestVariant :: Strategy a -> Frequency a
bestVariant (Strategy []) = mzero
bestVariant (Strategy (f : _)) = f
renameStrategy :: Text -> Strategy a -> Strategy a
renameStrategy newName (Strategy fs) = Strategy $ map (renameFreq newName) fs
returN :: Text -> a -> Strategy a
returN name x = Strategy $ return $! uniformFreq name [x]
mapStrategyM :: Monad m => (a -> m (Maybe b)) -> Strategy a -> m (Strategy b)
mapStrategyM f s = do
let mapFreq freq = do
let g (k, a) = do
mb <- f a
return $! (k,) <$> mb
lbm <- mapM g $ runFrequency freq
return $! toFreq "mapStrategyM" $ catMaybes lbm
ls = runStrategy s
lt <- mapM mapFreq ls
return $! normalizeStrategy $ Strategy lt