I am implementing a Stratego AI in Java. One of the things the AI needs to do, is to look at possible future moves. For this, it should be able to get a copy of the current board position, move pieces around there (without influencing the main board, of course), and pick the best move by looking multiple moves ahead (using the MiniMax algorithm).
However, I am having trouble with the copying the board part. My board is stored as a two-dimensional array of StrategoPieces:
StrategoPiece board[][];
Now, some pieces in Stratego have special rules. I've created special classes for the Spy, the Scout, the Miner, the Flag and the Bomb, that all inherit from the StrategoPiece class.
So, the board contains 'null' for an empty square, and an object that is a child class of StrategoPiece if it is occupied.
I want to copy over this board, but I cannot figure out how to make a proper deep copy. Reading on StackOverflow and other places on the Internet, I came across the following pieces of information:
- To make a deep copy of a (non-primitive) array (in one or more dimensions), one needs to copy over all objects one-by-one.
- Object.clone() does not work as most people want, and implementing this properly is difficult.
- It is advised to create a 'Factory' or Constructor Copy method instead.
What I am wondering about, however, is how I can create such a Factory or Constructor Copy method when I'm having an array of objects with multiple classes (that all inherit from the same base class, but some have extra logic attached).
Any help would be appreciated.