Phillip Trelford's Array

POKE 36879,255


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.


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).


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)

Pingbacks and trackbacks (2)+

Comments are closed