Commit 99a26590 authored by Nicolas Lenz's avatar Nicolas Lenz
Browse files

Init

parent eb4a51ab
module GameOfLife where
import Data.Maybe
data Cell = Dead | Alive deriving (Show)
data Pos = Pos {posX :: Int, posY :: Int} deriving (Show, Eq)
data Board = Board [[Cell]] deriving (Show)
data Ruleset = Ruleset [Int] [Int]
-- ---> x
-- |
-- V
-- y
testBoard :: Board
testBoard = Board [[Dead, Alive, Dead],
[Alive, Alive, Dead],
[Dead, Dead, Alive]]
isAlive :: Cell -> Bool
isAlive Alive = True
isAlive Dead = False
-- | Safe index operator using Maybe. Returns Just the n-th element of the list if the index is valid, else Nothing.
(!?) :: [a] -> Int -> Maybe a
(x:xs) !? 0 = Just x
(x:xs) !? n | n > 0 = xs !? (n - 1)
_ !? _ = Nothing -- The list is empty or the index negative, so return Nothing.
map2 :: (a -> b) -> [[a]] -> [[b]]
map2 f = map (map f)
getCell :: Board -> Pos -> Maybe Cell
getCell (Board css) (Pos x y) = (css !? x) >>= (!? y)
allPos :: Board -> [Pos]
allPos (Board []) = []
allPos (Board [[]]) = []
allPos (Board css)= [Pos x y | x <- [0 .. length css], y <- [0 .. length $ head css]]
neighborsPos :: Pos -> [Pos]
neighborsPos (Pos x y) = [Pos x' y' | x' <- [x - 1..x + 1], y' <- [y - 1..y + 1], not $ (x' == x) && (y' == y)]
neighbors :: Board -> Pos -> [Cell]
neighbors board pos = catMaybes $ (getCell board) <$> neighborsPos pos -- , not $ (x' == x) && (y' == y), x >= 0, y >= 0, x < length cs, y < length (head cs)]
neighborCount :: Board -> Pos -> Int
neighborCount board = length . (filter isAlive) . (neighbors board)
newState :: Ruleset -> Int -> Cell -> Cell
newState (Ruleset born surv) neighborCount Alive
| neighborCount `elem` surv = Alive
| otherwise = Dead
newState (Ruleset born surv) neighborCount Dead
| neighborCount `elem` born = Alive
| otherwise = Dead
transition :: Ruleset -> Board -> Board
transition ruleset (Board css) = undefined
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment