Finding a bug

I’ve spent well over a dozen hours trying to find a bug in my VBNET boxes program.

Debugging computer code can be time consuming and frustrating, but there’s also much pleasure to be gained by trying to unravel the puzzle. It’s a bit like struggling with a crossword clue where nothing fits the space and any existing letters. Something isn’t quite right but what is it? In the case of a crossword clue it’s often because one of the other completed words is incorrect and by putting in the right word one can solve the clue that was causing the problem. And so it was with my computer bug.

The code I had written was to play through all possible combination of moves in the boxes game in order to determine the best move to make. But sometimes my code came up with the worst move rather than the best. I studied the code for hours, went through the steps in my head, but I couldn’t see where the flaw in my logic was. I eventually resorted to stepping through the code as it was being executed, and watching as variables changed value. And then a little after midnight I found something strange happening, but it wasn’t in the code I was concentrating on.

My code called various functions – separate pieces of code I had written to perform specific tasks. And it was in one of these functions, which I thought was tested and working, that I found a poor piece of coding that resulted in the function sometimes returning a random result. An annoying mistake but a satisfying conclusion.

The original, buggy code is below – can you see the flaw?

Select Case region
    Case CRposition.pleft
        If col > 1 Then AdjacentBox = box - 1 : AdjacentSide = CRposition.pright
    Case CRposition.pright
        If col < nboxeswide Then AdjacentBox = box + 1 : AdjacentSide = CRposition.pleft
    Case CRposition.ptop
        If row > 1 Then AdjacentBox = box - nboxeswide : AdjacentSide = CRposition.pbottom
    Case CRposition.pbottom
        If row < nboxesdeep Then AdjacentBox = box + nboxeswide : AdjacentSide = CRposition.ptop
    Case Else
        AdjacentBox = 0 : AdjacentSide = 0
End Select

One response to “Finding a bug”

  1. AdjacentBox = 0 : AdjacentSide = 0

    Select Case region
    Case CRposition.pleft
    If col > 1 Then AdjacentBox = box – 1 : AdjacentSide = CRposition.pright
    Case CRposition.pright
    If col < nboxeswide Then AdjacentBox = box + 1 : AdjacentSide = CRposition.pleft
    Case CRposition.ptop
    If row > 1 Then AdjacentBox = box – nboxeswide : AdjacentSide = CRposition.pbottom
    Case CRposition.pbottom
    If row < nboxesdeep Then AdjacentBox = box + nboxeswide : AdjacentSide = CRposition.ptop
    End Select

    ….Mike

Have your say! (No need for any ID!)