on master help sign in
Get rid of the Examples/ directory. Planning on moving it to a separate repo.
9aa8e3bevancz
Examples/elm-happstack/Main.hsdeleted−71
@@ -1,71 +0,0 @@
1−{-# LANGUAGE QuasiQuotes, TemplateHaskell #-}
2−
3−import Control.Monad (msum)
4−import Happstack.Server
5−import Language.Elm
6−import Language.Elm.Quasi
7−
8−elmRuntime="elm-runtime.js"
9−elmRTPath='/':elmRuntime
10−
11−-- elmResponse is a "nice to have" helper function for compiling
12−-- Elm code when using Elm with Happstack. At some point this might
13−-- be moved to an elm-happstack package.
14−elmResponse :: ElmSource a
15− => String -- ^ Page title
16− -> a -- ^ elm source
17− -> Response
18−elmResponse title = toResponse . toHtml elmRTPath title
19−
20−-- embedding variables (in this case URLs)
21−rootHandler :: ServerPart Response
22−rootHandler = ok $ elmResponse "Welcome!" $ elmIndex
23− where
24− mouse = "/mouse" -- all three of these variables are used in elm_source/index.elm
25− clock = "/clock"
26− shapes = "/shapes"
27− elmIndex = $(elmFile "elm_source/index.elm")
28−
29−-- loading elm source from file
30−
31−mouseHandler :: ServerPart Response
32−mouseHandler = ok $ elmResponse "Mouse position demo"
33− $(elmFile "elm_source/mouse.elm")
34−
35−clockHandler :: ServerPart Response
36−clockHandler = ok $ elmResponse "A clock" $(elmFile "elm_source/clock.elm")
37−
38−-- embedding elm code inside Haskell using the QuasiQuoter:
39−shapesPage = [elm|
40−square = rect 200 200 (150,150)
41−circle = oval 140 140 (150,150)
42−pentagon = ngon 5 60 (150,150)
43−
44−main = collage 300 300
45− [ outlined black square
46− , filled green pentagon
47− , customOutline [8,4] blue circle
48− ]
49−|]
50−
51−shapesHandler :: ServerPart Response
52−shapesHandler = ok $ elmResponse "Simple shapes" $ shapesPage
53−
54−-- routing
55−elmExample :: String -> ServerPart Response
56−elmExample elmLoc = do
57− msum [ nullDir >> rootHandler
58− , dir elmRuntime $ nullDir >>
59− serveFile (guessContentTypeM mimeTypes) elmLoc
60− , dir "mouse" $ nullDir >>
61− mouseHandler
62− , dir "clock" $ nullDir >>
63− clockHandler
64− , dir "shapes" $ nullDir >>
65− shapesHandler
66− ]
67−
68−main :: IO ()
69−main = do
70− elmLoc <- Language.Elm.runtimeLocation
71− simpleHTTP nullConf {port = 3000} $ elmExample elmLoc
Examples/elm-happstack/elm_source/clock.elmdeleted−13
@@ -1,13 +0,0 @@
1−
2−import Time (every)
3−
4−hand clr len time =
5− let t = pi * time / 30 - pi / 2 in
6− solid clr $ line [(200,200), (200 + len * cos t, 200 + len * sin t)]
7−
8−clock t = collage 400 400 [ filled (rgb 96 176 224) $ ngon 12 110 (200, 200)
9− , hand red 100 t
10− , hand black 100 (t/60)
11− , hand black 60 (t/720) ]
12−
13−main = lift clock (every 1)
Examples/elm-happstack/elm_source/index.elmdeleted−44
@@ -1,44 +0,0 @@
1−title w = size w 60 . text . header . toText $ "Elm-Happstack"
2−
3−lightGrey = rgb 240 241 244
4−mediumGrey = rgb 216 221 225
5−heading outer inner =
6− color mediumGrey . size outer 61 .
7− color lightGrey . size outer 60 .
8− size inner 60 $ title inner
9−
10−skeleton body outer =
11− let inner = if outer < 820 then outer - 20 else 800 in
12− flow down [ heading outer inner
13− , body outer inner
14− ]
15−
16−----------------------
17−
18−section = text . bold . Text.height (5/4) . toText
19−
20−-- splicing of values works but literal substitution of strings
21−-- for this reason, we need to have quotes.
22−mouseLink = "#{mouse}"
23−clockLink = "#{clock}"
24−shapesLink = "#{shapes}"
25−
26−
27−info w = List.map (\f -> f ()) . List.intersperse (\x -> plainText "&nbsp;") . List.map ((\e x -> e) . width w) $
28− [ section "Written in Elm, served with Happstack"
29− , text $ toText "This page is written in " ++ Text.link "http://elm-lang.org/" (toText "Elm") ++
30− toText " and served using the " ++
31− Text.link "http://happstack.com/" (toText "Happstack Web Framework") ++
32− toText ". Since you are looking at this page it is safe to assume that you already have the example code. "
33− , text $ toText "URLs are rendered using simple QuasiQuoter variable interpolation."
34− , section "More examples:"
35− , text $ toText "- " ++ Text.link mouseLink (toText "A simple mouse input example")
36− , text $ toText "- " ++ Text.link clockLink (toText "An animated analog clock")
37− , text $ toText "- " ++ Text.link shapesLink (toText "Some simple rendered shapes")
38− ]
39−
40−-- The following line does not parse, replaced it something slightly different
41−-- body outer inner = width outer . flow down $ (:) (plainText "&nbsp;") $ info inner
42−body outer inner = width outer . flow down $ info inner
43−
44−main = lift (skeleton body) Window.width
Examples/elm-happstack/elm_source/mouse.elmdeleted−15
@@ -1,15 +0,0 @@
1−
2−-- Move your mouse around above the canvas!
3−
4−import Mouse (position)
5−import Window (dimensions)
6−
7−myBlue = rgb 0 85 170
8−myGreen = rgba 28 267 85 (1/2)
9−
10−scene (x,y) (w,h) =
11− collage w h [ rotate (toFloat (x+y) / 1000) $ filled myBlue $ ngon 4 100 (200,200)
12− , filled myGreen $ ngon 5 30 (x,y)
13− ]
14−
15−main = lift2 scene Mouse.position Window.dimensions
Examples/elm-js/GameSkeleton/GameSkeleton.elmdeleted−83
@@ -1,83 +0,0 @@
1−
2−module GameSkeleton where
3−
4−
5−
6−{-- Part 1: Model the user input ----------------------------------------------
7−
8−What information do you need to represent all relevant user input?
9−
10−Task: Redefine `UserInput` to include all of the information you need.
11− Redifene `userInput` to be a signal that correctly models the user
12− input as described by `UserInput`.
13−
14−------------------------------------------------------------------------------}
15−
16−data UserInput = UserInput
17−
18−userInput = constant UserInput
19−
20−data Input = Input Float UserInput
21−
22−
23−
24−{-- Part 2: Model the game ----------------------------------------------------
25−
26−What information do you need to represent the entire game?
27−
28−Tasks: Redefine `GameState` to represent your particular game.
29− Redefine `defaultGame` to represent your initial game state.
30−
31−For example, if you want to represent many objects that just have a position,
32−your GameState might just be a list of coordinates and your default game might
33−be an empty list (no objects at the start):
34−
35− data GameState = GameState [(Float,Float)]
36− defaultGame = GameState []
37−
38−------------------------------------------------------------------------------}
39−
40−data GameState = GameState
41−
42−defaultGame = GameState
43−
44−
45−
46−{-- Part 3: Update the game ---------------------------------------------------
47−
48−How does the game step from one state to another based on user input?
49−
50−Task: redefine `stepGame` to use the UserInput and GameState
51− you defined in parts 1 and 2. Maybe use some helper functions
52− to break up the work, stepping smaller parts of the game.
53−
54−------------------------------------------------------------------------------}
55−
56−stepGame (Input delta (UserInput)) (GameState) = GameState
57−
58−
59−
60−{-- Part 4: Display the game --------------------------------------------------
61−
62−How should the GameState be displayed to the user?
63−
64−Task: redefine `display` to use the GameState you defined in part 2.
65−
66−------------------------------------------------------------------------------}
67−
68−display (w,h) gameState = asText gameState
69−
70−
71−
72−{-- That's all folks! ---------------------------------------------------------
73−
74−The following code puts it all together and show it on screen.
75−
76−------------------------------------------------------------------------------}
77−
78−delta = fps 60
79−input = sampleOn delta (lift2 Input delta userInput)
80−
81−gameState = foldp stepGame defaultGame input
82−
83−main = lift2 display Window.dimensions gameState
Examples/elm-js/Logging/Log.elmdeleted−17
@@ -1,17 +0,0 @@
1−
2−module Log where
3−
4−import Foreign.JavaScript
5−import Signal.Input
6−
7−
8−foreign export jsevent "logMessage"
9− messages :: Signal JSString
10−
11−(field, message) = textField ""
12−(butn , pressed) = button " Log "
13−
14−messages =
15− lift castStringToJSString $ keepWhen pressed "" message
16−
17−main = field `beside` butn
Examples/elm-js/Logging/LogHelp.jsdeleted−3
@@ -1,3 +0,0 @@
1−document.addEventListener('logMessage', function(e) {
2− console.log(e.value);
3− });
Examples/elm-js/Logging/README.mddeleted−16
@@ -1,16 +0,0 @@
1−
2−To compile this example yourself use:
3−
4− elm --import-js="LogHelp.js" Log.elm
5−
6−This compiles the Elm file and includes the necessary JavaScript code.
7−It produces a self-contained HTML file.
8−
9−
10−You can see the logged messages in the developer console of your browser.
11−The keyboard shortcut is F12 in many browsers.
12−
13−
14−Note: Not all browsers like reading the elm-runtime-x.y.z.js file from
15−an absolute path, so you may have to specify a relative path with
16−the --runtime flag (e.g. --runtime="../../../elm/elm-runtime-0.3.5.js").
Examples/elm-js/Maps/Map.elmdeleted−14
@@ -1,14 +0,0 @@
1−
2−module Map where
3−
4−import JavaScript.Experimental
5−
6−foreign import jsevent "provideMap"
7− (castElementToJSElement $ spacer 640 360)
8− jsMaps :: Signal JSElement
9−
10−
11−center (w,h) elem = container w h middle elem
12−maps = lift (castJSElementToElement 640 360) jsMaps
13−
14−main = lift2 center Window.dimensions maps
Examples/elm-js/Maps/MapHelp.jsdeleted−25
@@ -1,25 +0,0 @@
1−
2−document.body.onload = function() {
3−
4−var lib = document.createElement('script');
5−lib.addEventListener('load', function() {
6− var div = document.createElement('div');
7− div.id = "demoMap";
8− div.style.width = "640px";
9− div.style.height = "360px";
10−
11− var e = document.createEvent('Event');
12− e.initEvent('provideMap', true, true);
13− e.value = div;
14− document.dispatchEvent(e);
15−
16− setTimeout(function() {
17− var map = new OpenLayers.Map("demoMap");
18− map.addLayer(new OpenLayers.Layer.OSM());
19− map.zoomToMaxExtent();
20− }, 0);
21− });
22−lib.src = "http://www.openlayers.org/api/OpenLayers.js";
23−document.head.appendChild(lib);
24−
25−}
Examples/elm-js/Maps/README.mddeleted−15
@@ -1,15 +0,0 @@
1−
2−To compile this example yourself use:
3−
4− elm --import-js="MapHelp.js" Map.elm
5−
6−This compiles the Elm file and includes the necessary JavaScript code.
7−It produces a self-contained HTML file.
8−
9−
10−Note: Not all browsers like reading the elm-runtime-x.y.z.js file from
11−an absolute path, so you may have to specify a relative path with
12−the --runtime flag (e.g. --runtime="../../../elm/elm-runtime-0.3.5.js").
13−
14−Warning: I am not sure how stable the OpenLayers API is. This is for
15−example only!
Examples/elm-js/Pong/Pong.elmdeleted−263
@@ -1,263 +0,0 @@
1−
2−{----- Overview ------------------------------------------------------
3−
4− This game displays some of the strengths of Functional Reactive
5− Programming (FRP). By the end of this file we will have written an
6− entire GUI/game without any imperative code! No global mutable state,
7− no flipping pixels, no destructive updates. In fact, Elm disallows all
8− of these things at the language level. So good design and safe coding
9− practices are a requirement, not just self-inforced suggestions.
10−
11− This code neatly divides Pong into three major parts: modeling the
12− game, updating the game, and viewing the game. It may be helpful to
13− think of it as a functional variation on the Model-View-Controller
14− paradigm.
15−
16− The code for Pong is structured as follows:
17−
18− 1. MODEL:
19− First we need to define Pong. We do this by modelling Pong with
20− simple data structures. We need two categories of model:
21− - Inputs to the game. For Pong, this is keyboard input from
22− users and clock-ticks from the frame rate manager.
23− - A model of the game itself: paddles, ball, score, etc.
24− Without a model of the game we would have nothing to update
25− or display!
26− These models are the basis for the next two sections, holding
27− all of the information about Pong that we will need.
28−
29− 2. UPDATE:
30− When new inputs come in, we need to update the current state
31− of the game. Without updates, this version of Pong would be very
32− very boring! This section defines a number of 'step functions'
33− that step the game forward based on our inputs. By separating
34− this from the model and display code, we can change how the game
35− works (how it steps forward) without changing anything else: the
36− underlying model and the display code need not be touched.
37−
38− 3. VIEW:
39− Finally, we need a display function that defines the user's view
40− of the game. This code is separate from the game logic, so like
41− the update logic, it can be modified without affecting any other
42− part of the program. We can also define many different views
43− of the same underlying model. In Pong there's not much need for
44− this, but as your model becomes more complex this may be very
45− useful!
46−
47− If you would like to make a game or larger application in Elm, use
48− this structure! Maybe even use this file as a starting point for
49− playing around with your own ideas.
50−
51− Let's get started!
52−
53−-----------------------------------------------------------------------}
54−
55−
56−module Pong where
57−
58−import JavaScript
59−
60−
61−-- Set the frames per second (FPS) to 60, calculate the deltas (the
62−-- difference between the two latest times, the amount of time since
63−-- the last frame), and convert the time into a number of seconds.
64−
65−delta = lift inSeconds (fps 60)
66−
67−
68−------------------------------------------------------------------------
69−------ Modelling User Input ------
70−------------------------------------------------------------------------
71−
72−-- During gameplay, all keyboard input is about the position of the
73−-- two paddles. So the keyboard input can be reduced to two directions,
74−-- each represented by an integer in {-1,0,1}. Furthermore, the SPACE
75−-- key is used to start the game between rounds, so we also need a
76−-- boolean value to represent whether it is pressed.
77−
78−data KeyInput = KeyInput Bool Int Int
79−
80−defaultKeyInput = KeyInput False 0 0
81−
82−keyInput = lift3 KeyInput Keyboard.space
83− (lift .y Keyboard.wasd)
84− (lift .y Keyboard.arrows)
85−
86−
87−------------------------------------------------------------------------
88−------ Combining all inputs ------
89−------------------------------------------------------------------------
90−
91−-- The inputs to this game include a timestep (which we extracted from
92−-- JavaScript) and the keyboard input from the users.
93−
94−data Input = Input Float KeyInput
95−
96−-- Combine both kinds of inputs and filter out keyboard events. We only
97−-- want the game to refresh on clock-ticks, not key presses too.
98−
99−input = sampleOn delta (lift2 Input delta keyInput)
100−
101−
102−
103−------------------------------------------------------------------------
104−------ Modelling Pong / a State Machine ------
105−------------------------------------------------------------------------
106−
107−-- Pong has two obvious components: the ball and two paddles.
108−
109−data Paddle = Paddle Float -- y-position
110−data Ball = Ball (Float,Float) (Float,Float) -- position and velocity
111−
112−-- But we also want to keep track of the current score and whether
113−-- the ball is currently in play. This will allow us to have rounds
114−-- of play rather than just having the ball move around continuously.
115−
116−data Score = Score Int Int
117−data State = Play | BetweenRounds
118−
119−-- Together, this information makes up the state of the game. We model
120−-- Pong by using the inputs (defined above) to update the state of the
121−-- game!
122−
123−data GameState = GameState State Score Ball Paddle Paddle
124−
125−
126−-- I have chosen to parameterize the size of the board, so it can
127−-- be changed with minimal effort.
128−
129−gameWidth = 600
130−gameHeight = 400
131−halfWidth = gameWidth / 2
132−halfHeight = gameHeight / 2
133−
134−
135−-- Before we can update anything, we must first define the default
136−-- configuration of the game. In our case we want to start between
137−-- rounds with a score of zero to zero.
138−
139−defaultGame = GameState BetweenRounds
140− (Score 0 0)
141− (Ball (halfWidth, halfHeight) (150,150))
142− (Paddle halfHeight)
143− (Paddle halfHeight)
144−
145−
146−
147−------------------------------------------------------------------------
148−------ Stepping from State to State ------
149−------------------------------------------------------------------------
150−
151−-- Now to step the game from one state to another. We can break this up
152−-- into smaller components.
153−
154−-- First, we define a step function for updating the position of
155−-- paddles. It depends on our timestep and a desired direction (given
156−-- by keyboard input).
157−
158−stepPaddle delta dir (Paddle y) =
159− Paddle $ clamp 20 (gameHeight-20) (y + toFloat dir * 200 * delta)
160−
161−
162−-- We must also step the ball forward. This is more complicated due to
163−-- the many kinds of collisions that can happen. All together, this
164−-- function figures out the new velocity of the ball based on
165−-- collisions with the top and bottom borders and collisions with the
166−-- paddles. This new velocity is used to calculate a new position.
167−
168−-- This function also determines whether a point has been scored and
169−-- who receives the point. Thus, its output is a new Ball and points
170−-- to be added to each player.
171−
172−makePositive n = if n > 0 then n else 0-n
173−makeNegative n = if n > 0 then 0-n else n
174−within epsilon n x = x > n - epsilon && x < n + epsilon
175−
176−stepVelocity velocity lowerCollision upperCollision =
177− if lowerCollision then makePositive velocity else
178− if upperCollision then makeNegative velocity else velocity
179−
180−stepBall delta (Ball (x,y) (vx,vy)) (Paddle y1) (Paddle y2) =
181− let hitPaddle1 = within 20 y1 y && within 8 25 x
182− hitPaddle2 = within 20 y2 y && within 8 (gameWidth - 25) x
183− vx' = stepVelocity vx hitPaddle1 hitPaddle2
184− vy' = stepVelocity vy (y < 7) (y > gameHeight - 7)
185− scored = x > gameWidth || x < 0
186− x' = if scored then halfWidth else x + vx' * delta
187− y' = if scored then halfHeight else y + vy' * delta
188− in ( Ball (x',y') (vx',vy')
189− , if x > gameWidth then 1 else 0
190− , if x < 0 then 1 else 0 )
191−
192−
193−-- Finally, we define a step function for the entire game. This steps from state to
194−-- state based on the inputs to the game.
195−
196−stepGame (Input delta (KeyInput space dir1 dir2))
197− (GameState state (Score s1 s2) ball paddle1 paddle2) =
198− let (ball',s1',s2') = if state == Play then stepBall delta ball paddle1 paddle2
199− else (ball, 0, 0)
200− state' = case state of
201− Play -> if s1' /= s2' then BetweenRounds else state
202− BetweenRounds -> if space then Play else state
203− in GameState state'
204− (Score (s1+s1') (s2+s2'))
205− ball'
206− (stepPaddle delta dir1 paddle1)
207− (stepPaddle delta dir2 paddle2)
208−
209−
210−-- Now we put it all together. We have a signal of inputs that changes whenever there
211−-- is a clock tick. This input signal carries the all the information we need about
212−-- the keyboard. We also have a step function that steps from one game-state to the
213−-- next based on some inputs.
214−
215−-- The `gameState` signal steps forward every time a new input comes in. It starts
216−-- as the default game and progresses based on user behavior.
217−
218−gameState = foldp stepGame defaultGame input
219−
220−
221−
222−------------------------------------------------------------------------
223−------ Displaying the Game ------
224−------------------------------------------------------------------------
225−
226−-- These functions take a GameState and turn it into something a user
227−-- can see and understand. It is totally independent of how the game
228−-- updates, it only needs to know the current game state. This allows us
229−-- to change how the game looks without changing any of the logic of the
230−-- game.
231−
232−
233−-- This function displays the current score and directions.
234−
235−scoreBoard w inPlay p1 p2 =
236− let code = text . monospace . toText
237− stack top bottom = flow down [ code " ", code top, code bottom ]
238− msg = width w . centeredText . monospace $ toText "Press SPACE to begin"
239− board = flow right [ stack "W" "S", spacer 20 1
240− , text . Text.height 4 . toText $ show p1 ++ " " ++ show p2
241− , spacer 20 1, stack "&uarr;" "&darr;" ]
242− score = container w (heightOf board) midTop board
243− in if inPlay then score else score `above` msg
244−
245−
246−-- This function displays the entire GameState.
247−
248−display (w,h) (GameState state (Score p1 p2) (Ball pos _) (Paddle y1) (Paddle y2)) =
249− layers
250− [ let pongGreen = rgb 60 100 60 in
251− container w h middle $ collage gameWidth gameHeight
252− [ filled pongGreen (rect gameWidth gameHeight (halfWidth,halfHeight))
253− , filled white (oval 15 15 pos) -- ball
254− , filled white (rect 10 40 ( 20, y1)) -- first paddle
255− , filled white (rect 10 40 (gameWidth - 20, y2)) -- second paddle
256− ]
257− , scoreBoard w (state == Play) p1 p2
258− ]
259−
260−-- We can now define a view of the game (a signal of Elements) that changes
261−-- as the GameState changes. This is what the users will see.
262−
263−main = lift2 display Window.dimensions gameState
Examples/elm-js/Pong/README.mddeleted−11
@@ -1,11 +0,0 @@
1−
2−
3−To compile this example yourself use:
4−
5− elm Pong.elm
6−
7−It produces a self-contained HTML file called Pong.html.
8−
9−As of version 0.6 of the compiler, no external code is necessary
10−to make this work, so the code is slightly cleaner and simpler than
11−the "Pong in Elm" walkthrough.
Examples/elm-js/Redirect/README.mddeleted−12
@@ -1,12 +0,0 @@
1−
2−To compile this example yourself use:
3−
4− elm --import-js="RedirectHelp.js" Redirect.elm
5−
6−This compiles the Elm file and includes the necessary JavaScript code.
7−It produces a self-contained HTML file.
8−
9−
10−Note: Not all browsers like reading the elm-runtime-x.y.z.js file from
11−an absolute path, so you may have to specify a relative path with
12−the --runtime flag (e.g. --runtime="../../../elm/elm-runtime-0.3.5.js").
Examples/elm-js/Redirect/Redirect.elmdeleted−17
@@ -1,17 +0,0 @@
1−
2−module Redirect where
3−
4−import Foreign.JavaScript
5−import Signal.Input
6−
7−
8−foreign export jsevent "redirect"
9− redirectTo :: Signal JSString
10−
11−(butn, pressed) = button " Redirect to elm-lang.org "
12−
13−redirectTo =
14− lift castStringToJSString $
15− keepWhen pressed "" (constant "http://elm-lang.org/")
16−
17−main = butn
Examples/elm-js/Redirect/RedirectHelp.jsdeleted−3
@@ -1,3 +0,0 @@
1−document.addEventListener('redirect', function(e) {
2− if (e.value.length > 0) { window.location = e.value; }
3− });
Examples/elm-js/Title/ChangeTitle.elmdeleted−14
@@ -1,14 +0,0 @@
1−
2−module ChangeTitle where
3−
4−import Foreign.JavaScript
5−import Signal.Input
6−
7−
8−foreign export jsevent "changeTitle"
9− title :: Signal JSString
10−
11−(field, title) = let (f,t) = textField "" in
12− (f, lift castStringToJSString t)
13−
14−main = plainText "Change this page's title to: " `beside` field
Examples/elm-js/Title/ChangeTitleHelp.jsdeleted−3
@@ -1,3 +0,0 @@
1−document.addEventListener('changeTitle', function(e) {
2− document.title = e.value;
3− });
Examples/elm-js/Title/README.mddeleted−7
@@ -1,7 +0,0 @@
1−
2−To compile this example yourself use:
3−
4− elm --import-js="ChangeTitleHelp.js" ChangeTitle.elm
5−
6−This compiles the Elm file and includes the necessary JavaScript code.
7−It produces a self-contained HTML file.
Examples/elm-yesod/Main.hsdeleted−81
@@ -1,81 +0,0 @@
1−{-# LANGUAGE QuasiQuotes, TemplateHaskell, OverloadedStrings, TypeFamilies, MultiParamTypeClasses #-}
2−
3−import Language.Elm
4−import Language.Elm.Quasi
5−import Language.Elm.Yesod
6−import Yesod
7−import Text.Hamlet
8−
9−data ElmTest = ElmTest
10−
11−-- loading external elm code
12−mousePage = $(elmFile "elm_source/mouse.elm")
13−
14−clockPage = $(elmFile "elm_source/clock.elm")
15−
16−-- embedding elm code inside Haskell using the QuasiQuoter:
17−shapesPage = [elm|
18−square = rect 200 200 (150,150)
19−circle = oval 140 140 (150,150)
20−pentagon = ngon 5 60 (150,150)
21−
22−main = collage 300 300
23− [ outlined black square
24− , filled green pentagon
25− , customOutline [8,4] blue circle
26− ]
27−|]
28−
29−-- our Yesod App
30−mkYesod "ElmTest" [parseRoutes|
31−/ RootR GET
32−/mouse MouseR GET
33−/clock ClockR GET
34−/shapes ShapesR GET
35−|]
36−
37−-- Your App data type needs to have an instance of YesodElm (see line 75&76)
38−-- so that toWidget can work with QuasiQuoted elm code. All URL interpolation
39−-- is done automatically. (e.g. lines 28-30 in elm_source/index.elm)
40−getMouseR :: Handler RepHtml
41−getMouseR =
42− defaultLayout $ do
43− setTitle "Mouse position demo"
44− toWidget mousePage
45−
46−getClockR :: Handler RepHtml
47−getClockR =
48− defaultLayout $ do
49− setTitle "A clock"
50− toWidget clockPage
51−
52−getShapesR :: Handler RepHtml
53−getShapesR =
54− defaultLayout $ do
55− setTitle "Simple shapes"
56− toWidget shapesPage
57−
58−getRootR :: Handler RepHtml
59−getRootR =
60− defaultLayout $ do
61− setTitle "Welcome!"
62− toWidget $(elmFile "elm_source/index.elm")
63−
64−
65−-- Our Yesod instance contains the default layout, which inserts the elm-min.js
66−-- file in the site's <head> tag. The YesodElm instance defines the location of
67−-- elm-min.js
68−
69−instance Yesod ElmTest where
70− jsLoader _ = BottomOfHeadBlocking
71− defaultLayout widget = do
72− mmsg <- getMessage
73− pc <- widgetToPageContent $ do
74− $(whamletFile "templates/default-layout.hamlet")
75− hamletToRepHtml $(hamletFile "templates/default-layout-wrapper.hamlet")
76−
77−instance YesodElm ElmTest where
78− urlElmJs _ = Right $ "https://raw.github.com/evancz/Elm/master/elm/elm-runtime-0.7.2.js"
79−
80−main :: IO ()
81−main = warpDebug 3000 ElmTest
Examples/elm-yesod/elm_source/clock.elmdeleted−11
@@ -1,11 +0,0 @@
1−
2−hand clr len time =
3− let t = pi * inSeconds time / 30 - pi / 2 in
4− solid clr $ line [(200,200), (200 + len * cos t, 200 + len * sin t)]
5−
6−clock t = collage 400 400 [ filled (rgb 96 176 224) $ ngon 12 110 (200, 200)
7− , hand red 100 t
8− , hand black 100 (t/60)
9− , hand black 60 (t/720) ]
10−
11−main = lift clock (every second)
Examples/elm-yesod/elm_source/index.elmdeleted−35
@@ -1,35 +0,0 @@
1−title w = size w 60 . text . header . toText $ "Elm-Yesod"
2−
3−lightGrey = rgb 240 241 244
4−mediumGrey = rgb 216 221 225
5−heading outer inner =
6− color mediumGrey . size outer 61 .
7− color lightGrey . size outer 60 .
8− size inner 60 $ title inner
9−
10−skeleton body outer =
11− let inner = if outer < 820 then outer - 20 else 800 in
12− flow down [ heading outer inner
13− , body outer inner
14− ]
15−
16−----------------------
17−
18−section = text . bold . Text.height (5/4) . toText
19−
20−info w = List.map (\f -> f ()) . List.intersperse (\x -> plainText "&nbsp;") . List.map ((\e x -> e) . width w) $
21− [ section "Written in Elm, served with Yesod"
22− , text $ toText "This page is written in " ++ Text.link "http://elm-lang.org/" (toText "Elm") ++
23− toText " and served using the " ++
24− Text.link "http://yesodweb.com/" (toText "Yesod Web Framework") ++
25− toText ". Since you are looking at this page it is safe to assume that you already have the example code. "
26− , text $ toText "Type-safe URLs are rendered using simple QuasiQuoter variable interpolation."
27− , section "More examples:"
28− , text $ toText "- " ++ Text.link "@{MouseR}" (toText "A simple mouse input example")
29− , text $ toText "- " ++ Text.link "@{ClockR}" (toText "An animated analog clock")
30− , text $ toText "- " ++ Text.link "@{ShapesR}" (toText "Some simple rendered shapes")
31− ]
32−
33−body outer inner = width outer . flow down . (:) (plainText "&nbsp;") $ info inner
34−
35−main = lift (skeleton body) Window.width
Examples/elm-yesod/elm_source/mouse.elmdeleted−13
@@ -1,13 +0,0 @@
1−
2−-- Move your mouse around above the canvas!
3−
4−myBlue = rgb 0 85 170
5−myGreen = rgba 28 267 85 0.5
6−
7−scene (x,y) (w,h) =
8− collage w h
9− [ rotate (toFloat (x+y) / 1000) (filled myBlue (ngon 4 100 (200,200)))
10− , filled myGreen (ngon 5 30 (x,y))
11− ]
12−
13−main = lift2 scene Mouse.position Window.dimensions
Examples/elm-yesod/templates/default-layout-wrapper.hamletdeleted−8
@@ -1,8 +0,0 @@
1−$doctype 5
2−<html>
3− <head>
4− <meta charset="UTF-8">
5− <title>#{pageTitle pc}
6− ^{pageHead pc}
7− <body>
8− ^{pageBody pc}
Examples/elm-yesod/templates/default-layout.hamletdeleted−3
@@ -1,3 +0,0 @@
1−$maybe msg <- mmsg
2− <div .message>#{msg}
3−^{widget}
Examples/mario_mp/.gitignoredeleted−2
@@ -1,2 +0,0 @@
1−*.html
2−mario_mp
Examples/mario_mp/Clicks.elmdeleted−6
@@ -1,6 +0,0 @@
1−
2−module Clicks where
3−import WebSocket
4−msgs = show <~ count Mouse.clicks
5−main = asText <~ open "ws://localhost:8080/ws" msgs
6−
Examples/mario_mp/Mario.elmdeleted−91
@@ -1,91 +0,0 @@
1−
2−module Mario where
3−
4−import Dict
5−import JavaScript
6−import JSON
7−import Random
8−import WebSocket
9−
10−{- INPUT -}
11−
12−jumpStep isJump obj = if isJump && obj.y == 0 then { obj | vy <- 5 } else obj
13−gravityStep t obj = { obj | vy <- if obj.y > 0 then obj.vy - t/4 else obj.vy }
14−timeStep t obj = let {x,y,vx,vy} = obj in
15− { obj | x <- x + t * vx , y <- max 0 $ y + t * vy }
16−walkStep dir obj = { obj | vx <- dir, dir <- if | dir < 0 -> "left"
17− | dir > 0 -> "right"
18− | otherwise -> obj.dir }
19−
20−step t d j = timeStep t . gravityStep t . jumpStep j . walkStep d
21−
22−delta = lift (flip (/) 20) (fps 25)
23−leftRight = toFloat . .x <~ Keyboard.arrows
24−jump = (\{y} -> y > 0) <~ Keyboard.arrows
25−steps = sampleOn delta (lift3 step delta leftRight jump)
26−
27−{- LOCAL STATE -}
28−
29−initialMario = { x = 0, y = 0, vx = 0, vy = 0, dir = "right" }
30−stateSignal = foldp ($) initialMario steps
31−
32−encode obj id =
33− castJSStringToString . (toPrettyJSString "") . JSON.fromList $
34− [ ("id", JsonNumber id)
35− , ("x", JsonNumber obj.x)
36− , ("y", JsonNumber obj.y)
37− , ("vx", JsonNumber obj.vx)
38− , ("dir", JsonString obj.dir) ]
39−--encode obj id = show id ++ " " ++ show obj.x ++ " " ++ show obj.y
40−
41−clientID = inRange 0 99999
42−myStream = encode <~ stateSignal ~ clientID
43−
44−{- NETWORK LAYER -}
45−
46−worldMessageStream = open "ws://localhost:8080/ws" myStream
47−
48−-- :: String -> Maybe (Float, Record)
49−parsePlayer msg =
50− case fromString msg of
51− Nothing -> Nothing
52− Just json ->
53− let id = findNumber "id" json
54− x = findNumber "x" json
55− y = findNumber "y" json
56− vx = findNumber "vx" json
57− dir = findString "dir" json
58− in Just (id, { x = x, y = y, vx = vx, vy = 0, dir = dir })
59−
60−-- :: Maybe (Float, Record) -> Dict String Record -> Dict String Record
61−updateWorldPositions maybeMario marioDict = case maybeMario of
62− Just (id, mario) -> (Dict.insert) (show id) mario marioDict
63− Nothing -> marioDict
64−
65−-- :: Signal (Dict String Record)
66−worldPositions = foldp updateWorldPositions Dict.empty (parsePlayer <~ worldMessageStream)
67−--worldPositions = constant empty
68−
69−marios = Dict.values <~ worldPositions
70−
71−{- RENDER CODE -}
72−
73−-- :: Record -> Form
74−mario2Form (w,h) mario =
75− let verb = if mario.vx /= 0 then "walk" else "stand"
76− src = "/imgs/mario/" ++ verb ++ "/" ++ mario.dir ++ ".gif"
77− in toForm (mario.x, (h-63)-mario.y) (image 35 35 src)
78−
79−-- :: (Int,Int) -> [Record] -> Element
80−render (w,h) marios =
81− collage w h ( (filled cyan $ rect w h (w `div` 2, h `div` 2))
82− : (filled green $ rect w 50 (w `div` 2,h-25))
83− : List.map (mario2Form (w,h)) marios )
84−
85−{- PUTTING IT TOGETHER -}
86−
87−-- :: Signal Element
88−main = render <~ Window.dimensions ~ marios
89−--main = above <~ ((plainText . show) <~ (marios)) ~ (render <~ Window.dimensions ~ marios)
90−--main = (plainText . show) <~ (marios)
91−
Examples/mario_mp/Object.elmdeleted−8
@@ -1,8 +0,0 @@
1−
2−module Object where
3−
4−import JavaScript
5−import JSON
6−
7−main = plainText . castJSStringToString . (toPrettyJSString "") . fromList $ [ ("answer", JsonNumber 42) ]
8−
Examples/mario_mp/Values.elmdeleted−7
@@ -1,7 +0,0 @@
1−
2−module Values where
3−
4−import Dict
5−
6−main = constant . plainText . show . values $ empty
7−
Examples/mario_mp/conn.godeleted−43
@@ -1,43 +0,0 @@
1−package main
2−
3−import (
4− "code.google.com/p/go.net/websocket"
5−)
6−
7−type connection struct {
8− // The websocket connection.
9− ws *websocket.Conn
10−
11− // Buffered channel of outbound messages.
12− send chan string
13−}
14−
15−func (c *connection) reader() {
16− for {
17− var message string
18− err := websocket.Message.Receive(c.ws, &message)
19− if err != nil {
20− break
21− }
22− h.broadcast <- message
23− }
24− c.ws.Close()
25−}
26−
27−func (c *connection) writer() {
28− for message := range c.send {
29− err := websocket.Message.Send(c.ws, message)
30− if err != nil {
31− break
32− }
33− }
34− c.ws.Close()
35−}
36−
37−func wsHandler(ws *websocket.Conn) {
38− c := &connection{send: make(chan string, 256), ws: ws}
39− h.register <- c
40− defer func() { h.unregister <- c }()
41− go c.writer()
42− c.reader()
43−}
Examples/mario_mp/elm-runtime.jsdeleted−1
@@ -1 +0,0 @@
1−../../elm/elm-runtime.js
Examples/mario_mp/hub.godeleted−44
@@ -1,44 +0,0 @@
1−package main
2−
3−type hub struct {
4− // Registered connections.
5− connections map[*connection]bool
6−
7− // Inbound messages from the connections.
8− broadcast chan string
9−
10− // Register requests from the connections.
11− register chan *connection
12−
13− // Unregister requests from connections.
14− unregister chan *connection
15−}
16−
17−var h = hub{
18− broadcast: make(chan string),
19− register: make(chan *connection),
20− unregister: make(chan *connection),
21− connections: make(map[*connection]bool),
22−}
23−
24−func (h *hub) run() {
25− for {
26− select {
27− case c := <-h.register:
28− h.connections[c] = true
29− case c := <-h.unregister:
30− delete(h.connections, c)
31− close(c.send)
32− case m := <-h.broadcast:
33− for c := range h.connections {
34− select {
35− case c.send <- m:
36− default:
37− delete(h.connections, c)
38− close(c.send)
39− go c.ws.Close()
40− }
41− }
42− }
43− }
44−}
Examples/mario_mp/imgs/mario/stand/left.gifdeleted

Binary file not shown.

Examples/mario_mp/imgs/mario/stand/right.gifdeleted

Binary file not shown.

Examples/mario_mp/imgs/mario/walk/left.gifdeleted

Binary file not shown.

Examples/mario_mp/imgs/mario/walk/right.gifdeleted

Binary file not shown.

Examples/mario_mp/main.godeleted−24
@@ -1,24 +0,0 @@
1−package main
2−
3−import (
4− "code.google.com/p/go.net/websocket"
5− "flag"
6− "log"
7− "net/http"
8−)
9−
10−var addr = flag.String("addr", ":8080", "http service address")
11−
12−func fileHandler(w http.ResponseWriter, r *http.Request) {
13− http.ServeFile(w, r, r.URL.Path[1:])
14−}
15−
16−func main() {
17− flag.Parse()
18− go h.run()
19− http.HandleFunc("/", fileHandler)
20− http.Handle("/ws", websocket.Handler(wsHandler))
21− if err := http.ListenAndServe(*addr, nil); err != nil {
22− log.Fatal("ListenAndServe:", err)
23− }
24−}
Examples/mario_mp/makefiledeleted−19
@@ -1,19 +0,0 @@
1−all: mario_mp Mario.html Clicks.html Object.html Values.html
2−
3−mario_mp: *.go
4− go build
5−
6−Mario.html: Mario.elm
7− elm -r elm-runtime.js Mario.elm
8−
9−Clicks.html: Clicks.elm
10− elm -r elm-runtime.js Clicks.elm
11−
12−Object.html: Object.elm
13− elm -r elm-runtime.js Object.elm
14−
15−Values.html: Values.elm
16− elm -r elm-runtime.js Values.elm
17−
18−clean:
19− rm -rf *.html mario_mp