1
+ module GameOfLife where
2
+
3
+ import Control.Concurrent (threadDelay )
4
+ import System.Process (system )
5
+ import GHC.IO.Exception (ExitCode )
6
+
7
+ height :: Int
8
+ height = 30
9
+
10
+ width :: Int
11
+ width = 30
12
+
13
+ -- In miliseconds
14
+ speed :: Int
15
+ speed = 500
16
+
17
+ type Pos = (Int , Int )
18
+
19
+ type Grid = [Pos ]
20
+
21
+ -- PRE-BUILT GRIDS --
22
+
23
+ gliderCol :: Grid
24
+ gliderCol = [(0 ,2 ),(1 ,0 ),(1 ,2 ),(2 ,1 ),(2 ,2 ),(3 ,11 ),(4 ,9 ),(4 ,10 ),(5 ,10 ),(5 ,11 )]
25
+
26
+ glider :: Grid
27
+ glider = [(0 ,2 ),(1 ,0 ),(1 ,2 ),(2 ,1 ),(2 ,2 )]
28
+
29
+ ship :: Grid
30
+ ship = [(0 ,0 ),(0 ,3 ),(1 ,4 ),(2 ,0 ),(2 ,4 ),(3 ,1 ),(3 ,2 ),(3 ,3 ),(3 ,4 )]
31
+
32
+ -- PRE-BUILT GRIDS --
33
+
34
+ showPos :: Pos -> Grid -> Char
35
+ showPos pos grid | pos `elem` grid = ' 0'
36
+ | otherwise = ' '
37
+
38
+ rowLines :: String -> String
39
+ rowLines " " = " "
40
+ rowLines gridStr = take width gridStr ++ " \n " ++ rowLines (drop width gridStr)
41
+
42
+ showGrid :: Grid -> String
43
+ showGrid grid = rowLines [showPos (r,c) grid | r <- [0 .. (height - 1 )],
44
+ c <- [0 .. (width - 1 )]]
45
+
46
+ neighbors :: Pos -> [Pos ]
47
+ neighbors (r,c) = [(r- 1 ,c- 1 ),(r- 1 ,c),(r- 1 ,c+ 1 ),
48
+ (r,c- 1 ) ,(r,c+ 1 ),
49
+ (r+ 1 ,c- 1 ),(r+ 1 ,c),(r+ 1 ,c+ 1 )]
50
+
51
+ livingNeighs :: Pos -> Grid -> Int
52
+ livingNeighs pos grid = length $ filter (`elem` grid) (neighbors pos)
53
+
54
+ survivors :: Grid -> Grid
55
+ survivors grid = filter (\ x -> livingNeighs x grid `elem` [2 ,3 ]) grid
56
+
57
+ births :: Grid -> Grid
58
+ births grid = [(r,c) | r <- [0 .. (height - 1 )],
59
+ c <- [0 .. (width - 1 )],
60
+ livingNeighs (r,c) grid == 3 && (r,c) `notElem` grid]
61
+
62
+ nextGen :: Grid -> Grid
63
+ nextGen grid = survivors grid ++ births grid
64
+
65
+ cls :: IO ExitCode
66
+ cls = system " cls"
67
+
68
+ play :: Grid -> IO ()
69
+ play grid = do
70
+ cls
71
+ putStr $ showGrid grid
72
+ threadDelay $ speed* 10 ^ 3
73
+ play $ nextGen grid
74
+
75
+ -- Choose any pre-built grid or customize your own!
76
+ main :: IO ()
77
+ main = do play gliderCol
0 commit comments