Types.hs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. {-# LANGUAGE OverloadedStrings #-}
  2. module Types where
  3. import qualified Data.Map.Strict as Map
  4. import qualified Data.Text as Text
  5. import qualified Data.Text.IO as Text
  6. import qualified System.Random as Rand
  7. data Range = Range { rFrom :: Int, rTo :: Int }
  8. deriving (Eq, Show)
  9. type TableMap = Map.Map Text.Text Table
  10. data Table = Table
  11. { tableName :: Text.Text
  12. , tableChoices :: [(Range, Result)]
  13. } deriving (Eq, Show)
  14. data Result
  15. = ResultText Text.Text
  16. | ResultRoll Text.Text
  17. deriving (Eq, Show)
  18. computeResult :: Int -> TableMap -> Result -> IO ()
  19. computeResult r _ (ResultText msg) = do
  20. Text.putStr ("\x1b[36m" <> Text.pack (show r) <> ":\x1b[39m ")
  21. Text.putStrLn msg
  22. computeResult r ts (ResultRoll name)
  23. | Just t <- Map.lookup name ts = do
  24. Text.putStr ("\x1b[36m" <> Text.pack (show r))
  25. Text.putStrLn (": (roll " <> name <> ")\x1b[39m")
  26. rollTable ts t
  27. | otherwise = Text.putStrLn ("error: no such table: " <> name)
  28. tableDie :: Table -> Int
  29. tableDie t = maximum [ x | (Range _ x, _) <- tableChoices t ]
  30. rollTable :: TableMap -> Table -> IO ()
  31. rollTable tables t = do
  32. roll <- Rand.randomRIO (1, tableDie t)
  33. case [ result
  34. | (range, result) <- tableChoices t
  35. , roll >= rFrom range && roll <= rTo range
  36. ] of
  37. [choice] -> computeResult roll tables choice
  38. _ -> Text.putStrLn $ Text.unwords
  39. [ "bad table "
  40. , tableName t
  41. , "(roll of"
  42. , Text.pack (show roll)
  43. , "has no matching result)"
  44. ]