Skip to content

Instantly share code, notes, and snippets.

@vagmi
Last active August 29, 2015 14:08
Show Gist options
  • Save vagmi/afe1cdcc377de8a5a14b to your computer and use it in GitHub Desktop.
Save vagmi/afe1cdcc377de8a5a14b to your computer and use it in GitHub Desktop.
import Window
import Mouse
relativem : (Int,Int) -> (Int,Int) -> (Float,Float)
relativem (w,h) (x,y) = (toFloat (x-(w//2)), toFloat ((h//2)-y))
type Bullet = {posX: Float, posY: Float, vel: Float}
defaultBullet = {posX=0, posY=-180.0, vel=5}
type GameState = {bullets: [Bullet]}
gameState = {bullets=[]}
spaceship : (Float,Float) -> Form
spaceship (x,y) = let clampedx = clamp -180 180 x
in move (clampedx, -180)
<| scale 20
<| filled white
<| polygon [ (-1,0.5), (-0.25,0.5)
, (-0.25,1), (0.25,1)
, (0.25,0.5), (1,0.5)
, (1,0), (-1,0)]
renderBullet : Bullet -> Form
renderBullet blt = rect 5 5
|> filled red
|> move (blt.posX, blt.posY)
render : (Int,Int) -> (Int,Int) -> GameState -> Element
render (w,h) pos state = let spship = spaceship <| relativem (w,h) pos
bullets = map renderBullet state.bullets
in container w h middle
<| color black
<| collage 400 400 ([spship] ++ bullets)
data Event = Draw (Int,Int) (Int,Int) Time | Click () (Int,Int) (Int,Int)
event = merges [(lift3 Draw Window.dimensions Mouse.position (fps 60)),
(lift3 Click Mouse.clicks Window.dimensions Mouse.position)]
nextBulletPos : Bullet -> Bullet
nextBulletPos blt = {blt | posY <- blt.posY + blt.vel}
nextStep : Event -> GameState -> GameState
nextStep event currentState =
case event of
Click () dim pos -> let (x,y) = relativem dim pos
clampedx = clamp -180 180 x
newBullets = {defaultBullet | posX <- clampedx} :: currentState.bullets
in {currentState | bullets <- newBullets}
Draw dim pos secs -> let newBullets = map nextBulletPos currentState.bullets
filtered = filter (\b -> b.posX < 200) newBullets
in {currentState | bullets <- filtered}
main = lift3 render Window.dimensions Mouse.position <| foldp nextStep gameState event
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment