[Haskell-beginners] State monad to help pass around game settings

Dave Martin davemartinnyc at aol.com
Fri Apr 7 01:26:09 UTC 2017


I'm trying to write a game with a "settings menu" where the user can adjust gameplay options. Right now I pass all the settings around as parameters. I'm trying to figure out how to use the State monad to simplify this task, but I can't figure out how to start. Or maybe my whole design approach is wrongheaded, and not in keeping with best practices. Haskell is my first language. This is the kind of thing I have now:

mainM color shape =
  putStrLn "\n\nMain Menu" >>
  (putStrLn . unlines) [
    "(1) Set",
    "(2) Display",
    "(3) Quit"] >>
  putStr "? " >>
  getChar >>= \c ->
    case c of
      '1' -> set color shape
      '2' -> display color shape
      '3' -> return ()
      _ -> mainM color shape

set color shape =
  putStrLn "\n\nSettings" >>
  (putStrLn . unlines) [
    "(1) Color",
    "(2) Shape",
    "(3) Main Menu"] >>
  putStr "? " >>
  getChar >>= \c ->
    case c of
      '1' -> setColor color shape
      '2' -> setShape color shape
      '3' -> mainM color shape
      _ -> set color shape
 
setColor color shape =
  putStr ("\n\nColor is " ++ color ++ ". New color? ") >>
  getLine >>= \cs ->
  set cs shape
  
setShape color shape =
  putStr ("\n\nShape is " ++ shape ++ ". New shape? ") >>
  getLine >>= \cs ->
  set color cs

display color shape =
  putStrLn ("\n\nColor is " ++ color ++ ". Shape is " ++ shape ++ ".") >>
  mainM color shape

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20170406/a58f709c/attachment.html>


More information about the Beginners mailing list