Category Archives: Monogame

Handling Input in XNA / MonoGame

This morning I didn’t have internet access and was trying to find this in my notes (which are also my blog posts), and I couldn’t; so purely for my own benefit, the following is a method of handling touch or mouse input in Monogame:

        public void HandleInput()
        {
            ProcessMouseInput();
            ProcessTouchInput();
            ProcessKeyboardInput();
        }

        private void ProcessMouseInput()
        {
            var currentMouse = Microsoft.Xna.Framework.Input.Mouse.GetState();

            if (currentMouse.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
            {
                HandlePressed(currentMouse.Position, _controlledObject);
            }
        }

        private void ProcessTouchInput()
        {
            var currentTouch = Microsoft.Xna.Framework.Input.Touch.TouchPanel.GetState();

            foreach (var touch in currentTouch.Where(t => t.State == Microsoft.Xna.Framework.Input.Touch.TouchLocationState.Pressed))
            {
                HandlePressed(touch.Position, _controlledObject);
            }


        }

        private void ProcessKeyboardInput()
        {
            var currentKeys = Microsoft.Xna.Framework.Input.Keyboard.GetState();
            if (currentKeys.IsKeyDown(Microsoft.Xna.Framework.Input.Keys.Left))
            {
                _handler.GoLeft(_controlledObject);

By changing Pressed to Released, you can detect when the mouse button click / touch finished; however, if you hold your finger / mouse button down, it will only return a single result.

Cannot change thread mode after it is set

I recently published this article on using asynchonous methods within a Windows Game, and this article on enabling consumables within a Windows Game

However, I encountered a problem when I tried to use these two methods in combination. My code looked something like this:

var result = MessageBoxHelper.MsgBox.ShowAsync(string.Format("You do not have sufficient widgets for this.\n" +
    "Would you like to purchase more?"), MessageBoxButton.YesNo).ContinueWith(async (answer) =>
{
    if (answer.Result == MessageBoxResult.Yes)
    {
        bool purchTask = await Purchase.RequestProductPurchase(WIDGETS);

However, when I ran this; I got the following exception:

cannotchangethread

This is a marginally documented error:

By Microsoft and by Stack Overflow

I could call the function Purchase.RequestProductPurchase directly, but not, for some reason, in conjunction with ContinueWith. I tried this combination in a basic console application:

        static void Main(string[] args)
        {
            continueWithTest();
        }

        private static void continueWithTest()
        {
            MyAsyncFunc().ContinueWith(async (a) =>
            {
                Console.WriteLine("test");
                await Task.Delay(2000);                
            }).Wait();
            Console.ReadLine();
        }
        static async Task MyAsyncFunc()
        {
            await Task.Delay(2000);
            Console.WriteLine("Test1");
    }

And it worked fine. Based on what is available to read on the web, it looks like the threading model is, in some way, different when using ContinueWith. Although, it would appear that if you specify the TaskScheduler.Current, you should be able to use this in place of await, but that seems to make no difference.

The fix, as so many people are quick to point out, is use await:

        private void MakePurchase(int cost, Action onSuccess, bool interactive)
        {
            if (App.settings.CashPot.Total > cost)
            {
                App.settings.CashPot.Total -= cost;
                onSuccess.Invoke();                
            }
            else if (interactive)
            {
                InsufficientFunds(cost, onSuccess);
            }
        }


        private async void InsufficientFunds(int cost, Action onSuccess)
        {
            var result = await MessageBoxHelper.MsgBox.ShowAsync(string.Format("You do not have sufficient funds for this.\n" +
                "Would you like to purchase additional cash?"),
                "Insufficient Funds", MessageBoxButton.YesNo);                
                            
            if (result == MessageBoxResult.Yes)
            {
                bool purchTask = await Purchase.RequestProductPurchase(WIDGETS);

                MakePurchase(cost, onSuccess, false);
            }
        }

Enabling Consumable Purchases in Windows Store Apps

What are consumables

Consumables are a type of in-app purchase that can be used within your app or game; by used, I mean, for example, coin, food, life-force, credit; anything that can be bought and then the same item be bought again. This is opposed to durables, which are in-app purchases, such as removing adverts, premium features, etc.

Where to go first

The MSDN article does cover most of what you need. However, it doesn’t seem to cover everything, hence this post.

The documentation for the CurrentAppSimulator is also useful.

The Principle

Actual purchasing is done through the CurrentApp class. However, there is an identical test version of this, which simulates the purchasing of in-app products. Part of the store certification process is to ensure you haven’t forgotten to switch these to their live counterparts; although using the #Debug and #Release configurations might be an idea, too (see the bottom of this post for more details on this).

Step 1 – WindowsStoreProxy.xml

When you run your application in real life, it will download the purchase information from the store. However, when you’re testing, you need to simulate this. The linked documents do have examples; however, IMHO, they don’t completely explain the implications of each section. Here’s an XML file:

<?xml version="1.0" encoding="utf-16" ?>
<CurrentApp>
  <ListingInformation>
    <App>
      <AppId>988b90e4-5d4d-4dea-99d0-e423e414ffbc</AppId>
      <LinkUri>http://apps.windows.microsoft.com/app/988b90e4-5d4d-4dea-99d0-e423e414ffbc</LinkUri>
      <CurrentMarket>en-gb</CurrentMarket>
      <AgeRating>12</AgeRating>
      <MarketData xml:lang="en-gb">
        <Name>App with several in-app products</Name>
        <Description>Sample app for demonstrating an expiring in-app product and a consumable in-app product</Description>
        <Price>0.00</Price>
        <CurrencySymbol>£</CurrencySymbol>
      </MarketData>
    </App>
    <Product ProductId="MORE_CASH_1000" LicenseDuration="0" ProductType="Consumable">
      <MarketData xml:lang="en-gb">
        <Name>Consumable Item</Name>
        <Price>0.99</Price>
        <CurrencySymbol>£</CurrencySymbol>
      </MarketData> 
    </Product>
  </ListingInformation>
  <LicenseInformation>
    <App>
      <IsActive>true</IsActive>
      <IsTrial>false</IsTrial>
    </App>
  </LicenseInformation>
  <!--
  <ConsumableInformation>
    <Product ProductId="MORE_CASH_1000" TransactionId="00000001-0000-0000-0000-000000000000" Status="Active" />
  </ConsumableInformation>
  -->
</CurrentApp>

It looks a lot like the MS example, with a few key differences: firstly, it only contains a single consumable; second, it’s in GBP; and thirdly, the “ConsumableInformation” is commented out. The single consumable is just because that’s what I’m working with, but the other two burnt me:

  • If you change the language or currency, you need to be consistent. I left an en-us in and it, point blank, refused to read the document. I spent a while checking the XML was the correct format, and finally just guessed at this.
  • The ConsumableInformation node is commented out. If you put it in, then when you read the license, it will tell you that it is unfulfilled. This is definitely useful for testing, but looks like a bug in your code if you don’t know this.

Store this in a Data folder within the project:

consumables1

Step 2 – Create a helper class for managing the purchase

Obviously, this isn’t a requirement; but I would create a class for each consumable purchase. If you have common code then create a helper and base class as well.

namespace BetRaces.Purchases
{
    public class Purchase
    {
        public const string MORE_CASH_PRODUCT = "MORE_CASH_1000";
        public const int MORE_CASH_AMOUNT = 1000;

The following steps are building on the existence of such a class.

Step 3 – Create a dictionary of purchased GUIDs

The idea here is that you can track what has been bought.

private Dictionary<string, List<Guid>> grantedConsumableTransactionIds;

Step 4 – Grant Feature Locally

If you read the linked documents, they suggest a version of this function; basically, you need a function that will perform the task that you’ve asked for. In this case, it will manage the purchase of the coins, time, bonus, whatever. The following code is pretty much an exact duplicate of that offered by MS:

        private async void GrantFeatureLocally(string productId, Guid transactionId)
        {
            if (grantedConsumableTransactionIds == null)
                grantedConsumableTransactionIds = new Dictionary<string, List<Guid>>();

            if (!grantedConsumableTransactionIds.ContainsKey(productId))
            {
                grantedConsumableTransactionIds.Add(productId, new List<Guid>());
            }
            grantedConsumableTransactionIds[productId].Add(transactionId);

            // Grant the user their content. You will likely increase some kind of gold/coins/some other asset count.
            App.settings.CashPot.Total += MORE_CASH_AMOUNT;
            App.settings.SaveSettings();  // Ensure that the purchase is saved before reporting it as successful.
            FulfillmentResult result = await CurrentAppSimulator.ReportConsumableFulfillmentAsync(MORE_CASH_PRODUCT, transactionId);

        }

Step 5 – Get Unfulfilled Consumables

The reasoning here is that you have started to make a purchase, but the line above `ReportConsumableFulfillmentAsync` has not been called. This then sits in a status which blocks future purchases.

        private async Task GetUnfulfilledConsumables()
        {
            var products = await CurrentAppSimulator.GetUnfulfilledConsumablesAsync();

            foreach (UnfulfilledConsumable product in products)
            {
                GrantFeatureLocally(product.ProductId, product.TransactionId);
            }
        }

Obviously, there is a risk that the code in step 4 will crash just at the point before you report the fulfilment; however, I’d rather that, than the user having paid for something they haven’t received.

Step 6 – Purchase

The next stage is a RequestProductPurchase() method; here’s the code:


        public async Task<bool> RequestProductPurchase(string productId)
        {
            Uri uri = new Uri("ms-appx:///Data/WindowsStoreProxy.xml");
            Windows.Storage.StorageFile storeProxy = await StorageFile.GetFileFromApplicationUriAsync(uri);

            await CurrentAppSimulator.ReloadSimulatorAsync(storeProxy);
            
            Guid product1TempTransactionId;

            PurchaseResults purchaseResults = await CurrentAppSimulator.RequestProductPurchaseAsync(productId);
            if (purchaseResults == null) return false;

            switch (purchaseResults.Status)
            {
                case ProductPurchaseStatus.Succeeded:
                    product1TempTransactionId = purchaseResults.TransactionId;

                    // Grant the user their purchase here, and then pass the product ID and transaction ID to currentAppSimulator.reportConsumableFulfillment
                    // To indicate local fulfillment to the Windows Store.
                    GrantFeatureLocally(productId, product1TempTransactionId);
                    return true;

                case ProductPurchaseStatus.NotFulfilled:
                    product1TempTransactionId = purchaseResults.TransactionId;

                    // First check for unfulfilled purchases and grant any unfulfilled purchases from an earlier transaction.
                    await GetUnfulfilledConsumables();

                    // Once products are fulfilled pass the product ID and transaction ID to currentAppSimulator.reportConsumableFulfillment
                    // To indicate local fulfillment to the Windows Store.
                    if (grantedConsumableTransactionIds != null && grantedConsumableTransactionIds.ContainsKey(productId))
                        return true;
                    return false;                    
            }

            return false;
        }

The above code is what I was referring to in Step 1, when I mentioned the NotFulfilled return status.

Step 7 – Test the change

When you try to make a purchase, you should see a screen such as this:

consumables2

You can then test possible eventualities.

Step 8 – Enable them in the store

The next step is to enable your purchases in the App Store. The code has to be the same; and for larger games (the producers of which will probably not be reading posts such as this) the codes will be generated on a server, so they can manage special offers, etc. centrally.

In the Services section of the dashboard:

consumables3

Now enter your offer code, along with the price and make it a “Consumable”:

consumables4

Step 9 – The Old Switcheroo

All you need to do now is to substitute CurrentAppSimulator for CurrentApp.

Because both classes are static, I couldn’t find a better way than this:

#if DEBUG
            PurchaseResults purchaseResults = await CurrentAppSimulator.RequestProductPurchaseAsync(productId);
#else
            PurchaseResults purchaseResults = await CurrentApp.RequestProductPurchaseAsync(productId);
#endif

Windows Store Apps automatically compile in Release mode for the store.

Once you’ve found all the CurrentAppSimulator references and replaced them with this conditional construct (by my count there are 4 places for this); you should see the following when you try to make the purchase:

consumables5

consumables6

Conclusion

The links at the start are by far the best resource available for this; but hopefully this will fill in a couple of the gaps that tripped me up.

Adding and Using a New Font in MonoGame (The 11 Step Program)

This is not an undocumented subject; however, I didn’t find everything I needed in a single place; so this is my single point of reference.

The Problem

There is currently no facility within MonoGame to create a new Sprite Font. The workaround described below is, to put it mildly, time consuming.

Adding a Font

Step 1

The first step is to download Visual Studio 2010

This is the only download link to the express edition (obviously if you have an MSDN license, you can get the full edition. VS Express has now been replaced by the Community Edition, but that’s VS2013.

Step 2

Next, you need to download XNA Game Studio

… and install it.

Step 3

Now, load up VS2010 and create a new XNA game:

MonoGame1

You should end up with a project that looks like this:

MonoGame2

Step 4

In the Content Project, add a new file:

MonoGame3

… and add a new SpriteFont:

MonoGame4

Step 5

If you now open the file, you can edit key aspects of the font, such as size, font name, etc…:

MonoGame5

Step 6

To test, make the following changes in the main project (Game1.cs):

        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
            spriteBatch = new SpriteBatch(GraphicsDevice);
            Font1 = Content.Load<SpriteFont>("SpriteFont2");
            FontPos = new Vector2(graphics.GraphicsDevice.Viewport.Width / 2, graphics.GraphicsDevice.Viewport.Height / 2);

        }
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();
            string output = "abcdefghijklmnopqrstuvwxyz!";
            Vector2 FontOrigin = Font1.MeasureString(output) / 2;
            spriteBatch.DrawString(Font1, output, FontPos, Color.Black,
                          0, FontOrigin, 1.0f, SpriteEffects.None, 0.5f);
            spriteBatch.End();

            base.Draw(gameTime);
        }

Step 7

Run the project:

MonoGame6

Step 8

Okay, now you have a font (the font was compiled when you ran the project in the previous step). Locate the compiled font:

MonoGame7

Step 9

Copy the compiled font to your MonoGame content directory.

Step 10

Set the properties of the font to be Content:

MonoGame8

MonoGame9

Step 11

You’re done, you can now use it in your project in the same manner as you did in the test project earlier.

Conclusion

Work is underway to incorporate this into MonoGame. However, it’s still a massively painful process!

References

Below are some useful links that I found (I’d be happy to add more, or just leave a comment):

http://www.c-sharpcorner.com/uploadfile/iersoy/how-to-use-spritefont-in-xna/

http://gamedev.stackexchange.com/questions/46128/how-to-generate-spritefonts-for-monogame

http://stackoverflow.com/questions/18268413/loading-a-font-using-monogame-with-vs2012-13

Handling both Touch and Mouse Input with Monogame

I’ve already posted a few times on handling input for Monogame. This one’s a little bit different though, and came from the fact that I had a game trying to get through certification that was repeatedly failing. What I was doing was detecting touch capabilities and, where I found them, using them; otherwise, using keyboard or mouse.

What I ended up doing was handling both. At the time this was just to get the game through certification in the Windows Store; but the more I think about it, the better I think the solution is.

Instead of maintaining a single input contoller, and assigning to it via a factory method, I maintain a list of controllers:

List<IInputController> _inputControllers;

Then, instead of an if / else statement to assign to the controllers, I simply add what’s available:

        // Determine how the user will interface with the game
        private void HandleInput()
        {
            // Instantiate the controllers collection
            if (_inputControllers == null) _inputControllers = new List<IInputController>();
            
            if (_inputControllers.Count == 0)
            {
                // Can we handle touch?  If so, add a new controller to handle touch
                Windows.Devices.Input.TouchCapabilities tc = new Windows.Devices.Input.TouchCapabilities();
                if (tc.TouchPresent == 1)
                {
                    _inputControllers.Add(new TouchController());
                }

                // Can we handle Mouse?  If so, add a new controller to handle mouse
                Windows.Devices.Input.MouseCapabilities mc = new Windows.Devices.Input.MouseCapabilities();
                if (mc.MousePresent == 1)
                {
                    _inputControllers.Add(new MouseController());
                }
            }

So, now we’ve got a list (and it doesn’t have to be restricted to 2 elements if, for example, you suddenly decide to support a thought-power interface http://en.wikipedia.org/wiki/Emotiv_Systems).

On the update method of your game, you now simply iterate through them:

foreach (IInputController inputController in _inputControllers)
{
    inputController.HandleInput();
}

Isn’t it a bit messy having the (potentially) giant conditional statement above

Yes. So, how about this.

            // Determine how the user will interface with the game
            if (_inputControllers == null) _inputControllers = new List<IInputController>();
            
            if (_inputControllers.Count == 0)
            {
                TouchController.AddController(_inputControllers);
                KeyboardController.AddController(_inputControllers);
            }

And then add the AddController function as a static method; like so:

        internal static void AddController(List<IInputController> controllers)
        {
            Windows.Devices.Input.MouseCapabilities mc = new Windows.Devices.Input.MouseCapabilities();
            if (mc.MousePresent == 1)
            {
                controllers.Add(new KeyboardController());
            }

        }

I’m unsure if this qualifies as a “Factory” method as such, although effectively that is what it is.

Conclusion

I’m now quite happy with this approach. I can foresee future uses for the logic, so at some point, if I get time, I might transfer it all to a PCL and publish on Codeplex… assuming I can work out how to get the Windows.Devices namespace to work in a PCL.

Detecting Keyboard Gestures Using Monogame

Recently, I got to the stage where I had just about finished one of my games, and suddenly realised that I had done nothing to deal with mouse gestures. Dealing with touch (which I have previously blogged about) can blind you to other input forms. Exactly how you deal with this will, of course, depend on what you’re trying to achieve.

Simple press and click – Touch

Let’s have a look at a piece of code to handle touch gestures:

private TouchCollection _currentTouch;

private void ProcessTouchInput()
{
    if (keypad == null) return;

    _currentTouch = TouchPanel.GetState();
    foreach( var touch in _currentTouch)
    {
        if (touch.State == TouchLocationState.Released)
        {
            keysPressed += keypad.GetKeyAt(touch.Position);
        }
    }
}

Okay, so this was ripped right out of the middle of a game. Most of it doesn’t matter, but `keypad` represents a customised on-screen keypad. So, to find out what’s been pressed, we simply call TouchPanel.GetState() and iterate the returned collection.

If we find that the TouchLocationState to be released then it must have been touched (how can you release something that was never touched?).

It then builds up a string containing the keys.

… And with mouse

Okay, here’s the first thing; this statement:

If we find that the TouchLocationState to be released then it must have been touched (how can you release something that was never touched?).

Is no longer true. `Released` where a mouse state is concerned is simply an absence of being pressed!

So, we need to track what has happened, and when:

private DateTime? _mousePressed;
private MouseState _currentMouse;

private void ProcessMouseInput()
{
    if (keypad == null) return;
           
    _currentMouse = Mouse.GetState();
    if (_currentMouse.LeftButton == ButtonState.Pressed)
         _mousePressed = DateTime.Now;

    if (_currentMouse.LeftButton == ButtonState.Released
       &amp;&amp; _mousePressed != null)
    {
        _mousePressed = null;
        keysPressed += keypad.GetKeyAt( new Vector2(_currentMouse.X, _currentMouse.Y));               
    }
}

Okay, so as far as mouse press is concerned, we have to roll our own. This isn’t particularly complicated code though.

What about gestures?

You can do gestures; it’s not straight-forward and, again, it’s not particularly well supported.

Here’s how I handle dragging:

MouseState mouseState = Mouse .GetState();
Vector2 mousePosition = new Vector2(mouseState.X, mouseState.Y);

// First, work out where and whether the drag has started
if (mouseState.LeftButton == ButtonState.Pressed)
{
if (_lastPressed == null || _lastPressed < _lastRelease) dragStart = null; // The current mouse location must be in a place where it // is acceptable to start a drag if (CheckLocation(mousePosition, acceptableDragStart, 60)) { if (dragStart == null) { dragStart = mousePosition; } } _lastPressed = DateTime.Now; } // Now work out when the drag is released if (mouseState.LeftButton == ButtonState.Released) { // For some reason, ButtonState.Released is // always flagged unless the button is pressed if (_lastPressed == null) return; _lastPressed = null; // Set the last release here _lastRelease = DateTime.Now; // Do whatever it is that you need for drag release DragRelease(mousePosition, dragStart, PlayerPosition); } [/sourcecode] So the code is in two distinct sections; the first being to determine is, and where, the mouse was pressed, and to store that information; the latter to determine if and where it was released. Double tap, hold, and other such gestures make this code more and more complex. It feels a lot like the main issue is the Released state.

Using data binding inside monogame to control ad control display

I’ve already blogged a few times on using monogame with XAML. One thing that occurred to me recently was that I could leverage this in order to better control when the ad control appears in one of my games. Basically, my idea was that I could bind the main game page to a model, which determined whether the ad would be displayed.

Obviously, the difficulty here is that you need to pass the view model around your app. Monogame doesn’t seem to be very good at allowing you to do that, so I decided to use this approach (in app.xaml.cs):

    sealed partial class App : Application
    {
        private static GamePageViewModel _gamePageViewModel;
        public static GamePageViewModel GamePageViewModel
        {
            get
            {
                if (_gamePageViewModel == null)
                {
                    _gamePageViewModel = new GamePageViewModel();
                }

                return _gamePageViewModel;
            }
        }

A couple of notes on that code:
1. Yes, I could have simply instantiated the viewmodel at the start of the app.
2. Yes, it is static. This is so you can access it elsewhere.

The GamePageViewModel isn’t particularly noteworthy:

namespace MyGame.ViewModel
{
    public class GamePageViewModel : INotifyPropertyChanged
    {
        private bool _showAds;
        public bool ShowAds
        {
            get { return _showAds; }
            set
            {
                _showAds = value;
                RaisePropertyChanged( "ShowAds");
            }
        }

        private void RaisePropertyChanged( string caller)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged( this, new PropertyChangedEventArgs(caller));
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

I do need to set this in code though; so when you display the GamePage:

         protected override void OnLaunched( LaunchActivatedEventArgs args)
        {
            var gamePage = Window.Current.Content as GamePage;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (gamePage == null)
            {
                // Create a main GamePage
                gamePage = new GamePage(args.Arguments);

                // Set the DataContext to the static instance of the ViewModel
                gamePage.DataContext = App.GamePageViewModel;

You need to bind the ad control (use somthing like this – I haven’t detailed the code for the converter, but I’m sure 3 seconds of Internet searching will reveal a few thousand examples):

               
<UI: AdControl x: Name ="adControl"                                          
ApplicationId ="appid"
      AdUnitId ="appunitid"      
Width ="728"
      Height ="90"
      IsAutoRefreshEnabled ="True"                         
      Margin ="5"      
      Visibility ="{Binding ShowAds , Converter ={StaticResource BoolToVisibilityConv}}">
/>

What this allows me to do, from ANYWHERE in the game is this:

               
         private async static void purchaseCommandInvoked(Windows.UI.Popups.IUICommand command)
        {
            bool success = await License.PurchaseApp();

            if (success)
            {
                // Updating the view model here!
                App.GamePageViewModel.ShowAds = false;
            }
        }

Conclusion

So, nothing new here, but using binding inside Monogame didn’t occur to me immediately, so there must be a least some people in the same boat.

Convert Monogame to Monogame with XAML

Some time ago, I blogged about the importance of creating a “Monogame With XAML” project. Before I’d written this, I’d started a long running project, and realised that I needed XAML (for reasons already indicated). So, is it possible to convert? YES!

Is it easy? Actually, it’s not too bad; but to save anyone else (and my future self) the hastle of working out how, I’ve broken it down into 7 easy steps. (Below, MyGame refers to your game namespace).

1. Add app.xaml as a blank xaml page. Once it’s added, change the BuildAction to ApplicationDefinition:

Image

2. Clear the XAML from the page, and replace with the following:

<Application
    x: Class="MyGame.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns: x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns: local="using:MyGame">

    <Application.Resources >
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>

                <!--
                    Styles that define common aspects of the platform look and feel
                    Required by Visual Studio project and item templates
                 -->
                <ResourceDictionary Source ="Common/StandardStyles.xaml"/>
            </ResourceDictionary.MergedDictionaries>

        </ResourceDictionary>
    </Application.Resources >
</Application>

3. StandardStyles.xaml referenced above will not exist. Create a new XAML file in the appropriate directory (the one in this example is in a Common subdirectory. This should look something like the following (although given that these are styles, you may have different ideas):

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <!-- Non-brush values that vary across themes -->

    <ResourceDictionary.ThemeDictionaries>
        <ResourceDictionary x:Key="Default">
            <x:String x:Key="BackButtonGlyph">&#xE071;</x:String>
            <x:String x:Key="BackButtonSnappedGlyph">&#xE0BA;</x:String>
        </ResourceDictionary>

        <ResourceDictionary x:Key="HighContrast">
            <x:String x:Key="BackButtonGlyph">&#xE071;</x:String>
            <x:String x:Key="BackButtonSnappedGlyph">&#xE0C4;</x:String>
        </ResourceDictionary>
    </ResourceDictionary.ThemeDictionaries>

    <x:String x:Key="ChevronGlyph">&#xE26B;</x:String>
...
</ResourceDictionary>

If you’re unsure about what to put in here then just create a blank store app and lift this file.

4. Next, you need to edit the code behind for the new App.Xaml file. In App.Xaml.cs, you should have the following code:

using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;

// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=234227

namespace MyGame
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
    sealed partial class App : Application
    {
        /// <summary>
        /// Initializes the singleton application object.  This is the first line of authored code
        /// executed, and as such is the logical equivalent of main() or WinMain().
        /// </summary>
        public App()
        {
            InitializeComponent();
            Suspending += OnSuspending;
        }

        /// <summary>
        /// Invoked when the application is launched normally by the end user.  Other entry points
        /// will be used when the application is launched to open a specific file, to display
        /// search results, and so forth.
        /// </summary>
        /// <param name="args">Details about the launch request and process.</param>
        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            var gamePage = Window.Current.Content as GamePage;

            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            if (gamePage == null)
            {
                // Create a main GamePage
                gamePage = new GamePage(args.Arguments);

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // TODO: Load state from previously suspended application
                }

                // Place the GamePage in the current Window
                Window.Current.Content = gamePage;
            }

            // Ensure the current window is active
            Window.Current.Activate();
        }

        /// <summary>
        /// Invoked when application execution is being suspended.  Application state is saved
        /// without knowing whether the application will be terminated or resumed with the contents
        /// of memory still intact.
        /// </summary>
        /// <param name="sender">The source of the suspend request.</param>
        /// <param name="e">Details about the suspend request.</param>
        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();

            // TODO: Save application state and stop any background activity

            deferral.Complete();
        }
    }
}

5. GamePage referenced above doesn’t exist; create a new Page, called GamePage.xaml, and paste the following Xaml into it:

<SwapChainBackgroundPanel
    x:Class="MyGame.GamePage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MyGame"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid>
    </Grid>

</SwapChainBackgroundPanel>

6. Next, press F7 to get to the code-behind for GamePage.Xaml. In GamePage.Xaml.cs, paste the following code:

    public sealed partial class GamePage : SwapChainBackgroundPanel
    {
        readonly GameEngine _game;

        public GamePage(string launchArguments)
        {
            this.InitializeComponent();

            // Create the game.
            _game = XamlGame<GameEngine>.Create(launchArguments, Window.Current.CoreWindow, this);
        }
    }

This should link the whole thing back to your initial GameEngine that MonoGame uses.

7. Finally, locate Program.cs and either comment out the code, or just delete it.

DONE

You should now find that your game runs exactly as before, except you now have XAML capabilities.

Please feel free to add any comments for anything that I might have missed, or improvements you may have on this process. Also, feel free to leave comments such as: “Yes, this worked!”.

Beware: asynchrony with monogame

The async / await keywords allow asynchrony extremely easily in comparison to previous implementations; however, this blog post is a word of caution for those working with monogame or XNA in general.

Imagine the following update method:

                try
                {
                    spriteBatch.Begin( SpriteSortMode.Deferred, BlendState.AlphaBlend);                   
                    await UpdateMySprites(spriteBatch);
                    await HandleInput();
                }
                finally
                {
                    spriteBatch.End();
                }

Okay, so this is spot on: where `UpdateMySprites` takes some time, it won’t stall execution… except that it will.

Why?

Because of the way `async` works. What the await function actually does is create a continuation block, which includes:

    spriteBatch.End();

As a result, the screen is not drawn until the slow function finishes (whether the function should be that slow at this part of the code is another matter).

So, how to fix? Well, one option is to simply not await the functions. You can prevent yourself from doing that by not making the Update function `async`. You can still call asynchronous functions from a non-async method, but you can’t await them. The compiler will give you a warning and, to be honest, it’s probably not the best practice (you pay in your ability to work out exactly what state your program is in).

Another option is to make this method synchronous; and, where it needs to be asynchronous, use a background worker.

Conclusion

Although it seems straightforward (at least it does if you understand async), this did take me a while to work out. Hopefully it’ll save you that time.

Games are not the same as apps and utilities. Although many things may occur at the same time, you really need to know what all of those things are and exactly what position or state they are in; maybe using asynchrony in game development in a bad idea.

Adding Privacy Statement to Windows 8 Store App Built With Monogame

This has been covered many times on the web, but when using Monogame it isn’t as straightforward (not that it’s rocket science).

The key thing is to make sure that when creating the Monogame project, it is created using Monogame and XAML (I’ve blogged about this previously here).

In App.xaml.cs, add the following function to call your privacy statement:


Private async privacyCommandInvoked(Windows.UI.Popups.IUICommand command)
{
    Uri uri = new Uri("http://mypage.com/privacystatement.htm"");
    await Launcher.LaunchUriAsync(uri);
}

As far as I’m aware, it is a requirement of the Win 8 approval process that this be a web site; that is, it can’t simply be a XAML page that displays the text.

Now create a function to add this to the menu, and an event to handle it when it’s selected:


private AddFlyouts()
{
    var settingsPane = SettingsPane.GetForCurrentView();
    settingsPane.CommandsRequested += settingsPane_CommandsRequested;
}

void settingsPane_CommandsRequested(Windows.UI.ApplicationSettings.SettingsPane sender, Windows.UI.ApplicationSettings.SettingsPaneCommandsRequestedEventArgs args)
{
    commandHelp = new SettingsCommand("privacy", "Privacy Policy", privacyCommandInvoked);
    args.Request.ApplicationCommands.Add(commandHelp);
}

You’ll need to change the OnLaunched event to call `AddFlyouts();` and you should be set.  

Remember that this will launch a web browser, so you may need to handle the suspend / resume events to deal with that.