Marbles

Marbles game for Windows 8

Finally my first Windows 8 game called Marbles is finished and available in the Windows Store!

That partially explains why i did not wrote any posts on this blog for almost a year :)

It’s been emotional!

Seriously, it has been quite a journey.

First i was learning XNA, then Monogame, and then game development in general.

I always wanted to write a game (aren’t we all?) so finally i decided to really do it!

At first i started very enthusiastically and tried building a 2d platformer game, and after solving most of technical problems like character and level rendering and physics i sadly realized that there is no way i will be able to complete it alone without help of level designer and gfx artist, sfx artist etc.

Since i was a one man band that meant this game is not gonna happen…

Just for the record, here is the video of that unfinished game – be warned it was just a early prototype.

So eventually after months of work i got real and abandoned that idea and started from scratch.

I realized that if i want to get anything done i need to start small and build simple game and this is how idea for Marbles was born.

Along the way I discovered that developing games is very much unlike writing other software applications.

When you are running at 60 FPS then every byte counts, every loop is considered not necessary until proven otherwise and every operation needs to be fast or its out!

But writing games is very fun so i enjoyed (almost) every moment of it :)

Monogame is for real!

I must say that guys from Monogame team did excellent job and gave XNA another life.

Once you get past initial problems like how to setup environment or how to make the Content Pipeline working you are already making games and Monogame tries to help without getting in your way – just as i expected it.

Forums on the Monogame Codeplex site are very helpful and if you post your questions there you are almost sure to get some answer.

Forget Class Inheritance!

Another interesting thing i discovered on this bumpy road is the Entity Component System pattern.

After struggling some time with class inheritance for the game, i realized that there has to be better way so i started researching and found out that many people are writing games using Entity Component Systems.

I wrote small Entity Component System framework for my game and it worked much better then deep class inheritance approach so i definitely recommend it to any aspiring game dev out there.

If you want to see how real world Entity Component System for game development looks like check out for example Artemis its quite stable framework.

To the future… And beyond!

So now that i wrote a game, i can proceed to my next task – learn how to play drums!

Ok seriously, whats next?

Probably i will soon write some Monogame tutorials on this blog to help beginners that are struggling with typical problems that every game has to solve.

Especially on how to setup Content Pipeline and how to easily do Resolution Independence – the holy grail of Game Programming :)

So what else can i say then – stay tuned and in the meantime check out my game and send some criticism or at least few bug reports ;)

msdn-logo

Dot Net Gotcha #2 – Loop variables and Closures

This one is my favorite.

Can you guess the output of this simple console application:

    class Program
    {
        static void Main()
        {
            var actions = new List();

            for (var i = 0 ; i < 10; i++)             
            {                 
                var writeToConsoleAction = new Action(() =>
                    {
                        Console.WriteLine(i);
                    });
                actions.Add(writeToConsoleAction);
            }

            foreach (var action in actions)
            {
                action();
            }

            Console.ReadLine();
        }
    }

One would expect to see numbers from 0 to 9 but here is the actual output of the app:



OK that’s strange right?

It turns out its like that by design. What you have there is a Closure over the loop variable. And closures in C# are done around variables and not around specific values of those variables – so that means that lambda expression gets to use the actual reference to the closed variable.

Let me explain in little bit more detail:

In first loop we iterate increasing the counter variable from 0 to 9 and then use it in the lambda expression. That means each lambda gets its access to the counter via closure.

So at the end of this first loop, value of the counter is 10 (its 10 because we used post-increment operator: counter++, so in last iteration of the loop we increase counter to 10 and then check if its <10 and we see its not, so we exit the loop).

Afterwards we start executing those actions we created in first loop, and they all have a Closure over this same variable counter – which has value of 10 and therefore each action prints out its current value 10 to the console.

So it works as expected, once you know what to expect. :)

And this is really common mistake C# developers make.

How to fix it?

Solution is very simple once you know what is going on. All we need to do is this: instead of passing the variable counter to the lambda expression, create a local copy of this variable and pass this copy to the lambda instead of passing the counter.

That way, closure will each time be done around that copy variable that has current value of counter at that moment of execution, and this local copy value stay that way and will not be changed afterwards by the loop.

Later when the actions are executed (in the second loop), each will use their own closure around copy of the counter and therefore each will have its own different, expected value.

Here is the code that works as we expect:

    class Program
    {
        static void Main()
        {
            var actions = new List();

            for (var i = 0 ; i < 10; i++)             
            {                 
                    int counterCopy = i;                 
                    var writeToConsoleAction = new Action(() =>
                    {
                        Console.WriteLine(counterCopy);
                    });
                actions.Add(writeToConsoleAction);
            }

            foreach (var action in actions)
            {
                action();
            }

            Console.ReadLine();
        }
    }

As you see we create a copy of counter called counterCopy and pass this to the lambda expression each time.

Although this seems like old news if you knew it, there are many C# developers that are not aware of this behavior (or tend to forget it from time to time) so make sure to spread the word and always remember it.

By the way, the C# team is changing this in C# version 5 to work as one would expect but until then we just need to copy those loop variables manually :)

msdn-logo

Dot Net Gotcha #1 – List versus Collection constructor

Don’t Google it!

Do you know (without Googling it) what will this console application display when executed?

    class Program
    {
        static void Main(string[] args)
        {
            var originalNumbers = new List<int> { 1, 2, 3, 4, 5, 6 };

            var list = new List<int>(originalNumbers);
            var collection = new Collection<int>(originalNumbers);

            originalNumbers.RemoveAt(0);

            DisplayItems(list, "List items: ");
            DisplayItems(collection, "Collection items: ");

            Console.ReadLine();
        }

        private static void DisplayItems(IEnumerable<int> items, string title)
        {
            Console.WriteLine(title);
            foreach (var item in items)
                Console.Write(item);
            Console.WriteLine();
        }
    }

If you try to think logically, you expect that both List and Collection will contain numbers from 1 to 6 when they are displayed, right?

Wrong, otherwise this would not be a proper gotcha ;)

Here is the actual output of the application (surprise, surprise):

Do you know why?

Answer is actually very simple. If you check the MSDN documentation for Collection constructor that accepts generic IList you will see this text:

Initializes a new instance of the Collection class as a wrapper for the specified list.

That means that this constructor creates just a wrapper around the existing IList, so adding or removing items to the original list will also affect the new Collection we just created,  because its just a wrapper and uses original List under the hood.

On the other hand List constructor that accepts IEnumerable<T> behaves properly and does what you would logically expect it to do:

Initializes a new instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied.

So when you create a new List and pass an existing List to its constructor it will create a proper new empty list, and then copy all the references from original List to the new List.

Because of that, the new List is ‘detached’ from the original and this is why it remains unchanged even if we modify the original List.

Moral of the story

This is simply how Microsoft made these two classes (i would not say its very consistent or good but who am i to judge, right?) and as long as you know it – its fine.

And if you don’t know this – it can bite you really hard.

All that you can do is to try to remember this, and also: RTFM.

Btw, did i said that this can be an excellent job interview question?   ;)

Until next Dot Net Gotcha, keep reading those manuals…

Windows-Phone-7-logo

Another way to close Windows Phone application from code


Correction

In my previous post on how to terminate the Windows Phone application i proposed a solution that is not really in accordance with Windows Phone Marketplace Technical Cerification Requirements (see requirement 5.1.2):

” An application that closes unexpectedly fails certification. ”

Even though I’m pretty sure that this requirement is not enforced since my apps use this approach and they were never rejected i decided to present another way.

Some good people suggested in comments of my previous post that you can terminate current application  simply by calling the XNA Game class Exit method like this:

using Microsoft.Xna.Framework;

namespace Roboblob
{
    public class AppLifetimeHelper
    {
        public void CloseApplication()
        {
            new Game().Exit();
        }
    }
}

The downside of this is that you need to add 2 XNA dll’s to your project:

  1. Microsoft.Xna.Framework
  2. Microsoft.Xna.Framework.Game
So there you have both approaches and you can choose which one is better for you until Microsoft exposes standardized way of closing application from code (i hope this will happen in Windows Phone 8 APIs).