java - 2d Maze How to Not Move Into a Wall or Out of Bounds? -


hi i've made code problem i'm having not move when there wall or out of bounds. hard way understand coding

if (character == line [2][0] && (dir.equalsignorecase("l")) {}.

("l" being left) way won't move in spot when player wants go left because there's wall, i'd have cases , seems pretty tedious. on how this? thanks.

here's part of if helps:

private final static char character = 'x'; private final static char blank = '.'; private final static char goal = 'o'; private final static char wall = 'w';  private final static int size = 4;  public static void main(string[] args) {      char[][] line = new char[size][size];      for(int = 0; < line.length; i++)      {         for(int j = 0; j < line[i].length; j++)          {             line[i][j] = blank;         }     }      line[2][0] = character;     line[0][0] = goal;     line[1][0] = wall;     line[1][1] = wall;     line[1][3] = wall;     line[2][1] = wall;     line[2][3] = wall;     int xpos = 2;     int ypos = 0; }                

you can work indices check if you're out of bounds or if there's wall. i'd suggest (note: works java 7 or higher)

// assume board square because of new char[size][size] private static boolean isoutofbounds(int coord) {     return coord < 0 || coord >= size; }  /**  * checks, if given coordinate inside bounds , not wall.  */ private static boolean isvalid(int x, int y) {     return !isoutofbounds(x) &&            !isoutofbounds(y) &&            line[x][y] != wall; }  // assume have directions "u", "r", "d", "l" public static boolean cangodirection(string direction, int currx, int curry) {     switch(direction) {         case "u": return isvalid(currx, curry - 1);         case "r": return isvalid(currx + 1, curry);         case "d": return isvalid(currx, curry + 1);         case "l": return isvalid(currx - 1, curry);         default: throw new illegalargumentexception(direction + " not valid direction.");     } } 

now can use cangodirection() current coordinates , direction want. if returns true, can go way , update new position.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -