private boolean assignSpeeds(Map m, ArrayList<Road> roads) { int[][] speeds = new int[m.getLengthX()][m.getLengthY()]; int count = 0; for (Road r : roads) { Tile[] adjTiles = getAdjTiles(m.grid, m.grid[r.getX()][r.getY()]); Road start = null; for (int i = 0; i < 4; i++) { if (adjTiles[i] instanceof TrafficLight) { start = r; } if (adjTiles[i] == null || adjTiles[i] instanceof NonRoad) { if (i == r.getDirection() || i == Math.abs(r.getDirection() - 4)) { start = r; } } } if (start != null) { int dir = start.getDirection(); int length = 1; Tile t = r; // if(m.getInDir(r,dir) != null){ t = m.getInDir(r, dir); if (t instanceof TrafficLight || t == null || t instanceof NonRoad) { int reverseDir = (dir + 2 > 3) ? dir - 2 : dir + 2; if (m.getInDir(r, reverseDir) != null) t = m.getInDir(r, reverseDir); while (!(t == null || t instanceof TrafficLight || t instanceof NonRoad)) { length++; if (m.getInDir(t, reverseDir) != null) t = m.getInDir(t, reverseDir); else break; } for (int i = 0; i < length; i++) { t = m.getInDir(t, dir); // reverse direction speeds[t.getX()][t.getY()] = determineSpeed(length); } } else { while (!(t == null || t instanceof TrafficLight || t instanceof NonRoad)) { length++; if (m.getInDir(t, dir) != null) t = m.getInDir(t, dir); else break; } int reverseDir = (dir + 2 > 3) ? dir - 2 : dir + 2; for (int i = 0; i < length; i++) { t = m.getInDir(t, reverseDir); // reverse directions speeds[t.getX()][t.getY()] = determineSpeed(length); } } } // } count++; } for (Road r : roads) { r.setSpeed(speeds[r.getX()][r.getY()]); } return true; }
private static Tile[] getAdjTiles(Tile[][] grid, Tile x) { Tile[] y = new Tile[4]; if (!(x.getX() == 0)) y[3] = grid[x.getX() - 1][x.getY()]; if (!(x.getY() == 0)) y[0] = grid[x.getX()][x.getY() - 1]; if (!(x.getX() == grid.length - 1)) y[1] = grid[x.getX() + 1][x.getY()]; if (!(x.getY() == grid[0].length - 1)) y[2] = grid[x.getX()][x.getY() + 1]; return y; }