1

I am creating a working chess game

My chess engine has a board. The board is a 2D board[Y][X], and the within it are Pieces. Pieces are enums, and it represents black pieces, white pieces, and NONE.

class ChessBoard
{
   vector<vector<Piece>> board(); //I made it 8*8 in the constructor
   enum Piece{NONE, white pieces, black pieces etc..}
}

My problem is validating if a square is within my board. Please let me elaborate. For example, when looking at the possible moves for A2 pawn, the pawn can either move up 1 2 or capture left right, or en passant left right:

(X,Y+1), (X,Y+2), (X+1,Y+1), (X-1,Y+1), (X+1,Y+2), (X-1,Y-2)

However, as you know, X-1 will cause the piece to go out of bounds.

Yes, I could implement a simple bool isSquareValid() function. But this means, where ever I am trying to access or set board[][], i need to call this function.

Is there a way to implement Board[][] so that when I am trying to access out of bound indexes, it will throw an error message or something without crashing my program?

Thanks

21
  • There is no way to implement an operator[][], except using two operator[] in tandem. std::vector provides an at() member function which checks for valid indices, but it is necessary to catch exceptions to prevent program termination. Note that vector<vector<Piece>> board(8*8) specifies a vector containing 64 vector<Piece>, each of which has no elements. It doesn't create an 8x8 array in any form.
    – Peter
    Jan 15, 2017 at 5:14
  • Of course, in chess, a pawn can't move through other pieces, even if the destination square is on the board.
    – Peter
    Jan 15, 2017 at 5:18
  • Yes I know, I kinda wrote psuedo code just to show that board was 8*8... Anyways, I really dont want to do if(isValidSquare(x,y)) EVERYTIME i try to look at or access the board.... Is there a smart way to do this? I thought maybe making it a 10*10 board with the outer layer as ERROR might help. Jan 15, 2017 at 5:23
  • That part is easy to check, I only move the pawn if board[y][x] == NONE, or if it can capture. Jan 15, 2017 at 5:29
  • Just write your code (e.g. for a single move) using vector's at() instead of [] syntax, as if the array indices are correct. Then wrap that in a try/catch block. If any of the indices are invalid, an exception will be thrown.
    – Peter
    Jan 15, 2017 at 5:43

1 Answer 1

1

You are mixing up two different problems.

The first is how to make sure that the game prevents a piece from ending up outside the board. This is not error handling; you must make sure that the piece never ends up there in the first place. In other words, you must restrict the program logic to valid moves before a choice is even presented to the user (or to an AI component, for that matter). If you fancy the idea of catching the exception thrown from at and then reverting the board to a valid state, stop right there and don't do that. It would be exception abuse at its finest.

The second is how to handle an error resulting from a bug in your code. You may have written code to prevent the game from putting pieces outside of the board, but you may have made a mistake, because we all do, so you do end up with illegal vector indices after all. In this case, the crash resulting from operator[] is actually a good thing, because immediate termination of a buggy program is usually the best thing that can happen to you. The alternative is to "somehow continue" and go on with corrupted data and broken game rules, perhaps not even noticing the bug quickly enough.

Because it's not guaranteed that a wrong operator[] call causes a crash, and forcing the runtime library to perform the checks can be a bit cumbersome (a wrong operator[] index is formally undefined behaviour, of course), you might want to add some assert statements of your own and make sure that NDEBUG does not prevent them from doing their job.

This gets considerably easier if you wrap the std::vector in a class of your own. While you're at it, you can then simplify element access with operator():

class Board
{
public:
    Piece& operator()(int x, int y)
    {
        assert(x >= 0);
        assert(x < 16);
        assert(y >= 0);
        assert(y < 16);
        return data[y][x];
    }

    Piece operator()(int x, int y) const
    {
        assert(x >= 0);
        assert(x < 16);
        assert(y >= 0);
        assert(y < 16);
        return data[y][x];
    }

    Board()
    {
        for (int row_index = 0; row_index < 16; ++row_index)
        {
            data.emplace_back(16, Piece::None);
        }
    }

private:
    std::vector<std::vector<Piece>> data;
};

Also note that std::vector is a poor choice for a chess board, because chess boards do not shrink or grow. Consider using std::array instead.

1
  • Ok, so when I try to access a board position i just do if(board(x,y)).. I really like this solution... Jan 15, 2017 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.