Friday, August 5, 2011

RTFM: First MonoDroid Steps

This will be a short post on my first experiences in using MonoDroid. It will primarily be a small list of the mistakes I made in getting a simple app to run on a configured device. This actually didn't work quite as easy as I thought it would.

I started with following the download and installation instructions for Visual Studio 2010 on the Xamarin site. Clicking all the SDK's and packages you need to download and installing all of those.

First error I made here is, they indicate at their site you need to install the Android SDK on a path with no spaces in it. This recommendation, actually, is one you should follow. If you install the Android SDK in the regular Program Files location, the Visual Studio plugin won't be able to find the SDK. That's the first mistake that made me have to reinstall the Android SDK.

After reinstalling the Android SDK, just check if the new path is filled out correctly under Tools - Options - Mono for Android in Visual Studio. If it is not, fill it out and restart your Visual Studio (and recheck if it is filled out correctly).


Another handy option here is the Adb logging option, which puts a log file on your desktop, so you can see a bit what's going on if things go terribly wrong.

That done, I tried to run the default project that's created when you start a new MonoDroid project. This failed miserably. I kept getting the error message that my activity could not be found: "Activity class {\} could not be found". I struggled quite some time with this error, figuring the mandroid process must have created an incorrect package name or maybe created an incorrect folder structure under my obj folder of the project. Whatever I tried, nothing worked:

  • renaming folders,
  • renaming the namespace, 
  • renaming the project, 
  • creating my own AndroidManifest.xml file
  • ...

After a lot of hair pulling and rereading the installation instructions and the first tutorial for the 100th time, my eye fell on the Java SDK version they recommended you download. You should install version 6, but if you click the link for downloading this, you get the download site for version 7. After uninstalling version 7, googling for version 6 and installing that one I finally could get the tutorial app deployed on an Android device.

Another error I thought I made along the way, is one I made out of laziness. While downloading the Android SDK I got tired by the size of the download, skipping it and only downloading the latest version (3.3 at the time of writing). And apparently MonoDroid doesn't support this latest version (yet). So installing revision 8 and configuring an Android device for this, made it all ok. But on the other side, deploying to the 3.3 version after I got revision 8 to work, went just fine. The only problem is that your UI gets stretched, because the 3.3 device is a tablet device. I still need to figure out how you can set op MonoDroid for bigger screens.

Monday, August 1, 2011

Playing GOLF, hole 3

So in hole 1 and 2 we started with the most simple tests and we already implemented a standard way of iterating over a game board, which is a list of lists. Time to add some more tests and to expand our example. Before I do, though, just one little side note on the F# development environment. I regularly use functions before they exist. The F# environment constantly checks my program for these loose, non-existent functions, which slows down my Visual Studio. Kind of like the VB compiler does. This is quite annoying. I haven't yet found how I can make the F# compiler not constantly check for coding errors.

That said, on to the next test. Let's make it a little more complex and skip two live cells, but go directly to three live cells.

 [<TestFixture>] 
 type ``Given a gameboard with three live neighbour cells`` ()= 
   let gameboard =  
     [[0; 0; 0]; 
     [1; 1; 1]; 
     [0; 0; 0]] 
  
   let gameboard_after_gen_1 =  
     [[0; 0; 0]; 
     [0; 1; 0]; 
     [0; 0; 0]] 
    
   [<Test>] member test. 
    ``When I ask for generation 1, the middle cell should still live`` ()= 
     conway gameboard 1 |> should equal gameboard_after_gen_1   

This test will be red, because all cells after a first generation will be dead. We will need to add extra code to keep certain cells (those with two living neighbours) alive. Remember the code we had up until now:

 module GOL 
  
 let kill gameboard = 
   let rec kill_row new_row =  
     let length = List.length (List.head gameboard) 
     if List.length new_row = length then 
       new_row 
     else 
       kill_row (0 :: new_row)  
          
   [1 .. List.length gameboard] |> 
      List.map(fun x -> kill_row List.Empty)  
  
 let conway gameboard n = 
   match n with 
     | 0 -> gameboard 
     | 1 -> kill gameboard  

The line that needs to be altered is the one where we prepend (cons in F# terms) the number 0 with the new_row parameter. In stead of always consing 0, we will need to calculate which number needs to be consed. To do this calculation we will also need some notion of the row and cell index for which we need to calculate this value, so this needs to be added somehow as well. The row index can be send along via the List.map function at the bottom. The cell index can be calculated from the length of the new_row parameter up until now.

If we add the notion of a row_index, the code will look like this (changes are marked in red):

 let kill gameboard = 
   let rec kill_row row_index new_row =  
     let length = List.length (List.head gameboard) 
     if List.length new_row = length then 
       new_row 
     else 
       kill_row row_index (0 :: new_row)  
          
   [1 .. List.length gameboard] |> 
     List.map(fun x -> kill_row x List.Empty)  
   
If we add a calculation of a new_cell_value for a certain cell index, it will look like this:
  
 let kill gameboard = 
   let calc_next_cell_value x y =  
     0 
   let rec kill_row row_index new_row =  
     let length = List.length (List.head gameboard) 
     if List.length new_row = length then 
       new_row 
     else 
       let new_cell_value = 
            calc_next_cell_value 
            (length - (List.length new_row)) row_index 
       kill_row row_index (new_cell_value :: new_row)  
          
   [1 .. List.length gameboard] |> 
      List.map(fun x -> kill_row x List.Empty)   

As for the calc_next_cell_value function, let's do this as naively as we did before. Implement just enough to make the test pass. I first tried it this way, using the build in Item function to get an item from a list:

 let calc_next_cell_value x y =  
   let current_cell_state = gameboard.Item(y).Item(x) 
   let number_of_alive_neighbours =  
     gameboard.Item(y).Item(x - 1) + 
     gameboard.Item(y).Item(x + 1) 
   if current_cell_state = 0 then 
     0 
   else if current_cell_state = 1 && 
     number_of_alive_neighbours = 2 then 
     1  
   else 0 

This might work, but the compiler seems to need type information concerning the list you get once you execute Item(y) on it (it is needed to resolve the Item(x) call). Adding this type information however, was not something I wanted to do. So instead of adding a type to the gameboard parameter, I wrote my own functions to get at a certain cell.

 let cell x y = 
   nth x (nth y gameboard) 
 let calc_next_cell_value x y =  
   let current_cell_state = cell x y 
   let number_of_alive_neighbours =  
     cell (x - 1) (y) + 
     cell (x + 1) (y) 
   if current_cell_state = 0 then 
     0 
   else if current_cell_state = 1 && 
     number_of_alive_neighbours = 2 then 
     1 
   else 0  

The nth function is written as a recursive function on the list and it actually adds some boundary checking. Once we go out of bounds (our n is bigger than our list length or smaller than 1), we always return 0. If we stay in bounds, we check if n is 1, this means we can return the head of the list. In all other cases, we decrement n and execute the nth function on the tail of the list.

 let rec nth n list =  
   if n > List.length list then  
     0 
   else if n < 1 then  
     0 
   else if n = 1 then  
     List.head list 
   else 
     nth (n - 1) (List.tail list)  

To make this implementation of the nth function more visible, suppose our list is as follows: [1; 2; 3; 4; 5] and we ask for the third element. The bottom else case will get executed. The nth function is called again with an n of 2 and a list of [2; 3; 4; 5] (the tail of the original list). Again the bottom else statement will be executed, which will call the nth function again with a n of 1 and a list of [3; 4; 5]. This time the n parameter equals 1 and the head of the list will be taken, which has the value of 3. This again is a very commonly used pattern when working with lists in functional languages.

But this implementation of nth actually keeps the problem of the compiler complaining about the type we get when executing the function (it is more or less the same problem we had with the Item(y) call). F# is quite strict in working with types. And this was one of the primary problems I had while implementing the Game Of Life. Where as a language as Scheme (from which I ripped the solution) doesn't bother with types, F# does. And if you execute the nth function as follows: (nth y gameboard), you actually want a list at a certain index in a list of lists. And if you execute the nth function again for the x parameter, you actually want the cell at position x in a list of integers. So one time you are operating on a list of lists and the next on a list of integers. F# doesn't like that. So, to solve this problem I added another function,to get the nth row in a list of lists.

 let rec nth_row n list = 
   if n > List.length list then 
     [] 
   else if n < 1 then 
     [] 
   else if n = 1 then 
     List.head list 
   else nth_row (n - 1)(List.tail list)  

This function looks very similar to the nth function, with the difference that it explicitly tells the compiler it will return something of the list type.

On the calling side, I changed the code to this:

 let cell x y = 
   nth x (nth_row y gameboard)  

The entire implementation now looks like this:

 let rec nth_row n list = 
   if n > List.length list then 
     [] 
   else if n < 1 then 
     [] 
   else if n = 1 then 
     List.head list 
   else nth_row (n - 1)(List.tail list) 
  
 let rec nth n list =  
   if n > List.length list then  
     0 
   else if n < 1 then  
     0 
   else if n = 1 then  
     List.head list 
   else 
     nth (n - 1) (List.tail list) 
  
 let do_generation gameboard = 
   let cell x y = 
     nth x (nth_row y gameboard) 
   let calc_next_cell_value x y =  
     let current_cell_state = cell x y 
     let number_of_alive_neighbours =  
       cell (x - 1) (y) + 
       cell (x + 1) (y) 
     if current_cell_state = 0 then 
       0 
     else if current_cell_state = 1 && 
       number_of_alive_neighbours = 2 then 
       1 
     else 0 
   let rec kill_row row_index new_row =  
     let length = List.length (List.head gameboard) 
     if List.length new_row = length then 
       new_row 
     else 
       let new_cell_value = 
         calc_next_cell_value 
         (length - (List.length new_row)) 
         row_index 
       kill_row row_index (new_cell_value :: new_row)  
          
   [1 .. List.length gameboard] |> 
     List.map(fun x -> kill_row x List.Empty)  
  
 let conway gameboard n = 
   match n with 
     | 0 -> gameboard 
     | 1 -> do_generation gameboard  

You might have noticed I also changed the name of the kill function to do_generation. Refactoring this was needed!

And this is actually already the main part of our Game Of Life. The only thing that still needs to be added, are some more calculations for the alive count of a cell and some extra rule checks for keeping cells alive or killing them off, and off course the ability to calculate more than 1 generation.

I will add all of those at the next hole.

Playing GOLF, hole 2

The first hole of playing GOLF, involved the first most simple tests one could write for Conway's Game Of Life. In this next post we will add tests for a gameboard with life cells (actually just one life cell for now). For this I created a new TestFixture, so all tests are nicely separated in the ReSharper runner.

 [<TestFixture>] 
 type ``Given a gameboard with 1 live cell`` ()= 
   let gameboard =  
     [[0; 0; 0]; 
     [0; 1; 0]; 
     [0; 0; 0]] 
   let dead_gameboard =  
     [[0; 0; 0]; 
     [0; 0; 0]; 
     [0; 0; 0]]
 
   [<Test>] member test. 
    ``When I ask for generation 0, should not change gameboard`` ()= 
     conway gameboard 0 |> should equal gameboard 
   [<Test>] member test. 
    ``When I ask for generation 1, the life cell should be dead`` ()= 
     conway gameboard 1 |> should equal dead_gameboard  

The example above immediately adds two new tests. The first one will be green immediately using the current implementation, this is why I didn't bother to split this example up. The second test, however, will not pass. The current implementation simply returns the gameboard as is and doesn't yet alter it. We need to implement our conway function further to make this test turn green. This is the code, I will explain it part by part, so it's not too overwhelming if you've done little to no F# coding.

 module GOL 
  
 let kill gameboard = 
   let rec kill_row new_row =  
     let length = List.length (List.head gameboard) 
     if List.length new_row = length then 
       new_row 
     else 
       kill_row (0 :: new_row)  
          
   [1 .. List.length gameboard] |> List.map(fun x -> kill_row List.Empty)  
  
 let conway gameboard n = 
   match n with 
     | 0 -> gameboard 
     | 1 -> kill gameboard 
   

This is actually quite a naive way of implementing the red test case. For making a first generation, we kill off the entire gameboard. I did this on purpose, because this way, you can see the basic way you can use for working with lists, or better, lists of lists in our case. The gameboard is actually a list of lists, so if we want to do some operation on it, we do this list per list (or row per row). This basic implementation is also the most simple implementation you can give, to make the test pass.

As for the starting point of our conway function, which you can find at the bottom of the example code, I used F#'s feature of pattern matching. This is actually something very powerful and looks a lot like a switch case in regular programming languages. Except that pattern matching in F# is more like a switch case on speed, since it gives you more opportunities. In this example the speed is still a bit missing, we just have two cases up until now, a 0 and a 1 case. For the 0 case we just return the gameboard as is. For generation 1 we kill off the gameboard.

As for the kill function, the actual starting point is the bottom line with the List.map in it (the other lines represent an inner function, but more about that in a while). This tells the compiler to execute the function kill_row for the input we give it. This input is actually a list of integers of 1 up until the length of our game board (which is the number of rows in it).

The kill_row function is an internal function of the kill function. This has the advantage that the gameboard input parameter is accessible and we can use it to calculate the length of one row. For this we take the first row, using List.head and of this we take the length, with List.length. This calculation of the length is something that will be done only once, not for each recursive call.

The input parameter for kill_row is an empty list. Item per item in a row, we will prepend the number 0 (kill off one cell) to this list. This process continues until we get a row of all zero's that has the same length as the length of one row of our game board (the length variable). And since the input for the List.map function is a list (one of integers), each resulting row will be put in this list. We actually transform a list of integers into a list of rows (where each row is again a list of integers).

This might seem an unusual way of working, but is actually quite a common pattern of iterating over lists and building new lists in a functional language. It takes some getting used to as well. And from time to time it just looks weird, since most of us are used to doing this with loops.

This implementation also made our tests green, so on to hole number 3.

Playing GOLF, hole 1

A while back I started with the idea of writing the Game Of Life test first using F#. I already blogged some about this, but this week I finally found the time to actually implement all this from start to finish. I did start all over again though, since my last post didn't really contain a functional starting point. And I did give it some tries to get the code right and I also took a peek at the Scheme implementation that can be found at this link (hey, it's been five years since I've done functional programming, I am allowed to make mistakes and to see what others have done). So it is quite possible that there are similarities between my implementation and the Scheme version. There is also an F# version that can be found at that site, but it's implementation uses a bit too many nested for loops for my liking.

First of all, I rewrote my first test. The idea of having cells that know how many living neighbours they have, was nice at first, but with this implementation I wanted to start of with a gameboard of all dead cells. For my first most simple test, I started of with: If I have all dead cells, than after zero generations all cells should still be dead.

 namespace GolF.Tests
 
 open NUnit.Framework 
 open FsUnit 
 open GOL 
 [<TestFixture>] 
 type ``Given a dead gameboard`` ()= 
   let gameboard =  
     [[0; 0; 0]; 
     [0; 0; 0]; 
     [0; 0; 0]] 
   [<Test>] member test. 
    ``When I ask for generation 0, should not change gameboard`` ()=  
     conway gameboard 0 |> should equal gameboard  

To make the test compile I added the conway function, which just returned a string (I didn't want to make the test green, yet).

 module GOL 
 let conway gameboard n = 
   "test"  

This made the test compile, but off course it was still red.


To make the test pass, I altered the conway function a bit.

 let conway gameboard n = 
   gameboard  

Plain and simple. Implement the most simple thing to make the test turn green.

So, time to add a second test: If I ask for generation 1 of a dead gameboard, the gameboard should still be dead.

   [<Test>] member test. 
    ``When I ask for generation 1, gameboard should still be dead`` ()= 
     conway gameboard 1 |> should equal gameboard  

This test actually immediately passes with the current implementation, but it is a good test to have around once we start adding the actual code of calculating generations.

That's all for the first hole of playing GolF, on to the second one.