0

I'm making a game played on a GameBoard (like 3 in a row).

I save the gameboard in a int [2] and like to define the method Move. In this method, with input which player (1 or 2), row, column and the previous board (Previous), we return a new board (Next).

However, the problem is that after running this method, the object Previous changes with it and this is not my intention. Can someone help me?

public class GameBoard {
    public int [] [] board;

    public GameBoard(GameBoard G) {
        this.Board=G.Board;
    }

    public static GameBoard Move(int player,int row, int column, GameBoard Previous) {
        GameBoard Next = new GameBoard(Previous);
        if (player==1) {
        Next.setBoard(row,column,-1); ();}
        if (player==2) {
        Next.setBoard(row,column,1);}
        return Next;
    }
}
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
  • 3
    `this.Board=G.Board;` doesn't copy the array. – Andy Turner Mar 08 '18 at 17:44
  • 1
    AndyTurner beat me to the likely reason; have a look here for what you possibly want to do instead: https://stackoverflow.com/questions/1686425/copy-a-2d-array-in-java – Michael Berry Mar 08 '18 at 17:45
  • Please follow Java naming conventions, variable names, fields and parmeters should start with a lowercase letter, so `g` (not `G`), `previous` (not `Previous`), `board` (not `Board`), `next` (not `Next`). Similarly, your `if`-formatting is rather odd. People take these conventions as visual hints, and not following them makes your code harder to read. – Mark Rotteveel Mar 08 '18 at 17:46
  • Related: https://stackoverflow.com/questions/12757841/are-arrays-passed-by-value-or-passed-by-reference-in-java – Mark Rotteveel Mar 08 '18 at 17:50

0 Answers0