Created
December 20, 2019 10:32
-
-
Save ayu-mushi/d8e75f2634b784fda929e27aaea38e3a to your computer and use it in GitHub Desktop.
Elm canvas alife template
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main exposing (main) | |
import Browser | |
import Browser.Events exposing (onAnimationFrameDelta) | |
import Canvas exposing (rect, shapes) | |
import Canvas.Settings exposing (fill) | |
import Canvas.Settings.Advanced exposing (rotate, transform, translate) | |
import Color | |
import Html exposing (Html, div) | |
import Html.Attributes exposing (style) | |
type alias Life = { position : (Float, Float) | |
, size : Float | |
} | |
type alias Model = | |
{ lifes : List Life } | |
type Msg | |
= Frame Float | |
main : Program () Model Msg | |
main = | |
Browser.element | |
{ init = \() -> init | |
, view = view | |
, update = update | |
, subscriptions = \model -> onAnimationFrameDelta Frame | |
} | |
init : (Model, Cmd Msg) | |
init = ({ lifes = [{position= (100, 100),size=30}, {position=(0, 0),size=30}] }, Cmd.none) | |
lifeUpdate : Life -> Life | |
lifeUpdate life = {life | position = (Tuple.first life.position + 1, Tuple.second life.position + 1)} | |
update : Msg -> Model -> (Model, Cmd Msg) | |
update msg model = | |
case msg of | |
Frame _ -> | |
( { model | lifes = List.map lifeUpdate model.lifes }, Cmd.none ) | |
width = | |
800 | |
height = | |
500 | |
centerX = | |
width / 2 | |
centerY = | |
height / 2 | |
view : Model -> Html Msg | |
view model = | |
div | |
[ style "display" "flex" | |
, style "justify-content" "center" | |
, style "align-items" "center" | |
] | |
[ Canvas.toHtml | |
( width, height ) | |
[ style "border" "2px solid rgba(0,0,0,0.1)" ] | |
([ clearScreen] ++ (List.map render model.lifes)) | |
] | |
clearScreen = | |
shapes [ fill Color.white ] [ rect ( 0, 0 ) width height ] | |
render life = | |
shapes | |
[fill (Color.hsl 0.5 0.3 0.7) | |
] | |
[ rect life.position life.size life.size ] | |
-- transform [ translate (Tuple.first life.position) (Tuple.second life.position) , rotate 0] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment