]> git.rkrishnan.org Git - yorgey.git/blob - hw12/Risk.hs
b78ac1002e30e094e6fa72e989a578dd84d2d69a
[yorgey.git] / hw12 / Risk.hs
1 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
2
3 module Risk where
4
5 import Control.Applicative
6 import Control.Monad.Random
7 import Control.Monad(replicateM, liftM)
8 import Data.List(sort)
9
10 ------------------------------------------------------------
11 -- Die values
12
13 newtype DieValue = DV { unDV :: Int } 
14   deriving (Eq, Ord, Show, Num)
15
16 first :: (a -> b) -> (a, c) -> (b, c)
17 first f (a, c) = (f a, c)
18
19 instance Random DieValue where
20   random           = first DV . randomR (1,6)
21   randomR (low,hi) = first DV . randomR (max 1 (unDV low), min 6 (unDV hi))
22
23 die :: Rand StdGen DieValue
24 die = getRandom
25
26 ------------------------------------------------------------
27 -- Risk
28
29 type Army = Int
30
31 data Battlefield = Battlefield { attackers :: Army, defenders :: Army }
32
33 -- battle :: Battlefield -> Rand StdGen Battlefield
34 battle (Battlefield {attackers = a, defenders = d}) =
35   let rolla = replicateM (min (a - 1) 3) die
36       rolld = replicateM (min d 2) die
37       zipped = liftA2 zip rolla rolld
38   in
39