/** * Initialize the list of path fragments. It is able to randomly generate a game path. It * recursively calls itself to add new path fragment to the game path until it is long enough to * cover the width of the panel. * * @param int targetLength: the horizontal distance for the path to cover. PathFragment * previousFragment, null if is the first path fragment * @return none. */ private void randomPath(int targetLength, PathFragment previousFragment) { int width = 80 + (int) (Math.random() * 100); // A random width for each // path fragment if (previousFragment == null) { // First path fragment // Randomly choose a starting point on the left side of the panel // and direction int y = random(TowerDefenseGame.WINDOW_HEIGHT); int direction = random(70); PathFragment newFragment = new PathFragment(0, y, width, direction); // Check if the new path is in bound while (!isInBound(newFragment.getPathEnd())) { direction = random(70); newFragment = new PathFragment(0, y, width, direction); } paths.add(newFragment); randomPath(targetLength - (int) (Math.cos(Math.toRadians(direction)) * width), newFragment); } else if (targetLength > 0) { int direction = randomDirection(); PathFragment newFragment; double[] pt = previousFragment.getPathEnd(); newFragment = new PathFragment((int) pt[0], (int) pt[1], width, direction); while (!isInBound(newFragment.getPathEnd()) || direction == previousFragment.getDirection() || direction == previousFragment.getDirection() - 180 || direction == previousFragment.getDirection() + 180) { direction = randomDirection(); newFragment = new PathFragment((int) pt[0], (int) pt[1], width, direction); } paths.add(newFragment); randomPath(targetLength - (int) (Math.cos(Math.toRadians(direction)) * width), newFragment); } }