<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Unsettling Blog]]></title><description><![CDATA[Strangely apt]]></description><link>https://unsettling.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1738232581505/96ca41f0-b27d-4e49-baeb-55065c8887f4.png</url><title>Unsettling Blog</title><link>https://unsettling.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Wed, 11 Nov 2026 22:54:33 GMT</lastBuildDate><atom:link href="https://unsettling.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Minefield Game in F#]]></title><description><![CDATA[A basic game in F# to show some language features and domain driven design]]></description><link>https://unsettling.hashnode.dev/minefield-game-in-fsharp</link><guid isPermaLink="true">https://unsettling.hashnode.dev/minefield-game-in-fsharp</guid><category><![CDATA[#fsharp]]></category><category><![CDATA[DDD]]></category><dc:creator><![CDATA[Richard Bogle]]></dc:creator><pubDate>Fri, 22 Sep 2023 23:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1738233247674/45cc12e1-56e0-4703-b40b-d76c9f66a582.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Here's a small console game, <a target="_blank" href="https://github.com/Boggin/minefield-game-fsharp/">Minefield.fsx</a>, that illustrates, succinctly, some useful features of F# when designing in a domain driven fashion.</p>
<p>The game can be played from the terminal:<br /><code>dotnet fsi .\minefield.fsx</code></p>
<h2 id="heading-the-brief">The Brief</h2>
<p>An engineering company is using the Minefield game as a screen for their software engineering hires.</p>
<p>"In the game a player navigates from one side of a chessboard grid to the other whilst trying to avoid hidden mines. The player has a number of lives, losing one each time a mine is hit, and the final score is the number of moves taken in order to reach the other side of the board. The command line / console interface should be simple, allowing the player to input move direction (up, down, left, right) and the game to show the resulting position (e.g. C2 in chess board terminology) along with number of lives left and number of moves taken."</p>
<p>They aren't looking for the game to be developed so much as to give a framework to show that the software engineers can apply a full test harness with dependency injection, etc.. This naturally leads to a lot of "Enterprise FizzBuzz" code that is quite horrible to see. The company in question asks the developers to post their efforts on Github in public repos so if you want to you can easily find examples of just how terrible this code looks.</p>
<h2 id="heading-why-f">Why F#?</h2>
<p>F# has a number of features that makes it much easier to model a domain, with events, in a safe manner. This code illustrates these features in places.</p>
<h2 id="heading-records">Records</h2>
<p>Elements like the Player, the Board and the Mines can be created as F# Records. The whole of the Game can be a Record, too.</p>
<pre><code class="lang-fsharp"><span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Game</span> </span>=
    { Player: Player
      Mines: Mine list
      Board: Board
      History: Moved list }
</code></pre>
<h2 id="heading-types">Types</h2>
<p>The state changes can be modelled as Discriminated Unions. For instance, the player's move will either be safe, result in a bang, or be off the board (i.e. not allowed).</p>
<pre><code class="lang-fsharp"><span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Moved</span> </span>=
    | Moved <span class="hljs-keyword">of</span> Player
    | Exploded <span class="hljs-keyword">of</span> Player
    | OutOfBounds <span class="hljs-keyword">of</span> Player
</code></pre>
<p>The whole game state can be easily tracked with another Discriminated Union (DU):</p>
<pre><code class="lang-fsharp"><span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">GameState</span> </span>=
    | Active <span class="hljs-keyword">of</span> Game
    | Won <span class="hljs-keyword">of</span> Game
    | Lost <span class="hljs-keyword">of</span> Game
</code></pre>
<p>These states are things that would normally be tracked with flags in your code, like <code>isGameOver</code> or <code>hasWon</code>. The advantage with the type system is we can use the compiler to check that we've handled all the cases.</p>
<p>Once we've thought through a few Records and DU types with which to model our domain we have a clear framework to hang our code on.</p>
<h2 id="heading-pattern-matching">Pattern Matching</h2>
<p>When we want to update the game with the player's move we can use the GameState type:</p>
<pre><code class="lang-fsharp"><span class="hljs-keyword">let</span> update (gameState: GameState) (direction: Direction) : GameState =
    <span class="hljs-keyword">let</span> hasDied player = player.Lives = <span class="hljs-number">0</span>
    <span class="hljs-keyword">let</span> hasEscaped board player = player.Position = board.Limit

    <span class="hljs-keyword">match</span> gameState <span class="hljs-keyword">with</span>
    | Active game -&gt;
        <span class="hljs-keyword">let</span> game' = move game direction

        <span class="hljs-keyword">if</span> game'.Player |&gt; hasDied <span class="hljs-keyword">then</span> Lost game'
        <span class="hljs-keyword">elif</span> game'.Player |&gt; hasEscaped game'.Board <span class="hljs-keyword">then</span> Won game'
        <span class="hljs-keyword">else</span> Active game'
    | Won _ -&gt; gameState
    | Lost _ -&gt; gameState
</code></pre>
<p>Note that Won and Lost here aren't doing anything but returning the game state. They wouldn't be called if the game was won or lost but the compiler is checking for them. We could just ignore these other elements of the DU but that's giving up an advantage of the language. So why have the Won and Lost cases at all?</p>
<pre><code class="lang-fsharp"><span class="hljs-keyword">let</span> display gameState =
   <span class="hljs-keyword">match</span> gameState <span class="hljs-keyword">with</span>
   | Active game -&gt; display' game
   | Won game -&gt;
       display' game
       printfn <span class="hljs-string">"You Won!"</span>
   | Lost game -&gt;
       display' game
       printfn <span class="hljs-string">"You Lost!"</span>
</code></pre>
<p>The domain logic isn't coupled to the UI logic but the UI, such as it is, can still use the different cases.</p>
<p>This code example also shows the simple power of pattern matching. We can rest easy knowing that all of the cases must be handled or the compiler will flag the error. We can also simply decompose the type to use the sub-types, for instance, to get the Game from the GameState.</p>
<p>It may be taking it a little far but I've even created types for a column and a row for each position on the board.</p>
<pre><code class="lang-fsharp"><span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Row</span> </span>= Row <span class="hljs-keyword">of</span> int
<span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Col</span> </span>= Col <span class="hljs-keyword">of</span> int

<span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Position</span> </span>= { x: Row y: Col }

...
    <span class="hljs-keyword">let</span> addRow (Row row) (Row n) = Row(row + n)
...
    <span class="hljs-keyword">match</span> direction <span class="hljs-keyword">with</span>
    | Left -&gt; { position <span class="hljs-keyword">with</span> x = addRow position.x (Row <span class="hljs-number">-1</span>) }
...
</code></pre>
<p>Now we have to explicitly use row and column types when we create a position. It's a good example of how the type system can help us guard against silly errors.</p>
<h2 id="heading-immutability">Immutability</h2>
<p>When we need to update the game state, say when the player has exploded and lost a life, we have to create a new game state:</p>
<pre><code class="lang-fsharp">    <span class="hljs-keyword">elif</span> isMine position <span class="hljs-keyword">then</span>
        Exploded
            { player <span class="hljs-keyword">with</span>
                Lives = player.Lives - <span class="hljs-number">1</span>
                Position = position }
</code></pre>
<p>We have a guarantee that no part of our code can reach into, for instance, the Lives field and change it without our being aware of it. You can also see from the above code example that in using the <code>with</code> keyword we can easily create a new record with only the values updated that we explicitly want updated.</p>
<h2 id="heading-recursion">Recursion</h2>
<p>It's the basis of a great deal of game code to have a game loop. If this were in an imperative language we'd have a <code>while</code> loop that would run until the game was over. In F# we tend to use recursion to achieve the same thing. We can even have inner loops by having recursive functions inside other recursive functions.</p>
<pre><code class="lang-fsharp">      <span class="hljs-keyword">let</span> <span class="hljs-keyword">rec</span> getDirection () =
          <span class="hljs-keyword">try</span>
              <span class="hljs-keyword">let</span> key = Console.ReadKey().KeyChar

              <span class="hljs-keyword">match</span> key <span class="hljs-keyword">with</span>
              | <span class="hljs-symbol">'w</span>' -&gt; Up
              | <span class="hljs-symbol">'a</span>' -&gt; Left
              | <span class="hljs-symbol">'s</span>' -&gt; Down
              | <span class="hljs-symbol">'d</span>' -&gt; Right
              | _ -&gt; raise (InvalidDirection <span class="hljs-string">"Invalid direction"</span>)
          <span class="hljs-keyword">with</span> e -&gt;
              printfn <span class="hljs-string">"%s. Try again!"</span> e.Message
              getDirection ()

      <span class="hljs-keyword">let</span> game' = getDirection () |&gt; update game
</code></pre>
<p>In the above code we even have our own custom exception, InvalidDirection, that we can throw and catch to handle an error. The recursion, in this case, can continue.</p>
<pre><code class="lang-fsharp"><span class="hljs-keyword">exception</span> InvalidDirection <span class="hljs-keyword">of</span> string
</code></pre>
<h2 id="heading-concision">Concision</h2>
<p>F# is a concise language. You may prefer its ability to see a large amount of meaningful code in each paragraph rather than a lot of punctuation.</p>
<pre><code class="lang-fsharp">    <span class="hljs-keyword">let</span> player' =
        direction |&gt; nextPosition player.Position |&gt; moved player &lt;| game.Mines
</code></pre>
<p>A mixture of pipelines and function composition makes for very succinct code that's easy to hold in your head.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The above code is no more than excerpts from a trivial script for a console game. It does illustrate how efficient F# is when you choose to model your domain first and foremost. The type system and the compiler will help you ensure that you've covered all the cases and that you're not making any silly mistakes. Hopefully you'll want to try and use F# for your next project and hopefully you'll avoid writing the next Enterprise FizzBuzz.</p>
]]></content:encoded></item></channel></rss>