Phillip Trelford's Array

POKE 36879,255

Mario

The Elm programming language has some fun game samples including Mario. Elm’s syntax is quite similar to F#’s so it turned out quite easy to port the Mario sample and use FunScript to compile the F# code to JavaScript:

Mario FunScript

Use the cursor keys to move Mario.

FunScript

With F# and FunScript you get to use Visual Studio (Windows) or Xamarin Studio (Mac), and get Intellisense over your code and JavaScript libraries via a Type Provider to TypeScript declaration files, which is nice.

The sample uses an F# record for state & function composition for Mario’s movement:

type mario = { x:float; y:float; vx:float; vy:float; dir:string }

let jump (_,y) m = if y > 0 && m.y = 0. then  { m with vy = 5. } else m
let gravity m = if m.y > 0. then { m with vy = m.vy - 0.1 } else m
let physics m = { m with x = m.x + m.vx; y = max 0. (m.y + m.vy) }
let walk (x,_) m = 
    { m with vx = float x 
             dir = if x < 0 then "left" elif x > 0 then "right" else m.dir }

let step dir mario = mario |> physics |> walk dir |> gravity |> jump dir

Alternatively the step function can be composed using the forward compose operator:

let step dir = physics >> walk dir >> gravity >> jump dir

FunScript is a lightweight open source F# to JavaScript compiler. It is still very much in development so if you want to take it out for a spin I’d recommend pulling the source directly from Zach’s Github repository (the current Nuget package is pretty old).

WebSharper

Another good option for F# to JavaScript compilation is WebSharper which is a mature, commercial offering from Intellifactory. I’ve ported the sample to WebSharper too:

The source code again is pretty close, with some minor differences in the way the JavaScript API’s are called. I’m pretty new to WebSharper, so found the slightly older WebSharper 2.4 the easiest version to get started with and adapted the HTML5 Canvas sample to get going.

WebSharper vs FunScript

Anton Tayanovskyy recently posted a WebSharper vs FunScript comparison.

To summarize:

  • FunScript aims to provide an easily extensible F# to JavaScript compiler for building client-side apps. The samples use a lightweight command line based web server built by Tomas Petricek so you don’t even need ASP.Net
  • WebSharper is a commercial enterprise scale web development platform with smooth integration with ASP.Net allowing seamless communication between client and server code

Which gives 2 good choices for creating web apps that target JavaScript with F# :)

For some more complete game implementations try:

  • Pacman (FunScript + HTML5 Canvas)
  • Pool (WebSharper + WebGL)

Pacman Kata at Progressive F# Tutorials NYC 2013

I’m a bit of a Pacman fan so when I came across the Pacman Kata in the Kata Catalogue I was hooked:

Pacman finds himself in a grid filled with monsters. Will he be able to eat all the dots on the board before the monsters eat him?

Back in early 2012 we ran a Pacman Kata at the F#unctional Londoners meetup where you start with a maze and sprites and your task is to write a simple AI. After the event I extended the sample to run on Windows 8, Windows Phone as well as Silverlight and WPF, and somehow got a mention from Channel 9.

A few months back Neil Danson ported the sample to iOS, and over the last few weeks I’ve been playing with the HTML 5 canvas and have created a FunScript version too.

When Rich Minerich suggested a version for the Progressive F# Tutorials in New York I jumped at the chance, and teamed up with Mathias Brandewinder to create a fun session centred around Pacman:

 

Code samples from the session: http://trelford.com/Pacman.Kata.zip

Test-driven Pacman

The session began with some good old unit tests:

[<Test>]
let ``pacman should wrap from left to right beyond left extent`` () =
    let p = wrap { x = leftExtent-1; y =0 }
    Assert.AreEqual(rightExtent, p.x)

Followed by automated acceptance tests using TickSpec:

Scenario: Pacman eats dots
  When pacman eats a pac-dot
  Then he scores 10

Scenario: Pacman eats power pellets
  When pacman eats a power pellet
  Then he scores 50

In the sample the scenarios are automated using attribute based step definitions:

type Property = PacDot | PowerPellet

let [<When>] ``pacman eats a pac-dot`` () =
    properties <- PacDot::properties

let [<When>] ``pacman eats a power pellet`` () =
    properties <- PowerPellet::properties

let [<Then>] ``he scores (.*)`` (points:int) =
    let scored =
        properties |> List.sumBy (function
            | PacDot -> 10
            | PowerPellet -> 50
        )
    Assert.AreEqual(points, scored)

Controls

Next up we looked at implementing keyboard controls, first with Mario and then Pacman, both in FunScript:

Pacman keys 

The controls can be composed from simple functions:

let left (dx,_) p = if dx = –1 then {p with x=p.x+dx} else p
let right (dx,_) p = if dx = 1 then {p with x=p.x+dx} else p
let up (_,dy) p = if dy = -1 then {p with y=p.y+dy} else p
let down (_,dy) p = if dy = 1 then {p with y=p.y+dy} else p

let step dir pacman = pacman |> left dir |> right dir |> up dir |> down dir

Ghosts

The grand finale was writing your own AI for the Ghosts (or Pacman) using an API designed by Mathias specifically for the session:

// Decision is based on current move, line of sight and possible moves
member this.Decide (current: Move) (lineOfSight: Sight) (choices: Move Set) =
    n <- n + 1
           
    let inSight (creatures:Creature list) =
        creatures                
        |> List.exists (function PacMan 0 -> true | _ -> false)

    let standard  () =
        let restricted =                 
            choices 
            |> Set.filter (fun c -> not (c = backwards current))
        if (restricted |> Set.count > 0)
        then randomMove restricted
        else randomMove choices

    let home () =
        let s = lineOfSight
        let xs = [Up,s.Up; Down,s.Down; Left,s.Left; Right,s.Right]
        let x = 
            xs 
            |> List.tryFind (fun (d,xs) ->
                xs |> List.exists (snd >> inSight)
            )
        match x with
        | Some (d,_) -> d
        | None -> standard ()

    if (n / 500) % 2 = 0 then home ()
    else standard ()

The simple AI above switches the ghosts between homing in on Pacman and random moves every 500 frame updates (roughly every 8 seconds).

At the end we played off Mathias’s payoff function based Pacman AI against my simple Ghosts on the big screen which ended in a tie :)

Blue ghosts

In the more competitive Pacman session ran by Paulmichael Blasucci and Rich Minerich the final was between Jack Fox and Tyler Smith.

More fun

And there’s more fun to come, Rich Minerich will be running a Pacman competition at the Progressive F# Tutorials in London this year:

ProgFsharp London 2013

and there’s a Pacman Kata scheduled for November at the F#unctional Londoners meetup.

Walkie Scorchie

From the window at the office I’ve seen a series of futuristic buildings erected, first the Gherkin, then the Shard and now the Walkie Talkie:

London skyline 

The last one being recently been re-dubbed the Walkie Scorchie as it produces a supercharged solar ‘death ray’ that has burned holes in carpets, melted furniture and even the interior of a Jaguar parked nearby.

It feels almost reminiscent of the dystopian future portrayed in the cult film Idiocracy:

Idiocracy skyline

Though our current society is probably closer to the surveillance society of 1984 with the omnipresent Big Brother watching over you:

Big brother is watching you

The everyday software we work with is no less broken, or so Scott Hanselman concludes in everything's broken and nobody's upset.

Software is increasingly a world of broken windows where developers are more accustomed to working around issues than giving feedback, let alone tackling the root causes.

waiting for background operation to complete modal dialog 

Anyone else struggling with the cognitive dissonance of a modal dialog waiting for a background operation to complete?

XAML

I’ve been using XAML in it’s various guises off an on for over 5 years now. Over that time I’ve used WPF, Silverlight and Metro. It feels like little has changed in that time. It’s still probably the best thing out there for desktop app development but surely we could do better.

XML

I’m still stuck editing views in XML, the poor man’s DSL. I, like the developers I know rarely use the designer view. When we do it frequently hangs and we’re left manually killing XDescProc.exe from task manager.

Data Binding

Data binding is central to XAML. With it you can easily bind a collection to a data grid and get sorting and filtering for free. But binding comes with a high performance cost and it’s stringly typed nature means you’re left finding binding errors in the output window at runtime.

Dynamically binding a view to a model would make more sense to me if I could edit the view at runtime, but you can’t, it’s compiled in.

Value Converters

If I want to transform a model value bound to the view to a different form I have to create a class that implements the IValueConverter interface then reference it as a static resource in the resources section. It has all the elegance of C++ header files. Achieving the same thing in ASP.Net is much simpler, you can just write inline some code in the view or call a function.

INotifyPropertyChanged

There’s a plethora of libraries and frameworks dedicated to working around this design decision, from the MVVM frameworks with LINQ expressions to PostSharp and attributes. The C# 5 compiler’s CallerMemberName attribute has finally brought some sanity to the situation. But I know many developers, including myself, have wasted countless hours dealing with it and trying to think of ways of subverting it.

Just about every view model class ends up inheriting from some ViewModelBase or ObservableObject class so that it can implement INotifyPropertyChanged.

Inheritance

It is often said that object-oriented programming is well suited to graphical user interfaces. Perhaps, but I start to have doubts when I see WPF’s Button class with 9 layers of inheritance and over 160 members.

Visual Studio 2010 introduced improved intellisense with substring search on members to partially work around this, but honestly I’d prefer to see buttons be closer to having content and a clicked event than their current diaspora of responsibilities.

Null Reference Exceptions

By far the most common error I see in C# applications is Null Reference Exceptions. Hardly a day goes by where yet another null check is added to the codebase. This needs to be fixed at the language level, functional-first languages like Scala and F# show it’s possible.

HTML5 & JavaScript

HTML 5 and JavaScript are now being pushed as an alternate environment for desktop development. JavaScript has come a long way performance and libraries wise and I like the HTML 5 Canvas model. However I’m not yet convinced how well this scales to multi-window applications that need to interact between processes.

Windows 8

I get that Metro style interfaces are good for tablets and touch, but for multi-window desktop applications it feels like a non-starter.

 

I’ve seen traders use 9 displays simultaneously, running a multitude of different apps from execution platforms and news services to Excel, Outlook and instant messengers.

To me Windows 8 appears to be consumer orientated release. I’m hoping the next version will bring something for the larger customer base of business users.

Vendors

One person’s problem is another’s opportunity. Third party vendors like JetBrains are grasping the opportunity with both hands by patching flaws in Visual Studio and C# with tools like Resharper. They’re now starting to provide elastoplasts over XAML editing too. Jetbrains are not the only ones, Telerik and others are making hay selling themes and datagrids.

627 

To temporarily workaround performance issues caused by the cost of the mouse handler events in one these products we were forced to throttle the number of system mouse events bubbling through the system.

Duct tape is a good short term solution, but surely at some point we should consider building a stronger foundation.

Simplicity

I would not give a fig for the simplicity this side of complexity, but I would give my life for the simplicity on the other side of complexity. - Oliver Wendell Holmes, Jr.

XAML is huge and bloated, WPF 4.5 Unleashed is 864 pages long, yet XAML’s focus on data binding makes it feel like a one-trick pony.

I think a modern desktop UI environment needs to cover a diverse range of product scenarios. There should be a low-level core that can be easily accessed with code for high performance features all the way up to a designer view for tacking databases on to views, and it should all interoperate seamlessly.

Sections of the development community are striving to bring simplicity to our environments. Language designers like Rich Hickey (Clojure) and Don Syme (F#) are bringing us simplicity at the language level. I’d love to see these thought processes applied to UI environments too.

To tackle the root causes of problems some times you need to stop continuously patching over the cracks, step back and take time to look at the big picture. To create Clojure Rich Hickey practised Hammock driven development. I’d love to see more of this kind of thoughtful design and less Mortgage driven development.

Tackling the root causes of complexity and defects in our software is not an easy choice, it requires investment and changes to the way we do things. But not changing is a choice too.

They live out their lives in this virtual reality as they would have around the turn of the 20th and 21st centuries. The time period was chosen because it is supposedly the pinnacle of human civilization. – Agent Smith

Must Java like languages and XML be considered the pinnacle of software development for time immemorial?