A blog about one man's journey through code… and some pictures of the Peak District

Category Archives: Monogame

In this previous post, I introduced Azure Event Hubs (to myself mostly). In this post, I’m going to attempt to create a very basic multi-player game, using Event Hubs to manage the multi-player part.

I’ve previously written extensively on MonoGame, although I haven’t done anything with it for a while.

Getting started with MonoGame

The first step is to install the MonoGame framework from here. At the time of writing, 3.6 was the latest version. This was released over a year ago, so maybe that says something about the direction this game platform is going. I’ve heard a lot of rumours about Microsoft buying Unity (which I believe is ultimately based on MonoGame) so it’s odd that they wouldn’t want to take this over (especially given that it’s a fork of XNA).

Once you’ve installed MonoGame, in VS create a new project; you’ll be beset by MonoGame project types:

As you can see from the above code, we’re just moving a ball around the screen. If you installed this on a second machine, they would also be able to move that ball as well; at this stage, neither screen would be aware in any sense of the other screen. The next step is that we want to see the ball from the first screen on the second. We won’t mess about with collision, as this isn’t about the game, it’s about the Event Hub traffic.

The EventHub client library in the post mentioned above is for .Net Standard only, so we’ll need to use the Service Bus Client Library.

The basis of what we’ll do next is to simply take the current player position and send it to Event Hub; however, to cater for the fact that more than one player will have a position, we’ll need to identify it. Let’s start by creating a class to encompass this information:

I’ve taken this opportunity to replace the Vector2, which is a struct, with class members. Changing the data in structs can end up with strange behaviour… and in this particular case, it point blank refuses to let you, but gives a message that says it can’t recognise the variable.

Now we’ll need to re-jig the calling code a little to reference this new class instead of the player position:

EventHub

Let’s add the event hub code here. In this article, I discussed how you might deal with a situation where you’re trying to send non-critical data in rapid succession, using a locking mechanism. Let’s start by writing the code to send the message:

SendPlayerInformation is a fire and forget method. Generally, using await statements inside MonoGame can cause some very strange, and difficult to diagnose issues. The reason being that the premise of a game loop is that it executes repeatedly – that’s how the game keeps updating: the Update method allows you to rapidly change the state of the game, and the Draw method allows that state to be rendered to the screen. However, if you stick an await in there, you’ve returned control to the caller, and because none of the MonoGame stack works with the async / await paradigm, the result is that the entire loop waits for your task. In the Draw method, this will result in an obvious blip in the rendering; but in the Update method, the effect will be more subtle.

Other Players

The next step is to implement the listener. Again, this is slightly different when using the service bus libraries:

As you can see, there’s a bit of faffing to get this going. The code does seem a little convoluted, but essentially all we’re doing is finding any messages that were queued after we started processing (this is a very crude checkpoint), and then look for that Player Id; if we find it then we move it, and if we don’t then we create it. There’s also a little check in there to make sure we’re not processing echos!

As it stands, this only registers the clients on start-up, meaning that, whilst client 2 can see client 1, client 1 cannot see client 2.

As you can see, the player on instance one is replicated on instance two. Remember that it only starts broadcasting after movement, so the player will need to move to appear in the second instance.

In the next post, I’ll investigate the possibility of using a game controller to allow both clients to interact simultaneously (or at least be simultaneously visible).

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:

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.

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.

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:

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:

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.

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:

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.

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:

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:

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

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:

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:

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.

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.

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:

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);
}

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.

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.

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!

// 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.

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):

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):

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:

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):

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:

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.