Java 2D Array Specific Move












0















I have made a class where a 6x10 2D array is generated to act as a board.



A random starting location is then generated in the constructor.I only want adjacent moves to be possible.



For example, if the random location has been generated as (2,3) then for example the user enters (1,2) it would be a valid move, but (6,1) would be an invalid move.



Then if the user enters say (1,2), they can then go to any adjacent cell from (1,2).



I have included the class below, and the adjacent method I tried to make to test it, but I'm a bit confused on how I am approaching this.



import java.util.Arrays;
import java.util.Random;

public class Test {

public static final int ROWS = 6;
public static final int COLUMNS = 10;
public int board;

public static void main(String args)
{
Test t = new Test();
t.getBoard();
t.makeMove(6,1); //I want this to be an invalid move.
t.getBoard();
t.makeMove(1,2); // this should be a valid move
t.getBoard();

}

public Test()
{
board = new int[ROWS][COLUMNS];
createRandomLocation();
}

public void createRandomLocation()
{
Random rand = new Random();
int x = rand.nextInt(6);
int y = rand.nextInt(10);
board[x][y] = 1;
}



public void makeMove(int x,int y){
if (Math.abs(x-cur_x)==0 || Math.abs(y-cur_y)==0) {
board[x][y] = 1;
}

public String getBoard() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
System.out.println();

return Arrays.deepToString(board);
}



}


Adjacent:



/*public boolean isMoveAllowed(int  array,int x, int y){
boolean adjacent = false;
int trueCount = 0;
if(array[x-1][y-1] == 0) trueCount++; //topleft
if(array[x-1][y] == 0) trueCount++; //top
if(array[x-1][y+1] == 0) trueCount++;//topright
if(array[x][y+1] == 0) trueCount++;//right
if(array[x][y-1] == 0) trueCount++;//left
if(array[x+1][y-1] == 0) trueCount++;//bottomleft
if(array[x+1][y] == 0) trueCount++;//bottom
if(array[x+1][y+1] == 0) trueCount++; //bottomright

if (trueCount == 8)
{
adjacent = true;
}
return adjacent;
}*/









share|improve this question

























  • You should have a way to keep track of where you are in the grid, and then if the move isn't one up/down/right/left from the current position then return false

    – GBlodgett
    Nov 20 '18 at 18:24
















0















I have made a class where a 6x10 2D array is generated to act as a board.



A random starting location is then generated in the constructor.I only want adjacent moves to be possible.



For example, if the random location has been generated as (2,3) then for example the user enters (1,2) it would be a valid move, but (6,1) would be an invalid move.



Then if the user enters say (1,2), they can then go to any adjacent cell from (1,2).



I have included the class below, and the adjacent method I tried to make to test it, but I'm a bit confused on how I am approaching this.



import java.util.Arrays;
import java.util.Random;

public class Test {

public static final int ROWS = 6;
public static final int COLUMNS = 10;
public int board;

public static void main(String args)
{
Test t = new Test();
t.getBoard();
t.makeMove(6,1); //I want this to be an invalid move.
t.getBoard();
t.makeMove(1,2); // this should be a valid move
t.getBoard();

}

public Test()
{
board = new int[ROWS][COLUMNS];
createRandomLocation();
}

public void createRandomLocation()
{
Random rand = new Random();
int x = rand.nextInt(6);
int y = rand.nextInt(10);
board[x][y] = 1;
}



public void makeMove(int x,int y){
if (Math.abs(x-cur_x)==0 || Math.abs(y-cur_y)==0) {
board[x][y] = 1;
}

public String getBoard() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
System.out.println();

return Arrays.deepToString(board);
}



}


Adjacent:



/*public boolean isMoveAllowed(int  array,int x, int y){
boolean adjacent = false;
int trueCount = 0;
if(array[x-1][y-1] == 0) trueCount++; //topleft
if(array[x-1][y] == 0) trueCount++; //top
if(array[x-1][y+1] == 0) trueCount++;//topright
if(array[x][y+1] == 0) trueCount++;//right
if(array[x][y-1] == 0) trueCount++;//left
if(array[x+1][y-1] == 0) trueCount++;//bottomleft
if(array[x+1][y] == 0) trueCount++;//bottom
if(array[x+1][y+1] == 0) trueCount++; //bottomright

if (trueCount == 8)
{
adjacent = true;
}
return adjacent;
}*/









share|improve this question

























  • You should have a way to keep track of where you are in the grid, and then if the move isn't one up/down/right/left from the current position then return false

    – GBlodgett
    Nov 20 '18 at 18:24














0












0








0








I have made a class where a 6x10 2D array is generated to act as a board.



A random starting location is then generated in the constructor.I only want adjacent moves to be possible.



For example, if the random location has been generated as (2,3) then for example the user enters (1,2) it would be a valid move, but (6,1) would be an invalid move.



Then if the user enters say (1,2), they can then go to any adjacent cell from (1,2).



I have included the class below, and the adjacent method I tried to make to test it, but I'm a bit confused on how I am approaching this.



import java.util.Arrays;
import java.util.Random;

public class Test {

public static final int ROWS = 6;
public static final int COLUMNS = 10;
public int board;

public static void main(String args)
{
Test t = new Test();
t.getBoard();
t.makeMove(6,1); //I want this to be an invalid move.
t.getBoard();
t.makeMove(1,2); // this should be a valid move
t.getBoard();

}

public Test()
{
board = new int[ROWS][COLUMNS];
createRandomLocation();
}

public void createRandomLocation()
{
Random rand = new Random();
int x = rand.nextInt(6);
int y = rand.nextInt(10);
board[x][y] = 1;
}



public void makeMove(int x,int y){
if (Math.abs(x-cur_x)==0 || Math.abs(y-cur_y)==0) {
board[x][y] = 1;
}

public String getBoard() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
System.out.println();

return Arrays.deepToString(board);
}



}


Adjacent:



/*public boolean isMoveAllowed(int  array,int x, int y){
boolean adjacent = false;
int trueCount = 0;
if(array[x-1][y-1] == 0) trueCount++; //topleft
if(array[x-1][y] == 0) trueCount++; //top
if(array[x-1][y+1] == 0) trueCount++;//topright
if(array[x][y+1] == 0) trueCount++;//right
if(array[x][y-1] == 0) trueCount++;//left
if(array[x+1][y-1] == 0) trueCount++;//bottomleft
if(array[x+1][y] == 0) trueCount++;//bottom
if(array[x+1][y+1] == 0) trueCount++; //bottomright

if (trueCount == 8)
{
adjacent = true;
}
return adjacent;
}*/









share|improve this question
















I have made a class where a 6x10 2D array is generated to act as a board.



A random starting location is then generated in the constructor.I only want adjacent moves to be possible.



For example, if the random location has been generated as (2,3) then for example the user enters (1,2) it would be a valid move, but (6,1) would be an invalid move.



Then if the user enters say (1,2), they can then go to any adjacent cell from (1,2).



I have included the class below, and the adjacent method I tried to make to test it, but I'm a bit confused on how I am approaching this.



import java.util.Arrays;
import java.util.Random;

public class Test {

public static final int ROWS = 6;
public static final int COLUMNS = 10;
public int board;

public static void main(String args)
{
Test t = new Test();
t.getBoard();
t.makeMove(6,1); //I want this to be an invalid move.
t.getBoard();
t.makeMove(1,2); // this should be a valid move
t.getBoard();

}

public Test()
{
board = new int[ROWS][COLUMNS];
createRandomLocation();
}

public void createRandomLocation()
{
Random rand = new Random();
int x = rand.nextInt(6);
int y = rand.nextInt(10);
board[x][y] = 1;
}



public void makeMove(int x,int y){
if (Math.abs(x-cur_x)==0 || Math.abs(y-cur_y)==0) {
board[x][y] = 1;
}

public String getBoard() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
System.out.println();

return Arrays.deepToString(board);
}



}


Adjacent:



/*public boolean isMoveAllowed(int  array,int x, int y){
boolean adjacent = false;
int trueCount = 0;
if(array[x-1][y-1] == 0) trueCount++; //topleft
if(array[x-1][y] == 0) trueCount++; //top
if(array[x-1][y+1] == 0) trueCount++;//topright
if(array[x][y+1] == 0) trueCount++;//right
if(array[x][y-1] == 0) trueCount++;//left
if(array[x+1][y-1] == 0) trueCount++;//bottomleft
if(array[x+1][y] == 0) trueCount++;//bottom
if(array[x+1][y+1] == 0) trueCount++; //bottomright

if (trueCount == 8)
{
adjacent = true;
}
return adjacent;
}*/






java






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 30 '18 at 11:51







JameshGong

















asked Nov 20 '18 at 18:22









JameshGongJameshGong

566




566













  • You should have a way to keep track of where you are in the grid, and then if the move isn't one up/down/right/left from the current position then return false

    – GBlodgett
    Nov 20 '18 at 18:24



















  • You should have a way to keep track of where you are in the grid, and then if the move isn't one up/down/right/left from the current position then return false

    – GBlodgett
    Nov 20 '18 at 18:24

















You should have a way to keep track of where you are in the grid, and then if the move isn't one up/down/right/left from the current position then return false

– GBlodgett
Nov 20 '18 at 18:24





You should have a way to keep track of where you are in the grid, and then if the move isn't one up/down/right/left from the current position then return false

– GBlodgett
Nov 20 '18 at 18:24












2 Answers
2






active

oldest

votes


















1














Your problem description has the answer baked into it already. You want any move from (a,b) to (c,d) to be legal if the distance between a and c, and b and d, is zero or one. So if you see Math.abs(a-c)>1, that's an illegal move. So: have the current position stored in some variables, and compare them to the desired new location:



public static void main(String args)
{
Board b = new Board(6, 10);
try {
b.tryMove(6,1);
} catch(IllegalMoveException e) {
// do whatever you need to do to inform the user that move is illegal
}
}


With the Board class responsible for tracking coordinates:



class Board {
protected int cur_x, cur_y, rows, cols;

public Board(int rows, int cols) {
this.rows = rows;
this.cols = cols;
this.setRandomPosition();
}

public void setRandomPosition() {
cur_x = (int) Math.round(Math.random() * cols);
cur_y = (int) Math.round(Math.random() * rows);
}

public void tryMove(int x, int y) throws IllegalMoveException {
if (Math.abs(x-cur_x)>1 || Math.abs(y-cur_y)>1) {
throw new IllegalMoveException(...);
}
// bounds check omitted here, but: ensure that
// 0<=x<cols and 0<=y<rows, otherwise throw an
// IllegalMoveException as well.
cur_x = x;
cur_y = y;
}
// with getters for the current x and y, etc.
}





share|improve this answer

































    0














    It would be much easier to test for a true case rather than a false case like you currently have, the isMoveAllowed method should look something like this:



    public boolean isMoveAllowed(int array, int x, int y) {
    return ((array[x + 1][y] == 1) ||
    (array[x - 1][y] == 1) ||
    (array[x][y + 1] == 1) ||
    (array[x][y - 1] == 1));
    }


    This will return true if the move is adjacent to the current player position






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53399209%2fjava-2d-array-specific-move%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Your problem description has the answer baked into it already. You want any move from (a,b) to (c,d) to be legal if the distance between a and c, and b and d, is zero or one. So if you see Math.abs(a-c)>1, that's an illegal move. So: have the current position stored in some variables, and compare them to the desired new location:



      public static void main(String args)
      {
      Board b = new Board(6, 10);
      try {
      b.tryMove(6,1);
      } catch(IllegalMoveException e) {
      // do whatever you need to do to inform the user that move is illegal
      }
      }


      With the Board class responsible for tracking coordinates:



      class Board {
      protected int cur_x, cur_y, rows, cols;

      public Board(int rows, int cols) {
      this.rows = rows;
      this.cols = cols;
      this.setRandomPosition();
      }

      public void setRandomPosition() {
      cur_x = (int) Math.round(Math.random() * cols);
      cur_y = (int) Math.round(Math.random() * rows);
      }

      public void tryMove(int x, int y) throws IllegalMoveException {
      if (Math.abs(x-cur_x)>1 || Math.abs(y-cur_y)>1) {
      throw new IllegalMoveException(...);
      }
      // bounds check omitted here, but: ensure that
      // 0<=x<cols and 0<=y<rows, otherwise throw an
      // IllegalMoveException as well.
      cur_x = x;
      cur_y = y;
      }
      // with getters for the current x and y, etc.
      }





      share|improve this answer






























        1














        Your problem description has the answer baked into it already. You want any move from (a,b) to (c,d) to be legal if the distance between a and c, and b and d, is zero or one. So if you see Math.abs(a-c)>1, that's an illegal move. So: have the current position stored in some variables, and compare them to the desired new location:



        public static void main(String args)
        {
        Board b = new Board(6, 10);
        try {
        b.tryMove(6,1);
        } catch(IllegalMoveException e) {
        // do whatever you need to do to inform the user that move is illegal
        }
        }


        With the Board class responsible for tracking coordinates:



        class Board {
        protected int cur_x, cur_y, rows, cols;

        public Board(int rows, int cols) {
        this.rows = rows;
        this.cols = cols;
        this.setRandomPosition();
        }

        public void setRandomPosition() {
        cur_x = (int) Math.round(Math.random() * cols);
        cur_y = (int) Math.round(Math.random() * rows);
        }

        public void tryMove(int x, int y) throws IllegalMoveException {
        if (Math.abs(x-cur_x)>1 || Math.abs(y-cur_y)>1) {
        throw new IllegalMoveException(...);
        }
        // bounds check omitted here, but: ensure that
        // 0<=x<cols and 0<=y<rows, otherwise throw an
        // IllegalMoveException as well.
        cur_x = x;
        cur_y = y;
        }
        // with getters for the current x and y, etc.
        }





        share|improve this answer




























          1












          1








          1







          Your problem description has the answer baked into it already. You want any move from (a,b) to (c,d) to be legal if the distance between a and c, and b and d, is zero or one. So if you see Math.abs(a-c)>1, that's an illegal move. So: have the current position stored in some variables, and compare them to the desired new location:



          public static void main(String args)
          {
          Board b = new Board(6, 10);
          try {
          b.tryMove(6,1);
          } catch(IllegalMoveException e) {
          // do whatever you need to do to inform the user that move is illegal
          }
          }


          With the Board class responsible for tracking coordinates:



          class Board {
          protected int cur_x, cur_y, rows, cols;

          public Board(int rows, int cols) {
          this.rows = rows;
          this.cols = cols;
          this.setRandomPosition();
          }

          public void setRandomPosition() {
          cur_x = (int) Math.round(Math.random() * cols);
          cur_y = (int) Math.round(Math.random() * rows);
          }

          public void tryMove(int x, int y) throws IllegalMoveException {
          if (Math.abs(x-cur_x)>1 || Math.abs(y-cur_y)>1) {
          throw new IllegalMoveException(...);
          }
          // bounds check omitted here, but: ensure that
          // 0<=x<cols and 0<=y<rows, otherwise throw an
          // IllegalMoveException as well.
          cur_x = x;
          cur_y = y;
          }
          // with getters for the current x and y, etc.
          }





          share|improve this answer















          Your problem description has the answer baked into it already. You want any move from (a,b) to (c,d) to be legal if the distance between a and c, and b and d, is zero or one. So if you see Math.abs(a-c)>1, that's an illegal move. So: have the current position stored in some variables, and compare them to the desired new location:



          public static void main(String args)
          {
          Board b = new Board(6, 10);
          try {
          b.tryMove(6,1);
          } catch(IllegalMoveException e) {
          // do whatever you need to do to inform the user that move is illegal
          }
          }


          With the Board class responsible for tracking coordinates:



          class Board {
          protected int cur_x, cur_y, rows, cols;

          public Board(int rows, int cols) {
          this.rows = rows;
          this.cols = cols;
          this.setRandomPosition();
          }

          public void setRandomPosition() {
          cur_x = (int) Math.round(Math.random() * cols);
          cur_y = (int) Math.round(Math.random() * rows);
          }

          public void tryMove(int x, int y) throws IllegalMoveException {
          if (Math.abs(x-cur_x)>1 || Math.abs(y-cur_y)>1) {
          throw new IllegalMoveException(...);
          }
          // bounds check omitted here, but: ensure that
          // 0<=x<cols and 0<=y<rows, otherwise throw an
          // IllegalMoveException as well.
          cur_x = x;
          cur_y = y;
          }
          // with getters for the current x and y, etc.
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 '18 at 18:39

























          answered Nov 20 '18 at 18:33









          Mike 'Pomax' KamermansMike 'Pomax' Kamermans

          28.2k759100




          28.2k759100

























              0














              It would be much easier to test for a true case rather than a false case like you currently have, the isMoveAllowed method should look something like this:



              public boolean isMoveAllowed(int array, int x, int y) {
              return ((array[x + 1][y] == 1) ||
              (array[x - 1][y] == 1) ||
              (array[x][y + 1] == 1) ||
              (array[x][y - 1] == 1));
              }


              This will return true if the move is adjacent to the current player position






              share|improve this answer




























                0














                It would be much easier to test for a true case rather than a false case like you currently have, the isMoveAllowed method should look something like this:



                public boolean isMoveAllowed(int array, int x, int y) {
                return ((array[x + 1][y] == 1) ||
                (array[x - 1][y] == 1) ||
                (array[x][y + 1] == 1) ||
                (array[x][y - 1] == 1));
                }


                This will return true if the move is adjacent to the current player position






                share|improve this answer


























                  0












                  0








                  0







                  It would be much easier to test for a true case rather than a false case like you currently have, the isMoveAllowed method should look something like this:



                  public boolean isMoveAllowed(int array, int x, int y) {
                  return ((array[x + 1][y] == 1) ||
                  (array[x - 1][y] == 1) ||
                  (array[x][y + 1] == 1) ||
                  (array[x][y - 1] == 1));
                  }


                  This will return true if the move is adjacent to the current player position






                  share|improve this answer













                  It would be much easier to test for a true case rather than a false case like you currently have, the isMoveAllowed method should look something like this:



                  public boolean isMoveAllowed(int array, int x, int y) {
                  return ((array[x + 1][y] == 1) ||
                  (array[x - 1][y] == 1) ||
                  (array[x][y + 1] == 1) ||
                  (array[x][y - 1] == 1));
                  }


                  This will return true if the move is adjacent to the current player position







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 20 '18 at 18:33









                  AleksWAleksW

                  1239




                  1239






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53399209%2fjava-2d-array-specific-move%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Guess what letter conforming each word

                      Run scheduled task as local user group (not BUILTIN)

                      Port of Spain