Donkey-Pong using Xamarin
Install the prerequisite and Elmish Xamarin Forms template first. Let’s create a new project called DonkeyPong using the following command
dotnet new elmish-forms-app -lang F# -n DonkeyPong
This will create the solution and projects for Andorid and iOS. Open the solution in Visual Studio. I am using Visual Studio 2017 on Windows 10. Update all the packages and build the solution.
Let’s copy files
Types.fs from DonkeyPong and add to DonkeyPong Class Library.
Let’s try and build this solution. The build fails because type
State.fs cannot be resolved. To fix this replace
open Elmish with
open Elmish.XamarinForms . Let’s build the solution again, it builds this time.
DonkeyPong.fs to use these files we added, to do this change the file as shown below.
module App =
let view (model: Model) dispatch =
for player in model.Players do
yield Xaml.StackLayout(padding=0.0, orientation=StackOrientation.Horizontal, horizontalOptions=LayoutOptions.Center,
children = [ yield Xaml.Label(text = player.Name + " Score: " + (player.Score |> Option.defaultValue ""))
yield Xaml.Button(text = " + ", heightRequest = 40., command = fun () -> dispatch (AddScore player))
if model.GameState = Over then
yield Xaml.Label(text = "Winner is: " + (model.Winner.Value.Name))
yield Xaml.Button(text="Reset", horizontalOptions=LayoutOptions.Center, command=fixf(fun () -> dispatch StartNew))
type App () as app =
inherit Application ()
let program = Program.mkProgram init update App.view
let runner =
|> Program.runWithDynamicView app
The only thing changed in this app is the view definition, Domain model and logic is the same between the web app and the mobile app, this allowing us to reuse the code.
Here are screenshots of the app after launching and after the game has finished.
The source code for this app is here.