    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Space invaders in Elm</title>
        <link>https://members.accu.org/index.php/journals/2359</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">Overload Journal #138 - April 2017 + Programming Topics</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c78/">Overload</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c372/">o138</a>
                    (7)
<br />

                                            <a href="https://members.accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/journals/c65/">Programming</a>
                    (877)
<br />

                                            <a href="https://members.accu.org/index.php/journals/c372-65/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/journals/c372+65/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Space invaders in Elm</h1>
<p><strong>Author:</strong>&nbsp;Martin Moene</p>
<p>
<strong>Date:</strong> 06 April 2017 18:55:05 +01:00 or Thu, 06 April 2017 18:55:05 +01:00</p>
<p><strong>Summary:</strong>&nbsp;Elm is a functional language which compiles to JavaScript. Ossi Hanhinen provides an overview.

</p>
<p><strong>Body:</strong>&nbsp;<p>I first learned about Elm in May 2015. I fell in love. I also wrote an article describing how to get started with the language by implementing the base for a game. Its title, â€˜Learning FP the hard wayâ€™ [<a href="#[Hanhinen15]">Hanhinen15</a>], was supposed to be a joke of sorts, as Elm is in fact a very easy language to learn! Iâ€™m not sure how many people got that. &#9786;</p>
<p>Since then, I have used Elm in two separate customer projects, and it has definitely made my work better!</p>

<p>The recent update (0.17) meant a rather large shift in the way the language works, so I decided to revisit the original subject. So here it is: the base for a Space Invaders game in Elm 0.17!</p>

<p>You can find all of the code on GitHub, along with some setup instructions. [<a href="#[SpaceInvaders]">SpaceInvaders</a>]</p>

<h2>Elm, what is it again?</h2>

<p>Elm is a â€œ<em>delightful language for reliable webapps.</em>â€ [<a href="#[Elm]">Elm</a>]. It is a functional language which compiles to JavaScript. You can explore it online at <a href="http://elm-lang.org/try">http://elm-lang.org/try</a>. If youâ€™re interested in an overview, I gave a talk about the language, called â€˜Confidence in the frontend with Elmâ€™ at GeeCON 2016. [<a href="#[Hanhinen16]">Hanhinen16</a>]</p>

<h2>Modeling the problem</h2>

<p>First off, letâ€™s re-iterate what we want to achieve.</p>


<p>From the playerâ€™s perspective the program should be like this:</p>

<ul>
	<li>There is a ship representing the player near the bottom of the screen</li>
	
	<li>The player can move the ship left and right with corresponding arrow buttons</li>
	
	<li>The player can shoot with the space bar</li>
</ul>

<p>And from the shipâ€™s perspective the same is:</p>

<ul>
	<li>Ship has a position on a 1D axis</li>
	
	<li>Ship can have a velocity (positive or negative)
		<ul>
			<li>Ship changes position according to its velocity</li>
		</ul>
	</li>
	
	<li>Ship can shoot</li>
</ul>


<p>This gives us a definition of what the <code>Model</code> of our little program should look like:</p>

<pre class="programlisting">
  type alias Model =
    { position : Float
    , velocity : Float
    , shotsFired : Int
    }</pre>
	
<p>This is an example of a data structure called Record. It is like a strongly typed and immutable cousin of the JavaScript object. Now, we have only defined the type of the data so far, so letâ€™s create a model to start from:</p>

<pre class="programlisting">
  model : Model -- this is a type annotation
  model =
    { position = 0
    , velocity = 0
    , shotsFired = 0
    }</pre>

<p>What we have here is a simple value, or a constant. As everything in Elm is immutable, <code>model</code> will always be the same no matter what happens in the app. If we tried to redefine it, the compiler would simply complain that there are multiple definitions for the same name and the code would not compile.</p>

<p>Alright, moving on to moving the ship! I remember from high school that <em>s</em> = <em>v</em>*<em>dt</em>, or moved distance is the product of the velocity and the time difference. So thatâ€™s how we can update the ship. In Elm, that would be something like the following.</p>

<pre class="programlisting">
  applyPhysics : Time -&gt; Model -&gt; Model
  applyPhysics dt model =
    { model | position =
      model.position +   (model.velocity * dt) }</pre>
	  
<p>The above is the way to update a record. We start off with the <code>model</code> as the base, but update the <code>position</code> as per the formula. Note that <code>{ record | x = newX }</code> creates a new record, as everything in Elm is immutable. We will never have to worry about affecting anyone elseâ€™s state by accident. Even better, we can be certain no one else is affecting our state either!</p>

<p>The type annotation on <code>applyPhysics</code> says: given a <code>Float</code> and a <code>Model</code>, I will return a <code>Model</code>, but also: given a <code>Float</code>, I will return <code>Model -&gt; Model</code>. For example, <code>(applyPhysics 16.7)</code> would actually return a working function to which we can pass a <code>Model</code>, and get the physics-applied ship as the return value. This property is called Currying and all Elm functions automatically behave this way. Currying is very useful in many cases, but that is a topic for another article.</p>

<p>We can update the other properties in the very same way (see Listing 1).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
updateVelocity : Float -&gt; Model -&gt; Model
updateVelocity newVelocity model =
    { model | velocity = newVelocity }

incrementShotsFired : Model -&gt; Model
incrementShotsFired model =
  { model | shotsFired = model.shotsFired + 1 }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 1</td>
	</tr>
</table>

<p>Using these little functions we can update all of our state, but weâ€™re missing something quite necessary: 1. View of the current state, and 2. getting input from the user and turning that into updates.</p>

<h2>Showing the state</h2>

<p>Our game wouldnâ€™t be much use if it couldnâ€™t show the current state in some way. To keep things as simple as possible, letâ€™s just print the model as text. We can do it like so:</p>

<pre class="programlisting">
  view : Model -&gt; Html msg
  view model =
    text (toString model)</pre>
	
<p>Here, <code>toString</code> turns the <code>model</code> record into a readable String representation of it, and <code>text</code> from the Html package turns a String into an HTML text node. Pretty handy! Now the strange part here might be the return type of our <code>view</code> function: <code>Html msg</code>. We donâ€™t need to worry about it too much right now, but what the type annotation is saying is in essence: â€œI am returning some HTML, which may produce messages of the <code>msg</code> variety.â€</p>

<p>This will do for now, so letâ€™s move on to the interactive part!</p>

<h2>Subscribing to user input</h2>

<p>Elm 0.17 brought a new way of reacting to changes: Subscriptions. What we will do is this: we will subscribe to certain changes in the world, and when they happen, give the changes some names. We want to control the game by keyboard, so letâ€™s start by taking a look at the Keyboard package. It seems we want to listen for both pressing down on buttons, and letting go of them. With these, we can determine when the user is pressing down on a certain key. We will need something else as well: to keep updating the position of our ship, we need to have a somewhat steady rhythm of <code>applyPhysics</code> with the time difference! That we can get using the <code>AnimationFrame.diffs</code>. Bundling that up into code works like this, defining the messages in our program:</p>

<pre class="programlisting">
  type Msg
    = TimeUpdate Time
    | KeyDown KeyCode
    | KeyUp KeyCode</pre>
	
<p>Here we have a union type. For something to be considered a <code>Msg</code> in this module, it will have to be one of the above (<code>TimeUpdate</code>, <code>KeyDown</code> or <code>KeyUp</code>). Furthermore, the contents of e.g. <code>TimeUpdate</code> must be something that can be considered <code>Time</code>, and so on.</p>

<p>Okay, now letâ€™s declare the subscriptions we need, and name them with our newly-defined message types.</p>

<pre class="programlisting">
  subscriptions : Model -&gt; Sub Msg
  subscriptions model =
    Sub.batch
      [ AnimationFrame.diffs TimeUpdate
      , Keyboard.downs KeyDown
      , Keyboard.ups KeyUp
      ]</pre>
	  
<p>This again will just return a subscription, or a <code>Sub Msg</code>. It doesnâ€™t do anything on its own, but we need it for the actual wiring part of our code (see Listing 2).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
main =
  Html.program
    { init = init
    , view = view
    , update = update
    , subscriptions = subscriptions
    }
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 2</td>
	</tr>
</table>

<p>If you are really paying attention, you might notice that we have <code>view</code> and <code>subscriptions</code> done by now, but both <code>init</code> and <code>update</code> are still missing. Luckily we already have all the building blocks, so taking this home shouldnâ€™t be too much of a stretch anymore! In fact, <code>init</code> is so simple that we should get it out of the way right now.</p>

<pre class="programlisting">
  init : ( Model, Cmd Msg )
  init =
    ( model, Cmd.none )</pre>
	
<p>Thatâ€™s all there is to it! Again, we can leave the <code>Cmd</code> stuff for later, but just as a primer: commands are the only way to have effects in an Elm program. What are effects? They are anything that can affect the world outside the app (such as posting something to the Internet), or whose value can vary between program runs (such as the current time, or random numbers). Here we donâ€™t need to do any commands, so we define it to be <code>none</code>.</p>

<h2>Putting it all together: the update</h2>

<p>All right, nowâ€™s the time to make it all work!</p>

<p>Letâ€™s begin from the high level. The <code>update</code> function takes the incoming message and the old model, and returns the updated model along with possible commands. In this case we wonâ€™t need any commands, but we still need to fulfil the contract with <code>none</code>s (see Listing 3).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )
update msg model =
  case msg of
    TimeUpdate dt -&gt;
      ( applyPhysics dt model, Cmd.none )

    KeyDown keyCode -&gt;
      ( keyDown keyCode model, Cmd.none )

    KeyUp keyCode -&gt;
      ( keyUp keyCode model, Cmd.none )
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 3</td>
	</tr>
</table>

<p>Note that each of the possible <code>Msg</code> options is handled. If they werenâ€™t, the Elm compiler would catch the problem, which is pretty cool and impressive. Anyway, the <code>TimeUpdate</code> is nice and easy. We can simply use the <code>applyPhysics</code> function to get the updated model. For the keypressing cases, I decided to split the handling into their own functions as well.</p>

<p>When it comes to the packages, Elm 0.17 is still a bit of a work in progress. So to make the keyboard handling a little nicer, I made a tiny helper module. There is a function that can turn a <code>KeyCode</code> into a <code>Key</code>, which is a simple union type. It only has the keys we need for this exercise now, but could easily be extended (see Listing 4).</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
keyDown : KeyCode -&gt; Model -&gt; Model
keyDown keyCode model =
  case Key.fromCode keyCode of
    Space -&gt;
      incrementShotsFired model

    ArrowLeft -&gt;
      updateVelocity -1.0 model

    ArrowRight -&gt;
      updateVelocity 1.0 model

    _ -&gt;
      model
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 4</td>
	</tr>
</table>

<p>The above should be pretty clear. Spacebar shoots once as soon as it is pressed down and doesnâ€™t do anything else. The arrow keys set the velocity of the ship when pressed down. Notice that we need an â€œotherwiseâ€ case, customarily denoted as _. This is because there are many other possible keys on the keyboard besides the ones weâ€™ve covered.</p>

<p>How about the release part? See Listing 5...</p>

<table class="sidebartable">
	<tr>
		<td>
			<pre class="programlisting">
keyUp : KeyCode -&gt; Model -&gt; Model
keyUp keyCode model =
  case Key.fromCode keyCode of
    ArrowLeft -&gt;
      updateVelocity 0 model

    ArrowRight -&gt;
      updateVelocity 0 model

    _ -&gt;
      model
			</pre>
		</td>
	</tr>
	<tr>
		<td class="title">Listing 5</td>
	</tr>
</table>

<p>If the released key happened to be one of the movement keys, reset the velocity to 0, otherwise letâ€™s just keep the current model. Pretty straightforward, right?</p>

<p>Now it should work!</p>

<h2>References</h2>

<p class="bibliomixed"><a id="[Elm]"></a>[Elm]  <a href="http://elm-lang.org/">http://elm-lang.org/</a></p>

<p class="bibliomixed"><a id="[Hanhinen15]"></a>[Hanhinen15]  Learning FP the hard way: Experiences on the Elm language <a href="https://gist.github.com/ohanhi/0d3d83cf3f0d7bbea9db#learning-fp-the-hard-way-experiences-on-the-elm-language">https://gist.github.com/ohanhi/0d3d83cf3f0d7bbea9db#learning-fp-the-hard-way-experiences-on-the-elm-language</a></p>

<p class="bibliomixed"><a id="[Hanhinen16]"></a>[Hanhinen16]  <a href="https://speakerdeck.com/ohanhi/confidence-in-the-frontend-with-elm-1">https://speakerdeck.com/ohanhi/confidence-in-the-frontend-with-elm-1</a></p>

<p class="bibliomixed"><a id="[SpaceInvaders]"></a>[SpaceInvaders]  <a href="https://github.com/ohanhi/elm-game-base">https://github.com/ohanhi/elm-game-base</a></p>


<p>Kindly republished from Ossiâ€™s blog:<a href="http://ohanhi.github.io/base-for-game-elm-017.html">http://ohanhi.github.io/base-for-game-elm-017.html</a></p>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
