/** * 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); } }
/** * Paints all the components on the game map. Towers are painted first, then the path, then all * the enemies. * * @return none. */ @Override public void paintComponent(Graphics g) { super.paintComponent(g); // Draws all the towers for (Tower tower : towers) { tower.draw(g); } // Draws the path for (PathFragment fragment : paths) { fragment.draw(g); } // Draws all the enemies for (Enemy enermy : enemies) { enermy.draw(g); } }