The problem is that init sets width and height of screen to 0 and doesn't 
update them until the screen resizes. How can I get the values of window 
width and height in init with Tasks?


Here's my code:


import Color exposing (..)
import Collage exposing (..)
import Element exposing (..)
import Random
import Window exposing (..)
import Mouse
import Task
import Platform.Sub as Sub

import Html.App as App
import Html exposing (..)



main =
  App.program
    { init = init
    , view = view
    , update = update
    , subscriptions = subscriptions
    }


-- MODEL

type alias Model =
   { screen : Size
   , balls : List (Ball)
   , previousMouse : Mouse
   }


type alias Ball =
   { position : (Int, Int)
   , color : Color
   }

type alias Mouse =
   { x : Int
   , y : Int
   }



-- UPDATE

type Msg
   = Move Mouse
   | Click Mouse
   | NewBall Color
   | WindowResize Size

update : Msg -> Model -> (Model, Cmd Msg)
update msg ({previousMouse} as model) =
  case msg of
      Move position ->
        let
            (px,py) = (previousMouse.x, previousMouse.y)
            (x, y) = (position.x, position.y)
            newBalls = List.map (updateCoordinates (x-px, py-y)) model.balls
        in
            (Model model.screen newBalls position, Cmd.none)

      Click _ ->
         (model, Random.generate NewBall rgb)

      NewBall color ->
         let
            newBalls = model.balls ++ [ Ball (0,0) color ]
         in
            (Model model.screen newBalls model.previousMouse, Cmd.none)

      WindowResize size ->
         (Model size model.balls model.previousMouse, Cmd.none)


updateCoordinates : (Int,Int) -> Ball -> Ball
updateCoordinates upd ball =
  let
    (x,y) = ball.position
    (dx,dy) = upd
    newPosition = (x+dx, y+dy)
  in
   { ball |
      position = newPosition
   }


rgb : Random.Generator Color.Color
rgb =
  Random.map3 Color.rgb (Random.int 0 255) (Random.int 0 255) (Random.int 0 
255)




-- VIEW

view : Model -> Html Msg
view model =
   -- div [] [ Html.text (toString (Window.height \a -> a)) ]
   (collage model.screen.width model.screen.height
      (List.map drawBall model.balls))
      |> Element.toHtml



drawBall : Ball -> Form
drawBall ball =
   let
      (x,y) = ball.position
      color = ball.color
   in
      circle 10
         |> filled color
         |> move ((toFloat x), (toFloat y))



-- SUBSCRIPTIONS

subscriptions : Model -> Sub Msg
subscriptions model =
   Sub.batch
      [ (Mouse.moves Move)
      , (Mouse.clicks Click)
      , (Window.resizes WindowResize)
      ]


-- INIT

init : (Model, Cmd Msg)
init =
   (Model { width = 0, height = 0 } [] { x=0 , y=0 }, Cmd.none)







-- 
You received this message because you are subscribed to the Google Groups "Elm 
Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
For more options, visit https://groups.google.com/d/optout.

Reply via email to