XNA Game – Rotation – Discovering whether words have been made – Part 12

 

In this post I am going to go through the code that I have designed and written to detect if the player has made a word.  As stated in previous blog posts the player can make a word either vertically or horizontally.  The word has to have a minimum length.

The first thing that I needed to do was add a new property to the Square class CanUseInWord.  This is a bool that says whether that square can be used as a part of a word.  The reason for adding this is that I am currently thinking that I am going to have squares falling down from outside of the board, this will allow the player to see which squares will enter the board when they make a word.  I need a way to tell if the square can be used as a part of a word.  This will also allow me to put the game into a different mode that I have an idea about (more on that in later posts).  All of the squares that are selectable ie all of the ones that get filled with letters are eligible to be used in a word so currently I have set that property using the same logic.  I have obviously added a unit test for that in the board creation specs.

Next I need to design a collection to hold all of the possible words that the user can play.  This collection is hidden behind the interface IWordList which has one property Words which returns an IEnumerable<string>.  I have designed a factory to populate the word list, the default factory implementation populates the word list from a file.

Now that I can create a word list so I know all of the possible words a player can play, I need a way to check those words against every possible word in the board.  To do this I have designed an interface IWordChecker that has one method Check.  Check returns an IEnumerable<IWord> which is all of the words which have been found (if any) and it takes an IEnumerable<IEnumerable<Square>> (ie either all of the board’s columns or rows).  IWord is a simple interface that allows me to represent a collection of squares as a word.  It has two properties one which contains the string value that the list of squares represent and another which is the total value of those letters in points.

All of the above code is unit tested but I have left out the unit tests as they are straight forward.  If you wish to see them you can grab the code from github and check them out.  The interesting unit tests are the ones around checking for the existence of words in the board ie testing WordChecker.  I have designed 6 unit tests to do this:

1.  Check that if you have a set of squares that make a known word but all of the squares are squares in which the squares cant be used in a word then make sure that no words are returned.

2.  Check that a word is returned when a known word is in the list of squares that are passed in

3.  Check that two words are returned when two words are in the list of squares that are passed in (simulating two words being made in one row or column)

4.  Check that two words are returned when two words are in the list of squares and the words share letters e.g. HOUSEED should return HOUSE and SEED both words sharing the S and E

5.  Check that two words are returned when two words are in different lists in the lists of squares that are passed in (simulating that two words are made in two different rows or columns)

6.  Check that if there are no matching words in the lists that are passed in then no words are returned

To implement the code to check every possible word in the grid we first need to extract every possible word of a certain length.  We can do this with the following code

private IEnumerable<IWord> GetWordsOfLength(IEnumerable<Square> squares, int length)
{

    for (int i = 0; i + length <= squares.Count();  i++)
    {

        var currentWordSquares = squares.Skip(i).Take(length);

        if (currentWordSquares.All(s => s.CanUseInWord))
            yield return new Word(currentWordSquares);
    }
}

This private method works first by looping through all of the numbers from 0 to the total number of squares minus length of the words you are searching for.  Inside the loop the first thing we do is we skip to the starting square for the loop.  e.g. for the first iteration we will start at square 0.  The take statement then takes as many squares as we want this of course is the length of the word.  Next we check to make sure that all of those squares can be used in the word.  If all of those squares can be used in the word then we return that as a word from the grid.

public IEnumerable<IWord> Check(IEnumerable<IEnumerable<Square>> squares)
{
    var foundWords = new List<IWord>();

    foreach (var squareList in squares)
    {
        for (int j = GameConstants.MIN_WORD_LENGTH; j <= squareList.Count(); j++)
        {

            var words = GetWordsOfLength(squareList, j);

            foundWords.AddRange(words.Where(w => _wordList.Words.Contains(w.ToString())));

        }

    }

    return foundWords;
}

The method above completes the code for checking every word and passes all of the unit tests.  This code is pretty simple.  All we are doing is iterating around each list of squares ie basically looping around all of the rows or columns.  For each list of squares we loop around getting every word in that list of every length starting at the minimum word length and ending at the number of squares in the list (as obviously its impossible to have a word longer than that).  Once we have returned every possible word contained in that list all we have to do now is simply check to see if any of those words are in our word list and if so add them to the results.

That is all the code we need to implement word checking.  It’s good when a complex problem like this gets solved with a few simple lines of code.  It shows that we have broken our classes down and given them single responsibilities.  Because we have designed our unit tests upfront we have got confidence that our code works.  That is the beauty of TDD.

As always you can download the latest version of the code on Github.  Switch to the part12 branch to see the code at this point.  As always comments welcome.  Instructions on how to download the code from github or get in contact can be found on this page.

 

 

XNA Game – Rotation – Adding AutoFac IoC Container – Part 11

 

Now that I have the game starting to take shape (well that animations working and drawing the board) I have decided to put in an IoC container to get rid a lot of the custom wire up code, aka the following code block:

_board = new BoardFactory().Create();
var boardFiller = new BoardFiller(new StandardTileFactory(new LetterLookup()));
boardFiller.Fill(_board);

Func getMainSelectedSquare = () =&gt; _board.GetMainSelectedSquare();

var textureLoader = new TextureLoader(s =&gt; Content.Load(s));
		    _itemDrawerFactory =
		        new ItemDrawerFactory(new List
		                                  {
		                                      new SquareDrawer(
		                                          new TileTextureFactory(new List
		                                                                     {
		                                                                         new BlankTileTextureCreator(textureLoader),
		                                                                         new StandardTileTextureCreator(textureLoader)
		                                                                     }),
		                                          new SquareColourSelector(),
		                                          new SquarePositionCalculator(getMainSelectedSquare),
		                                          new SquareOriginCalculator(getMainSelectedSquare))
		                                  });

		    var itemAnimatorFactory = new ItemAnimatorFactory(new List {new RotationAnimator()});

            _animationEngine = new AnimationEngine(itemAnimatorFactory, _itemDrawerFactory, _board.GetAnimatables);

            _currentPos = new Point(4, 4);
            _squareSelector = new SquareSelector();
            _squareSelector.Select(_board, _currentPos.X, _currentPos.Y);

            _selectionRotatator = new SelectionRotatator();

I think you will agree that the above code is a bit long winded because of course we are providing all of the dependencies manually to every constructor.

The first thing that I want to do is write a module to install classes by convention.  By registering by convention I mean if I have an interface called ITest and it’s implemented by a class called Test then that class will get installed automatically as it’s name is the same as the interface without the leading ‘I’.

Registering classes by convention is a good thing to do as one of the main reasons we use dependency injection (other than to reduce coupling) is to allow easy unit testing of our components.  However, when we come to use these components in the application it can get a bit long winded to register all of them one by one.   I know most IoC containers support auto registration of all classes by scanning your assemblies but this is not what I want either.  The reason is that if I implement an interface with a class that I intend to always use as the implementation of that interface then I will give it a name so that it’s installed by convention.  If I intend to swap the component out then I will use a different class name so that I have to implicitly install it.  I know you can never really say that you will always use a certain concrete implementation of an interface but what I am saying is that for the foreseeable future that is the implementation I will be using.

The IoC container that I have chosen to use is AutoFac.  Mainly because I have quite a bit of experience with using Castle and AutoFac and I prefer the syntax of AutoFac over Castle.  For what I want to do with IoC any of the main IoC containers would do the job.

Ok so on with writing my module (that is the name of installers in AutoFac) to install classes by convention I need a unit test.  This is quite a simple test:

var container = default(IContainer);
var result = default (ITest);

"Given I have installed the instant convention installer with this assembly".Context(() =>
                 {
                    var containerBuilder = new ContainerBuilder();
                    containerBuilder
                        .RegisterModule(new InterfaceConventionModule(new[] { typeof(ITest).Assembly }));
                     container = containerBuilder.Build();
                 });

"When I resolve an ITest interface".Do(() => result = container.Resolve());

"Then the returned type should be a Test class".Observation(() => result.ShouldBeOfType());

The reason that my installer takes an array of assemblies is that it provides me with a neat way of choosing which assemblies to consider when installing by convention.  So when I am unit testing (as I am above) all I need to do is pass in the current assembly.  Obviously in the main code I will pass in all of the assemblies that I am using in the game. Implementing this installer is a pretty simple method:

protected override void Load(ContainerBuilder builder)
{
    builder.RegisterAssemblyTypes(_assemblies)
        .Where(t =&gt; t.GetInterfaces().Any(i =&gt; i.Name.TrimFirstChar('I').Equals(t.Name)))
         AsImplementedInterfaces();   
}

TrimFirstChar is a simple extension method that I have written on string that simply chops off the first character if the character passed in matches, if it doesn’t then it returns the string that’s passed in.

The only other thing to do is write a few installers to install the classes that haven’t been installed by convention.  The installers are pretty mundane so I won’t list them here, if you want to see them pull down the latest version of the code and view branch part11.

Now that we can install all of the classes that we need all we need to do is fire up the container in the program start method, resolve the RotationGame class and call run on it:

using(var container = new Builder().Build())
{
    var childContainerBuilder = new ContainerBuilder();
    childContainerBuilder.RegisterInstance(container).As();
    childContainerBuilder.Update(container);

    using (var game = container.Resolve())
    {
        game.Run();
    }
}

Pretty straight forward. Now in our game we can specify all of the dependencies in the constructor and AutoFac will do the rest.  Nearly all of the first block of code can be removed 🙂

In the future I want to use the IoC container to swap out some of the components to make the game more difficult as the player progresses. This means that all of my code should stay the same and to progress levels all I should have to do is register different classes with the container. That’s the plan anyway for a later post.

As always if you want to get the latest version of the code you can do so from github, I have marked the code at this point as part11.

XNA Game – Rotation – Implementing the rotation animations – Part 10

 

Now that I have the graphics plumbed in the next step is to start to implement the rotation animation (after all that is what the game is named).

Before I go into how I have implemented the animations, a quick word about what has changed in the solution.  I have tidied up some of the code.  Firstly I have put the code that gets the textures for the drawable items behind a factory, this allows that code to be abstracted away.  Next I have introduced a constants class.  This class is responsible for setting different things like the colours of the tiles, by having a constants class I have one place in which I can tweak the game.  Obviously being a constants class all of these variables get compiled into the code.

Last post I naively stated that I was doing a lot of redundant drawing by redrawing every single item for every single frame.  I have since read that this is the way that the XNA framework works.  Normally it is more efficient to just redraw everything in a frame rather than calculate what has moved and just redraw that.  This makes sense, but means that I’ve had to go a slightly different path as to how I am going to do the animations.

When the player presses a button to rotate the squares this key press gets picked up in the update method.  Then the rotate right or left method is called on the square rotator and the squares are updated instantly in the board in memory.  This means that the next time the draw method gets called (i.e. a maximum of 1/60 of a second away) the board will instantly get redrawn with the tiles in the new position.  This is not what we want.  We want the tiles to animate round and finish in their final resting place in a smooth animation.

The way that the XNA framework implements rotations is in one of the overloads to the spritebatch’s draw method.  The overload takes a vector to represent the sprites position in space, a vector for the origin of rotation and a float for the amount of rotation in radians.

With the above knowledge of how the XNA framework handles rotations the trick to get our animations to work is to change the way that we draw our sprites for the tiles on the board.  The first implementation that we saw in part 9 just looped round all of the tiles and drew them at a specific point in space i.e. the first tile was drawn at 0, 0 the next at 40, 0 (40 being the width of a tile) and so on.  What we need to do is change this and use the overload of the draw method.  Except that we need to specify a position of the centre of the currently selected square, an origin of the offset from the currently selected square back to the point in space where we want to draw the square and a rotation of 0 degrees (for now).

For example when the centre square is selected (as is the default starting position) we set the position of the top left square to 180, 180 which is the exact centre of the selected square (tile).  A square is 40×40 so its 4.5 squares to the centre in both directions (4.5×40 = 180).  Next we need to get the offset from this point back to the top left corner of where we want to draw the square and pass that in as the origin.  In this case it’s -180, -180.  Obviously the degrees of rotation is 0.

To calculate these values I have introduced two new classes SquarePositionCalculator and SquareOriginCalculator.  These classes both have one method and are responsible for calculating a square’s position and a square’s origin respectively according to the currently selected square.  To see the full unit tests and implementation of both of these classes see the source code.  Now we have these classes all we need to do is inject them into the SquareDrawer class and call them to get the vectors out for when we draw the square.

Now that we have overcome that obstacle all that is left to do to animate the selection is to wrap the draw method with something that works out which squares are selected and slowly changes the angle of rotation.

To do this I have setup some new interfaces.  Firstly I have change the IDrawableItem to IAnimatableItem as for now everything that is animatable is drawable so IDrawableItem became redundant.  One might argue that I could need IDrawableItem again in the future.  That is true and if I need it again then I will add it back in.  But I don’t like leaving dead code hanging round in case I might need it in the future.  Doing this leads to code smell and can mean when people look at the code in the future they have a hard time following it when there are unused methods and classes all over the place.

The next interface that I need to define is a type of animation.  For now there is only one type of animation a rotation animation, the interface I have defined is IRotationAnimationItem that has two properties a direction (clockwise/anti-clockwise) and an angle of rotation (I’m going to work in degrees as I find that easier than radians and I can simply convert this before I call draw).  IRotationAnimationItem also implements the IAnimatableItem interface (obviously as if an item supports the rotation animation then it is obviously animatable).

To get the animation for the current item I have again used the factory pattern.  I have defined an interface IItemAnimator that has two methods CanAnimate and Animate.  This pattern is almost identical to how the item drawers worked.  I have a factory class that takes the currently animatable item and returns a collection of animators that can animate all of the animations applied to the current animatable item.  Then I loop around the animators and call animate on each one.  For now obviously I only have one item animator the RotationAnimator.  This class simply checks the direction of the item to see if it is currently being rotated.  If it is then it checks the direction and either increments or decrements the angle by the amount defined in the constants class.  Defining the amount in the constants easily allows me to tweak the animation speed.  If we are incrementing the angle and we head above 0 then we set it to 0 and set the direction to none and vice versa if we are decrementing the angle.

Next we have to update the SquareRotation class so that the left and right methods also set the direction and angle of rotation.  So when the user rotates left it sets the direction to anti-clockwise and the angle to 90 degrees.  Obviously we need to update the SquareRotator unit tests to check this.

Now that we have all of those pieces in place it is simply a matter of calling them once per frame and voila we have animations.  I have moved all of the code for animating and drawing the items into the AnimationEngine class.  This provides a nice clean wrapper for getting all of the animatable items, applying all of the animations and then finally drawing them all.  It also helps to keep the code in the game class nice and clean.

The game is starting to take shape.  If you want to get the latest version of the code then simply get the latest version from the github repository and checkout the part10 branch.  For details of how to do that see this page.

XNA Game – Rotation – Starting the Graphics – Part 9

The next stage in the game is to plumb in the graphics and start to link up the XNA game so that it initialises and draws the board.

When you create a new XNA game project in Visual Studio it creates you a game class that inherits from Microsoft.Xna.Framework.Game.  This class gives you the basic game pipeline that you can easily add your code into.  Below is a listing of the class (with the methods that we are interested in).

public class RotationGame : Microsoft.Xna.Framework.Game
{
    protected override void LoadContent()
    {
    }

    protected override void Update(GameTime gameTime)
    {
    }

    protected override void Draw(GameTime gameTime)
    {
    }
}

Here is an explanation of what the methods are for:

LoadContent: where you put all of your code to initially load all of your graphics that you are going to need in the game.  I believe that the XNA framework behind the scenes loads your content into RAM providing fast access during the game.

Update: where you put all of your game logic.  This method is for updating the state of the game, reading inputs from the user and reacting to them.

Draw: where you put all of your code to draw the graphics onto the screen.

The first thing that I had to do was create a tile graphic that I can draw onto the screen.  I made a design decision to make all of the tiles in the game 40 pixels by 40 pixels.  I then cracked open paint and created a tile for every letter, a blank tile and a tile that can never contain a letter.  When naming the files I gave each letter a standard name which was StandardTile + LetterName ie for C the file name is “StandardTileC”.  The reason for this will become apparent later.

As I’m now starting to use the XNA framework to make my game come alive, I am conscious of the fact that I don’t want to couple the game to the XNA framework.  My goal is to have a clear separation.  What I ideally want is for the game logic and libraries to expose a set of interfaces to send inputs to and receive outputs from.  This way I can plug in an implementation for the XNA framework for now and in the future it should be more straight forward to use something like Mono Touch so I can bring the game to the iPhone and iPad.

To move towards the end goal of not tying myself to the XNA framework I have added a new class library called Rotation.Drawing.  The rule of thumb for now is that any class that references the XNA framework goes into this class library.  This way I am forced to think about separation as I go along and it will make it easier to clearly see what needs reworking to make the code even more loosely coupled.

My idea to keep the code loosely coupled is to have an interface class IDrawable item.  Any class marked with this in the main library is drawable and needs drawing on the screen.  At the moment I am only concentrating on drawing the squares of the board so I have marked the Square class as IDrawable.  I have designed another interface IGetDrawableItems.  Any class that implements this provides a way to return a collection of all of its drawable items.  The Board class implements this interface and simply returns all of it’s squares.

Now I have a way of easily extracting out all of the classes that need drawing, I need a way of drawing them to the screen.  To do this I have another interface IItemDrawer.  This interface has two methods on it CanDraw and Draw.  The idea is to have an implementation of this interface for each type that I want to draw.  The implementation will return true for CanDraw for the type that it can draw and implement draw to draw that item to the screen.

As the only drawable item I have at the moment is a square, I have just implemented the square item drawer.  The square item drawer draws the square and tile to the screen.  Remember when I said that I named the tile images using predictable file names, well the reason for that is that the square item drawer can get the current tile and use that to build the file name of which letter to draw onto the screen.

I am using the factory pattern to create my ItemDrawers.  I have a factory called ItemDrawererFactory that is responsible for choosing the correct item drawer based on the drawable item that you give it.

All of this means that the basic work flow for drawing the board is:

1.  Call get drawable items to get all of the things that we need to draw

2.  For each drawable item call the ItemDrawerFactory to create us an Item Drawer for that item

3.  Call draw on the Item Drawer passing in the drawable item

That’s it!  I love the way by using patterns and keeping our classes simple and focused you can implement powerful solutions in a few simple steps.

To get a board to draw on the screen all we need to do is plug all of the classes together that we have designed so far to spin up a new board and fill it with letters.  Here is the code:

_board = new BoardFactory().Create();
var boardFiller = new BoardFiller(new StandardTileFactory(new LetterLookup()));
boardFiller.Fill(_board);

Then we just need to implement the workflow detailed above the get the item drawers and draw each item, to do that the first bit of code to get the drawables (step 1 in the work flow) can go in load content as for now it only needs to be called once.  Here is the code:

_itemDrawerFactory = new ItemDrawerFactory(new List&lt;IItemDrawer&gt;{ new SquareDrawer()});
_drawableItems = _board.GetDrawables();

Now all that needs to be done is implement steps 2 and 3 of the work flow in the Draw method of the game:

foreach (var drawable in _drawableItems)
{
    var drawer = _itemDrawerFactory.Create(drawable);
    drawer.Draw(spriteBatch, _textureLoader, drawable);
}

For now I am using manual constructor injection rather than using an IoC container just to get things up and running.  

Well it’s certainly a start but I think the designers out there will definitely be sleeping easy!  Pretty cool to finally see my vision for the game being rendered onto the screen.

At the moment the code to fire things up is hard coded, clunky and not optimal.  The main purpose of this post was just to get the graphics being drawn to the screen.  The other thing I don’t like is that the draw code is being called every frame (60 times per second) for every square (all 81 of them) even though they aren’t changing.  It would be nice if draw was only called if that part of the screen needs updating.  I have a really cool idea for how to implement that but that’s for a future post so stay tuned.

As always you can get the source code down it’s on github.  I have also marked this post with branch name part9, so if you are reading this in the future you can switch to that branch to see what I was up to at this point. Git commands to do so are:

If you don’t have the source code:

git clone git@github.com:kevholditch/Rotation.git
git checkout -b part9 origin/part9

If you have the code on cloned already then issue the following git commands:

git fetch
git checkout -b part9 origin/part9

As always comments & suggestions invited, until next time…

XNA Game – Rotation – Rotating square selection – Part 8

 

Today I started to work on the part of the game where Rotation gets it’s name from.  That’s right, the square rotation classes.

I got to the point where I had to make a few key decisions about how the game was going to work.  A lot of the operations in the game happen to the board like selecting a square, filling the board, rotating the board.  There were 3 ways that I could’ve gone with the infrastructure:

  1. Added all of the methods directly onto the board class & interface
  2. Added a bunch of extension methods onto the board interface
  3. Added a set of interfaces that have methods that manipulate the board

Let’s evaluate the options that I could’ve taken in turn.  Firstly option 1, adding the methods directly onto board.  This would’ve left me with board having methods like:

board.SelectSquare(int x, int y);
board.RotateSelectionLeft();
board.Fill(IBoardFiller boardFiller);

The thing that put me off this approach is that board would’ve very quickly become a monolithic beast.  I am always very wary when a class gets bigger than what can comfortably fit on a screen or two.  The other reason why I was put off this approach was the fact that it tied the implementation of board to how squares are selected, selections are rotated etc.  So if in the future I just wanted to change dynamically the way squares are rotated this would’ve been difficult.

Option 2 solves the problem of being able to swap out a piece of functionality e.g. how tiles are selected as I can just reference a different extension method with the same signature (although obviously this is tricky to do at runtime).  But extension methods don’t feel right in this situation either as they are really meant to extend classes that you don’t have access to or they can be used to extend classes to make unit testing easier but it may not be appropriate to include that code in production.  So they don’t feel right in this situation either.

So I’ve gone with option 3, providing a set of interfaces that manipulate the board.  I have defined an interface for selecting squares on the board, rotating them etc.  By doing this each interface (and class that implements it) is very small, concise and has a single responsibility.  The interface for rotating the board for example is defined as follows:

public interface IBoardRotator
{
    void Left(IBoard board);
    void Right(IBoard board);
}

I can now test each of the components on their own and dynamically swap them out very easily later on if I want to change game behaviour in later levels or for a power up or whatever.

To implement rotating a square selection left or right I needed to have the board in a known state.  To do this I built an alphabetical board filler that fills the board (yep you guessed it) in alphabetical order.  I have added unit tests for the alphabetical board filler even though it is only used in my unit tests.  This is an important point as if I am going to be using the alphabetical board filler to set the board in a known state then I had better be sure that the board is in the state that I think it’s in.  This is something that really frustrates me in code that I see in the outside world (but that is a rant for another day).

Once I know that the board is going to be in a known state it is a pretty trivial job to write unit tests for rotating a square selection left or right.  If you want to know what the board looks like visually before and after a rotation see this earlier post.

Here is the psuedo code for implementing rotating a square selection right

  • get centre square selection coordinates
  • set numSqures to 1
  • while a square is selected and exists in all directions of the centre square selection coordinates
  • do loop->
  •     move the tile numSqures squares up from the centre of selection to numSqures squares right of selection
  •     move the tile numSqures squares right from the centre of selection to numSqures squares down of selection
  •     move the tile numSqures squares down from the centre of selection to numSqures squares left of selection
  •     move the tile numSqures squares left from the centre of selection to numSqures squares up of selection
  •     increment numSquares
  • end loop

Quite a simple algorithm.  But again the key to making this easy is by writing our tests first.  This gives us the confidence that the code is working when we write it.

To get the version of the code as it was at the end of this post issue the following commands:

If you don’t have the source code:

git clone git@github.com:kevholditch/Rotation.git

git checkout -b part8 origin/part8

If you have the code on cloned already then issue the following git commands:

git fetch
git checkout -b part8 origin/part8

As always comments & suggestions invited, until next time…

XNA Game – Rotation – Moving to github – Part 7

 

When I first created my repository I forgot what was important.  I thought that it was important to have control of the branch and only allow one private contributor.  I’ve realised that the whole point of this project is to talk through developing an XNA game, the mistakes, triumphs and all.  So I’ve decided to setup a new repository on github and move over there.

The github repository can be found at git@github.com:kevholditch/Rotation.git.  What I am going to do is make a new branch at the end of every blog post so that you will be able to clone/fetch down the repository and then switch to that branch to see what I was thinking at that time.  It would be great to get feedback!

To get latest and switch to the branch issue the following commands:

git clone git@github.com:kevholditch/Rotation.git

git checkout -b part7 origin/part7

The first command will clone the repository.  The second command will create you a new local branch called part7 and set it to the location of origin/part7.

If you have already cloned the repository then instead of the clone command use “git fetch”.

So from now on you know where to find the repository, I look forward to your comments.

XNA Game – Rotation – Knowing when you’re wrong – Part 6

Sometimes in programming you realise that you have made a wrong turn somewhere. Often the first signs are the fact that changing one part of the code breaks everything or doing what should be the simplest thing becomes very difficult. I realised that my rotation game source code had taken one of those turns.

I was modelling the board literally. As described in my previous post.  Each row was modelled as an array of squares.  The top row had one item in the array, the next row had three items in it’s array etc.  The problem with modelling the board in this way became apparent when I got to trying to write the code to rotate letters or move the user’s selection around.

The trouble with modelling the board this way as that what should be simple movement on the board ie moving up one square, is very tricky.  To calculate the new row and column index to move the selection up one square is a matter of recalculating both of the row and column indexes due to their being a different number of squares in each array that represents a row or column.

To get around this problem I’ve decided to rewrite the code so that the board is represented as a square of squares ie each row and column has the same number of squares in.  Then I can model the selectable squares that make up the actual usuable board by setting a property on those squares.  This way, although I’ve got a small amount of redundant objects, the algorithm for moving around the board is simplified massively.  To move the selection up one is simply a matter of taking one from the row index (the column index will stay the same), simples!

Although this was about an hour or so’s work to do the rewrite, I am sure that it will be well worth it in the long run, especially when I come to tackle the algorithm around rotation.  Dread to think about that with the way it was modelled before.

The message that comes out of this episode is that if you find yourself fighting against your code, don’t be afraid to stop and work out why.  Then if you can go back and change it.  In the long run you will be glad that you did.

 

 

XNA Game – Rotation – Mapping out the main game objects – Part 5

This will be the first blog post where I will upload the latest version of the source code.  Giving you the chance to look through what I’m doing.  Before we get to that I’m going to list out the main objects in the game and what their purpose is:

Letter – Represents a letter at it’s lowest level, it is essentially a character and it’s points value

Tile – A tile contains a letter, I picture a tile like a tile in the game of Scrabble

Square – A square is a position where a tile can be, in terms of Scrabble again there are many squares on the board each of which can contain a tile.

Board – A collection of squares (and their position relationships) with one another

The first objective is to work out how we can build a board.  At the moment we are only talking about building the board in the sense of the relationship of the objects in memory not how the board will be drawn graphically (we will handle graphics in a later post).  In case you have forgotten here is what the board looks like:

board

Before we dive in and just model out the board we need to think a little into the future as to how the game is going to work.  When finding which words have been made we will need to have a way of extracting all of the letters that are next to each other both horizontally and vertically.

To do this we need a way of modelling rows and columns.  A row is simply a list of a list of squares and a column is the same.  So we can define to properties on Board to be:

public List<Line> Rows { get; private set; }		
public List<Line> Columns { get; private set; }

Where Line is essentially a wrapper class that is a List<Square>.  Now looking at how the board needs to be we can write some tests to assert those facts.  Firstly we need a test to assert that we have the right number of squares in each row and column.  Row 1 should have 1 square, row 2 should have 3 squares etc.  And the same can be said for columns.

The second test for a successfully created board is that the instance of a square is shared between the row and column.  This is most important.  By using both rows and columns we are really storing redundant data.  Technically using only the information in the Rows collection we could ascertain everything we need to (and the same can be said for Columns).  The reason that we are using two collections is to make evaluation much easier for ourselves later due to the shape of the board.

So to test that the Rows and Columns collections point to the same set of tests we need to setup a board and then simply test each square in each row is the same as it’s corresponding square in the column.  E.g. the first square in the first row should be the same as the first square in the fifth column.  See the BoardCreation.cs file for the complete tests.

Now we have the tests we need to go about implementing them and making them pass.  To create a board we are going to use a BoardFactory.  The board factory will be responsible for setting up a board in a good state.  By using the factory pattern we can easily swap out this factory we are about to write for a different one in later levels of the game for example.

To implement the BoardFactory we are going to need two loops (there is probably a way to do it with one but that just melts my mind to think about).  The first loop is responsible for creating the rows.  This is relatively simple (view the source code to see the implementation of this).  The harder part is the second loop the one that’s looping around the rows and creating columns for the same squares.

We are going to create the columns from left to right.  What we are doing for each column is selecting out the square from the rows collection and adding it to the column collection.  The key thing here are the two sequences that we need to correctly iterate around the row collection to select them into the column collection.  The first sequence that we need it to iterate around the correct row.  If you look at the board the first column needs one square from the 5th row.  The second column needs three squares from rows 4, 5 and 6.  The third column needs 5 squares from columns 2, 3, 4, 5 and 6.  Hopefully a pattern is emerging by now.  Back to our tests we need to create RowIndexSequenceGenerator class that is responsible for creating this sequence.  You can see the class and full tests for it in the code.  The other sequence that we need is one to loop around the square index in the row.  The first column needs square index 0 (from row 5), the second column needs square index 0 (from row 4), 1 (from row 5) and 0 (from row 6).  The third column needs square index 0 (from row 3), 1 (from row 4), 2 (from row 5), 1 (from row 6) and 0 (from row 7).  You can check out the full implmentation for the class and specs in the LineIndexSequenceGenerator and LineIndexSequenceGeneratorSpecs respectively.

Once we have both of these sequence generator classes the second loop becomes much easier.  A problem like this highlights how much TDD can help you.  We had a relatively tough problem in getting the second loop right.  This was made so much simpler by breaking it down into smaller components and writing tests for them.  Then when we put them all together to function as a whole it works first time.  Simples.

Download the code so far from here. Feedback welcome on the code or if you have any questions let me know.

XNA Game – Rotation – A small tangent – Part 4

 

Before I continue on the journey of developing my XNA game Rotation, I’m going to take a small tangent on continuous testing.  Inspired by talking to a few of my colleagues at easyJet and from listing to this Herding Code podcast.

The basic premise of continuous testing is that it allows you to streamline your workflow and concentrate on writing tests and writing code, not having to stop and keep running tests.

Consider this TDD workflow which I follow:

1. Write tests (that fail)
2. Stop and run tests
3. Write code
4. Stop and run tests
5. Refactor code

A continuous testing tool gives you is that automation of running your tests every time you make changes to your code and then giving you feedback as to the status of your tests.  This means that your workflow becomes:

1. Write tests
2. Write code

The fabulous tool nCrunch will revolutionise the way you write code.  I’ve only been using it for about a week and already it’s made a big difference.  If you are into your TDD/BDD development (which you should be) then this tool is definitely worth adding to your toolbox.  Above all it’s free at the time of writing so you’ve got no reason not to give it a try.

XNA Game – Rotation – Designing the first game objects and tests – Part 3

I’m really into my TDD. It gives you direction. TDD is good if you write meaningful tests that test the intention of your code. Far too often (and I’ll try not to go down too much of a tangent here) I see developers writing test code like this:

var obj = new MyObject();
Assert.IsNotNull(obj);

Tests like this achieve nothing. You are testing that the CLR is doing it’s job.  A test needs to capture the intent of an object (or set of objects) and how they are meant to function together. A well designed test makes writing the code much simpler. One could argue that this is BDD, in my eyes the line between these two is quite blurred (let’s not go down that avenue).

The first two classes that I need to define are a letter (which will simply represent a letter and a value) and a collection of letters that holds a collection of all possible letters.

This first class

public class Letter
{
	public Letter(int points, char value)
	{
		Points = points;
		Value = value;
	}

	public int Points { get; set; }
	public char Value { get; set; }

	public bool IsVowel
	{
		get { return false; }
	}
}

This defines the letter class.  The letter class pairs a char with a value and adds an extra property so that we can tell if the letter is a vowel.  Strictly speaking I suppose we shouldn’t add this property just yet as we have no need to know if a letter is a vowel but thinking ahead to board composition (and checking if the game is playable) we will do.  The next class I need is a lookup collection of all of the possible letters:

public class LetterLookup : ILetterLookup
{
	private IEnumerable&lt;Letter&gt; _letters;

	public IEnumerable&lt;Letter&gt; Letters
	{
		get { return _letters; }
	}
}

As you can see this class returns an IEnumerable.  Where possible it’s best to return the least constricting type possible.  The purpose of this class is to be a static collection of all of the possible letters and their values (a master list if you will).  Notice that I’ve extracted an interface (ILetterLookup).  This gives me better de-coupling as all of the classes that I will write later on that need a list of letters (LetterLookup) will only need to depend on the ILetterLookup interface.  Meaning that I could potentially swap out the list per level or mid game quite easily for example.

Now to write our first test.  Rather than list out all of the code for the test I’m going to just write them in the Given, When, Then syntax:

Given I have a letter lookup interface

When I create the interface

Then I should have 26 letters

And all of the letters should be different

This test is clear in it’s intent.  You could look at this test for the first time and it would be obvious what the letter lookup class does.  It holds letters, there are 26 of them and each of them should be different.  For my unit testing framework I’m using sub spec.  Created by Phil Haack (amongst others) it’s built on top of xunit and uses extension methods on string.  This means that you can write your tests in the following way:

"Given I have something".Context(() => {/*context here*/});

"When I do something".Do(() => {/* do stuff */});

"Then I should see a result".Observation(() => {/* assert stuff */});

What I like about this syntax it is clean and readable.  There is not much fluff getting between you and what the test is trying to achieve.  As an aside for the Then step you can use Assert or Observation.  The difference being that Assert will re-run you context and do statements for each assertion (which I guess is the way it should be) and an observation will observe the result and then the next observation will run on the same result without re-running the context and do steps.  I make a point of not altering my result in my observation step (something you should never do) so using observation simply speeds up my tests.

We can now run this test and see that it fails and then go ahead an implement it.  Implementing it is as simple as creating a list of all of the letters in the constructor of LetterLookup and returning it through the Letters property.  Now we can re-run the test and check that it passes, bingo our first green light.

Next time I’m going to talk about how the rest of the game objects fit together plus a look at NCrunch a fabulous continuous testing tool and publish a first edition of the source code.