Understanding Game Design: Introductory Help

A lot of the game on the mobile market share characteristics with other games of the same type, and can thus be grouped together in a similar category.  Regardless of the type of game we are talking about building, one of the more useful features of the game is to provide some instruction at the beginning of the game.  There is usually an interactive explanation of the game’s mechanics that forces you to perform certain actions to make sure you understand how the game is played.

For instance, for a running game, the game guides the user to use the various mechanisms:  swipe up to jump, swipe down to slide, swipe left and right to move left and right, and whatever other controls may be involved.  The introductory help may also cover what the various menus do, and typically show you how you can upgrade your character.

For a civilization building game, the game illustrates how towns and cities can be built to improve your commerce capabilities, how to speed up the development by spending a secondary currency (like gems), how to upgrade characters in the game, how the menu system works, and detail any other game characteristic.

It’s good to have introductory help; even though the game may be self explanatory and a lot of the games have similar mechanics, it’s good to explain the mechanics so the user can unleash the full potential of the game.

Xamarin Forms Threading Fun

I’ve been trying out the async/await model in Xamarin Forms, and have had trouble getting it to work. It turns out there is great challenge in ensuring everything runs on the same thread. In this I learned a few lessons:

1) Make sure that once you start an operation asynchronously, make sure everything is also called in an async fashion. For instance, I had the following call hierarchy:

async LoginButton_Click
async HandleSignInCompleted(..);
async loginService.Login(..);
async HttpClient.PostAsync(..);

It’s important to make sure everything uses the async model, rather than calling the method directly. For instance, an async method can be called directly, or the results invoked directly with the .Result property on the Task. But don’t do it! Be consistent with the async/await setup.

2) Use ConfigureAwait(false)

The Task object has a ConfigureAwait method. I had success using it by applying it EVERYWHERE, on every async operation. In my above stack trace, this looked like:

async void LoginButton_Click //Since a button callback, can't define here
    async HandleSignInCompleted(..).ConfigureAwait(false);
       async loginService.Login(..).ConfigureAwait(false);
          async HttpClient.PostAsync(..).ConfigureAwait(false);

3) UI Synchronization

In my call stack, in the HandleSignInCompleted, there was a call to:

var page = new DashboardPage();
await this.Navigation.PushAsync(newPage);

This failed with an Android error (tested on an Android device) stating that the view was modified on a different thread that the original, which makes sense since we are in the async thread. The solution to that was to wrap the call in a Device.BeginInvokeOnMainThread method call. This built up the UI for the Dashboard page in the main UI thread instead.

Device.BeginInvokeOnMainThread(() => {
var page = new DashboardPage();
await this.Navigation.PushAsync(newPage);
});

Read more about BeginInvokeOnMainThread to understand the specifics, and why it may work in some situations and not others. So far that has been the tale of my adventures in asynchronous operations in Xamarin Forms. Hopefully this might help you as you use Xamarin Forms.

Understanding Game Design: Currencies

Within any specific game, there are various forms of currency, but it usually works out that there are two to three types of currency. The first type of currency, which I’ll call the primary currency, is the most easy to accrue. It usually exists within the game and is collected during the game play. For instance, for an endless runner game, the currency is in the path of the player waiting to be collected. For a city or civilization building game, currency is produced by a factory, mine, etc. and slowly builds up over time. These “factories” can be improved to yield a better economic output.

A secondary form of currency is rarer to collect. It doesn’t normally appear in the game, but can be collected in various ways: the most common way is through purchasing online. Other ways are usually as a form of daily reward, or lifetime achievements (for instance, as a form of reward for doing X action a lot of times). Sometimes, there is a third rare currency available to enable certain special actions, which can only usually be purchased.

Some examples of game currencies are the following:

  • Clash of Clans – Primary currency exists as gold/elixir, and secondary currency exists as gems. Primary currency is earned over time as produced by gold mines and elixir stations. Gems can be used to speed up the progress.
  • Boom Beach – Primary currency exists as gold for purchases, wood/stone/iron for producing buildings. Diamonds are available as a secondary currency and can be used to speed through the game.
  • Spiderman Unlimited – The primary currency are vials, with a secondary currency of ISO-8. Vials are collected during the course of running in the game, while ISO-8 is earned for completing levels.

During the game, the “economies of scale” usually favor a quicker accumulation of the primary currency, a slower accumulation of a secondary currency, and a purchase only accumulation of a tertiary currency. If you are unfamiliar with the term “Economies of Scale”, is defined as the following in Wikipedia:

In microeconomics, economies of scale are the cost advantages that enterprises obtain due to size, output, or scale of operation, with cost per unit of output generally decreasing with increasing scale as fixed costs are spread out over more units of output.

… For example, a large manufacturing facility would be expected to have a lower cost per unit of output than a smaller facility, all other factors being equal, while a company with many facilities should have a cost advantage over a competitor with fewer.

While we aren’t dealing with businesses or manufacturing, from a game design perspective, economies of scale can refer to paid vs. free users. There will be users that buy the game or pay for in-game currency to get ahead faster in the game, while other users will take a slower track and earn all currency. A good economy of scale with these two types of users should obviously slant to players willing to pay money in order to take the fast track, while making sure to offer an incentive to play the game for free users.

Incentives appear in many forms; some are the following examples:

  • They may be daily rewards for coming back to play the game day in and day out.
  • Special game modes can be made available that offer a higher level of currency than usual, but which is only available for a short period of time. These add some variances to the game

A Surprising Fact About Extension Methods

Extension methods are awesome. They allow extending the API of an object by creating a static method that “attaches” to an instance of an object, provided the extension method targets that type, which can be a generic or non-generic class, or an interface. Did you know that Extension methods extend an instance of an object, and can be called even if the object is null? For instance, suppose we had an extension method:

public static class ObjectExtensions
{
   public bool IsNull(this object obj)
   {
      return obj == null;
   }
}

And can be called on an object:

object obj;
var isNull = obj.IsNull();

Behind the scenes, the .NET framework passes the reference to obj to the static IsNull method, which will be null.

This works great for chaining references to objects which may or may not exist. For instance, I like to write extensions for LINQ to XML, to chain drilling through a series of objects which may or may not exist. The following is the extension method:

public static class XmlExtensions
{
   public static XElement GetElement(XElement el, string childName)
   {
      if (el == null)
       return null;

      return el.Element(childName);
   }

   public static string GetElementValue(XElement el, string childName)
   {
      if (el == null)
        return null;

      return el.Value("childName");
   }
}

Using these extensions, you can drill through a large hierarchy. Whether the elements exist or not, the drill through code works because we handle null, and continue the null chain. If all the elements exist in the document, the value is returned. A sample of using this is below:

var doc = XDocument.Load("test.xml");
doc.Root.GetElement("Customer")
        .GetElement("LastOrder")
        .GetElement("Details")
        .GetElementValue("Cost");

If Customer, LastOrder, Details, or Cost elements are not in the XML, then a null is returned from GetElementValue. However, if all are provided, the cost is returned as a string. A simple extension can make working with hierarchical data much easier.

Using TEF in Xamarin Forms

TEF (Typed Extensibility Framework) is similar to MEF, but was designed to be flexible, customizable, and easy to implement. In this guide, we’re going to look at how to use TEF in a Xamarin Forms project. TEF is pretty easy to get started, but certain features are not available in a portable environment, which are in a Xamarin Android or Xamarin iOS project (for instance, the AppDomain is not portable, but is available in these projects). Therefore, we need to do some customization. To start, let’s go through the following steps:

Create a Project

In Visual Studio or Xamarin Studio, create a new portable or shared Xamarin.Forms project. TEF will work with either option.

Import TEF

Using Nuget, download the TEF package using Import-Package TEF via command line, or search for TEF in the Nuget Window Search Bar.

Add an AppDomain Assembly Loader

Or whatever other strategy you like to use. The following snippet uses the AppDomain to look for the loaded assemblies and find any ExportType or ExportDependency attributes. To do this, we need to create a class that implements TEF.Consumption.IAssemblyLoader. It will return a list of assemblies, and must exist in both the iOS and Android project.

Find your iOS and Android projects and create a new folder called “Library” or “Services”, or whatever you like to call it, and include the following code snippet below in each project. Note: if you are using a shared project, this may work by placing the reference there. I haven’t tried using a shared project.

[assembly:Dependency(typeof(AppDomainAssemblyLoader))]

public class AppDomainAssemblyLoader : TEF.Consumption.IAssemblyLoader
{
	public IEnumerable LoadAssemblies ()
	{
		return System.AppDomain.CurrentDomain.GetAssemblies ();
	}
}

I chose to use Xamarin’s DependencyService, which is a service locator, as the means to register and fetch this type (you’ll see the fetch later on). To register types, see my previous blog post, which explains how the assembly attributes are used.

Add a Consumer

A consumer is the component that takes the types and produces a dependency injection container. In this example, I’m using SimpleInjector PCL. Any container can be used, and you can find more about supporting containers via the Container Integration documentation. Note: it’s not complicated to create your own IConsumer class though; see the documentation for how.

Import Types

We need to add the TypeFactory code that ties all of these components together. In the App class that the Xamarin.Forms project creates, this code can exist in OnStart, or it can also be utilized with the Lazy class. I chose a different route: define it in the property of the App class:

public class App : Application
{
	private SimpleInjector.Container _container;

	public SimpleInjector.Container Container {
		get 
		{
			if (_container == null) {
				_container = TypeFactory.Configure ((c) => {
					c.AssemblyLoader (
						DependencyService.Get (DependencyFetchTarget.GlobalInstance)
					).Consumer (
						new SimpleInjectorConsumer()
					);
				}).Initialize () as SimpleInjector.Container;
			}

			return _container;
		}
	}

Here we use the TypeFactory to tie everything together. The configure method takes the assembly loader and consumer references, while the Initialize() uses this to construct the container. The container is returned and can be used in your app (weakly typed). In my example, to use the container in your application, use ((App)Application.Current).Container. And that’s all it takes to incorporate TEF into an assembly. The benefit is we can mark a type like:

[ExportType(typeof(ISomeType))]
public class SomeType : ISomeType
{

or as:

[ExportAssembly(typeof(ISomeType), typeof(SomeType))]

public interface ISomeType { }

public class SomeType : ISomeType { }

And these will be automatically consumed for us and put in our dependency injection container.

Xamarin Forms Async Loading of Data

Xamarin supports the async/await model of the .NET framework, which is an awesome capability. Because async/await is supported, it’s possible to use this to load the data in your application on demand. For instance, suppose we had a page with two listviews, such as the following sample page:



	
		
			
				
					
						
							
							
							
						
					
				
			
		
	

	
		
			
				
					
						
							
							
							
						
					
				
			
		
	


Let’s take a second to look at the ListView markup. The ListView renders a custom ViewCell for each item in the list. We can use ViewCell to create a custom UI for each list item, which is provided by the inner StackLayout. The ListView is bound in code (though could be easily bound in the markup) as shown below, each delaying a specific period of time (for the purposes of simulating a network request).

public class Game
{
	public string Name { get; set; }
	public int Score { get; set; }
	public string PlayerImageUrl { get; set; }
}
public class HighScore
{
	public string Name { get; set; }
	public string Level { get; set; }
	public int Score { get; set; }
}

private async void LoadGames()
{
	await Task.Delay (3000);

	//All zeros is used for demoing purposes.
	this.GamesList.ItemsSource = new List {
		new Game { Name = "Paul J.", Score = 5350, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Peter K.", Score = 3410, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Bill C.", Score = 960, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Bobby B.", Score = 3190, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" },
		new Game { Name = "Amy S.", Score = 5950, PlayerImageUrl = "http://www.gravatar.com/avatar/00000000000000000000000000000000?s=40" }
	};
}

private async void LoadHighScores()
{
	await Task.Delay (5000);

	this.HighScoresList.ItemsSource = new List {
		new HighScore { Name = "Robby10210.", Score = 907409, Level = "Lv. 42" },
		new HighScore { Name = "Peter K.", Score = 891399, Level = "Lv. 41" },
		new HighScore { Name = "Bill C.", Score = 801222, Level = "Lv. 39" },
		new HighScore { Name = "Bobby B.", Score = 681202, Level = "Lv. 34" },
		new HighScore { Name = "Amy S.", Score = 660198, Level = "Lv. 33" }
	};
}

This loads data into the lists after a delay without interruption to the user. A quick demo of the app is illustrated below for your viewing pleasure on Youtube at the URL, taken with Camtasia – a great screen recording tool: http://www.youtube.com/watch?v=3l2B9v2b0gw.

Dependencies in Xamarin Forms

Dependency Injection and Service Location, in the .NET world, is becoming widely accepted as a flexible way to link resources between classes dynamically. One of the many frameworks out on the market provide a very flexible way to locate dependencies or build up an object via constructor/property injection. Some of these containers also contain a bootstrapper component that make registration in the application easier.

There are two components to this: the type registration, and the type location. Let’s take a look at both of these separately.

Type Registration

There are a variety of ways to do this. Outside of defining the registrations manually, there are other frameworks out there that make defining dependencies easier. For instance, I’ve recently created a product called TEF (typed extensibility framework), which is similar to MEF, but for types. By marking a type as a dependency using assembly attributes, or by marking the type with an exportable attribute, the system extracts these types from the assembly and makes them available for registration in the container. Below is an example of how you can mark a type as exportable:

public interface ISomeType { .. }

[ExportType(typeof(ISomeType))]
public class SomeType : ISomeType { .. }

OR

<assembly:ExportDependency(GetType(ISomeType), GetType(SomeType))>

The system can then parse the assemblies in the application, extracting out all of the individual types. I go through this example because the DependencyService registers components in the assembly in a very similar way. It follows a similar design to TEF for registration; however, it only supports assembly attributes as in the following example:

[assembly: Xamarin.Forms.Dependency (typeof (SomeType))]

Marking all of your dependencies will automatically import them into the dependency service.

Type Retrieval

The Xamarin Forms Dependency Service has a similarity to ASP.NET MVC’s IDependencyResolver, which has the same purpose of supplying types to the various components.

This is not the same as a dependency injection container; it is a service locator designed to locate references. For instance, if you have this page:

public partial class DependencyPage : ContentPage
	{
	private ICacheService _cache = null;
	private IDependentService _dependent = null;

	public DependencyPage (ICacheService cache, IDependentService dependent)
	{
		InitializeComponent ();

		_cache = cache;
		_dependent = dependent;
	}

}

Notice it has two constructor dependencies. The following will produce an error with the dependency service.

var page = DependencyService.Get (DependencyFetchTarget.NewInstance);

With a Dependency Injection container, the above code would actually work because the container can handle cascading dependencies. Instead, to use DependencyService, it would have to be created this way:

var page = new DependencyPage(
    DependencyService.Get (DependencyFetchTarget.NewInstance), 
    DependencyService.Get (DependencyFetchTarget.NewInstance)
);

for the page to work. If anyone has any tips, or if there are inconsistencies, please post a comment and I’ll update the post.

Understanding Game Design: Challenges

Previously we looked at offering a reward as an incentive to bring people back to your game day after day. In this post, we are going to look at an additional incentive: challenges. Challenges occur in several forms:

Daily Challenges – Challenges only available for that day; as long as the challenges are met, then the streak continues. Usually there are three challenges that need completed to finish the challenges for the day.
Mission Challenges – Challenges related to the game or mission at hand, that try to shape the way the user plays the game. For instance, while a player may try to get through point A to B as quickly as possible, Mission Challenges try to convince the player to achieve certain objectives within the game that extend the game even further, with some incentive (such as in-game currency).
Coincidental Challenges – For the lack of a better word, some challenges encourage the user to perform certain actions in the game (jump over something 5 times, slide under this or that, etc.) that may not directly relate to the actions of the game.

Challenges give the user the opportunity to achieve some perk for completing certain tasks. The challenge should be enticing enough to encourage users to continually come back to the game. However, these perks do not amount to the same amount of incentives offered for purchasing in-game currency; daily challenges usually progress the game a little faster, but overall progress continues forward a bit more slowly than users who pay money to buy currency. Challenges reward users for completing the challenge, and may offer a continual streak for completing the challenge day after day.

As the user gets more skilled, challenges should increase in difficulty. For instance, maybe the player has to run 250 feet to achieve the challenge. That distance should increase slowly over time. It should always be within grasp though; if the challenge is increased too much, it may dissuade the player from trying to put in the effort. Additionally, increases shouldn’t occur after every time they complete it, but after so many completions of the perk.

Let’s take a look at some examples of challenges:

– Subway Surfer – the player gets rewards for performing in-game activities. Jumping over train cars, rolling X times, collecting X coins, stumbling into train cars, are all challenges that can be completed to increase the overall score multiplier. Increasing the score multiplier leads to higher scores.
– Mini Golf MatchUp -This game provides 3 daily challenges that have to be earned within the game. While these challenges don’t streak, completing the challenge offers a coin reward. The rewards are provided for certain actions: making a hole in one, activating certain features, etc.

Understanding Game Design: Daily Rewards

Almost every mobile game I see offers a daily reward of some sort.  Whether it be a form of currency or an in-game product for temporary or permanent use, a daily reward seems to be a common occurrence for most games.  There have been a few variances between the forms of daily rewards offered, so let’s look at the various kinds of setups:

When to Offer

Once a day – this is the most common setup; a user can get a daily reward just by logging into the game, but only once per day. The perk screen would appear the next day the user logged in. Sometimes, these types of perks had to be collected everyday, or the streak was lost. We’ll discuss that later.
Exactly 24 Hours – This is a setup that’s also been used; at exactly the 24 hour mark, the perk will become available. A countdown timer is usually displayed to let the user know how long to wait.

An important decision point here is whether missing a day breaks the streak. That may make sense for the once a day perk, but may not make sense for the exactly 24 hours perk.

How to Offer

Randomization – A random reward is chosen and given to the user. A common method of displaying the chosen perk is by a spinning wheel (similar to Wheel of Fortune or the Price is Right).
5 Day Reward System – A common setup is a 5 day reward system. Rewards can either progress up to include better prizes. They may also offer the same prize; on completion of the fifth day, a bigger reward is usually granted. Missing one day often causes this reward system to reset back to zero.
5 Day Sliding Reward System – I only saw this in one game, but thought it was interesting. The game offered a 5 day reward system. At specific intervals (which for larger inventory items may occur at day 50, or smaller inventory items at day 20/25), would offer a powerful item the user typically wanted.
Continual Day Reward System – This reward system contains a reward system with a large number of days, building up to something epic if the user is committed to the game. Missing a day may or may not break the streak (which breaking the streak would cause the system to reset).

What to Offer

The most common offering is in-game currency. Usually, it’s the primary currency offered by the game; the daily reward helps the user obtain currency quicker by being committed to the game. As the game progresses, additional forms of currency may become available (we’ll be talking about currency in another post). At the end of a 5 day reward system, the game may offer an item used within the game.

Some Examples

Let’s look at some game examples:

Subway Surfer – Upon spelling a word by collecting letters in the game, the user gets a certain amount of coins in the game. Every day the reward is collected, more money is achieved. Upon completing the 5 day challenge, the last prize is a Mystery Box.
Despicable Me: Minion Rush (older version) – Before they changed it to the current reward system, the previous version offered a 5 day reward system that could be collected once certain in-game achievements were completed. For the first 4 days, random achievements were earned. On day 5, a puzzle piece could be claimed. Puzzle pieces were used to unlock characters. If one day was missed, the process would start over again.
Temple Run 2 – Upon completing in game achievements, rewards are earned. There are 5 days, and the reward increases every day.
Candy Crush Saga – A daily challenge wheel appears and offers a daily prize.
Spy Wars – In game currency is earned by logging in every day. Additionally, a secondary currency is earned if the user logs in with Facebook. The reward system continues up in the amount of money earned, and eventually resets. Breaks in days do not reset the reward.
Punch Hero – A continual reward system that is offered at exactly 24 hours. Nothing in the game needs to be completed to receive it. A break in the day does not break the streak; however, the maximum prize offered is only available if collected within the month.

TEF Available As A Nuget Package

I’ve added TEF as a Nuget package available for download in two flavors now:

Install-Package TEF

TEF is a PCL library which allows you to define types for exporting into a dependency injection container. Since it’s PCL, it can work in Silverlight, Xamarin.iOS, Xamarin.Android, and more.

Install-Package TEF.NET

This is a .NET 4.5 version that provides .NET framework specific add-ons, such as parsing the assemblies in the app domain.