Introduction
This article will walk you through how to build a simple data-driven mobile game application using the power of Xamarin and Web API. We will also build a real-time leaderboard page using ASP.NET SignalR.
Background
In the past year, I was tasked to create proof-of-concept application about Working Memory in the form of a game. I was a bit excited about it since building a game application isn’t really my area of expertise and I was very curious about it. I decided to use Xamarin and Visual Studio for the following reasons:
- Xamarin is now fully integrated with the latest Visual Studio release (VS 2017 as of this time of writing).
- Xamarin allows you to build cross-platform apps (iOS, Andriod, and UWP) using C#.
- I am an experienced C# developer.
- I am more familiar with Visual Studio development tools.
- I don't need to learn how to use other frameworks, editors, tools and other programming languages to build native apps.
- I can take advantage of the cool features provided by Xamarin such as cloud testing and app monitoring.
- Xamarin and Visual Studio are quite popular and stable platform for building real-world apps.
- Xamarin has its own dedicated support site. So when you encounter any problem during your development, you can easily post your query to their dedicated forums.
I'm writing this article so anyone interested in mobile app development can reference this if they need a simple working game app that requires some kind of features that connects data from a mobile app to other services such as a REST application or web application. This article will walk you through on how to build a simple Working Memory game application using the power of Xamarin and ASP.NET
Before we dig down further, let’s take about a bit of Working Memory.
What is a Working Memory?
According to the documentation, a Working memory is a cognitive system with a limited capacity that is responsible for temporarily holding information available for processing. Working memory is important for reasoning and the guidance of decision-making and behavior. We can say that Working Memory is a crucial brain function that we use to focus our attention and control our thinking.
What You Will Learn
This article is targeted for beginners to intermediate .NET developers who want to build a data-driven mobile application that connects to other services from scratch and get their hands dirty with a practical example. I've written this book in such a way that it’s easy to follow and understand. As you go along and until such time you finished following the book, you will learn how to:
- Set up an SQL Server database from scratch.
- Build a simple Working Memory game application using Xamarin.Forms that targets both, iOS and Android platform.
- Create an ASP.NET Web API project.
- Integrate Entity Framework as our data access mechanism.
- Create an ASP.NET MVC 5 project.
- Integrate ASP.NET SignalR within ASP.NET MVC.
PrerequisitesBefore you go any further, make sure that you have the necessary requirements for your system and your development environment is properly configured. This particular demo uses the following tools and frameworks:
- Visual Studio 2015
- SQL Server Management Studio Express 2014
- Xamarin 4.1
- NET Web API 2
- NET MVC 5
- NET SignalR 2.2
- Entity Framework 6
A basic knowledge on the following language and concept is also required.
- C#
- JavaScript
- AJAX
- CSS
- HTML
- XAML
- HTTP Request and Response
- OOP
Five Players, One Goal
As you can see from the prerequisites section, we are going to use various technologies to build this whole game application to fulfil a goal. The diagram below illustrates the high-level process on how each technologies connects to each other.
Based on the illustration above, we are going to need to the following projects,
- A Mobile app
- A Web API app
- A Web app
To summarize that, we are going to build a mobile application using (1) Xamarin.Forms that can target both iOS and Android platform. The mobile app is where the actual game is implemented. We will build a (2) Web API project to handle CRUD operations using (3) Entity Framework. The Web API project will serve as the central gateway to handle data request that comes from the mobile app and web app. We will also build a web application to display the real-time dashboard for ranking using (4) ASP.NET MVC and (5) ASP.NET SignalR. Finally, we are going to create a database for storing the player information and their scores in SQL Server.
Game Objective
The objective of this game is very simple; you just need to count how many times: The light will blink on, the speaker will beep and the device will vibrate within a span of time. The higher your level is, the faster it blinks, beeps and vibrates. This would test how great your memory is.
Game Views
This section will give some visual reference about the outputs of the applications that we are going to build.
The very first time you open the app, it will bring the Registration page wherein you could register using your name and email. This page also allows you to log-in using your existing account.
Here’s running view of the Registration page,
Once you registered or after you successfully logon to the system, it will bring the following page below,
Clicking the “START” button will start playing the game within a short period of time as shown in the figure below,
After the time has elapsed, it will bring you to the result page wherein you can input your answer of how many times each event happened.
Clicking the “SUBMIT” button will validate your answers whether you got them right and proceed to the next level or restart the game to your current level. Note that your score will automatically synced to the database once you surpass your current best score.
Here are some of the screenshots of the results:
And here’s a screenshot of the real-time web app dashboard for the rankings which triggered by ASP.NET SignalR.
That’s it. Now that you already have some visual reference how the app will look like, it’s time for us to build the app.
Let’s Begin!
Let’s go ahead and fire up Visual Studio 2015 and then create a new Blank XAML App (Xamarin.Forms Portable) project as shown in the figure below,
Figure 1: New Project
For this demo, we will name the project as “MemoryGame.App”. Click OK to let Visual Studio generate the default project templates for you. You should now be presented with this,
Note that the solution only contains the .Droid and .iOS projects. This is because I omitted the .Windows project for specific reasons. This means that, we will be focusing on Android and iOS apps instead.
The Required NuGet Packages
The first thing we need is to add the required packages that are needed for our application. Now go ahead and install the following packages in all projects:
- Plugins.Settings
- Plugin.Connectivity
We'll be using the Xam.Plugins.Settings to provide us a consistent, cross platform settings/preferences across all projects (Portable library, Android and iOS projects). The Xam.Plugin.Connectivity will be used to get network connectivity information such as network type, speeds, and if connection is available. We'll see how each of these references is used in action later.
You can install them via PM Console or via NPM GUI just like in the figure below,
We also need to install the following package under the MemoryGame.App project:
We will be using Newtonsoft.Json later in our code to serialize and deserialize object from an API request.
Once you’ve installed them all, you should be able to see them added in your project references just like in the figure below,
Setting Up a New Database
The next step is setup a database for storing the challenger and rank data. Now go ahead and fire-up SQL Server Management Studio and execute the following SQL script below:
- CREATE Database MemoryGame
- GO
-
- USE [MemoryGame]
- GO
-
- CREATE TABLE [dbo].[Challenger](
- [ChallengerID] [int] IDENTITY(1,1) NOT NULL,
- [FirstName] [varchar](50) NOT NULL,
- [LastName] [varchar](50) NOT NULL,
- [Email] [varchar](50) NULL,
- CONSTRAINT [PK_Challenger] PRIMARY KEY CLUSTERED
- (
- [ChallengerID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
- IGNORE_DUP_KEY = OFF,
- ALLOW_ROW_LOCKS = ON,
- ALLOW_PAGE_LOCKS = ON)
- ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
-
- CREATE TABLE [dbo].[Rank](
- [RankID] [int] IDENTITY(1,1) NOT NULL,
- [ChallengerID] [int] NOT NULL,
- [Best] [tinyint] NOT NULL,
- [DateAchieved] [datetime] NOT NULL,
- CONSTRAINT [PK_Rank] PRIMARY KEY CLUSTERED
- (
- [RankID] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
- IGNORE_DUP_KEY = OFF,
- ALLOW_ROW_LOCKS = ON,
- ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
-
- GO
The SQL script above should create the “MemoryGame” database with the following table,
The database tables that we’ve created earlier are very plain and simple. The dbo.Challenger table just contains some basic properties for us to identify a user who plays the game. The dbo.Rank table holds some basic property to help us identify which user has the highest rank.
Creating the Web API Project
Now that we’ve done setting up our database, it’s time for us to build a REST service to handle database calls and CRUD operations. We are choosing Web API because it’s a perfect fit to build RESTful services in the context of .NET. It also allows other apps (Mobile, Web Apps and even Desktop Apps) to consume our API via EndPoints. This would enable our application to allow clients to access data in any form of application for as long as it supports HTTP services.
Ok let’s proceed to our work. Switch back to Visual Studio and then create a new project by right-clicking on the main Solution and then select Add > New Project > Visual C# > Web. Select ASP.NET Web Application(.NET Framework) and name the project as “MemoryGame.API” just like in the figure below,
Click OK and then select “Empty” from the ASP.NET project template. Check the “Web API” option only and then click Ok to let Visual Studio generate the project for you just like in the figure below,
Integrating Entity Framework
What is EF?
…………..
Now that we have our Web API project ready, let’s continue by implementing our Data Access to work with data from database. For this demo, we are going to use Entity Framework as our Data Access mechanism.
In the MemoryGame.API project, create a new folder called “DB” under the Models folder. Within the “DB” folder, add an ADO.NET Entity Data Model. To do this, just follow these steps:
- Right click on the “DB” folder and then select Add > New Item > ADO.NET Entity Data Model.
- Name the file as “MemoryGameDB” and then click Add.
- In the next wizard, select EF Designer from Database.
- Click the “New Connection…” button.
- Supply the Database Server Name to where you created the database in the previous section.
- Select or enter the database name. In this case, the database name for this example is “MemoryGame”.
- Click the Test Connection button to see if it’s successful just like in the figure below,
- Click OK to generate the connection string that will be used for our application.
- In the next wizard, Click “Next”
- Select Entity Framework 6.x and then click “Next”
- Select the “Challenger” and “Rank” tables and then click “Finish”.
The .EDMX file should now be added under the “DB” folder just like in the figure below,
Implementing Data Access for CRUD Operations
The next step is to create a central class for handling Create, Read Update and Delete (CRUD) operations. Now, create a new folder called “DataManager” under the “Models” folder. Create a new class called “GameManager” and then copy the following code below:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using MemoryGame.API.Models.DB;
-
- namespace MemoryGame.API.Models.DataManager
- {
- #region DTO
- public class ChallengerViewModel
- {
- public int ChallengerID { get; set; }
- public string FirstName { get; set; }
- public string LastName { get; set; }
- public byte Best { get; set; }
- public DateTime DateAchieved { get; set; }
- }
- #endregion
-
- #region HTTP Response Object
- public class HTTPApiResponse
- {
- public enum StatusResponse
- {
- Success = 1,
- Fail = 2
- }
-
- public StatusResponse Status { get; set; }
- public string StatusDescription { get; set; }
- }
- #endregion
-
- #region Data Access
- public class GameManager
- {
- public IEnumerable<ChallengerViewModel> GetAll { get { return GetAllChallengerRank(); } }
-
- public List<ChallengerViewModel> GetAllChallengerRank()
- {
-
- using (MemoryGameEntities db = new MemoryGameEntities())
- {
- var result = (from c in db.Challengers
- join r in db.Ranks on c.ChallengerID equals r.ChallengerID
- select new ChallengerViewModel
- {
- ChallengerID = c.ChallengerID,
- FirstName = c.FirstName,
- LastName = c.LastName,
- Best = r.Best,
- DateAchieved = r.DateAchieved
- }).OrderByDescending(o => o.Best).ThenBy(o => o.DateAchieved);
-
- return result.ToList();
- }
- }
-
-
- public HTTPApiResponse UpdateCurrentBest(DB.Rank user)
- {
- using (MemoryGameEntities db = new MemoryGameEntities())
- {
- var data = db.Ranks.Where(o => o.ChallengerID == user.ChallengerID);
- if (data.Any())
- {
- Rank rank = data.FirstOrDefault();
- rank.Best = user.Best;
- rank.DateAchieved = user.DateAchieved;
- db.SaveChanges();
- }
- else
- {
- db.Ranks.Add(user);
- db.SaveChanges();
- }
- }
-
- return new HTTPApiResponse
- {
- Status = HTTPApiResponse.StatusResponse.Success,
- StatusDescription = "Operation successful."
- };
- }
-
- public int GetChallengerID(string email)
- {
- using (MemoryGameEntities db = new MemoryGameEntities())
- {
- var data = db.Challengers.Where(o => o.Email.ToLower().Equals(email.ToLower()));
- if (data.Any())
- {
- return data.FirstOrDefault().ChallengerID;
- }
-
- return 0;
- }
- }
-
- public HTTPApiResponse AddChallenger(DB.Challenger c)
- {
- HTTPApiResponse response = null;
- using (MemoryGameEntities db = new MemoryGameEntities())
- {
- var data = db.Challengers.Where(o => o.Email.ToLower().Equals(c.Email.ToLower()));
- if (data.Any())
- {
- response = new HTTPApiResponse
- {
- Status = HTTPApiResponse.StatusResponse.Fail,
- StatusDescription = "User with associated email already exist."
- };
- }
- else
- {
- db.Challengers.Add(c);
- db.SaveChanges();
-
- response = new HTTPApiResponse
- {
- Status = HTTPApiResponse.StatusResponse.Success,
- StatusDescription = "Operation successful."
- };
- }
-
- return response;
- }
- }
-
- public ChallengerViewModel GetChallengerByEmail(string email)
- {
- using (MemoryGameEntities db = new MemoryGameEntities())
- {
- var result = (from c in db.Challengers
- join r in db.Ranks on c.ChallengerID equals r.ChallengerID
- where c.Email.ToLower().Equals(email.ToLower())
- select new ChallengerViewModel
- {
- ChallengerID = c.ChallengerID,
- FirstName = c.FirstName,
- LastName = c.LastName,
- Best = r.Best,
- DateAchieved = r.DateAchieved
- });
- if (result.Any())
- return result.SingleOrDefault();
- }
- return new ChallengerViewModel();
- }
-
- public HTTPApiResponse DeleteChallenger(int id)
- {
- HTTPApiResponse response = null;
- using (MemoryGameEntities db = new MemoryGameEntities())
- {
- var data = db.Challengers.Where(o => o.ChallengerID == id);
- if (data.Any())
- {
- try
- {
- var rankData = db.Ranks.Where(o => o.ChallengerID == id);
- if (rankData.Any())
- {
- db.Ranks.Remove(rankData.FirstOrDefault());
- db.SaveChanges();
- }
-
- db.Challengers.Remove(data.FirstOrDefault());
- db.SaveChanges();
-
- response = new HTTPApiResponse
- {
- Status = HTTPApiResponse.StatusResponse.Success,
- StatusDescription = "Operation successful."
- };
- }
- catch (System.Data.Entity.Validation.DbUnexpectedValidationException)
- {
-
- response = new HTTPApiResponse
- {
- Status = HTTPApiResponse.StatusResponse.Fail,
- StatusDescription = "An unexpected error occured."
- };
- }
- }
- else
- {
- response = new HTTPApiResponse
- {
- Status = HTTPApiResponse.StatusResponse.Fail,
- StatusDescription = "Associated ID not found."
- };
- }
-
- return response;
- }
- }
- }
- #endregion
- }
Let’s take a look of what we just did there.
The code above is composed of three (3) main regions: The Data Transfer Object (DTO), the HTTP response object and the GameMananger class.
The DTO is nothing but just a plain class that houses some properties that will be used in the View or any client that consumes the API.
The HTTPApiResponse object is class that holds 2 main basic properties: Status and StatusDescription. This object will be used in the GameManager class methods as a response or return object.
The GameManager class is the central class where we handle the actual CRUD operations. This is where we use Entity Framework to communicate with the database by working with conceptual data entity instead of real SQL query. Entity Framework enables us to work with a database using .NET objects and eliminates the need for most of the data-access code that developers usually need to write.
The GameManager class is composed of the following methods
- GetAll() – A short method that calls the GetAllChallengerRank() method.
- GetAllChallengerRank() - Gets all the challenger names and it’s rank. It uses LINQ to query the model and sort the data.
- GetChallengerByEmail(string email) – Gets the challenger information and rank by email.
- GetChallengerID(string email) – Gets the challenger id by passing an email address as parameter.
- AddChallenger(DB.Challenger c) – Adds a new challenger to the database.
- UpdateCurrentBest(DB.Rank user) – Updates the rank of a challenger to then newly achieved high score.
- DeleteChallenger(int id) – Deletes a challenger from the database.
The Web API EndPoints
Now that we have our data access ready, we can now start creating the API endpoints to serve data.
Create a new folder called “API” within the root of the application. Create a new Web API 2 Controller – Empty class and name it as “GameController” and then copy the following code below
- using MemoryGame.API.Models.DataManager;
- using MemoryGame.API.Models.DB;
- using System.Collections.Generic;
- using System.Web.Http;
-
- namespace MemoryGame.API.API
- {
- public class GameController : ApiController
- {
- GameManager _gm;
- public GameController()
- {
- _gm = new GameManager();
- }
-
- public IEnumerable<ChallengerViewModel> Get()
- {
- return _gm.GetAll;
- }
-
- [HttpPost]
- public HTTPApiResponse AddPlayer(Challenger user)
- {
- return _gm.AddChallenger(user);
- }
-
- [HttpPost]
- public void AddScore(Rank user)
- {
- _gm.UpdateCurrentBest(user);
- }
-
- [HttpPost]
- public HTTPApiResponse DeletePlayer(int id)
- {
- return _gm.DeleteChallenger(id);
- }
-
- public int GetPlayerID(string email)
- {
- return _gm.GetChallengerID(email);
- }
-
- public ChallengerViewModel GetPlayerProfile(string email)
- {
- return _gm.GetChallengerByEmail(email);
- }
- }
- }
Just like in the GameManager class, the GameController API is composed of the following methods:
Method | EndPoint | Description |
Get() | | Get all the challenger and rank data |
AddPlayer(Challenger user) | | Adds a new challenger |
AddScore(Rank user) | | Adds or updates a challenger score |
DeletePlayer(int id) | | Removes a player |
GetPlayerID(string email) | | Get the challenger id based on email |
GetPlayerProfile(string email) | | Get challenger information based on email |
Enabling Cors
Now that we have our API ready, the final step that we are going to do on this project is to enable Cross-Orgin Resource Sharing (a.k.a CORS). We need this because this API will be consumed in other application that probably has a difference domain.
To enable CORS in ASP.NET Web API, do,
- Install AspNet.WebApi.Cors via nugget
- Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:
config.EnableCors();
- Finally add the [EnableCors] attribute to the GameController class,
[EnableCors(origins: "http://localhost:60273", headers: "*", methods: "*")]
public class GameController : ApiController
Note that you’ll have to replace the value of origins based on the URI of the consuming client. Otherwise you can use the “*” wild-card to allow any domain to access your API.
Building the Mobile Application with Xamarin Forms
MemoryGame.App(Portable) Project
Now that we have the API ready, we can now start implementing the Memory Game app and start consuming the Web API that we’ve just created earlier. Switch back to MemoryGame.App(Portable) project and then create the following folders:
The GameAPI Class
Since we’ve done creating out API endpoints earlier, let’s start by creating the class for consuming the API. Create a new class called “GameAPI.cs” under the REST folder and then copy the following code below
- using System;
- using System.Text;
- using System.Threading.Tasks;
- using Newtonsoft.Json;
- using MemoryGame.App.Classes;
- using System.Net.Http;
-
- namespace MemoryGame.App.REST
- {
- public class GameAPI
- {
- private const string APIUri = "<YOUR API URI>";
- HttpClient client;
- public GameAPI()
- {
- client = new HttpClient();
- client.DefaultRequestHeaders.Host = "yourdomain.com"; >";
- client.MaxResponseContentBufferSize = 256000;
- }
-
- public async Task<bool> SavePlayerProfile(PlayerProfile data, bool isNew = false)
- {
- var uri = new Uri($"{APIUri}/AddPlayer");
-
- var json = JsonConvert.SerializeObject(data);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
-
- HttpResponseMessage response = null;
- if (isNew)
- response = await ProcessPostAsync(uri, content);
-
-
- if (response.IsSuccessStatusCode)
- {
- Settings.IsProfileSync = true;
- return true;
- }
-
- return false;
- }
-
- public async Task<bool> SavePlayerScore(PlayerScore data)
- {
- var uri = new Uri($"{APIUri}/AddScore");
-
- var json = JsonConvert.SerializeObject(data);
- var content = new StringContent(json, Encoding.UTF8, "application/json");
- var response = await ProcessPostAsync(uri, content);
-
- if (response.IsSuccessStatusCode)
- return true;
-
- return false;
- }
-
- public async Task<int> GetPlayerID(string email)
- {
- var uri = new Uri($"{APIUri}/GetPlayerID?email={email}");
- int id = 0;
-
- var response = await ProcessGetAsync(uri);
- if (response.IsSuccessStatusCode)
- {
- var content = await response.Content.ReadAsStringAsync();
- id = JsonConvert.DeserializeObject<int>(content);
- }
-
- return id;
- }
-
- public async Task<PlayerData> GetPlayerData(string email)
- {
- var uri = new Uri($"{APIUri}/GetPlayerProfile?email={email}");
- PlayerData player = null;
-
- var response = await ProcessGetAsync(uri);
- if (response.IsSuccessStatusCode)
- {
- player = new PlayerData();
- var content = await response.Content.ReadAsStringAsync();
- player = JsonConvert.DeserializeObject<PlayerData>(content);
- }
-
- return player;
- }
-
- private async Task<HttpResponseMessage> ProcessPostAsync(Uri uri, StringContent content)
- {
- return await client.PostAsync(uri, content); ;
- }
-
- private async Task<HttpResponseMessage> ProcessGetAsync(Uri uri)
- {
- return await client.GetAsync(uri);
- }
- }
- }
The code above is pretty much self-explanatory as you could probably guess by its method name. The class just contains some methods that call the API endpoints that we have created in the previous section.
Implementing the Service Interfaces
Next, we will create a few services that our app will need. Add the following class/interface files under the Services folder:
Now copy the corresponding code below for each file.
The IHaptic Interface
- namespace MemoryGame.App.Services
- {
- public interface IHaptic
- {
- void ActivateHaptic();
- }
- }
The ILocalDataStore Interface
- namespace MemoryGame.App.Services
- {
- public interface ILocalDataStore
- {
- void SaveSettings(string fileName, string text);
- string LoadSettings(string fileName);
- }
- }
The ISound Interface
- namespace MemoryGame.App.Services
- {
- public interface ISound
- {
- bool PlayMp3File(string fileName);
- bool PlayWavFile(string fileName);
- }
- }
The reason why we are creating the services above is because iOS and Android have different code implementation on setting the device vibration and sound. That’s why we are defining interfaces so both platform can just inherit from it and implement code specific logic.
Let’s move on by creating the following objects within the Classes folder
Before we start, let’s do a bit of clean-up first. Remember we’ve installed the Xam.Plugins.Settings in the previous section right? You will notice that after we installed that library, the Settings.cs file was automatically generated within the Helpers folder. Leaving the Settings.cs file there is fine but we wanted to have clean separation of objects so we will move the Settings.cs file within the Classes folder. Once you’ve done moving the file that, it’s safe to delete the Helper folder. To summarize the project structure should now look similar to this,
The Settings Class
Now open the Settings.cs file and then replace the default generated code with the following
- using Plugin.Settings;
- using Plugin.Settings.Abstractions;
- using System;
-
- namespace MemoryGame.App.Classes
- {
- public static class Settings
- {
- private static ISettings AppSettings => CrossSettings.Current;
-
- public static string PlayerFirstName
- {
- get => AppSettings.GetValueOrDefault(nameof(PlayerFirstName), string.Empty);
- set => AppSettings.AddOrUpdateValue(nameof(PlayerFirstName), value);
- }
-
- public static string PlayerLastName
- {
- get => AppSettings.GetValueOrDefault(nameof(PlayerLastName), string.Empty);
- set => AppSettings.AddOrUpdateValue(nameof(PlayerLastName), value);
- }
-
- public static string PlayerEmail
- {
- get => AppSettings.GetValueOrDefault(nameof(PlayerEmail), string.Empty);
- set => AppSettings.AddOrUpdateValue(nameof(PlayerEmail), value);
- }
-
- public static int TopScore
- {
- get => AppSettings.GetValueOrDefault(nameof(TopScore), 1);
- set => AppSettings.AddOrUpdateValue(nameof(TopScore), value);
- }
-
- public static DateTime DateAchieved
- {
- get => AppSettings.GetValueOrDefault(nameof(DateAchieved), DateTime.UtcNow);
- set => AppSettings.AddOrUpdateValue(nameof(DateAchieved), value);
- }
-
- public static bool IsProfileSync
- {
- get => AppSettings.GetValueOrDefault(nameof(IsProfileSync), false);
- set => AppSettings.AddOrUpdateValue(nameof(IsProfileSync), value);
- }
-
- public static int PlayerID
- {
- get => AppSettings.GetValueOrDefault(nameof(PlayerID), 0);
- set => AppSettings.AddOrUpdateValue(nameof(PlayerID), value);
- }
-
- }
- }
If you notice from the code above, we have defined some basic properties that our app needs. We are defining them in Settings.cs file so that we can access properties from shared code across all our applications, thus having a central location for shared properties.
The Helper Class
Let’s proceed by creating a new class called “Helper.cs” and then copy the following code below
- using Plugin.Connectivity;
-
- namespace MemoryGame.App.Helper
- {
- public static class StringExtensions
- {
- public static int ToInteger(this string numberString)
- {
- int result = 0;
- if (int.TryParse(numberString, out result))
- return result;
- return 0;
- }
- }
-
-
- public static class Utils
- {
- public static bool IsConnectedToInternet()
- {
- return CrossConnectivity.Current.IsConnected;
- }
- }
- }
The Helper.cs file is composed of two classes: StringExtension and Utils. The StringExtension class contains a ToIntenger() extension method to convert a valid numerical string value into an integer type. The Utils class on the other hand contains an IsConnectedToInternet() method to verify internet connectivity. We will be using these methods later in our application.
The PlayerManager Class
Now let’s create the class for managing the player data and score. Create a new class called “PlayerManager.cs” and then copy the following code below
The code above is composed of a few methods for handling CRUD and syncing data. Notice that each method calls the method defined in the GameAPI class. We did it like this so we can separate the actual code logic for the ease of maintenance and separation of concerns.
The Required XAML Pages
Now that we are all set, it’s time for us to create the following pages for the app:
Let’s start building the Register page. Right click on the Pages folder and then select Add > New Item > Cross-Platform > Forms Xaml Page. Name the page as “Register” and then copy the following code below:
The Register Page
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="MemoryGame.App.Pages.Register">
-
- <StackLayout VerticalOptions="CenterAndExpand">
- <Label Text="Working Memory Game"
- FontSize="30"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand" />
-
- <Label x:Name="lblWelcome" Text="Register to start the fun, or Log-on to continue the challenge!"
- FontSize="20"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand" />
- <StackLayout x:Name="layoutChoose" Orientation="Horizontal" Spacing="5" VerticalOptions="CenterAndExpand" HorizontalOptions="Center">
- <Button x:Name="btnNew"
- Text="Register"
- FontSize="20"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand"
- Clicked="OnbtnNewClicked"/>
- <Button x:Name="btnReturn"
- Text="Log-on"
- FontSize="20"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand"
- Clicked="OnbtnReturnClicked"/>
- </StackLayout>
-
- <StackLayout x:Name="layoutRegister" VerticalOptions="CenterAndExpand" IsVisible="False">
- <Label Text="First Name" />
- <Entry x:Name="entryFirstName" />
- <Label Text="Last Name" />
- <Entry x:Name="entryLastName" />
- <Label Text="Email" />
- <Entry x:Name="entryEmail" />
-
- <StackLayout Orientation="Horizontal" Spacing="3" HorizontalOptions="Center">
- <Button x:Name="btnRegister"
- Text="Let's Do This!"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand"
- Clicked="OnbtnRegisterClicked"/>
- <Button x:Name="btnCancelRegister"
- Text="Cancel"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand"
- Clicked="OnbtnCancelRegisterClicked"/>
- </StackLayout>
- </StackLayout>
-
- <StackLayout x:Name="layoutLogin" VerticalOptions="CenterAndExpand" IsVisible="False">
- <Label Text="Email" />
- <Entry x:Name="entryExistingEmail" />
-
- <StackLayout Orientation="Horizontal" Spacing="3" HorizontalOptions="Center">
- <Button x:Name="btnLogin"
- Text="Let me in!"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand"
- Clicked="OnbtnLoginClicked"/>
- <Button x:Name="btnCancelLogin"
- Text="Cancel"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand"
- Clicked="OnbtnCancelLoginClicked"/>
- </StackLayout>
- </StackLayout>
- </StackLayout>
- </ContentPage>
Here’s the corresponding code behind for the Register page
- using System;
- using Xamarin.Forms;
- using MemoryGame.App.Classes;
- using System.Threading.Tasks;
- using MemoryGame.App.Helper;
-
- namespace MemoryGame.App.Pages
- {
- public partial class Register : ContentPage
- {
- public Register()
- {
- InitializeComponent();
- }
-
- enum EntryOption
- {
- Register = 0,
- Returning = 1,
- Cancel = 2
- }
-
- protected override void OnAppearing()
- {
- base.OnAppearing();
- NavigationPage.SetHasBackButton(this, false);
- }
- async void CheckExistingProfileAndSave(string email)
- {
- if (Utils.IsConnectedToInternet())
- {
- try
- {
- PlayerData player = await PlayerManager.CheckExistingPlayer(email);
- if (string.IsNullOrEmpty(player.FirstName) && string.IsNullOrEmpty(player.LastName))
- {
- await App.Current.MainPage.DisplayAlert("Error", "Email does not exist.", "OK");
- }
- else
- {
- Settings.PlayerFirstName = player.FirstName.Trim();
- Settings.PlayerLastName = player.LastName.Trim();
- Settings.PlayerEmail = email.Trim();
- Settings.TopScore = player.Best;
- Settings.DateAchieved = player.DateAchieved;
-
- await App._navPage.PopAsync();
- }
- }
- catch
- {
- await App.Current.MainPage.DisplayAlert("Oops", "An error occured while connecting to the server. Please check your connection.", "OK");
- }
- }
- else
- {
- await App.Current.MainPage.DisplayAlert("Error", "No internet connection.", "OK");
- }
-
- btnLogin.IsEnabled = true;
- }
-
- void Save()
- {
- Settings.PlayerFirstName = entryFirstName.Text.Trim();
- Settings.PlayerLastName = entryLastName.Text.Trim();
- Settings.PlayerEmail = entryEmail.Text.Trim();
- App._navPage.PopAsync();
- }
-
- void ToggleEntryView(EntryOption option)
- {
- switch (option)
- {
- case EntryOption.Register:
- {
- lblWelcome.IsVisible = false;
- layoutChoose.IsVisible = false;
- layoutLogin.IsVisible = false;
- layoutRegister.IsVisible = true;
- break;
- }
- case EntryOption.Returning:
- {
- lblWelcome.IsVisible = false;
- layoutChoose.IsVisible = false;
- layoutRegister.IsVisible = false;
- layoutLogin.IsVisible = true;
- break;
- }
- case EntryOption.Cancel:
- {
- lblWelcome.IsVisible = true;
- layoutChoose.IsVisible = true;
- layoutRegister.IsVisible = false;
- layoutLogin.IsVisible = false;
- break;
- }
- }
- }
- void OnbtnNewClicked(object sender, EventArgs args)
- {
- ToggleEntryView(EntryOption.Register);
- }
- void OnbtnReturnClicked(object sender, EventArgs args)
- {
- ToggleEntryView(EntryOption.Returning);
- }
- void OnbtnCancelLoginClicked(object sender, EventArgs args)
- {
- ToggleEntryView(EntryOption.Cancel);
- }
- void OnbtnCancelRegisterClicked(object sender, EventArgs args)
- {
- ToggleEntryView(EntryOption.Cancel);
- }
-
- void OnbtnRegisterClicked(object sender, EventArgs args)
- {
- if (string.IsNullOrEmpty(entryFirstName.Text) || string.IsNullOrEmpty(entryLastName.Text) || string.IsNullOrEmpty(entryEmail.Text))
- App.Current.MainPage.DisplayAlert("Error", "Please supply the required fields.", "Got it");
- else
- Save();
- }
-
- void OnbtnLoginClicked(object sender, EventArgs args)
- {
- if (string.IsNullOrEmpty(entryExistingEmail.Text))
- App.Current.MainPage.DisplayAlert("Error", "Please supply your email.", "Got it");
- else
- {
- btnLogin.IsEnabled = false;
- CheckExistingProfileAndSave(entryExistingEmail.Text);
- }
- }
- }
- }
Let’s continue by building the Home page. Right click on the Pages folder and then select Add > New Item > Cross-Platform > Forms Xaml Page. Name the page as “Home” and then copy the following code below:
The Home Page
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="MemoryGame.App.Pages.Home">
-
- <StackLayout Padding="10">
- <StackLayout>
- <StackLayout Orientation="Horizontal">
- <Label x:Name="lblBest" FontSize="20" HorizontalOptions="StartAndExpand" />
- <Button x:Name="btnSync" Text="Sync" Clicked="OnbtnSyncClicked" HorizontalOptions="EndAndExpand" VerticalOptions="CenterAndExpand" />
- </StackLayout>
-
- <Label x:Name="lblTime"
- FontSize="30"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand" />
- </StackLayout>
-
- <Label x:Name="lblLevel"
- FontSize="30"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand" />
- <StackLayout Orientation="Horizontal" Spacing="3" HorizontalOptions="Center" BackgroundColor="White">
- <Image x:Name="imgLightOff" Source="lightoff.png" WidthRequest="100" HeightRequest="40" />
- <Image x:Name="imgLightOff2" Source="lightoff.png" IsVisible="False" WidthRequest="100" HeightRequest="40" />
- <Image x:Name="imgLightOn" Source="lighton.png" IsVisible="False" WidthRequest="100" HeightRequest="40" />
- <Image x:Name="imgSpeaker" Source="speakeron.png" WidthRequest="100" HeightRequest="40" />
- <Image x:Name="imgHaptic" Source="vibration.png" WidthRequest="100" HeightRequest="40" />
- </StackLayout>
- <Label Text="The light will blink on, the speaker will beep and the device will vibrate at different times. Try to count how many times each one happens."
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand" />
-
- <Button x:Name="btnStart"
- Text="Start"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand"
- Clicked="OnButtonClicked"/>
- </StackLayout>
-
- </ContentPage>
Here’s the corresponding code behind that you will see in Home.xaml.cs
- using System;
- using System.Threading.Tasks;
- using MemoryGame.App.Classes;
- using Xamarin.Forms;
- using MemoryGame.App.Services;
- using MemoryGame.App.Helper;
-
- namespace MemoryGame.App.Pages
- {
- public partial class Home : ContentPage
- {
- private static int _blinkCount = 0;
- private static int _soundCount = 0;
- private static int _hapticCount = 0;
- private static int _level = 1;
-
- public int _cycleStartInMS = 0;
- public int _cycleMaxInMS = 7000;
- private const int CycleIntervalInMS = 2000;
- private const int PlayTimeCount = 3;
-
- enum PlayType
- {
- Blink = 0,
- Sound = 1,
- Haptic = 2
- }
-
- public static int CurrentGameBlinkCount
- {
- get { return _blinkCount; }
- }
-
- public static int CurrentGameSoundCount
- {
- get { return _soundCount; }
- }
-
- public static int CurrentGameHapticCount
- {
- get { return _hapticCount; }
- }
-
- public static int CurrentGameLevel
- {
- get { return _level; }
- }
-
- public Home()
- {
- InitializeComponent();
- }
-
- protected async override void OnAppearing()
- {
- base.OnAppearing();
-
- if (string.IsNullOrEmpty(Settings.PlayerFirstName))
- await App._navPage.PushAsync(App._registerPage);
- else
- {
-
- PlayerManager.UpdateBest(_level);
-
- if (Result._answered)
- LevelUp();
- else
- ResetLevel();
-
- lblBest.Text = $"Best: Level {PlayerManager.GetBestScore(_level)}";
- lblLevel.Text = $"Level {_level}";
- }
- }
-
- static void IncrementPlayCount(PlayType play)
- {
- switch (play)
- {
- case PlayType.Blink:
- {
- _blinkCount++;
- break;
- }
- case PlayType.Sound:
- {
- _soundCount++;
- break;
- }
- case PlayType.Haptic:
- {
- _hapticCount++;
- break;
- }
- }
- }
-
- public static void IncrementGameLevel()
- {
- _level++;
- }
-
- void ResetLevel()
- {
- _level = 1;
- _cycleStartInMS = CycleIntervalInMS;
- lblTime.Text = string.Empty;
- }
-
- async void StartRandomPlay()
- {
- await Task.Run(() =>
- {
-
- Random rnd = new Random(Guid.NewGuid().GetHashCode());
- int choice = rnd.Next(0, PlayTimeCount);
-
- switch (choice)
- {
- case (int)PlayType.Blink:
- {
- Device.BeginInvokeOnMainThread(async () =>
- {
-
- await imgLightOff.FadeTo(0, 200);
- imgLightOff2.IsVisible = false;
- imgLightOff.IsVisible = true;
- imgLightOff.Source = ImageSource.FromFile("lighton.png");
- await imgLightOff.FadeTo(1, 200);
-
- });
- IncrementPlayCount(PlayType.Blink);
- break;
- }
- case (int)PlayType.Sound:
- {
- DependencyService.Get<ISound>().PlayMp3File("beep.mp3");
- IncrementPlayCount(PlayType.Sound);
- break;
- }
- case (int)PlayType.Haptic:
- {
- DependencyService.Get<IHaptic>().ActivateHaptic();
- IncrementPlayCount(PlayType.Haptic);
- break;
- }
- }
- });
- }
-
- void ResetGameCount()
- {
- _blinkCount = 0;
- _soundCount = 0;
- _hapticCount = 0;
- }
-
- void LevelUp()
- {
- _cycleStartInMS = _cycleStartInMS - 200;
- }
-
- void Play()
- {
- int timeLapsed = 0;
- int duration = 0;
- Device.StartTimer(TimeSpan.FromSeconds(1), () =>
- {
- duration++;
- lblTime.Text = $"Timer: { TimeSpan.FromSeconds(duration).ToString("ss")}";
-
- if (duration < 7)
- return true;
- else
- return false;
- });
-
- Device.StartTimer(TimeSpan.FromMilliseconds(_cycleStartInMS), () => {
- timeLapsed = timeLapsed + _cycleStartInMS;
-
- Device.BeginInvokeOnMainThread(async () =>
- {
- imgLightOff2.IsVisible = true;
- imgLightOff.IsVisible = false;
- await Task.Delay(200);
-
- });
-
- if (timeLapsed <= _cycleMaxInMS)
- {
- StartRandomPlay();
- return true;
- }
-
- btnStart.Text = "Start";
- btnStart.IsEnabled = true;
-
- App._navPage.PushAsync(App._resultPage);
- return false;
- });
- }
-
- void OnButtonClicked(object sender, EventArgs args)
- {
- btnStart.Text = "Game Started...";
- btnStart.IsEnabled = false;
-
- ResetGameCount();
- Play();
- }
-
- async void OnbtnSyncClicked(object sender, EventArgs args)
- {
-
- if (Utils.IsConnectedToInternet())
- {
- btnSync.Text = "Syncing...";
- btnSync.IsEnabled = false;
- btnStart.IsEnabled = false;
-
- var response = await PlayerManager.Sync();
- if (!response)
- await App.Current.MainPage.DisplayAlert("Oops", "An error occured while connecting to the server. Please check your connection.", "OK");
- else
- await App.Current.MainPage.DisplayAlert("Sync", "Data synced!", "OK");
-
- btnSync.Text = "Sync";
- btnSync.IsEnabled = true;
- btnStart.IsEnabled = true;
- }
- else
- {
- await App.Current.MainPage.DisplayAlert("Error", "No internet connection.", "OK");
- }
- }
- }
- }
The StartRandomPlay() method above is the core method of the class above. The method is responsible for playing different criteria on random, whether invoke a sound, vibration or just blink an image. Notice that we’ve used the DependencyService class to inject the Interface that we’ve defined in the previous steps. These allow us to call platform specific methods for playing a sound or vibration.
Now right click on the Pages folder and then select Add > New Item > Cross-Platform > Forms Xaml Page. Name the page as “Result” and then copy the following code below:
The Result Page
- <?xml version="1.0" encoding="utf-8" ?>
- <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
- xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
- x:Class="MemoryGame.App.Pages.Result">
-
- <StackLayout>
- <Label Text="How many times did the light blink, the speaker beep and the device vibrate?"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand" />
-
- <StackLayout Orientation="Horizontal" Spacing="3" HorizontalOptions="Center" BackgroundColor="White">
- <Image x:Name="imgLight" Source="lightoff.png" WidthRequest="100" HeightRequest="40" />
- <Image x:Name="imgSpeaker" Source="speakeron.png" WidthRequest="100" HeightRequest="40" />
- <Image x:Name="imgHaptic" Source="vibration.png" WidthRequest="100" HeightRequest="40" />
- </StackLayout>
-
- <StackLayout Orientation="Horizontal" HorizontalOptions="Center" Spacing="5">
- <Picker x:Name="pickerLight" HorizontalOptions="FillAndExpand" WidthRequest="100">
- <Picker.Items>
- <x:String>0</x:String>
- <x:String>1</x:String>
- <x:String>2</x:String>
- <x:String>3</x:String>
- <x:String>4</x:String>
- <x:String>5</x:String>
- <x:String>6</x:String>
- <x:String>7</x:String>
- <x:String>8</x:String>
- <x:String>9</x:String>
- <x:String>10</x:String>
- </Picker.Items>
- </Picker>
- <Picker x:Name="pickerSpeaker" HorizontalOptions="FillAndExpand" WidthRequest="100">
- <Picker.Items>
- <x:String>0</x:String>
- <x:String>1</x:String>
- <x:String>2</x:String>
- <x:String>3</x:String>
- <x:String>4</x:String>
- <x:String>5</x:String>
- <x:String>6</x:String>
- <x:String>7</x:String>
- <x:String>8</x:String>
- <x:String>9</x:String>
- <x:String>10</x:String>
- </Picker.Items>
- </Picker>
- <Picker x:Name="pickerHaptic" HorizontalOptions="FillAndExpand" WidthRequest="100">
- <Picker.Items>
- <x:String>0</x:String>
- <x:String>1</x:String>
- <x:String>2</x:String>
- <x:String>3</x:String>
- <x:String>4</x:String>
- <x:String>5</x:String>
- <x:String>6</x:String>
- <x:String>7</x:String>
- <x:String>8</x:String>
- <x:String>9</x:String>
- <x:String>10</x:String>
- </Picker.Items>
- </Picker>
- </StackLayout>
- <Label x:Name="lblText" FontSize="20"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand" />
- <StackLayout Orientation="Horizontal" HorizontalOptions="Center" Spacing="40">
- <Label x:Name="lblBlinkCount"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand" />
- <Label x:Name="lblBeepCount"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand" />
- <Label x:Name="lblHapticCount"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand" />
- </StackLayout>
- <Button x:Name="btnSubmit"
- Text="Submit"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand"
- Clicked="OnButtonClicked"/>
- <Button x:Name="btnRetry"
- Text="Retry"
- IsVisible="False"
- HorizontalOptions="Center"
- VerticalOptions="CenterAndExpand"
- Clicked="OnRetryButtonClicked"/>
- </StackLayout>
-
- </ContentPage>
Here’s the corresponding code behind
- using System;
- using Xamarin.Forms;
- using MemoryGame.App.Classes;
-
- namespace MemoryGame.App.Pages
- {
- public partial class Result : ContentPage
- {
- public static bool _answered = false;
- public Result()
- {
- InitializeComponent();
- ClearResult();
-
- }
-
- protected override void OnAppearing()
- {
- base.OnAppearing();
- ClearResult();
- NavigationPage.SetHasBackButton(this, false);
- }
- void ClearResult()
- {
- lblText.Text = string.Empty;
- lblBlinkCount.Text = string.Empty;
- lblBeepCount.Text = string.Empty;
- lblHapticCount.Text = string.Empty;
- pickerLight.SelectedIndex = 0;
- pickerSpeaker.SelectedIndex = 0;
- pickerHaptic.SelectedIndex = 0;
- btnSubmit.IsVisible = true;
- btnRetry.IsVisible = false;
- _answered = false;
- }
-
- bool CheckAnswer(int actualAnswer, int selectedAnswer)
- {
- if (selectedAnswer == actualAnswer)
- return true;
- else
- return false;
- }
-
- void Retry()
- {
- btnSubmit.IsVisible = false;
- btnRetry.IsVisible = true;
- }
- async void OnButtonClicked(object sender, EventArgs args)
- {
- if (pickerLight.SelectedIndex >= 0 && pickerSpeaker.SelectedIndex >= 0 && pickerHaptic.SelectedIndex >= 0)
- {
- lblText.Text = "The actual answers are:";
- lblBlinkCount.Text = Home.CurrentGameBlinkCount.ToString();
- lblBeepCount.Text = Home.CurrentGameSoundCount.ToString();
- lblHapticCount.Text = Home.CurrentGameHapticCount.ToString();
-
- if (CheckAnswer(Home.CurrentGameBlinkCount, Convert.ToInt32(pickerLight.Items[pickerLight.SelectedIndex])))
- if (CheckAnswer(Home.CurrentGameSoundCount, Convert.ToInt32(pickerSpeaker.Items[pickerSpeaker.SelectedIndex])))
- if (CheckAnswer(Home.CurrentGameHapticCount, Convert.ToInt32(pickerHaptic.Items[pickerHaptic.SelectedIndex])))
- {
- _answered = true;
- Home.IncrementGameLevel();
-
- var isSynced = PlayerManager.CheckScoreAndSync(Home.CurrentGameLevel);
-
- var answer = await App.Current.MainPage.DisplayAlert("Congrats!", $"You've got it all right and made it to level {Home.CurrentGameLevel}. Continue?", "Yes", "No");
-
- if (answer)
- await App._navPage.PopAsync();
- else
- Retry();
- }
-
- if (!_answered)
- {
- var isSynced = PlayerManager.CheckScoreAndSync(Home.CurrentGameLevel);
-
- var answer = await App.Current.MainPage.DisplayAlert("Game Over!", $"Your current best is at level {Home.CurrentGameLevel}. Retry?", "Yes", "No");
- if (answer)
- await App._navPage.PopAsync();
- else
- Retry();
- }
- }
- }
-
- void OnRetryButtonClicked(object sender, EventArgs args)
- {
- App._navPage.PopAsync();
- }
- }
- }
The code above handles the logic for validating your answers against the actual count of each play type occurred. If all your answers are correct then it will get you the next level, otherwise it resets back.
Implementing Haptic and Sound Service iOS and Android Platform
Now it’s time for us to implement an actual implementation for each interface that we have defined in the previous steps. Let’s start with Android. Add a new folder called “Services” in the MemoryGame.App.Droid project and then copy the following code for each class:
The Haptic Service (Droid)
- using Android.Content;
- using Android.OS;
- using Xamarin.Forms;
- using MemoryGame.App.Droid.Services;
- using MemoryGame.App.Services;
-
- [assembly: Dependency(typeof(HapticService))]
- namespace MemoryGame.App.Droid.Services
- {
- public class HapticService : IHaptic
- {
- public HapticService() { }
- public void ActivateHaptic()
- {
- Vibrator vibrator = (Vibrator)global::Android.App.Application.Context.GetSystemService(Context.VibratorService);
- vibrator.Vibrate(100);
- }
- }
- }
The Sound Service (Droid)
- using Xamarin.Forms;
- using Android.Media;
- using MemoryGame.App.Droid.Services;
- using MemoryGame.App.Services;
-
- [assembly: Dependency(typeof(SoundService))]
-
- namespace MemoryGame.App.Droid.Services
- {
- public class SoundService : ISound
- {
- public SoundService() { }
-
- private MediaPlayer _mediaPlayer;
-
- public bool PlayMp3File(string fileName)
- {
- _mediaPlayer = new MediaPlayer();
- var fd = global::Android.App.Application.Context.Assets.OpenFd(fileName);
- _mediaPlayer.Prepared += (s, e) =>
- {
- _mediaPlayer.Start();
- };
- _mediaPlayer.SetDataSource(fd.FileDescriptor, fd.StartOffset, fd.Length);
- _mediaPlayer.Prepare();
- return true;
- }
-
- public bool PlayWavFile(string fileName)
- {
-
- return true;
- }
- }
- }
Note
For Android add the required images under the “drawable” folder and add the sound file under the “raw” folder.
Now, do the same for the MemoryGame.App.iOS project. Copy the following code below for each service,
The Haptic Service (iOS)
- using Xamarin.Forms;
- using AudioToolbox;
- using MemoryGame.App.iOS.Services;
- using MemoryGame.App.Services;
-
- [assembly: Dependency(typeof(HapticService))]
- namespace MemoryGame.App.iOS.Services
- {
- public class HapticService : IHaptic
- {
- public HapticService() { }
- public void ActivateHaptic()
- {
- SystemSound.Vibrate.PlaySystemSound();
- }
- }
- }
The Sound Service (iOS)
- using Xamarin.Forms;
- using MemoryGame.App.iOS.Services;
- using System.IO;
- using Foundation;
- using AVFoundation;
- using MemoryGame.App.Services;
-
- [assembly: Dependency(typeof(SoundService))]
-
- namespace MemoryGame.App.iOS.Services
- {
- public class SoundService : NSObject, ISound, IAVAudioPlayerDelegate
- {
- #region IDisposable implementation
-
- public void Dispose()
- {
-
- }
-
- #endregion
-
- public SoundService()
- {
- }
-
- public bool PlayWavFile(string fileName)
- {
- return true;
- }
-
- public bool PlayMp3File(string fileName)
- {
-
- var played = false;
-
- NSError error = null;
- AVAudioSession.SharedInstance().SetCategory(AVAudioSession.CategoryPlayback, out error);
-
- string sFilePath = NSBundle.MainBundle.PathForResource(Path.GetFileNameWithoutExtension(fileName), "mp3");
- var url = NSUrl.FromString(sFilePath);
- var _player = AVAudioPlayer.FromUrl(url);
- _player.Delegate = this;
- _player.Volume = 100f;
- played = _player.PrepareToPlay();
- _player.FinishedPlaying += (object sender, AVStatusEventArgs e) => {
- _player = null;
- };
- played = _player.Play();
-
- return played;
- }
- }
-
- }
Note
For IOS add the required images and sound file under the Resource folder.
Setting Permissions
For android, add the following configuration under AndroidManifest.xml
- <uses-permission android:name="android.permission.VIBRATE" />
- <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
- <uses-permission android:name="android.permission.INTERNET" />
The Output
Here’s an actual screenshot of the output when deploying and running the app in real device,
Building a Simple Real-time Leaderboard Web App with ASP.NET SignalR and MVC
Create a new ASP.NET Web Application project and name it as “MemoryGame.Web” just like in the figure below,
Click “Ok” and then select the “ Empty MVC” template in the next wizard and then hit “OK” again to generate the project for you.
Integrating ASP.NET SignalR
Install “Microsoft.Asp.Net.SignalR” in your project via NuGet. The version used for this project is “2.2”. Once installed, you should be able to see them added under the references folder,
Adding a Middleware for SignalR
Create a new class and name it as “Startup.cs”. Copy the following code below,
- using Microsoft.Owin;
- using Owin;
-
- [assembly: OwinStartup(typeof(MemoryGame.Web.Startup))]
- namespace MemoryGame.Web
- {
- public class Startup
- {
- public void Configuration(IAppBuilder app)
- {
- app.MapSignalR();
- }
- }
- }
The configuration above will add the SignalR service to the pipeline and enable us to use ASP.NET SignalR in our application.
Adding a Hub
Next is to add an ASP.NET SignalR Hub. Add a new class and then copy the following code below,
- using Microsoft.AspNet.SignalR;
-
- namespace MemoryGame.Web
- {
- public class LeaderboardHub : Hub
- {
- public static void Show()
- {
- IHubContext context = GlobalHost.ConnectionManager.GetHubContext<LeaderboardHub>();
- context.Clients.All.displayLeaderBoard();
- }
- }
- }
To provide you a quick overview, the Hub is the center piece of the SignalR. Similar to the Controller in ASP.NET MVC, a Hub is responsible for receiving input and generating the output to the client. The methods within the Hub can be invoked from the server or from the client.
Adding an MVC Controller
Now add a new “Empty MVC 5 Controller” class within the “Controllers” folder and then copy the following code below,
- using System.Web.Mvc;
-
- namespace MemoryGame.Web.Controllers
- {
- public class HomeController : Controller
- {
- public ActionResult Index()
- {
- return View();
- }
- }
- }
The code above is just an action method that throws an Index View.
Adding a View
Add a new Index view within the “Views/Home” folder and then copy the following code below,
- <div id="body">
- <section class="featured">
- <div class="content-wrapper">
- <hgroup class="title">
- <strong>Leader Board</strong>
- </hgroup>
- </div>
- </section>
- <section class="content-wrapper main-content clear-fix">
- <strong>
- <span>
- Top Challengers
- <img src="Images/goals_256.png" style="width:40px; height:60px;" />
- </span>
- </strong>
- <table id="tblRank" class="table table-striped table-condensed table-hover">
- </table>
- </section>
- </div>
-
- @section scripts{
- @Scripts.Render("~/Scripts/jquery.signalR-2.2.2.min.js")
- @Scripts.Render("~/signalr/hubs")
-
- <script type="text/javascript">
- $(function () {
- var rank = $.connection.leaderboardHub;
- rank.client.displayLeaderBoard = function () {
- LoadResult();
- };
-
- $.connection.hub.start();
- LoadResult();
- });
-
- function LoadResult() {
- var $tbl = $("#tblRank");
- $.ajax({
- url: 'http://localhost:61309/api/game/get',
- type: 'GET',
- datatype: 'json',
- success: function (data) {
- if (data.length > 0) {
- $tbl.empty();
- $tbl.append('<thead><tr><th>Rank</th><th></th><th></th><th>Best</th><th>Achieved</th></tr></thead>');
- var rows = [];
- for (var i = 0; i < data.length; i++) {
- rows.push('<tbody><tr><td>' + (i +1).toString() + '</td><td>' + data[i].FirstName + '</td><td>' + data[i].LastName + '</td><td>' + data[i].Best + '</td><td>' + data[i].DateAchieved + '</td></tr></tbody>');
- }
- $tbl.append(rows.join(''));
- }
- }
- });
- }
- </script>
- }
Take note of the sequence for adding the client Scripts references,
- jQuery
- signalR
- /signalr/hub
jQuery should be added first, then the SignalR Core JavaScript and finally the SignalR Hubs script.
The LoadResult() function uses a jQuery AJAX to invoke a Web API call through AJAX GET request. If there’s any data from the response, it will generate an HTML by looping through the rows. The LoadResult () function will be invoked when the page is loaded or when the displayLeaderboard() method from the Hub is invoked. By subscribing to the Hub, ASP.NET SignalR will do the entire complex plumbing for us to do real-time updates without any extra work needed in our side.
Output
Here’s the final output when you deploy and run the project.
The data above will automatically update without refreshing the page once a user from the mobile app syncs their best score.
GitHub Repo
You can view and fork the source code here: https://github.com/proudmonkey/Xamarin.MemoryGameApp
Summary
In this article we've learned the following,
- Setting up a SQL Server database from scratch
- Building a simple Working Memory game application using Xamarin.Forms that targets both iOS and Android platform.
- Creating an ASP.NET Web API project
- Integrating Entity Framework as our data access mechanism
- Creating an ASP.NET MVC 5 project
- Integrating ASP.NET SignalR within ASP.NET MVC
References
- https://en.wikipedia.org/wiki/Working_memory
- https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
- https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/hubs-api-guide-server