]> git.rkrishnan.org Git - yorgey.git/blobdiff - hw12/Risk.hs
hw12: wip
[yorgey.git] / hw12 / Risk.hs
diff --git a/hw12/Risk.hs b/hw12/Risk.hs
new file mode 100644 (file)
index 0000000..b78ac10
--- /dev/null
@@ -0,0 +1,39 @@
+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
+
+module Risk where
+
+import Control.Applicative
+import Control.Monad.Random
+import Control.Monad(replicateM, liftM)
+import Data.List(sort)
+
+------------------------------------------------------------
+-- Die values
+
+newtype DieValue = DV { unDV :: Int } 
+  deriving (Eq, Ord, Show, Num)
+
+first :: (a -> b) -> (a, c) -> (b, c)
+first f (a, c) = (f a, c)
+
+instance Random DieValue where
+  random           = first DV . randomR (1,6)
+  randomR (low,hi) = first DV . randomR (max 1 (unDV low), min 6 (unDV hi))
+
+die :: Rand StdGen DieValue
+die = getRandom
+
+------------------------------------------------------------
+-- Risk
+
+type Army = Int
+
+data Battlefield = Battlefield { attackers :: Army, defenders :: Army }
+
+-- battle :: Battlefield -> Rand StdGen Battlefield
+battle (Battlefield {attackers = a, defenders = d}) =
+  let rolla = replicateM (min (a - 1) 3) die
+      rolld = replicateM (min d 2) die
+      zipped = liftA2 zip rolla rolld
+  in
+