Java chess: not sure how to clone correctly

I am writing a basic java chess game and have written the following classes: game, player, chessboard, square, pieces (super class of each specific piece), and each specific piece class (such as pawn, knight, bishop, etc.)

One tricky method is to determine whether the movement is effective based on whether the player causing the movement is checked My solution is as follows:

>Clone the current board > move > see if the mobile player is under inspection > if so, prohibit moving; Otherwise, movement is allowed

I'm thinking about how to clone from here: http://www.jusfortechies.com com/java/core-java/cloning. PHP

The board object now consists of a 2D square object Each square object has a part field that is empty (there is no part on it) or references an assembly object (there is a part on it) The board object also has a whitekingsquare and a blackkingsquare (both square objects), which can locate the white king or black king faster / easier

I have written the following methods in the board course:

public Object clone() throws CloneNotSupportedException {
    Board clonedBoard = (Board) super.clone();
    for (int i = 0; i < HEIGHT; i++) {
        for (int j = 0; j < WIDTH; j++) {
            clonedBoard.myBoard[i][j] = new Square(this,i,j); 
            clonedBoard.whiteKingSquare = myBoard[7][4];
            clonedBoard.blackKingSquare = myBoard[0][4];
        }
    }
    return clonedBoard; 
}

However, since board refers to an array of 8 x 8 square objects, I have to clone each of them I wrote this method in the square class:

public Object clone() throws CloneNotSupportedException {
    return (Square) super.clone();
}

Finally, I wrote this method in the piece class:

public Object clone() throws CloneNotSupportedException {
    return (Piece) super.clone();
}

On the issue:

>Does this look roughly right? > My square object also has a board field, which basically lets me refer to the board to which they belong Would this screw up my attempt to clone by having my 64 squares cloned separately?

Solution

I have another solution to see if you like it

Cloning is not necessary! I just wrote a Chinese chess program Let me explain what I did: (it's just an outline, you have to do the details yourself)

I have a 2D array and another 2D array button When the user clicks piece, the abstract method getvalidlocations in the piece class will be called, and this method returns a set of coordinates to indicate where piece can go When the user clicks the button, the block moves to the position of the button

The bad news is that I don't know how to play chess I only know Chinese chess, so I can't tell you how to write the algorithm of getvalidlocations. Sorry!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>