Guest User

Untitled

a guest
May 24th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. main :: IO()
  2. main = do
  3. putStrLn "Enter board configuration"
  4. -- board <- getLine
  5. let board = "1 0 2 1 0 1 1 2 2"
  6. let gameBoard = parseGameBoard board
  7. printBoard $ sliceBoard gameBoard
  8. print $ translateResult $ verifyGame gameBoard
  9.  
  10. parseInt :: String -> Int
  11. parseInt s = read s :: Int
  12.  
  13. parseGameBoard :: String -> [Int]
  14. parseGameBoard inputString = map parseInt $ words inputString
  15.  
  16. translateResult :: Int -> String
  17. translateResult result
  18. | result == 0 = "game is not over"
  19. | result == 1 = "game is a tie"
  20. | result == 2 = "x won"
  21. | result == 3 = "O won"
  22.  
  23. verifyGame :: [Int] -> Int
  24. verifyGame gameBoard = maximum $ map verifyLine $ map (translatePositions gameBoard) possibleLines
  25.  
  26. verifyLine :: (Int, Int, Int) -> Int
  27. verifyLine (a, b, c)
  28. | a == 0 || b == 0 || c == 0 = 0
  29. | a == b && b == c = (a + 1)
  30. | otherwise = 1
  31.  
  32. possibleLines :: [(Int, Int, Int)]
  33. possibleLines = [(0, 1, 2), (3, 4, 5), (6, 7, 8),(0, 3, 6), (1, 4, 7), (2, 5, 8), (1, 4, 8), (2, 4, 6)]
  34.  
  35. listGet :: Ord a => [a] -> Int -> a
  36. listGet (x:xs) i
  37. | i == 0 = x
  38. | otherwise = listGet xs (i-1)
  39.  
  40. mapTuple :: (a -> b) -> (a, a, a) -> (b, b, b)
  41. mapTuple f (a1, a2, a3) = (f a1, f a2, f a3)
  42.  
  43. translatePositions :: [Int] -> (Int, Int, Int) -> (Int, Int, Int)
  44. translatePositions board pos = mapTuple (listGet board) pos
  45.  
  46. boardGet :: Ord a => [a] -> Int -> Int -> a
  47. boardGet board i j = listGet board ((i*3) + (j))
  48.  
  49. sliceBoard :: [Int] -> [(Int, Int, Int)]
  50. sliceBoard board = map (translatePositions board) $ take 3 possibleLines
  51.  
  52. getTuppleString :: (Int, Int, Int) -> String
  53. getTuppleString (a,b,c) = show a ++ " " ++ show b ++ " " ++ show c ++ "\n"
  54.  
  55. printBoard :: [(Int, Int, Int)] -> IO()
  56. printBoard board = putStr $ concatMap getTuppleString board
Add Comment
Please, Sign In to add comment