evancz / elm-playground

Create pictures, animations, and games with Elm!
https://package.elm-lang.org/packages/evancz/elm-playground/latest/
BSD 3-Clause "New" or "Revised" License
107 stars 17 forks source link

This could be a nice example to add to the library (and possibly to https://elm-lang.org/examples) #21

Open lucamug opened 4 years ago

lucamug commented 4 years ago

This "tree interactive animation" could be a nice example for the elm-playground as it is written with few lines of codes and generate a nice visual effect.

Disclaimer: I am not the author of the code and I don't know who the author is.

https://ellie-app.com/7QZ8nYhnGNna1

Screen Shot 2020-04-10 at 8 29 30

module Main exposing (main)

import Playground exposing (..)

main =
    game view update initialModel

colors =
    [ brown, orange, yellow, red, purple, green, blue, darkGreen, lightPurple, darkCharcoal ]

initialModel =
    { w = 80, h = 200, s = 0, t = 0 }

view computer { w, h, s, t } =
    [ words black "move the mouse and use arrow keys" |> moveY (computer.screen.top - 20)
    , fractalTree w h s t colors 10
        |> move -(w / 2) -(computer.screen.height / 3)
    ]

update computer { w, h, s, t } =
    { w = w + toX computer.keyboard
    , h = h + toY computer.keyboard
    , s = w / 2 + w * computer.mouse.x / computer.screen.width
    , t = 150 * computer.mouse.y / computer.screen.height
    }

fractalTree w h s t colorList n =
    let
        currentColor =
            List.head colorList |> Maybe.withDefault charcoal

        restColors =
            List.tail colorList |> Maybe.withDefault colors

        toDegrees alpha =
            alpha / pi * 180

        hypotenus e f =
            sqrt (e ^ 2 + f ^ 2)

        ( wLeft, wRight ) =
            ( hypotenus s t
            , hypotenus (w - s) t
            )

        baseRect =
            rectangle currentColor w h
                |> move (w / 2) (h / 2)

        children =
            if n == 0 then
                []

            else
                [ fractalTree w h s t restColors (n - 1)
                    |> scale (wLeft / w)
                    |> rotate (toDegrees (asin (t / wLeft)))
                    |> moveUp h
                , fractalTree w h s t restColors (n - 1)
                    |> scale (wRight / w)
                    |> rotate -(toDegrees (asin (t / wRight)))
                    |> move s (t + h)
                ]
    in
    group (baseRect :: children)
mrvary commented 3 years ago

I think @erkal might be the author of this :)

erkal commented 3 years ago

yes, I did also a 3d-version: https://erkal.github.io/elm-3d-playground-exploration/recursive-tree/ the code is here: https://github.com/erkal/elm-3d-playground-exploration/tree/main/games/recursive-tree/src