about summary refs log tree commit diff
path: root/src/Xanthous/Monad.hs
blob: acf7775ede414f9d224758c2792fb9d92fe13894 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module Xanthous.Monad
  ( AppT(..)
  , runAppT
  , continue
  , halt
  , say
  , say_
  ) where

import Xanthous.Prelude
import Control.Monad.Random
import Control.Monad.State
import qualified Brick
import Brick (EventM, Next)
import Data.Aeson

import Xanthous.Game
import Xanthous.Messages (message)

newtype AppT m a
  = AppT { unAppT :: StateT GameState m a }
  deriving ( Functor
           , Applicative
           , Monad
           , MonadState GameState
           )
       via (StateT GameState m)

instance MonadTrans AppT where
  lift = AppT . lift

instance (Monad m) => MonadRandom (AppT m) where
  getRandomR rng = randomGen %%= randomR rng
  getRandom = randomGen %%= random
  getRandomRs rng = uses randomGen $ randomRs rng
  getRandoms = uses randomGen randoms

runAppT :: Monad m => AppT m a -> GameState -> m (a, GameState)
runAppT appt initialState = flip runStateT initialState . unAppT $ appt

halt :: AppT (EventM n) (Next GameState)
halt = lift . Brick.halt =<< get

continue :: AppT (EventM n) (Next GameState)
continue = lift . Brick.continue =<< get

-- say :: [Text] -> AppT m ()
-- say :: [Text] -> params -> AppT m ()

class SayR a where
  say :: [Text] -> a

instance Monad m => SayR (AppT m ()) where
  say msgPath = say msgPath $ object []

instance (Monad m, ToJSON params) => SayR (params -> AppT m ()) where
  say msgPath params = do
    msg <- message msgPath params
    messageHistory %= pushMessage msg

say_ :: Monad m => [Text] -> AppT m ()
say_ = say