/examples/BlackjackClient.hs

http://github.com/DanBurton/netspec · Haskell · 71 lines · 58 code · 13 blank · 0 comment · 9 complexity · 1c0d6dbe557914d41e6c959490f2cf0a MD5 · raw file

  1. module BlackjackClient where
  2. import BlackjackData
  3. import Network.NetSpec
  4. import Network.NetSpec.Json
  5. import Control.Monad (void)
  6. import Data.List (intercalate)
  7. import System.Environment (getArgs)
  8. import Text.Printf (printf)
  9. readInt :: String -> Int
  10. readInt = read
  11. data ClientState = CS
  12. { myIndex :: Int }
  13. askAction :: Hand -> IO BlackjackClientMessage
  14. askAction _ = putStrLn "Hit or Stand?" >> read <$> getLine
  15. botAction :: Hand -> IO BlackjackClientMessage
  16. botAction h
  17. | hiVal h > 17 = putStrLn "Stand" >> return Stand
  18. | loVal h > 14 = putStrLn "Stand" >> return Stand
  19. | otherwise = putStrLn "Hit" >> return Hit
  20. resolution :: String -> ClientState -> BlackjackState -> IO ()
  21. resolution str (CS i) (BJ hs _) = printEnd hs i >> putStrLn str
  22. win :: ClientState -> BlackjackState -> IO ()
  23. win = resolution "You win!"
  24. lose :: ClientState -> BlackjackState -> IO ()
  25. lose = resolution "You lose!"
  26. printEnd :: [Hand] -> Int -> IO ()
  27. printEnd [h0,h1] i = let (you, opp) = if i == 0 then (h0,h1) else (h1,h0)
  28. in do putStrLn $ replicate 40 '-'
  29. void $ printf "You: %s (%d)\n" (show you) (bestVal you)
  30. void $ printf "Them: %s (%d)\n" (show opp) (bestVal opp)
  31. printEnd _ _ = error "Unexpected number of hands"
  32. displayTurn :: Hand -> Card -> Int -> IO ()
  33. displayTurn hand c n = do
  34. void $ printf "You: %s" (show hand)
  35. putStrLn $ replicate 20 ' '
  36. void $ printf "Opponent: [%s,%s]\n" (show c) oHand
  37. where oHand = intercalate "," $ replicate (pred n) "|??|"
  38. main :: IO ()
  39. main = do
  40. (host:port:bot) <- getArgs
  41. let chooseAction = if null bot then askAction else botAction
  42. runSpec ClientSpec
  43. { _conns = [(host, PortNumber (fromIntegral $ readInt port))]
  44. , _begin = \[h] -> do
  45. Just m <- receive h
  46. case m of YouAre i -> return $ CS i
  47. , _loop = \[h] s -> do
  48. Just m <- receive h
  49. case m of
  50. YourTurn hand c n -> do
  51. displayTurn hand c n
  52. action <- chooseAction hand
  53. h ! action
  54. continue s
  55. YouWin gs -> win s gs >> stop s
  56. YouLose gs -> lose s gs >> stop s
  57. , _end = \_ _ -> return ()
  58. }