Skip to content

Instantly share code, notes, and snippets.

@roryc89
Created March 8, 2017 21:36
Show Gist options
  • Save roryc89/716f6940a84e1e364fe9f6a524daf8c0 to your computer and use it in GitHub Desktop.
Save roryc89/716f6940a84e1e364fe9f6a524daf8c0 to your computer and use it in GitHub Desktop.
-- Read more about this program in the official Elm guide:
-- https://guide.elm-lang.org/architecture/effects/time.html
module App exposing (..)
import Html exposing (Html)
import Svg exposing (..)
import Svg.Attributes exposing (..)
import Time exposing (Time, second)
import Set
import Tuple
main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
-- MODEL
type alias Model =
{ livingCells : Set.Set ( Int, Int )
, antCell : ( Int, Int )
, direction : Direction
}
type Direction
= North
| East
| South
| West
initialModel =
{ livingCells = Set.fromList [ ( 1, 2 ), ( 5, 6 ) ]
, antCell = ( 10, 10 )
, direction = South
}
init : ( Model, Cmd Msg )
init =
( initialModel, Cmd.none )
-- UPDATE
type Msg
= Tick Time
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
Tick newTime ->
let
( x, y ) =
model.antCell
width =
10
isLiving =
Set.member model.antCell model.livingCells
in
case model.direction of
North ->
( { model
| antCell = ( x, y - width )
, direction =
(if isLiving then
East
else
North
)
}
, Cmd.none
)
East ->
( { model | antCell = ( x + width, y ) }, Cmd.none )
South ->
( { model
| antCell = ( x, y + width )
, direction =
(if isLiving then
West
else
South
)
}
, Cmd.none
)
West ->
( { model | antCell = ( x - width, y ) }, Cmd.none )
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every second Tick
-- VIEW
view : Model -> Html Msg
view model =
let
intList =
List.range 0 100
rectCoords =
intList
|> List.concatMap createListOfTuples
createListOfTuples i =
List.map (\j -> ( i, j )) intList
antCircle =
circle
[ cx (model.antCell |> Tuple.first |> (+) 5 |> toString)
, cy (model.antCell |> Tuple.second |> (+) 5 |> toString)
, r "5"
, fill "#0B79CE"
]
[]
in
svg [ viewBox "0 0 200 200", width "600px" ]
((List.map (viewRect model.livingCells) rectCoords) ++ [ antCircle ])
-- rect [ x "50", y "50", width "100", height "100", fill "black" ] []
viewRect livingCells ( xVal, yVal ) =
let
width_ =
10
xCoord =
toString (xVal * width_)
yCoord =
toString (yVal * width_)
isLiving =
Set.member ( xVal, yVal ) livingCells
colour =
if isLiving then
"white"
else
"black"
in
rect
[ x xCoord
, y yCoord
, width (toString width_)
, height (toString width_)
, fill colour
, stroke "grey"
]
[]
@bobwhitelock
Copy link

Thanks for putting this up, hopefully see you at the next one!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment