Xamarin App Development: How to Build Portable Games

Xamarin App Development, Writing Mobile Games

I recently read an article on the mono project’s blog about the “Wordament” game developed by a Microsoft team, and how they used Xamarin to ship the mobile app to Android and iOS platforms, with the code that is 80% shared.

Wordament can be compared to any common application: it is made with common controls as buttons, displays a lot of text, etc. But most of the mobile games do not look like this. Most of the games make large use of image drawings, musics, sounds and 3D, etc. In this article, we will see how it is possible to write traditional games using Xamarin, and with levels up to 90% of the shared code base, by developing a simple tic tac toe mobile game.

Presentation of the Monogame framework

Microsoft first released the XNA framework [1] in December 2007, which gives developers the possibility to make games targeting both PC and XBOX 360. This framework has seen a lot of improvements and new features and final version was released on 31 January 2013. Meanwhile, the Monogame [2] project appeared to port XNA framework to the Mono framework. This open source project is actively maintained, and is compatible with Xamarin, allowing developers to target a large amount of systems, including Windows, Linux, IOS, Android, Ouya [3] consoles, and many more.

Setting up a Monogame project

Our project will be split in 2 distincts parts:

1 – Minimal platform specifics projects
2 – Shared game logic in a Portable Class Library [4] which can be referenced within our specifics platform projects.

First, you have to download the Monogame installer from the official website.

Then, we will create a Portable class library project, which will contain all the game logic:

Xamarin Mobile App development, games

Then create monogame projects for our target platforms

Create monogame projects resized 600

At the end, your solution should looks like this:

Xamarin solutions preview resized 600

Writing the specific code

Each target platform must ship with a Game.cs file, which will init the specific parts for the device (graphics, sounds, etc…), and delegate all the logic to our PCL project.

As you can see, each project comes with a Game.cs file. This class has 3 key methods:

protected override void Initialize ()
protected override void Update(GameTime gameTime)
protected override void Draw(GameTime gameTime); 

We will use the initialize methods to instantiate our TicTacToeGame class from the PCL core, and initialize it with the screen dimensions so we can scale and locate our images on the screen whatever the resolution of our device is.

protected override void Initialize ()
{
          base.Initialize ();
          var screenHeight = graphics.PreferredBackBufferHeight;
          TicTacToeGame.Init(graphics.PreferredBackBufferWidth, graphics.PreferredBackBufferHeight);
}

Then, we will use the Update override to get the inputs from the player:

protected override void Update(GameTime gameTime)
{
          var touchCollection = TouchPanel.GetState().Where(x => x.State == TouchLocationState.Pressed);
          foreach (var touch in touchCollection)
          {
                    {
                              foreach(var cell in column)
                              {
                                        if (cell.Collide (touch.Position.X, touch.Position.Y, cell.Size, cell.Size))
                                        {
                                                  TicTacToeGame.CellClicked (cell);
                                         }
                               }
                      }
            }
}

And finally, draw our game’s images to the screen:

protected override void Draw(GameTime gameTime)
{
graphics.GraphicsDevice.Clear(Color.CornflowerBlue);
          spriteBatch.Begin();
foreach (var column in TicTacToeGame.Board)
{
          foreach (var cell in column)
          {
                    //Draw the table background
                    priteBatch.Draw(Square, new Vector2(cell.PositionOnScreenX, cell.PositionOnScreenY), Color.White); 
                    //Draw the table border
                    DrawBorder(new Rectangle(cell.PositionOnScreenX, cell.PositionOnScreenY, cell.Size, cell.Size), 2, Color.Black); 
//Draw an image if a player has made a move in the cell
                    if (cell.Move != Player.NOTHING)
                    {
                              var cellCenter = cell.Center;
                              var color = (cell.Move == Player.CROSS) ?
Color.Green : Color.Red;
spriteBatch.Draw(logoTexture, new Vector2(cellCenter.X -
(logoTexture.Width / 2), cellCenter.Y - (logoTexture.Height /
2)), color);
                              }
                    }
          }
          spriteBatch.End();
          base.Draw(gameTime);
}

That’s all we have to do in our Game.cs file, as the whole logic, image location and scaling, will be done in our Portable Class Library.

Writing the shared code base

Now it is time to write our game logic inside the Portable Class Library. A Tic Tac Toe game consists of a 3×3 board, in which a player makes move. The first one to make a row of 3 moves to win.

Our library will have a TicTacToeGame class which will encapsulate our Cells objects, and a Solver class to determine if someone has won the game.

Our Cells will have a position on screen, a position on the board game, and a player move which can be a cross, circle, or nothing.

We initialize our tic tac toe game so that the board will occupy 3/4 of the screen, and center it:

public void Init(int screenWidth, int screenHeight)
{
          int cellSize = screenHeight / 4;
          var totalSize = cellSize * 3; //3 cells for a row
          var adjustHorizontal = CalculAdjust(screenWidth, totalSize);
          var adjustVertical = CalculAdjust(screenHeight, totalSize);
          for (int i = 0; i < Board.Length; i++)
          {
                    Board[i] = new Cell[3];
                    for (int j = 0; j < Board[i].Length; j++)
                    {
                              Board[i][j] = new Cell(cellSize, j, i, adjustHorizontal, adjustVertical);
                    }
          }
}
private int CalculAdjust(int screenTotal, int cellsTotal)
{
           (cellsTotal >= screenTotal)
                    return 0;
           return (screenTotal - cellsTotal) / 2;
}

And we will call the solver each time a player makes a move:

public void CellClicked(Cell cell)
{
          if (Winner == Player.NOTHING)
          {
                    (Board [cell.Y] [cell.X].Move == Player.NOTHING)
                    {
                              Board [cell.Y] [cell.X].Move = CurrentPlayer;
                                        CurrentPlayer = (CurrentPlayer == Player.CROSS) ? Player.CIRCLE : Player.CROSS;
                              }
                              Solver.Solve(cell.X, cell.Y, 3, this);
                     }
           }
}

 

Here is our Solver class:

public class Solver
          {
                   public void Solve(int x, int y, int rowSize, TicTacToeGame game)
                   {
                             SolveInternal(Player.CROSS, x, y, n, game);
                             SolveInternal(Player.CIRCLE, x, y, n, game);
                   }
                   private void SolveInternal(Player testAgainst, int x, int y, int n, TicTacToeGame game)
                  {
                             //check col
                             for (int i = 0; i < n; i++)
                             {
                                      if (game.Board[x][i].Move != testAgainst)
                                      break;
                                      if (i == n - 1)
                                      game.Winner = testAgainst;
                             }

                             //check row
                             for (int i = 0; i < n; i++)
                             {
                                      if (game.Board[i][y].Move != testAgainst)
                                      break;
                                      if (i == n - 1)
                                      game.Winner = testAgainst;
                             }
                             //check diag
                             if (x == y)
                             {
                                      for (int i = 0; i < n; i++)
                                      {
                                                if (game.Board[i][i].Move != testAgainst)
                                                break;
                                                if (i == n - 1)
                                                game.Winner = testAgainst;
                                       }
                              }
                           
                             //check anti diag
                             for (int i = 0; i < n; i++)
                             {
                                       if (game.Board[i][(n - 1) - i].Move != testAgainst)
                                       break;
                                       if (i == n - 1)
                                       game.Winner = testAgainst;
                             }
                   }
         }
}

We are now ready to test our tic tac toe!

You can checkout the solution on github, fork it, improve it 🙂

Run the game!

Android monogame demo

Android

iOS Monogame demo resized 600

IOS

Desktop monogame demo resized 600

Desktop

For more references please visit:

1. Monogame 
2. XNA
3. Ouya console
4. Portable class library
5. Wordament

About the Author

Mathieu Clerici has a bachelors degree in software programing from the European Institute of Technologies in Paris, France. He has 5 years of experience developing .Net software and Xamarin App Development.

Leave a Reply

Your email address will not be published. Required fields are marked *