Skip to main content
2 of 2
added 2106 characters in body
Mike Nakis
  • 32.7k
  • 7
  • 80
  • 116

I looked at your code and it does not seem to me that it can be simplified in the sense of reducing the total number of lines. It could be made less verbose if you got rid of some of the unnecessary, annoying curly brackets, but I suppose if you liked that idea you would have already done it:

        if (arrayX == 0)
        {
            if (board.GetBoard(arrayX + 1, arrayY - 1).Piece == null)
                return true;
        }
        else if (arrayX == 7)
        {
            if (board.GetBoard(arrayX - 1, arrayY - 1).Piece == null)
                return true;
        }

However, there is one thing that you could try and see if it would simplify your code: define an immutable struct to hold a point.

struct Point
{
    readonly int x; //these are 32-bit, so the entire struct will fit inside a
    readonly int y; //   machine word in a 64-bit architecture.
    Point( int x, int y )
    { 
        Assert( x >= 0 && x < 7 );  
        Assert( y >= 0 && y < 7 ); 
        this.x = x;  
        this.y = y; 
    }
    Point left { get { Assert( x >= 0 );  return new Point( x - 1, y ); } }
    Point right { get { Assert( x <= 7 );  return new Point( x + 1, y ); } }
    bool isLeftmost { get { return x == 0; } }
    bool isRightmost { get { return x == 7; } }
    ...
}

then, you will be able to add cool things to your structure, like this:

    IEnumerable<Point> EnumerateSurrounding()
    {
        for( int dx = -1;  dx <= 1;  dx++ )
        {
            for( int dy = -1;  dy <= 1;  dy++ )
            {
                int xx = x + dx; 
                int yy = y + dy;
                if( xx < 0 || xx > 7 )
                     continue;
                if( yy < 0 || yy > 7 )
                     continue;
                if( xx == 0 && yy == 0 )
                     continue;
                yield return new Point( xx, xy );
            }
        }
    }

So, you will be able to visit all cells surrounding a given cell like this:

foreach( Point p in mypoint.EnumerateSurrounding() )
{
    //do something with p here
}

Disclaimer: I just typed all of the above code, so it is bound to have syntax errors, and perhaps even logical errors. Do not rely on it blindly, read it carefully and use your judgement.

Mike Nakis
  • 32.7k
  • 7
  • 80
  • 116