Main.hs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. {-# LANGUAGE OverloadedStrings #-}
  2. {-# LANGUAGE OverloadedLists #-}
  3. {-# LANGUAGE TypeFamilies #-}
  4. module Main where
  5. import qualified Control.Monad as M
  6. import qualified Data.IORef as IO
  7. import qualified Data.Map.Strict as Map
  8. import Data.Monoid ((<>))
  9. import qualified Data.Text as Text
  10. import qualified Data.Text.IO as Text
  11. import qualified System.Console.Readline as Readline
  12. import qualified System.Exit as Exit
  13. import qualified Parser
  14. import qualified Types
  15. readMap :: FilePath -> IO Types.TableMap
  16. readMap path = do
  17. cs <- Text.readFile path
  18. pure $ Map.fromList
  19. [ (Types.tableName t, t)
  20. | t <- Parser.parseTable cs
  21. ]
  22. main :: IO ()
  23. main = do
  24. tablesRef <- IO.newIORef =<< readMap "perilous-wilds.txt"
  25. Readline.setCompletionEntryFunction $ Just $ \ rs -> do
  26. tables <- IO.readIORef tablesRef
  27. pure [ Text.unpack k
  28. | k <- Map.keys tables
  29. , Text.pack rs `Text.isPrefixOf` k
  30. ]
  31. M.forever $ do
  32. input <- Readline.readline "\x1b[31m--> \x1b[39m"
  33. case input of
  34. Nothing -> do
  35. putStrLn "farewell"
  36. Exit.exitSuccess
  37. Just "" -> pure ()
  38. Just ":l" -> do
  39. tables <- IO.readIORef tablesRef
  40. Text.putStrLn "Available tables: "
  41. Text.putStrLn (" " <> Text.unwords (Map.keys tables))
  42. Just ":r" ->
  43. IO.writeIORef tablesRef =<< readMap "perilous-wilds.txt"
  44. Just choice -> do
  45. tables <- IO.readIORef tablesRef
  46. let names = Text.unwords (Map.keys tables)
  47. Readline.addHistory choice
  48. case Map.lookup (Text.strip (Text.pack choice)) tables of
  49. Nothing -> do
  50. Text.putStrLn ("table not found: " <> Text.pack (show choice))
  51. Text.putStrLn (" valid tables include: " <> names)
  52. Just t -> Types.rollTable tables t