Skip to content

Instantly share code, notes, and snippets.

@raimohanska
Created August 5, 2013 19:16
Show Gist options
  • Save raimohanska/6158612 to your computer and use it in GitHub Desktop.
Save raimohanska/6158612 to your computer and use it in GitHub Desktop.
Snake in Elm
import Keyboard
import Window
startPos = {x = 10, y = 10}
startDir = {x = 1, y = 0}
dir = foldp rotate startDir Keyboard.arrows
rotateLeft p = {x=p.y * (0-1), y=p.x}
rotateRight p = {x=p.y, y=p.x * (0-1)}
rotate dir p = if | dir.x < 0 -> rotateLeft p
| dir.x > 0 -> rotateRight p
| otherwise -> p
pos = let plus a b = {x=a.x+b.x,y=a.y+b.y} in
(foldp plus startPos (sampleOn (fps 2) dir))
snake = slidingWindow 5 pos
renderDot (w,h) color pos = rect 10 10 |> filled color |> move (pos.x * 10, pos.y * 10)
renderSnake (w,h) snake =
let snakeDots = map (renderDot (w,h) (rgb 240 50 50 )) snake
in collage w h snakeDots
main = lift2 renderSnake Window.dimensions snake
slidingWindow max s =
let limit xs = take max xs
window x xs = limit (x :: xs)
in foldp window [] s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment