Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -- GameOfLife.hs
- import Control.Comonad
- import ListZipper
- --- Beginning of game logic
- countNeighbours :: ListZipT ListZip Bool -> Int
- -- Counts number of living cells in current 3x3 square (including this one in the center)
- countNeighbours llwonad =
- let countNeighbours1 lwonad = length $ filter (== True) $ [extract lwonad, head $ l lwonad, r lwonad !! 1]
- in sum $ fmap countNeighbours1 [tget llwonad, head $ tl llwonad, tr llwonad !! 1]
- rule :: ListZipT ListZip Bool -> Bool
- -- Decides wether current cell should be alive or dead in next turn
- rule llwonad =
- let n = countNeighbours llwonad
- in n == 3 || (n == 4 && extract llwonad)
- life :: ListZipT ListZip Bool -> [ListZipT ListZip Bool]
- life = iterate $ extend rule
- --- End of game logic
- window :: Int -> Int -> ListZipT ListZip a -> [[a]]
- -- Returns values of x*y rectagle in the zipper
- window x y llwonad =
- fmap (take x) $ fmap r $ take y $ tr llwonad
- toStr :: [[Bool]] -> String
- -- Translates a 2D Bool array into a readable representation,
- -- Each line -> line in the array,
- -- in each line True -> '#', False -> '-'
- toStr =
- let toStr1 :: [Bool] -> String
- toStr1 = map (\x -> if x then '#' else '-')
- in unlines . map toStr1
- fromStr :: String -> [[Bool]]
- -- Translates a readable representation of a 2D Bool grid
- fromStr = map (map (== '#')) . lines
- falseLine :: ListZip Bool
- -- An infinite False line
- falseLine = fromList (repeat False) (repeat False)
- gridFromStr :: String -> ListZipT ListZip Bool
- -- Translates a string representation into an infinite grid
- gridFromStr lsts =
- let infFlsLZ = fromList (repeat False) (repeat False)
- in LZ (repeat infFlsLZ) ((map (\x -> fromList (repeat False) (x ++ repeat False)) (fromStr lsts)) ++ repeat infFlsLZ)
- play :: Int -> Int -> ListZipT ListZip Bool -> IO ()
- play turns windowSize p0 = foldl1 (\x y -> x >> putStrLn "" >> y) (take turns $ map (putStr . toStr . window windowSize windowSize) $ life p0)
- main :: IO ()
- main = play 6 10 $ gridFromStr "\n\n...###\n..#####\n...###"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement