Created
January 4, 2015 19:47
-
-
Save mitchmindtree/0431d229fe789abb7933 to your computer and use it in GitHub Desktop.
Mario Ice-Skating (first Elm code)
This file contains hidden or 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
import Color (..) | |
import Graphics.Collage (..) | |
import Graphics.Element (..) | |
import Keyboard | |
import Signal | |
import Time (..) | |
import Window | |
-- MODEL | |
mario = { x=0, y=0, vx=0, vy=0, dir="right" } | |
-- UPDATE -- ("m" is for Mario) | |
jump {y} m = if y > 0 && m.y == 0 then { m | vy <- 5 } else m | |
gravity dt m = if m.y > 0 then { m | vy <- m.vy - dt/4 } else m | |
physics dt m = { m | x <- m.x + dt*m.vx , y <- max 0 (m.y + dt*m.vy) } | |
skate {x} m = { m | vx <- if | abs x > 0 && m.y == 0 -> dash m.vx x | |
| m.y > 0 -> m.vx | |
| otherwise -> drag m.vx | |
, dir <- if x < 0 then "left" else | |
if x > 0 then "right" else m.dir } | |
step (dt, keys) = jump keys >> gravity dt >> skate keys >> physics dt | |
-- Skate Update Functions | |
dash vx x = let newVx = vx + toFloat x * 0.05 | |
in if abs newVx > 5 then vx else newVx | |
drag vx = if abs vx < 0.02 then 0 else vx - amount vx | |
amount vx = 0.01 * if vx > 0 then 1 else if vx < 0 then -1 else 0 | |
-- DISPLAY | |
render (w',h') mario = | |
let (w,h) = (toFloat w', toFloat h') | |
verb = if | mario.y > 0 -> "jump" | |
| mario.vx /= 0 -> "walk" | |
| otherwise -> "stand" | |
src = "http://elm-lang.org/imgs/mario/" ++ verb ++ "/" ++ mario.dir ++ ".gif" | |
in collage w' h' | |
[ rect w h |> filled (rgb 174 238 238) | |
, rect w 50 |> filled (rgb 74 163 41) | |
|> move (0, 24 - h/2) | |
, toForm (image 35 35 src) |> move (mario.x, mario.y + 62 - h/2) | |
] | |
-- MARIO | |
input = let delta = Signal.map (\t -> t/20) (fps 300) | |
in Signal.sampleOn delta (Signal.map2 (,) delta Keyboard.arrows) | |
main = Signal.map2 render Window.dimensions (Signal.foldp step mario input) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment