Donkey-Pong using Xamarin

In this blog we will implement Donkey-Pong using Elmish Xamarin Forms. This is second part of article Donkey-Pong.

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 State.fs and Types.fs from DonkeyPong and add to DonkeyPong Class Library.

Let’s try and build this solution. The build fails because type Cmd in 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.

Let’s modify DonkeyPong.fs to use these files we added, to do this change the file as shown below.

namespace DonkeyPong
open Elmish.XamarinForms
open Elmish.XamarinForms.DynamicViews
open Xamarin.Forms
open Game.State
open Game.Types
module App = 
let view (model: Model) dispatch =
Xaml.ContentPage(
content=Xaml.StackLayout(padding=20.0,
children=[
yield
Xaml.StackLayout(padding=0.0, verticalOptions=LayoutOptions.Center,
children=[
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
|> 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.

Screenshot after launching the app.
Screenshot after the game is over.

The source code for this app is here.

Like what you read? Give Sandeep Chandra a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.