gdritter repos potrero / d996f23
Handle non-contiguous ranges Getty Ritter 5 years ago
1 changed file(s) with 18 addition(s) and 12 deletion(s). Collapse all Expand all
44
55 import qualified Control.Exception as Exn
66 import qualified Data.Map.Strict as Map
7 import qualified Data.Set as Set
78 import qualified Data.Text as Text
89 import qualified System.Random as Rand
910
1213
1314 data Range = Range { rFrom :: Roll, rTo :: Roll }
1415 deriving (Eq, Show)
16
17 -- needed to handle d66 tables
18 rangeMap :: [Range] -> [Int]
19 rangeMap = Set.toList . foldr (Set.union . toSet) Set.empty
20 where toSet (Range x y) = Set.fromList [x..y]
1521
1622 type TableMap = Map.Map TableName Table
1723
9298 vs <- mapM (computeFragments ctx) msgs
9399 pure (concatValues ctx vs)
94100
95 tableDie :: Table -> Int
96 tableDie t = maximum [ x | (Range _ x, _) <- tableChoices t ]
97
98101 rollTable :: TableMap -> Table -> IO Value
99102 rollTable tables t = do
100 roll <- Rand.randomRIO (1, tableDie t)
101 let ctx = Context
103 let rmap = rangeMap (map fst (tableChoices t))
104 rollIdx <- Rand.randomRIO (0, length rmap - 1)
105 let roll = rmap !! rollIdx
106 ctx = Context
102107 { ctxMap = tables
103108 , ctxRoll = roll
104109 , ctxSelf = tableName t
108113 , roll >= rFrom range && roll <= rTo range
109114 ] of
110115 [choice] -> stripValue <$> computeResult ctx choice
111 _ -> error $ unwords
112 [ "bad table "
113 , Text.unpack (tableName t)
114 , "(roll of"
115 , show roll
116 , "has no matching result)"
117 ]
116 [] -> error $ unwords
117 [ "bad table "
118 , Text.unpack (tableName t)
119 , "(roll of"
120 , show roll
121 , "has no matching result)"
122 ]
123 _ -> error "ambiguous result (TODO)"