Вопрос

I am trying to move a game piece from its initial position to its new position. Note: the move is assumed to be "legal".

public void move ( int fromRow, int fromCol, int toRow, int toCol) {
    GamePiece tmp; //Gamepiece is superclass
    tmp=board[fromRow][fromCol];
    board[toRow][toCol]=tmp;
    board[fromRow][fromCol]=new Gamepiece(); //default constructor
    System.out.print(toString()); //this method has the board array printed in correct format
}

When I test this, it does not move the correct pieces and doesn't give a blank. Why?

Это было полезно?

Решение

What you're doing in your code is swapping. In a regular chess game, you never need to swap. Just replace

       tmp=board[fromRow][fromCol];   // don't need this
       board[toRow][toCol]=tmp;  // don't need this
       board[fromRow][fromCol]=new Gamepiece();  // don't need this

Just do:

       board[toRow][toCol] = board[fromRow][fromCol];
       board[fromRow][fromCol] = null

This is all considering your board is a 2D array of ChessPieces, for example ChessPiece[][] board = new ChessPiece[8][8];

I don't know if this will solve your problem, without seeing more code, but I was just point this out.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top