User prompt
Action Items: Grid.getPossibleNextCellsForPath Method Refinement A critical bug exists in the directional logic for PATH_CORNER GridItemType cells, causing path calculation failures. 1.1. Correct Corner Pathing Logic: Instruction: Modify the switch statement cases for GridItemType.PATH_CORNER_TOP_LEFT (5), GridItemType.PATH_CORNER_TOP_RIGHT (6), GridItemType.PATH_CORNER_BOTTOM_LEFT (7), and GridItemType.PATH_CORNER_BOTTOM_RIGHT (8) within the Grid.getPossibleNextCellsForPath method. Instruction: For each corner type, calculate the entryDirection vector: { x: currentCell.x - previousCell.x, y: currentCell.y - previousCell.y }. Instruction: Update the conditional checks (if (dx > 0), if (dy > 0), etc.) to accurately reflect the correct exit direction based on the entryDirection and the corner's visual orientation as per the provided Grid Implementation Guide. For PATH_CORNER_TOP_LEFT (5, ┌ connects Bottom to Right): If entryDirection.y === 1 (came from Top): Push { x: currentCell.x + 1, y: currentCell.y } (exit Right). If entryDirection.x === -1 (came from Right): Push { x: currentCell.x, y: currentCell.y + 1 } (exit Bottom). For PATH_CORNER_TOP_RIGHT (6, ┐ connects Bottom to Left): If entryDirection.y === 1 (came from Top): Push { x: currentCell.x - 1, y: currentCell.y } (exit Left). If entryDirection.x === 1 (came from Left): Push { x: currentCell.x, y: currentCell.y + 1 } (exit Bottom). For PATH_CORNER_BOTTOM_LEFT (7, └ connects Top to Right): If entryDirection.y === -1 (came from Bottom): Push { x: currentCell.x + 1, y: currentCell.y } (exit Right). If entryDirection.x === -1 (came from Right): Push { x: currentCell.x, y: currentCell.y - 1 } (exit Top). For PATH_CORNER_BOTTOM_RIGHT (8, ┘ connects Top to Left): If entryDirection.y === -1 (came from Bottom): Push { x: currentCell.x - 1, y: currentCell.y } (exit Left). If entryDirection.x === 1 (came from Left): Push { x: currentCell.x, y: currentCell.y - 1 } (exit Top). Note: For all PATH_STRAIGHT and PATH_CORNER types, ensure getPossibleNextCellsForPath returns an array containing only one valid next cell, as these are deterministic paths. For PATH_CROSSROAD and SPAWN types, it should return all valid, non-backtracking neighbors. Enemy Initialization and Waypoint Following Adjustment The initial positioning and waypoint indexing for newly spawned enemies require precise alignment with the pre-calculated paths. 2.1. Enemy.assignedPath Initialization: Instruction: In game.update, within the enemy spawning loop, after enemy.assignedPath is set for a non-flying enemy, ensure enemy.currentWaypointIndex is explicitly set to 0. Instruction: Set enemy.currentCellX to enemy.assignedPath[0].x + 0.5 and enemy.currentCellY to enemy.assignedPath[0].y + 0.5. This places the enemy precisely at the center of the first cell on its assigned path. Note: The initial enemy.currentCellY = spawnCell.y + 0.5 - (1 + Math.random() * 5); offset for entry animation should now lead into this exact first waypoint position. The subsequent hasReachedEntryArea logic in Grid.updateEnemy should be re-evaluated to ensure a smooth transition from off-screen to the first waypoint without immediate GOAL detection. The current entry animation snap logic enemy.currentCellY >= enemy.assignedPath[0].y + 0.5 is correct for snapping to the center of the first cell if assignedPath[0] truly represents the first pathable cell. 2.2. Grid.updateEnemy Waypoint Advancement: Instruction: In Grid.updateEnemy, specifically for non-flying enemies following assignedPath: When distToTarget < enemy.speed * 1.5 (or a similar small threshold) is met, indicating the enemy has reached the current targetWaypoint: Instruction: Immediately snap enemy.currentCellX to targetWaypoint.x + 0.5 and enemy.currentCellY to targetWaypoint.y + 0.5 to prevent floating-point drift and ensure accurate cell transitions. Instruction: Then, increment enemy.currentWaypointIndex. Instruction: Re-evaluate the GOAL check. The check if (cell && cell.type === GridItemType.GOAL) should be triggered when enemy.currentWaypointIndex is equal to enemy.assignedPath.length - 1 (i.e., the enemy has reached the final waypoint, which is the goal). The function should then return true. This ensures enemies are not destroyed prematurely or pass through the goal. DebugCell.render Enhancements 3.1. Clear Existing Arrows: Instruction: In DebugCell.render, ensure all previously drawn debug arrows are removed before drawing new ones. The existing loop while (self.children.length > 1) handles this for children beyond the initial cellGraphics. This needs to be done before drawing new arrows. 3.2. Implement _getDebugArrowsForCell: Instruction: Implement the Grid._getDebugArrowsForCell(cell) method. This method should return an array of {x: dx, y: dy} vectors representing the directions that an enemy could potentially move from that cell type, assuming valid path connections (i.e., not backtracking to the previous cell). For PATH_STRAIGHT_UP: {x: 0, y: -1}. For PATH_STRAIGHT_DOWN: {x: 0, y: 1}. For PATH_STRAIGHT_LEFT: {x: -1, y: 0}. For PATH_STRAIGHT_RIGHT: {x: 1, y: 0}. For PATH_CORNER_TOP_LEFT, PATH_CORNER_TOP_RIGHT, PATH_CORNER_BOTTOM_LEFT, PATH_CORNER_BOTTOM_RIGHT: Add two vectors, one for each valid connection point (e.g., for PATH_CORNER_TOP_LEFT (┌), add {x: 0, y: -1} for up and {x: -1, y: 0} for left relative to the corner's "open" directions). For PATH_CROSSROAD: Add all four cardinal direction vectors: {x: 0, y: -1}, {x: 0, y: 1}, {x: -1, y: 0}, {x: 1, y: 0}. For SPAWN: Retrieve the possibleCells from self.getPossibleNextCellsForPath(cell, []) and convert these into relative vectors from cell.x, cell.y. For GOAL, WALL, TOWER_SLOT: Return an empty array. Instruction: In DebugCell.render, call grid._getDebugArrowsForCell(data) to get the vectors and then iterate over them to create and add arrow assets to self, setting their rotation using Math.atan2(vector.y, vector.x). Position them slightly offset from the center (vector.x * 10, vector.y * 10) so they are visible. Note: This visualization will show all potential exits from a cell type, not the specific path an individual enemy follows. This is valuable for verifying the grid structure itself.
User prompt
Please fix the bug: 'TypeError: Cannot read properties of null (reading '0')' in or related to this line: 'if (enemy.currentCellY >= enemy.assignedPath[0].y + 0.5) {' Line Number: 970
User prompt
Please fix the bug: 'TypeError: Cannot read properties of null (reading '0')' in or related to this line: 'var hasReachedEntryArea = enemy.currentCellY >= enemy.assignedPath[0].y + 0.5;' Line Number: 964
User prompt
Objective: Resolve premature enemy disappearance by refining ground enemy movement and path progression logic, and implement per-cell directional debug visualizations. Action Items: Grid Class Refinement 1.1. Property Removal Instruction: Remove score, pathId, targets, and nextPathCell properties from self.cells[i][j] initialization within the Grid constructor. These are remnants of the previous A* system. 1.2. Pathfinding Method Update Instruction: Remove the entire self.pathFind = function() { ... } block. This method is deprecated by the multi-path system. Instruction: Ensure grid.buildAllGroundPaths(); is called exactly once during game initialization (e.g., after Grid instantiation). Remove any other calls to grid.pathFind() from Tower.placeOnGrid, game.up (for draggedTower), or elsewhere. Path calculation should be static. 1.3. buildAllGroundPaths Method Logic Instruction: Add a maxPathLength constant or variable within Grid (e.g., this.maxPathLength = gridWidth * gridHeight * 2;) to guard against excessive recursion/infinite loops during path discovery. Instruction: Within self.findPathsFromCell(startCell, currentPathCells): Add a check at the beginning: if (currentPathCells.length > self.maxPathLength) { return []; } 1.4. Debug Visualization Helper Instruction: Implement a new private method Grid.prototype._getDebugArrowsForCell = function(cell) that returns an array of {dx, dy} vectors representing visual arrow directions from the center of cell. Instruction: Within _getDebugArrowsForCell, use a switch (cell.type) statement to define these vectors: GridItemType.PATH_STRAIGHT_UP: [{x: 0, y: -1}] GridItemType.PATH_STRAIGHT_DOWN: [{x: 0, y: 1}] GridItemType.PATH_STRAIGHT_LEFT: [{x: -1, y: 0}] GridItemType.PATH_STRAIGHT_RIGHT: [{x: 1, y: 0}] GridItemType.PATH_CORNER_TOP_LEFT (visual ┌): [{x: 0, y: -1}, {x: -1, y: 0}] (representing the two segments of the corner from its center). GridItemType.PATH_CORNER_TOP_RIGHT (visual ┐): [{x: 0, y: -1}, {x: 1, y: 0}] GridItemType.PATH_CORNER_BOTTOM_LEFT (visual └): [{x: 0, y: 1}, {x: -1, y: 0}] GridItemType.PATH_CORNER_BOTTOM_RIGHT (visual ┘): [{x: 0, y: 1}, {x: 1, y: 0}] GridItemType.PATH_CROSSROAD: [{x: 0, y: -1}, {x: 0, y: 1}, {x: -1, y: 0}, {x: 1, y: 0}] (all four cardinal directions). GridItemType.SPAWN: Return self.getPossibleNextCellsForPath(cell, null). Transform results from {x,y} to {dx,dy} relative to cell. GridItemType.GOAL, GridItemType.WALL, GridItemType.TOWER_SLOT: Return [] (no arrows). Enemy Class Movement Logic 2.1. Property Initialization Instruction: In Enemy constructor, set self.prevCellX = -1; and self.prevCellY = -1; (or similar non-path coordinates) to clearly indicate the enemy has not yet entered the grid for path following. Remove any other prevCellX/Y initializations. 2.2. Initial Spawn Position Correction Instruction: In game.update where enemies are spawned: Modify enemy.currentCellX = spawnCell.x; to enemy.currentCellX = spawnCell.x + 0.5; to ensure horizontal centering in the spawn cell. Modify enemy.currentCellY = spawnCell.y - (1 + Math.random() * 5); to enemy.currentCellY = (spawnCell.y + 0.5) - (1 + Math.random() * 5); for vertical centering. 2.3. Grid.updateEnemy Method Overhaul Instruction: Within grid.updateEnemy(enemy): Modify the hasReachedEntryArea condition: var hasReachedEntryArea = enemy.currentCellY >= (enemy.assignedPath[0].y + 0.5); (checks if enemy reached the visual center of the spawn cell vertically). Inside the if (!hasReachedEntryArea) block: When enemy.currentCellY reaches (enemy.assignedPath[0].y + 0.5) for the first time: Set enemy.currentCellY = enemy.assignedPath[0].y + 0.5; Set enemy.cellX = enemy.assignedPath[0].x; Set enemy.cellY = enemy.assignedPath[0].y; Initialize enemy.currentWaypointIndex = 0; (if not already handled by spawn assignment). Instruction: In the else if (!enemy.isFlying) block (ground enemy path following): Remove the if (!enemy.currentTarget) { ... } block and if (cell.score < enemy.currentTarget.score) { ... } condition (A* remnants). The logic should always proceed with enemy.assignedPath and enemy.currentWaypointIndex. The check if (enemy.currentWaypointIndex >= enemy.assignedPath.length - 1) for reaching the goal is correct and should remain as the primary return true condition for path completion. Retrieve the targetWaypoint: var targetWaypoint = enemy.assignedPath[enemy.currentWaypointIndex + 1]; Crucial Correction: Recalculate dx and dy for movement vector from enemy's current floating-point grid position to the center of the targetWaypoint cell: var dx = (targetWaypoint.x + 0.5) - enemy.currentCellX; var dy = (targetWaypoint.y + 0.5) - enemy.currentCellY; Recalculate distToTarget: var distToTarget = Math.sqrt(dx * dx + dy * dy); (this distToTarget is now in grid units). Correction: Change the waypoint advancement condition to if (distToTarget < enemy.speed * 1.5). The 1.5 factor provides a small buffer to ensure the enemy fully 'enters' the target cell before advancing the waypoint. Inside the advancement block (if (distToTarget < enemy.speed * 1.5)): Snap enemy.currentCellX = targetWaypoint.x + 0.5; Snap enemy.currentCellY = targetWaypoint.y + 0.5; Increment enemy.currentWaypointIndex; Update integer grid coordinates: enemy.cellX = targetWaypoint.x; enemy.cellY = targetWaypoint.y; Immediately re-check if (enemy.currentWaypointIndex >= enemy.assignedPath.length - 1) and return true; if at or past the goal. In the else block (if not close enough to snap): Continue updating enemy.currentCellX and enemy.currentCellY using the angle and enemy.speed. Ensure enemy.x and enemy.y are updated at the end of the updateEnemy function using the floating-point enemy.currentCellX and enemy.currentCellY to maintain smooth movement. Tower Class Targeting 3.1. findTarget Method Logic Instruction: In self.findTarget = function() { ... }, for ground enemies (else block of if (enemy.isFlying)): Replace the cell && cell.pathId === pathId check (old A*). Prioritize enemies based on their progress along assignedPath: Calculate var pathProgress = enemy.currentWaypointIndex / (enemy.assignedPath.length - 1); (0.0 to 1.0, where 1.0 is at goal). Use -pathProgress as the closestScore metric for ground enemies (higher progress = lower negative score = higher priority). Ensure enemy.assignedPath is not null or empty before using pathProgress. DebugCell Class Enhancement 4.1. Arrow Rendering Instruction: In DebugCell.render(data): Remove the debugArrows array and the self.removeArrows() function. At the start of render, call while (self.children.length > 1) { self.removeChild(self.children[self.children.length - 1]); } to clear all children except numberLabel. Inside the switch (data.type) statement, for all path-related GridItemType cases (PATH_CROSSROAD, PATH_STRAIGHT_*, PATH_CORNER_*, SPAWN): Retrieve arrow vectors: var arrowVectors = grid._getDebugArrowsForCell(data.cell); (or just data if cell itself is passed as data). Loop through arrowVectors: For each {dx, dy} in arrowVectors: Create a new arrow asset: var arrow = LK.getAsset('arrow', { anchorX: -.5, anchorY: 0.5 }); Set arrow.alpha = .5; Set arrow.rotation = Math.atan2(dy, dx); Set arrow.x and arrow.y to a small offset from 0,0 (local center of DebugCell) to ensure visibility if multiple arrows are stacked. E.g., arrow.x = dx * 10; arrow.y = dy * 10; for small outward shift. Add self.addChild(arrow); Note: Pass the actual cell object to DebugCell.render so it has direct access to cell.type etc. Adjust debugCell.render(self.cells[i][j]); in Grid.renderDebug() accordingly.
Code edit (1 edits merged)
Please save this source code
User prompt
Objective: Implement a comprehensive pre-calculated pathfinding system for ground enemies, enabling all possible paths from spawn to goal to be traversed, and ensuring round-robin path assignment at spawn. Action Items: Grid Pathfinding Rework Transition from on-the-fly path determination to a full, pre-calculated path network. 1.1. Clear Existing Path Data Remove the nextPathCell property from all self.cells[i][j] objects during Grid initialization. This property is no longer relevant for the new pathfinding approach. Remove cell.crossroadLastAssignedIndex from Grid initialization. 1.2. Implement buildAllGroundPaths Method Define a new method self.buildAllGroundPaths within the Grid class. This method must perform a graph traversal (e.g., Depth-First Search) starting from each SPAWN cell (GridItemType.SPAWN) to discover all unique, valid paths leading to any GOAL cell (GridItemType.GOAL). Store these complete paths as ordered arrays of cell coordinates (e.g., [{x, y}, {x, y}, ...]) in a new self.allGroundPaths array. The traversal logic must respect GridItemType definitions: WALL and TOWER_SLOT cells (when isOccupied) are impassable. For PATH_STRAIGHT_UP, PATH_STRAIGHT_DOWN, PATH_STRAIGHT_LEFT, PATH_STRAIGHT_RIGHT, the next cell is fixed based on the tile's explicit direction (e.g., PATH_STRAIGHT_UP always moves towards y-1). For PATH_CORNER_TOP_LEFT, PATH_CORNER_TOP_RIGHT, PATH_CORNER_BOTTOM_LEFT, PATH_CORNER_BOTTOM_RIGHT, the next cell is determined by the entry direction to ensure correct turning. For PATH_CROSSROAD, all valid cardinal neighbors (excluding the cell from which the current cell was entered) are considered as potential next steps, leading to path branching. Implement a mechanism to prevent infinite loops during path traversal (e.g., by tracking visited cells within a single path segment). Upon completion, self.allGroundPaths should contain all valid paths. Note: This method will replace the function previously named pathFind. 1.3. Update Grid.pathFind Modify Grid.pathFind to simply call self.buildAllGroundPaths(). This function now acts as an orchestrator for the full path pre-calculation. Remove all pathId, score, and targets related logic from Grid.pathFind as it's deprecated. 1.4. Remove Obsolete Pathfinding Helpers Delete self.getEnemyNextWaypoint from the Grid class. Delete self._getPossibleNextCells from the Grid class. These methods are no longer necessary as enemies will follow pre-calculated paths. Enemy Path Management Ground enemies will now be explicitly assigned a path from the pre-calculated list. 2.1. Enemy Path Initialization Add a new property self.assignedPath to the Enemy class. Initialize it to null. Add a new property self.currentWaypointIndex to the Enemy class. Initialize it to 0. The prevCellX and prevCellY properties on the Enemy class are now largely obsolete for explicit path traversal; they can be repurposed or simplified to track the actual previous waypoint for precise movement or rotation. 2.2. Round-Robin Path Assignment at Spawn In the game.update function, within the enemy spawning logic (if (!waveSpawned) block): Introduce a global or Grid level index (e.g., grid.nextPathAssignmentIndex) to track which path to assign next. Initialize it to 0. When spawning a ground enemy (!enemy.isFlying): Assign enemy.assignedPath = grid.allGroundPaths[grid.nextPathAssignmentIndex % grid.allGroundPaths.length]. Increment grid.nextPathAssignmentIndex. Initialize enemy.currentWaypointIndex = 0. Set enemy.cellX and enemy.cellY to the coordinates of the first waypoint in enemy.assignedPath. Set enemy.currentCellX and enemy.currentCellY similarly, adjusting for the initial vertical entry animation. Initialize enemy.prevCellX and enemy.prevCellY to the actual cell before the first path cell (e.g., enemy.cellY - 1 if the first path cell is directly below the spawn). This will be used for rotation logic. Note: Flying enemies retain their existing direct-to-goal movement. 2.3. Update Enemy Movement (Grid.updateEnemy) For ground enemies (!enemy.isFlying): Remove all logic that calls grid.getEnemyNextWaypoint or relies on cell.nextPathCell. Modify movement logic to iterate through enemy.assignedPath. If enemy.currentWaypointIndex is less than enemy.assignedPath.length - 1: Set enemy.targetWaypoint = enemy.assignedPath[enemy.currentWaypointIndex + 1]. Move enemy.currentCellX and enemy.currentCellY towards enemy.targetWaypoint.x * CELL_SIZE + CELL_SIZE / 2 and enemy.targetWaypoint.y * CELL_SIZE + CELL_SIZE / 2 respectively, using enemy.speed. When the enemy reaches the center of enemy.assignedPath[enemy.currentWaypointIndex + 1] (i.e., distToCenter < enemy.speed * 0.5), increment enemy.currentWaypointIndex. Update enemy.prevCellX and enemy.prevCellY to enemy.cellX and enemy.cellY before updating enemy.cellX and enemy.cellY to the new targetWaypoint's coordinates. This preserves the entry direction for rotation. If enemy.currentWaypointIndex is enemy.assignedPath.length - 1 and the enemy reaches the goal cell: Return true to indicate the enemy has reached the end of its path. Ensure enemy rotation logic correctly uses enemy.prevCellX, enemy.prevCellY and the new enemy.cellX, enemy.cellY (which now represents the next waypoint target) to determine orientation. The initial vertical movement from off-screen to currentCellY >= 4 remains unchanged for both ground and flying enemies. Tower Targeting (Tower.findTarget) Adjust ground enemy prioritization to use progress along assigned path. 3.1. Prioritize Ground Enemies by Path Progress For !enemy.isFlying enemies, replace cell.score based prioritization. Prioritize enemies with a higher enemy.currentWaypointIndex (meaning they are further along their assigned path towards the goal). If multiple enemies have the same currentWaypointIndex, secondary sort by distance to tower, or distance to goal, as appropriate. Cleanup and Refinement Remove all pathId and maxScore global variables. Remove any remaining debug rendering or logic tied to score, targets, or the old A* pathfinding system in DebugCell and Grid.renderDebug. Review Tower.placeOnGrid and Tower.sellButton.down to ensure grid.pathFind() (now grid.buildAllGroundPaths()) is called only when grid impassability changes (tower placed/removed), but note that path recalculation is no longer strictly required for every tower action since enemies don't dynamically pathfind around new towers. However, if path validity can be blocked by a tower, grid.buildAllGroundPaths() should still be called to check. Verify that TowerPreview.updatePlacementStatus correctly uses GridItemType.TOWER_SLOT and cell.isOccupied. The mapLayout in Grid should correspond to the new editor map layout that uses the GridItemType enum values (0-12). The provided map layout is already updated, so no changes there.
User prompt
Enemy Class Refactor Manage the enemy's current and previous grid positions for path traversal. 3.1. Enemy Properties Instruction: Remove self.currentTarget = undefined;. Instruction: Add new properties self.prevCellX = 0; and self.prevCellY = 0;. 3.2. Constructor Initialization Instruction: In the Enemy constructor, after setting initial enemy.cellX and enemy.cellY from the spawn cell, initialize enemy.prevCellX = enemy.cellX; and enemy.prevCellY = enemy.cellY;. This sets the 'previous' cell to the spawn point for the first movement step. Tower.findTarget() Refactor Adjust enemy prioritization for ground enemies without cell.score. 4.1. Ground Enemy Prioritization Instruction: In Tower.prototype.findTarget, for ground enemies (!enemy.isFlying), remove the if (cell && cell.pathId === pathId) check and the reliance on cell.score. Instruction: For ground enemies, change the prioritization to target the enemy with the highest enemy.cellY (assuming goals are generally at higher Y coordinates in the grid) or, more accurately, the closest Euclidean distance to any GridItemType.GOAL cell. The latter is preferred for robust targeting. Instruction: Modify Tower.findTarget to prioritize non-flying enemies by their Euclidean distance to the closest GridItemType.GOAL cell. Lower distance implies higher priority. DebugCell Class Refactor Simplify debug rendering, removing irrelevant A* visualizations. 5.1. render Method Simplification Instruction: In DebugCell.prototype.render, remove all logic related to data.score, data.pathId, and data.targets. Instruction: Remove debugArrows array, self.removeArrows(), and all associated arrow rendering logic. Instruction: Ensure cellGraphics.tint and cellGraphics.alpha are set purely based on data.type (GridItemType) and data.isOccupied, as defined in the new GridImplementationGuide for visual clarity. Example: GridItemType.SPAWN should be green, GridItemType.GOAL should be red, GridItemType.TOWER_SLOT should reflect isOccupied. Game Initialization Flow 6.1. Initial Path Setup Instruction: Ensure grid.initializePathData(); is called exactly once after the grid object is instantiated and its cells are populated, typically in the Initialize Game section. This effectively replaces the initial grid.pathFind() call. 6.2. Remove Redundant Blocker Placement Instruction: Remove the commented-out section for blocker placement, as the grid now has a fixed layout and blocker class is not defined.
User prompt
Grid Class Refactor Redefine internal grid cell structure and pathfinding logic. 2.1. self.cells Initialization Instruction: Modify the Grid constructor. For each cell object in self.cells[i][j], remove the properties score, pathId, and targets. Instruction: Remove cell.upLeft, cell.up, cell.upRight, cell.left, cell.right, cell.downLeft, cell.down, cell.downRight, and cell.neighbors assignments as these neighbor references are no longer directly used for pathfinding. Instruction: Add a new property cell.crossroadLastAssignedIndex = 0; to cell objects only if cell.type is GridItemType.PATH_CROSSROAD. 2.2. mapLayout Integration Instruction: Update the mapLayout array in the Grid constructor to precisely match the provided GridImplementationGuide's mapLayout data. 2.3. Pathfinding Logic Replacement Instruction: Delete the entire self.pathFind = function() { ... } method. Instruction: Implement a new private helper function Grid.prototype._getPossibleNextCells(currentCell, previousCell) within the Grid class: This function should take the current grid cell currentCell and the previousCell (where the enemy just came from) as arguments. It must return an array of {x: number, y: number} coordinates representing all valid, non-backtracking path cells reachable from currentCell. For GridItemType.PATH_CROSSROAD cells: Identify all four adjacent cells. Filter out the previousCell and any WALL or TOWER_SLOT cells. Return the remaining valid path cells. For GridItemType.PATH_STRAIGHT_UP/DOWN/LEFT/RIGHT cells: Determine the single valid forward cell based on previousCell (entry direction) and currentCell.type. Return this single cell in an array. For GridItemType.PATH_CORNER_TOP_LEFT/TOP_RIGHT/BOTTOM_LEFT/BOTTOM_RIGHT cells: Determine the single valid exit cell based on previousCell (entry direction) and currentCell.type, as per the logic described in the GridImplementationGuide. Return this single cell in an array. Note: The previousCell parameter is crucial for determining the correct exit for straight and corner path segments. Instruction: Implement a new Grid.prototype.getEnemyNextWaypoint(enemyCurrentX, enemyCurrentY, enemyPrevX, enemyPrevY) method: Retrieve currentCell = self.getCell(enemyCurrentX, enemyCurrentY). Retrieve previousCell = self.getCell(enemyPrevX, enemyPrevY). If currentCell.type is GridItemType.GOAL, return null. If currentCell.type is GridItemType.PATH_CROSSROAD: Call this._getPossibleNextCells(currentCell, previousCell) to get all valid branching paths. Sort this array (e.g., by X then Y coordinate) for deterministic cycle order. Update currentCell.crossroadLastAssignedIndex = (currentCell.crossroadLastAssignedIndex + 1) % possibleExits.length;. Return the {x, y} coordinate from possibleExits[currentCell.crossroadLastAssignedIndex]. For all other path GridItemTypes (straights, corners): Call this._getPossibleNextCells(currentCell, previousCell). This should return an array with a single next cell. Return that cell's {x,y}. Handle cases where currentCell or previousCell is invalid (e.g., null or WALL). 2.4. self.updateEnemy Method Refactor Instruction: Modify the Grid.prototype.updateEnemy(enemy) method significantly. Instruction: For non-flying enemies that have entered the playable grid area (enemy.currentCellY >= 4): Determine if the enemy has reached the center of its current (enemy.cellX, enemy.cellY) grid square. A small epsilon comparison (distance < enemy.speed * 0.5) can be used to detect proximity. If the enemy is at the center or has just crossed into the new cell: Call nextWaypoint = self.getEnemyNextWaypoint(enemy.cellX, enemy.cellY, enemy.prevCellX, enemy.prevCellY); If nextWaypoint is null, the enemy has reached a GOAL. Return true. Update enemy.prevCellX = enemy.cellX; and enemy.prevCellY = enemy.cellY;. Update enemy.cellX = nextWaypoint.x; and enemy.cellY = nextWaypoint.y;. Move the enemy's visual enemy.x and enemy.y towards the center of its current target cell (grid.x + enemy.cellX * CELL_SIZE + CELL_SIZE / 2, grid.y + enemy.cellY * CELL_SIZE + CELL_SIZE / 2). Ensure enemy rotation is correctly updated to face the current target cell. Note: The enemy.currentCellX and enemy.currentCellY should represent the continuous, floating-point position of the enemy on the grid, while enemy.cellX and enemy.cellY should represent the integer grid coordinates of the target cell the enemy is currently moving towards. Adjust existing movement logic (enemy.currentCellX += ..., enemy.currentCellY += ...) to use the target cell enemy.cellX, enemy.cellY for calculation. 2.5. Grid.initializePathData() Calls Instruction: Remove all calls to grid.pathFind() from Tower.placeOnGrid, game.move, and game.up event handlers. The path is now explicitly defined and not affected by tower placement. 2.6. self.spawns and self.goals Population Instruction: Ensure self.spawns and self.goals arrays are populated correctly during Grid initialization by iterating through the mapLayout and identifying cells with GridItemType.SPAWN and GridItemType.GOAL.
User prompt
Objective: Refactor the grid system to align with the provided GridImplementationGuide, transitioning from A*-based pathfinding to explicit path traversal with crossroad splitting. Action Items: Global Game State and Constants Define GridItemType enum, if not already present. 1.1. pathId and maxScore Removal Instruction: Delete global variables pathId and maxScore. Note: These are remnants of the A* pathfinding system, which will be entirely replaced.
Code edit (1 edits merged)
Please save this source code
User prompt
Objective: Refactor the game's grid and pathfinding systems to align with the explicit GridItemType enum and path traversal logic provided by the TD Level Editor. Action Items: GridItemType Definition Define a global or static class containing constants for all GridItemType values. 1.1. Constants Declaration Instruction: Declare integer constants for PATH_CROSSROAD (0), PATH_STRAIGHT_UP (1), PATH_STRAIGHT_DOWN (2), PATH_STRAIGHT_LEFT (3), PATH_STRAIGHT_RIGHT (4), PATH_CORNER_TOP_LEFT (5), PATH_CORNER_TOP_RIGHT (6), PATH_CORNER_BOTTOM_LEFT (7), PATH_CORNER_BOTTOM_RIGHT (8), WALL (9), SPAWN (10), GOAL (11), TOWER_SLOT (12). Note: These constants will replace hardcoded magic numbers for cell types throughout the codebase. Grid Class (Grid) Core logic for map structure, cell properties, and path management. 2.1. Constructor Refactor Instruction: Update the mapLayout array in the Grid constructor to reflect the new GridItemType values from the level editor. Ensure the provided mapLayout in the current code (Version 1) is entirely replaced by the new integer mappings. Instruction: Modify the cell initialization loop (for (var i = 0; i < gridWidth; i++) { for (var j = 0; j < gridHeight; j++) { ... } }) to remove cell.score, cell.pathId, and cell.targets. Instruction: Add a new property cell.nextPathCell to each cell object. Initialize it to null. This will store the next cell in the calculated path for ground enemies. Instruction: Ensure self.spawns and self.goals are populated correctly by identifying cells with GridItemType.SPAWN and GridItemType.GOAL respectively. Instruction: Modify the DebugCell instantiation within the constructor. Temporarily comment out or remove the DebugCell instantiation if DebugCell is not yet updated, to prevent errors. It will be re-enabled after DebugCell is refactored. 2.2. pathFind Method Refactor Instruction: Completely replace the existing pathFind method implementation. Instruction: Implement a path-building algorithm that traverses from SPAWN to GOAL using the explicit GridItemType connections. Instruction: Introduce a helper function, findFirstPathCell(spawnPos, grid), to determine the first path cell an enemy would enter from a SPAWN cell. Instruction: Implement getNextPosition(x, y, prevX, prevY, grid) as described in the guide, using the new GridItemType enum for logic branches. Instruction: Create a master path array (e.g., self.groundPath) by calling a buildPath(grid) function. Instruction: After self.groundPath is built, iterate through it to populate cell.nextPathCell for all cells on the path. For example, self.groundPath[k].nextPathCell = self.groundPath[k+1]. The GOAL cell should not have a nextPathCell. Instruction: Update the path validation logic to check if self.groundPath is empty or if any enemy on a ground path is in a cell without a nextPathCell (indicating a broken path). Instruction: Remove all references to maxScore and pathId. 2.3. updateEnemy Method Refactor Instruction: For ground enemies (not enemy.isFlying): Remove enemy.currentTarget = cell.targets[0]. Instead, enemy.currentTarget should be set to cell.nextPathCell if the enemy has fully entered the current cell. Update the movement logic to direct the enemy towards enemy.currentTarget (which is cell.nextPathCell). When an enemy reaches its currentTarget cell, update its enemy.cellX and enemy.cellY to the currentTarget's coordinates, and then update its currentTarget to the newly entered cell's nextPathCell. Instruction: For flying enemies (enemy.isFlying): Ensure enemy.flyingTarget is explicitly set to the GridItemType.GOAL cell identified during grid initialization, not just self.goals[0]. If multiple goals exist, implement closest goal selection. Instruction: Remove all checks or logic dependent on cell.score or cell.pathId. Enemy Class (Enemy) Handles individual enemy behavior and interaction with the grid. 3.1. Constructor Refactor Instruction: Review enemy.currentCellY = spawnCell.y - (1 + Math.random() * 5); to ensure it aligns with the new map's spawn y-coordinates, which may differ from the hardcoded y = 4 assumption elsewhere. 3.2. update Method Refactor Instruction: Ensure the enemyGraphics.targetRotation and associated tweening correctly uses the direction from the enemy's current position to its enemy.currentTarget (the nextPathCell for ground enemies or flyingTarget for flying enemies). Tower Preview Class (TowerPreview) Manages the visual feedback for tower placement. 4.1. updatePlacementStatus Method Refactor Instruction: Change the condition cell.type !== 4 to cell.type !== GridItemType.TOWER_SLOT when checking for valid tower placement cells. Tower Class (Tower) Manages individual tower properties and actions. 5.1. placeOnGrid Method Refactor Instruction: Retain cell.isOccupied = true; for the 2x2 area covered by the tower. Instruction: Retain calls to grid.pathFind() and self.refreshCellsInRange() after tower placement, as grid.pathFind() will now recalculate the explicit ground path based on new obstacles. Debug Cell Class (DebugCell) Provides visual debugging for grid cells. 6.1. render Method Refactor Instruction: Simplify the switch (data.type) block. Remove cases that handle data.pathId and data.score. Instruction: Update tinting logic to reflect the new GridItemType enum values for clearer visual representation of cell types. Instruction: Remove numberLabel.setText("") and any other operations related to score or pathId. Instruction: Adapt or remove the debugArrows logic, as cell.targets no longer exists. Consider repurposing debugArrows to show cell.nextPathCell if detailed path visualization is still required, otherwise remove. For initial refactor, remove arrow logic. 6.2. Grid Constructor Re-enable Instruction: After DebugCell.render is refactored, uncomment or re-add the DebugCell instantiation block in the Grid constructor. Wave Indicator Class (WaveIndicator) Displays wave progression and manages wave properties. 7.1. Constructor Refactor Instruction: Review and potentially update the block.tint logic for wave markers to align with specific visual themes or type colors associated with the new GridItemType definitions, ensuring consistent aesthetics. Global Game Logic Adjust initialization and interaction points. 8.1. Game Setup Instruction: Review grid.y = 200 - CELL_SIZE * 4; and grid.x = 150; based on the new map layout's actual origin. Adjust as necessary to correctly align the game world with the visual background.
Code edit (1 edits merged)
Please save this source code
User prompt
Objective: Implement advanced enemy pathing including multi-path cycling at crossroads and forced single-direction movement on specialized path cells, requiring re-indexing of grid cell types. Action Items: Grid Cell Type Re-indexing Refactor Grid class to utilize new cell type numeric assignments across all related logic, strictly adhering to the following mapping: 0: Crossroad (multi-path splitting) 1: Path_Up (forces movement to (x, y-1)) 2: Path_Down (forces movement to (x, y+1)) 3: Path_Left (forces movement to (x-1, y)) 4: Path_Right (forces movement to (x+1, y)) 5: Corner_Left_Down (forces movement to (x, y+1)) 6: Corner_Left_Up (forces movement to (x, y-1)) 7: Corner_Right_Down (forces movement to (x, y+1)) 8: Corner_Right_Up (forces movement to (x, y-1)) 9: Wall (formerly 1) 10: Spawn (formerly 2) 11: Goal (formerly 3) 12: Tower Slot (formerly 4) Instruction: Update all instances in Grid.init (specifically the for loops populating self.cells and self.spawns/self.goals), Grid.pathFind, and Grid.updateEnemy where cell.type is referenced to reflect these new integer values. Note: The mapLayout array hardcoded within the Grid class must be manually updated by the user to use these new numerical cell types (0-12) for the system to function as intended. The coder is to implement the logic assuming these values will be present in mapLayout. Grid.pathFind Modifications Instruction: Modify the processNode function within Grid.pathFind to ensure only the newly defined walkable path cell types (0 through 8) are considered for pathfinding calculations. Cell types 9 (Wall) and 12 (Tower Slot) must remain impassable. Note: The pathFind algorithm's core logic (Dijkstra-like calculation of score and targets pointing towards the goal) will remain mostly as is. The directional nature of cells 1-8 will be enforced at the enemy movement stage (Grid.updateEnemy), not during the global path score calculation. Grid.updateEnemy Enemy Movement Logic Modify the Grid.updateEnemy function to implement specialized pathing behaviors for non-flying enemies, contingent on their current grid cell type, after they have entered the viewable game area (enemy.currentCellY >= 4). 3.1. Forced Direction Paths (Types 1-8) Instruction: When an enemy is located on a cell whose cell.type is between 1 and 8 (inclusive), enemy.currentTarget must be explicitly determined by the cell's type, overriding any shortest-path calculation from cell.targets. Instruction: For each type, define the exact relative (offsetX, offsetY) to determine the enemy.currentTarget: 1 (Path_Up): (0, -1) 2 (Path_Down): (0, 1) 3 (Path_Left): (-1, 0) 4 (Path_Right): (1, 0) 5 (Corner_Left_Down): (0, 1) (Next cell is one unit down from current) 6 (Corner_Left_Up): (0, -1) (Next cell is one unit up from current) 7 (Corner_Right_Down): (0, 1) (Next cell is one unit down from current) 8 (Corner_Right_Up): (0, -1) (Next cell is one unit up from current) Instruction: Before setting enemy.currentTarget to the forced cell, validate that the calculated target cell exists (grid.getCell(...)) and is a valid walkable path type (0-8, 10, or 11). If the forced cell is invalid (e.g., a wall or out of bounds), the enemy should fallback to the shortest path calculated by pathFind (i.e., enemy.currentTarget = cell.targets[0]). Note: This implementation for corner types (5-8) assumes a fixed outgoing direction, not an incoming-direction-aware turn. 3.2. Crossroad Splitting (Type 0) Instruction: For cells with cell.type === 0, introduce a new property cell.lastChosenPathIndex on the Grid.Cell object during its initialization within Grid.init. Initialize this property to 0. Instruction: When an enemy arrives at a cell of type 0 and cell.targets.length > 1 (indicating multiple shortest paths): Increment cell.lastChosenPathIndex. Apply modulo arithmetic to cycle through the available paths: cell.lastChosenPathIndex = cell.lastChosenPathIndex % cell.targets.length; Set enemy.currentTarget to cell.targets[cell.lastChosenPathIndex]. Instruction: If cell.targets.length <= 1, the existing enemy.currentTarget = cell.targets[0] logic (or lack thereof, if targets is empty) should apply. 3.3. General Enemy Movement Instruction: Ensure the existing positional (enemy.x, enemy.y) and graphical rotation (enemy.children[0].rotation) updates continue to function correctly based on the enemy.currentTarget derived from the above logic. DebugCell.render Visualizations Modify DebugCell.render to visually represent all new path types (0-8) and the re-indexed non-path types (9-12). Instruction: Update the switch (data.type) statement to include cases for all 13 defined cell types (0-12). Instruction: For path types 1-8, self.removeArrows() should be called. Assign distinct cellGraphics.tint values for each type to clearly indicate its forced direction. Instruction: For data.type === 0 (Crossroad), set cellGraphics.tint to a distinct color (e.g., 0x00FF00). Continue to display arrows for all data.targets as they represent the multiple valid shortest paths for enemy cycling. Instruction: Adjust cellGraphics.tint and alpha for re-indexed types 9 (Wall), 10 (Spawn), 11 (Goal), and 12 (Tower Slot) to maintain their current visual distinctions. Instruction: Remove the numberLabel.setText("") statement located at the end of the self.render function. DebugCell.down Modification Instruction: Update the conditional check in self.down from self.cell.type == 0 || self.cell.type == 1 to correctly reference the new Wall cell type (9) if the cell toggling functionality is to be retained. Alternatively, if this interaction is no longer desired, remove the if block and its contents. Grid.init Neighbor Connections Instruction: Review and adjust the cell.neighbors array population to ensure it accurately reflects connectivity for the new path types (0-8). For forced-direction cells (1-8), ensure that only the explicitly allowed next cell is considered a valid "neighbor" in terms of path traversal for enemies, even if pathFind still calculates score based on all orthogonal/diagonal neighbors. (Note: cell.neighbors is used in pathFind and for general cell awareness, not directly for enemy movement target selection. This is a consistency check.)
User prompt
Objective: Implement enemy path splitting at crossroads and re-categorize grid cell types with corresponding visual updates. Action Items: Global Constants and Cell Type Remapping Establish new integer constants for all grid cell types, adhering to the requested numbering scheme. 1.1. Cell Type Definitions Instruction: Define new global constants for cell types in the game's initialization or a shared utility area. Instruction: CELL_TYPE_PATH_CROSSROAD = 0 Instruction: CELL_TYPE_PATH_STRAIGHT_UP = 1 Instruction: CELL_TYPE_PATH_STRAIGHT_RIGHT = 2 Instruction: CELL_TYPE_PATH_STRAIGHT_DOWN = 3 Instruction: CELL_TYPE_PATH_STRAIGHT_LEFT = 4 Instruction: CELL_TYPE_PATH_CORNER_UL_DR = 5 Instruction: CELL_TYPE_PATH_CORNER_UR_DL = 6 Instruction: CELL_TYPE_PATH_CORNER_DL_UR = 7 Instruction: CELL_TYPE_PATH_CORNER_DR_UL = 8 Instruction: CELL_TYPE_WALL = 9 Instruction: CELL_TYPE_SPAWN = 10 Instruction: CELL_TYPE_GOAL = 11 Instruction: CELL_TYPE_TOWER_SLOT = 12 Grid Class Modifications Update cell type assignment in the constructor and introduce path cycling state. 2.1. Constructor Cell Type Mapping Instruction: Modify the Grid class constructor where cell.type is assigned from mapLayout[j][i]. Instruction: Implement a mapping: if mapLayout[j][i] is 0, assign cell.type to CELL_TYPE_PATH_CROSSROAD. Instruction: If mapLayout[j][i] is 1, assign cell.type to CELL_TYPE_WALL. Instruction: If mapLayout[j][i] is 2, assign cell.type to CELL_TYPE_SPAWN. Instruction: If mapLayout[j][i] is 3, assign cell.type to CELL_TYPE_GOAL. Instruction: If mapLayout[j][i] is 4, assign cell.type to CELL_TYPE_TOWER_SLOT. Instruction: Initialize a new property cell.lastPathChoiceIndex = 0; for all grid cells. 2.2. pathFind Method Updates Instruction: In Grid.pathFind, update the processNode function's conditional check node.type !== 1 && node.type !== 4 to use the new constants node.type !== CELL_TYPE_WALL && node.type !== CELL_TYPE_TOWER_SLOT. Note: The existing pathfinding logic for generating node.targets should remain as is, ensuring it identifies all equally optimal next cells. 2.3. updateEnemy Method for Path Splitting Instruction: In Grid.updateEnemy, locate the logic block responsible for ground enemy target selection (!enemy.isFlying). Instruction: Modify the target assignment: If enemy.currentTarget is undefined (meaning the enemy just arrived at enemy.cellX, enemy.cellY or needs a new path), perform the following: Retrieve currentCell = self.getCell(enemy.cellX, enemy.cellY);. If currentCell.type === CELL_TYPE_PATH_CROSSROAD and currentCell.targets.length > 1: Assign enemy.currentTarget = currentCell.targets[currentCell.lastPathChoiceIndex % currentCell.targets.length];. Increment currentCell.lastPathChoiceIndex++;. Else (if not a crossroad, or no multiple targets from pathfinding), if currentCell.targets.length > 0: Assign enemy.currentTarget = currentCell.targets[0];. Else (no valid targets, potentially stuck or at goal): If currentCell.type === CELL_TYPE_GOAL: return true. Else: log warning and return true (enemy considered lost). Instruction: Ensure that when an enemy successfully reaches its enemy.currentTarget, enemy.currentTarget is reset to undefined to trigger the re-evaluation and splitting logic for the next cell. This is typically done within the if (dist < enemy.speed) block. DebugCell Class Modifications Update rendering logic to visually distinguish the new cell types. 3.1. render Method Tints Instruction: In DebugCell.render, update the switch (data.type) block to use the new cell type constants. Instruction: For case CELL_TYPE_PATH_CROSSROAD:, assign a distinct tint (e.g., 0x888800 for yellow/brownish) and ensure numberLabel.visible = false; is set. Instruction: For case CELL_TYPE_WALL:, set cellGraphics.tint = 0xAAAAAA; cellGraphics.alpha = 0; numberLabel.visible = false;. Instruction: For case CELL_TYPE_SPAWN:, set cellGraphics.tint = 0x008800; cellGraphics.alpha = 0.1; numberLabel.visible = false;. Instruction: For case CELL_TYPE_GOAL:, set cellGraphics.tint = 0x00BFFF; cellGraphics.alpha = 0.1; numberLabel.visible = false;. Instruction: For case CELL_TYPE_TOWER_SLOT:, set cellGraphics.tint = data.isOccupied ? 0x0088CC : 0x00BFFF; cellGraphics.alpha = 0.1; numberLabel.visible = false;. Instruction: For path types CELL_TYPE_PATH_STRAIGHT_UP through CELL_TYPE_PATH_CORNER_DR_UL (1-8), add case statements. Assign unique tints for each of these new path types to visually differentiate them if they are ever used in the mapLayout. For now, cellGraphics.tint = 0x880000; cellGraphics.alpha = 0.1; numberLabel.visible = false; can serve as a default for these, or pick distinct colors if the map explicitly uses them. Note: The existing arrow rendering logic (debugArrows loop) should remain as is; it will correctly display multiple arrows for crossroads if data.targets contains multiple equally optimal paths.
User prompt
Objective: Redefine enemy path traversal to utilize explicit, pre-configured directional cell types, ensuring deterministic path commitment through crossroads and curved segments. Action Items: Grid Cell Definition Augmentation Introduce a comprehensive set of new cell type constants within Grid class, or as global constants, to represent explicit directional and junction behaviors. 1.1. New Cell Types: CELL_TYPE_PATH_STRAIGHT_VERTICAL (e.g., 0) CELL_TYPE_PATH_STRAIGHT_HORIZONTAL (e.g., 5) CELL_TYPE_CROSSROADS_FOUR_WAY (e.g., 6) CELL_TYPE_CORNER_TOP_LEFT_TO_DOWN (e.g., 7) CELL_TYPE_CORNER_TOP_RIGHT_TO_DOWN (e.g., 8) CELL_TYPE_CORNER_BOTTOM_LEFT_TO_UP (e.g., 9) CELL_TYPE_CORNER_BOTTOM_RIGHT_TO_UP (e.g., 10) CELL_TYPE_PATH_SPLIT_DOWN_LEFT (e.g., 11) - for a three-way split: main path continues down, one path branches left. CELL_TYPE_PATH_SPLIT_DOWN_RIGHT (e.g., 12) - for a three-way split: main path continues down, one path branches right. (Retain existing CELL_TYPE_WALL, CELL_TYPE_SPAWN, CELL_TYPE_GOAL, CELL_TYPE_TOWER_SLOT) 1.2. Grid mapLayout Update: Modify the mapLayout array within Grid constructor to encode these new directional cell.type values for all path cells, reflecting the desired fixed routes. Note: Manually assigning these values in mapLayout is critical to define the specific paths. Enemy Path Commitment Refactor Completely revise Grid.updateEnemy for ground enemies to eliminate reliance on cell.score, cell.targets, and cell.availableNextCells for movement decisions after initial spawn. 2.1. Remove Pathfinding Dependencies: Delete enemy.currentTarget property. Delete enemy.committedPath and enemy.committedPathIndex properties. Remove all grid.pathFind() calls after map initialization or tower placement, as this system will no longer be used for enemy movement. Remove pathId, maxScore global variables. 2.2. Implement Directional Movement Logic in Grid.updateEnemy: For a ground enemy that has hasReachedEntryArea == true: Determine enemy.nextDirection based on its current cell.type. If cell.type is a CELL_TYPE_CROSSROADS_FOUR_WAY: Introduce a cell.lastChosenDirectionIndex property (initialized to 0 for each cell). Define an array of possibleDirections (e.g., [DOWN, LEFT, RIGHT, UP] for a four-way). Select enemy.nextDirection = possibleDirections[cell.lastChosenDirectionIndex % possibleDirections.length]. Increment cell.lastChosenDirectionIndex. If cell.type is a specific straight or corner type (e.g., CELL_TYPE_CORNER_TOP_LEFT_TO_DOWN): Explicitly set enemy.nextDirection based on the predefined flow of that cell type. Based on enemy.nextDirection, calculate the precise targetX and targetY grid coordinates for the center of the next cell. Update enemy.currentCellX and enemy.currentCellY to smoothly interpolate towards these targetX and targetY coordinates using enemy.speed. When enemy.currentCellX and enemy.currentCellY are sufficiently close to targetX and targetY (e.g., dist < enemy.speed), update enemy.cellX and enemy.cellY to the integer values of targetX and targetY, and ensure enemy.nextDirection is re-evaluated for the new current cell. Handle enemy rotation (enemyGraphics.rotation) to align with enemy.nextDirection. 2.3. Path Blockage Handling: Since pathfinding is removed, Grid.pathFind can no longer check for blocked paths. You must implement alternative collision detection if placing towers can block a fixed path, or ensure towers are only placeable on CELL_TYPE_TOWER_SLOT which are implicitly impassable. Debug Visualization Adjustment Modify DebugCell.render to display visual cues corresponding to the new directional cell types instead of score and targets. 3.1. Visual Feedback: Change cellGraphics.tint based on the new cell.type to visually distinguish path types (straight, corner, crossroad).
User prompt
Objective: Modify Grid.generatePathSegment to extend enemy paths along unambiguous segments derived from availableNextCells, ensuring commitment to a chosen path at a crossroad until the next decision point or goal. Action Items: Grid.generatePathSegment Method Refactor Instruction: Locate the self.generatePathSegment function within the Grid class. Instruction: Re-implement the while loop logic to iterate through currentNode.availableNextCells instead of currentNode.targets. Instruction: Ensure the segment is extended only if currentNode.availableNextCells contains exactly one element. Instruction: Terminate segment generation if currentNode.type is 3 (Goal), or if currentNode.availableNextCells is null/undefined, empty, or contains more than one element (indicating a crossroads where a new decision is required). Note: This ensures that once an enemy chooses a branch at a junction, it follows that specific branch until it reaches the end of an unambiguous path segment, allowing other enemies to select alternative branches at that same initial junction. Enemy.committedPath Behavior (Verification) Instruction: Confirm Enemy.committedPath is initialized as an empty array and Enemy.committedPathIndex is initialized to 0. Instruction: Verify that in Grid.updateEnemy, enemy.committedPath is reset to empty and enemy.committedPathIndex to 0 whenever enemy.currentTarget becomes undefined, triggering a new path segment calculation using cell.availableNextCells and cell.lastChosenPathIndex. Instruction: Verify cell.lastChosenPathIndex is incremented using the modulo operator (% cell.availableNextCells.length) when a new path segment is chosen.
User prompt
Objective: Identify and remediate the core logic error preventing enemy path commitment, ensuring long-route adherence without a full system re-architecture. Action Items: Grid.updateEnemy Method Refactor Target: Grid.prototype.updateEnemy. 1.1. Eliminate Premature Path Re-evaluation Instruction: Locate and remove the following conditional statement block: if (cell.score < enemy.currentTarget.score) { enemy.currentTarget = cell; } Note: This line is located within the if (enemy.currentTarget) block for "normal pathfinding enemies". Its presence overrides any committedPath selection by forcing enemies to always revert to the shortest available path from their current cell, directly causing the observed "snapping back" behavior. Its removal is critical for path commitment.
User prompt
Objective: Enable enemies to commit to an entire path segment chosen at a crossroad, rather than re-evaluating at each subsequent cell, and ensure path selection cycling functions robustly. Action Items: Grid Class - generatePathSegment Method Modification Description: Adjust the path segment generation logic to trace a full path to the goal, not just to the next crossroad. 1.1. Modify Path Tracing Logic: Instruction: Locate Grid.prototype.generatePathSegment. Instruction: Remove the condition if (currentNode.availableNextCells.length > 1) { break; } from inside the while(true) loop. Instruction: Inside the while(true) loop, within the block that handles currentNode.availableNextCells.length === 1, change the condition to if (currentNode.targets && currentNode.targets.length > 0). Instruction: Replace the line currentNode = currentNode.availableNextCells[0]; with currentNode = currentNode.targets[0];. Instruction: Ensure the segment.push(currentNode); line remains, adding the new currentNode to the segment. Note: The currentNode.targets array is populated during pathFind with the single (or multiple, if scores are equal) optimal next step(s) from that currentNode. By always taking targets[0], we ensure a deterministic "shortest path" continuation from that chosen branch. Grid Class - updateEnemy Method Modification Description: Correct the cycling index logic to prevent out-of-bounds access and ensure continuous path rotation. 2.1. Fix lastChosenPathIndex Modulo: Instruction: Locate Grid.prototype.updateEnemy. Instruction: Find the line cell.lastChosenPathIndex = cell.lastChosenPathIndex + 1;. Instruction: Modify this line to cell.lastChosenPathIndex = (cell.lastChosenPathIndex + 1) % cell.availableNextCells.length;. Note: This ensures lastChosenPathIndex always stays within the valid bounds of availableNextCells and properly cycles through all options for subsequent enemies arriving at the same crossroad. Enemy Class - Initialize committedPath Properties Description: Ensure enemy path state is reset correctly on spawn for path commitment. 3.1. Initialize Enemy committedPath and committedPathIndex: Instruction: Locate the Enemy class constructor. Instruction: Verify that self.committedPath = []; and self.committedPathIndex = 0; are present and correctly initialized for new Enemy instances.
User prompt
Objective: Eliminate premature path re-evaluation, enabling enemies to commit to chosen path segments, including longer routes, after selecting a branch at a crossroads. Action Items: Grid Cell Property Refinement Ensure each cell object is initialized with only necessary pathfinding state. 1.1. Instruction: In the Grid constructor, within the inner loop that initializes self.cells[i][j], remove the pathCycleIndex property from the cell object if it exists. Retain lastChosenPathIndex. Enemy Path Commitment Implementation Introduce properties on the Enemy class to manage a committed path segment. 2.1. Instruction: In the Enemy constructor, initialize two new properties: self.committedPath = []; (an empty array to store the sequence of cells in the current committed segment) self.committedPathIndex = 0; (an index to track progress within the committedPath) 2.2. Instruction: In the Grid.updateEnemy function, locate the "Handle normal pathfinding enemies" section. CRITICAL REMOVAL: Locate and delete the following entire if block: if (cell.score < enemy.currentTarget.score) { enemy.currentTarget = cell; } Note: This line is the root cause of enemies reverting to the shortest path prematurely. Its removal is essential for path commitment. Segment Progression Logic: Modify the if (dist < enemy.speed) block (where the enemy reaches its currentTarget) to advance its committedPathIndex rather than clearing currentTarget immediately. if (dist < enemy.speed) { enemy.cellX = Math.round(enemy.currentCellX); enemy.cellY = Math.round(enemy.currentCellY); // Advance to the next cell in the committed path segment enemy.committedPathIndex++; // If the end of the committed segment is reached, clear it to trigger a new decision if (enemy.committedPathIndex >= enemy.committedPath.length) { enemy.committedPath = []; // Clear the segment enemy.committedPathIndex = 0; // Reset index enemy.currentTarget = undefined; // Signal need for new path decision } else { // Otherwise, set the next target from the current committed segment enemy.currentTarget = enemy.committedPath[enemy.committedPathIndex]; } return; // Early exit, as enemy has reached its current target and potentially set a new one } New Segment Selection Logic: Modify the initial if (!enemy.currentTarget) block to generate and commit to a multi-cell path segment. if (!enemy.currentTarget) { // If enemy has no current target (just spawned or finished a segment) // and there's no committed path, determine a new segment. if (cell.availableNextCells && cell.availableNextCells.length > 0) { var chosenIndex = cell.lastChosenPathIndex % cell.availableNextCells.length; var startOfSegment = cell.availableNextCells[chosenIndex]; // Increment the cycle index for the *current cell* for the next enemy cell.lastChosenPathIndex = (cell.lastChosenPathIndex + 1); // --- GENERATE PATH SEGMENT --- // This function should trace a path from startOfSegment until it hits // a cell with multiple exits (a crossroad), or the goal, or an invalid cell. enemy.committedPath = self.generatePathSegment(cell, startOfSegment); // Implement this helper enemy.committedPathIndex = 0; enemy.currentTarget = enemy.committedPath[enemy.committedPathIndex]; } else { // Fallback if no valid next cells (e.g., dead end, or pathfinding issue) console.warn("Enemy stuck or no path available from cell:", cell.x, cell.y); return true; // Enemy cannot move, consider it reached goal or blocked } } // The rest of the movement logic for enemy.currentTarget var ox = enemy.currentTarget.x - enemy.currentCellX; var oy = enemy.currentTarget.y - enemy.currentCellY; // ... (rest of the movement and rotation code remains unchanged) 2.3. Instruction: Within the Grid class, implement a new helper method self.generatePathSegment(startCell, nextCellInPath). This method should take the currentCell the enemy is in, and the nextCellInPath (which was chosen from availableNextCells), and return an array of Cell objects representing a continuous path segment. Method Signature: self.generatePathSegment = function (currentOriginCell, firstTargetCell) Logic: Initialize segment = [firstTargetCell]. Set currentNode = firstTargetCell. Loop: Get currentNode.availableNextCells. If currentNode is a goal cell (currentNode.type === 3) or has no availableNextCells, break the loop. This is the end of the segment. If currentNode.availableNextCells.length > 1 (it's a new crossroad), break the loop. The segment ends here, and the next decision will be made. If currentNode.availableNextCells.length === 1 (it's a straight path), add currentNode.availableNextCells[0] to the segment and update currentNode. Return the segment array. Note: This generatePathSegment ensures that an enemy, once it chooses a direction at a crossroad, follows that path without re-evaluating until it reaches the next crossroad or the goal. This effectively creates "longer routes" as requested. Pathfinding Sorting Reinforcement Ensure the availableNextCells are consistently sorted to maintain predictable cycling at crossroads. 3.1. Instruction: In the Grid.pathFind function, after the main while (toProcess.length) loop completes and self.availableNextCells are populated for each cell, verify the sorting logic within that section: // Populate availableNextCells for all cells after pathfinding for (var i = 0; i < gridWidth; i++) { for (var j = 0; j < gridHeight; j++) { var currentCell = self.cells[i][j]; currentCell.availableNextCells = []; // ... (existing logic to populate availableNextCells based on neighbors and score) ... // Ensure this sorting is present and correct: currentCell.availableNextCells.sort(function (a, b) { if (a.score !== b.score) { return a.score - b.score; } if (a.x !== b.x) { // Secondary sort by X for consistency return a.x - b.x; } return a.y - b.y; // Tertiary sort by Y for consistency }); } } Note: Consistent sorting is crucial for lastChosenPathIndex to cycle through paths deterministically. This revised approach directly addresses the "no continuation" issue by making enemies commit to multi-cell segments, while still leveraging the existing A* score system for overall path validity and initial branch selection.
User prompt
Objective: Modify enemy pathfinding to ensure consistent traversal of selected long routes at crossroads, preventing immediate re-evaluation to the shortest path after initial selection. Action Items: Grid Class - Cell Property Initialization Instruction: Confirm that each cell object in the Grid constructor's nested loop (for (var i = 0; i < gridWidth; i++) { for (var j = 0; j < gridHeight; j++) { ... } }) is initialized with lastChosenPathIndex: 0. Instruction: Confirm that availableNextCells: [] is also initialized for each cell. Note: These properties are critical for the cycling path selection logic to function per-cell. Grid.pathFind Function - availableNextCells Population & Sorting Instruction: Verify that the logic populating currentCell.availableNextCells includes all valid adjacent path cells that lead towards the goal (i.e., neighbor.pathId === pathId && neighbor.score < currentCell.score). Instruction: Ensure currentCell.availableNextCells is sorted deterministically after population to guarantee consistent path cycling order. The existing sort by score, then x, then y is acceptable. Grid.updateEnemy Function - Ground Enemy Path Selection Logic Instruction: Locate the // Handle normal pathfinding enemies block. Instruction: Remove the line if (cell.score < enemy.currentTarget.score) { enemy.currentTarget = cell; } entirely. This line causes the immediate "snapping back" to the shortest path by prematurely re-evaluating the currentTarget. Once an enemy.currentTarget is assigned, it must be committed to until the enemy physically reaches that cell's coordinates. Instruction: In the if (!enemy.currentTarget) block: Modify the chosenIndex assignment to var chosenIndex = currentGridCell.lastChosenPathIndex % currentGridCell.availableNextCells.length;. Modify the lastChosenPathIndex increment to include a modulo operator for proper cycling: currentGridCell.lastChosenPathIndex = (currentGridCell.lastChosenPathIndex + 1) % currentGridCell.availableNextCells.length;. This ensures the index wraps around to 0 after all options have been cycled through. Ensure that if currentGridCell.availableNextCells is empty and the current cell is not a goal (type === 3), the enemy is considered stuck/lost and removed (return true;). This handles cases where a tower placement might block the last valid path. Instruction: In the if (enemy.currentTarget) block (after the problematic line removal): When dist < enemy.speed (enemy has nearly reached its currentTarget), set the enemy's grid position directly to the currentTarget's coordinates: enemy.cellX = enemy.currentTarget.x; enemy.cellY = enemy.currentTarget.y; enemy.currentCellX = enemy.currentTarget.x; enemy.currentCellY = enemy.currentTarget.y; Instruction: Ensure enemy.currentTarget is set to undefined only after the enemy has fully "snapped" to the center of the currentTarget cell, preparing it to pick a new target in the next frame. Instruction: Adjust the enemy.x and enemy.y assignment at the end of the updateEnemy function to correctly center the enemy within its current grid cell: enemy.x = grid.x + enemy.currentCellX * CELL_SIZE + CELL_SIZE / 2; enemy.y = grid.y + enemy.currentCellY * CELL_SIZE + CELL_SIZE / 2; Note: The core issue stemmed from the if (cell.score < enemy.currentTarget.score) check. This condition would frequently be true for chosen "longer" paths, causing the enemy to discard its chosen currentTarget and re-evaluate, often resulting in it snapping back to what it perceived as the (statically) shortest route. Removing this line will enforce the commitment to the currentTarget until it is reached.
User prompt
Objective: Modify enemy pathfinding to enable deterministic cycling through all available valid path continuations at crossroads, ensuring successive enemies utilize different routes, including longer ones, instead of defaulting to the shortest path at each cell. Action Items: Cell Data Structure Augmentation (Grid Class) Extend the internal cell object structure within the Grid class to support persistent state for path selection. 1.1. Add lastChosenPathIndex Property Instruction: In the Grid constructor's nested loop (for (var i = 0; i < gridWidth; i++) { for (var j = 0; j < gridHeight; j++) { ... } }), add cell.lastChosenPathIndex = 0; to each cell object initialized. Note: This integer will track the next path option to select when an enemy enters this specific cell. 1.2. Add availableNextCells Property Instruction: In the same Grid constructor loop, add cell.availableNextCells = []; to each cell object initialized. Note: This array will store references to all valid neighboring cells that represent a progression towards the goal, not just the shortest path options. Pathfinding Algorithm Refinement (Grid.pathFind Method) Adjust the pathFind method to correctly identify and populate availableNextCells for all pathable grid cells after the primary score calculation. 2.1. Populate availableNextCells Instruction: After the main while (toProcess.length) loop concludes (i.e., after all score and pathId values are finalized for the current pathfinding iteration), add a new nested loop that iterates through all self.cells (from i = 0 to gridWidth-1, j = 0 to gridHeight-1). Instruction: Inside this loop, for each currentCell: Clear its previous availableNextCells: currentCell.availableNextCells = [];. Iterate through all 8 of currentCell's potential neighbors (including diagonal: upLeft, up, upRight, left, right, downLeft, down, downRight). For each neighbor: Verify neighbor exists (if (neighbor)). Verify neighbor is a walkable path or goal cell (neighbor.type === 0 || neighbor.type === 2 || neighbor.type === 3). Verify neighbor is part of the currently active path graph (neighbor.pathId === pathId). Verify neighbor is genuinely a step closer to the goal (neighbor.score < currentCell.score). If all conditions are met, add neighbor to currentCell.availableNextCells. 2.2. Sort availableNextCells Instruction: Immediately after populating availableNextCells for all cells (within the same loop or in a subsequent loop), add a sort operation for each cell.availableNextCells array. Instruction: Sort currentCell.availableNextCells using a stable sort criteria: Primary sort key: cell.score in ascending order (prioritizes shorter paths). Secondary sort key: cell.x in ascending order (for consistent tie-breaking). Tertiary sort key: cell.y in ascending order (for consistent tie-breaking). Note: This deterministic sorting ensures predictable cycling behavior regardless of iteration order. Enemy Path Selection Logic (Grid.updateEnemy Method) Modify how non-flying enemies select their currentTarget to leverage the new availableNextCells property and the cycling lastChosenPathIndex. 3.1. Update currentTarget Assignment Instruction: Locate the if (!enemy.currentTarget) block within the Grid.updateEnemy method (specifically the one handling non-flying enemies, currently line 710: if (!enemy.currentTarget) { enemy.currentTarget = cell.targets[0]; }). Instruction: Replace the line enemy.currentTarget = cell.targets[0]; with the following logic: if (cell.availableNextCells && cell.availableNextCells.length > 0) { let chosenIndex = cell.lastChosenPathIndex % cell.availableNextCells.length; enemy.currentTarget = cell.availableNextCells[chosenIndex]; cell.lastChosenPathIndex = (cell.lastChosenPathIndex + 1); } // No 'else' block needed here, as the check at the top of updateEnemy for cell.type == 3 handles goal arrival, // and an enemy without a target in an unpathable/dead-end cell would correctly remain stuck. Note: This ensures that whenever an enemy needs a new target, it cycles through all valid forward path options available from its current cell, and the next enemy arriving at that same cell will pick the subsequent option. The prior sorting of availableNextCells ensures a weighted (shorter first) but complete cycle.
User prompt
Objective: Modify enemy pathfinding logic to distribute enemies across all viable forward paths at crossroads, ensuring sequential utilization of different routes. Action Items: Grid Cell Initialization (Grid Class) Initialize a new property pathCycleIndex to 0 for each cell object within the self.cells array. This index will manage path distribution at crossroads. Instruction: Locate the Grid class constructor. Instruction: Within the nested loop where self.cells[i][j] objects are created, add pathCycleIndex: 0 to the cell's properties. Enemy Path Selection Logic (Grid.updateEnemy Method) Refactor the enemy.currentTarget assignment to identify all valid forward-moving neighbors and cycle through them based on pathCycleIndex. Instruction: Navigate to the Grid.updateEnemy method. Instruction: Locate the block where enemy.currentTarget is assigned when !enemy.currentTarget. This is typically where enemy.currentTarget = cell.targets[0]; occurs. Instruction: Before assigning enemy.currentTarget, implement a new logic to identify possibleNextSteps: Declare an empty array, possibleNextSteps. Iterate through all eight direct neighbors of the current cell (e.g., cell.upLeft, cell.up, cell.upRight, cell.right, cell.downRight, cell.down, cell.downLeft, cell.left). For each potentialNextCell neighbor, apply the following conditions for inclusion in possibleNextSteps: potentialNextCell must exist (not null or undefined). potentialNextCell.type must not be 1 (Wall) or 4 (Tower Slot). potentialNextCell.pathId must strictly equal the global pathId (ensuring it's part of the current valid pathfinding solution). potentialNextCell.score must be strictly less than currentCell.score (ensuring movement towards the goal). Additionally, if potentialNextCell.type is 3 (Goal), include it in possibleNextSteps if its score is less than or equal to currentCell.score. Add potentialNextCell to possibleNextSteps if all conditions are met. Instruction: After possibleNextSteps is populated, check if possibleNextSteps.length is greater than 0. If true, assign enemy.currentTarget from possibleNextSteps using the currentCell.pathCycleIndex: enemy.currentTarget = possibleNextSteps[currentCell.pathCycleIndex % possibleNextSteps.length]; Increment currentCell.pathCycleIndex by 1. If possibleNextSteps.length is 0, assign enemy.currentTarget = null; to indicate no valid path forward from this cell. Note: The existing cell.targets property, populated by Grid.pathFind, is no longer directly used for enemy movement decision and can be disregarded in this context. The new possibleNextSteps logic explicitly defines the valid outgoing paths for enemy traversal.
User prompt
Objective: Modify the grid pathfinding algorithm to allow enemies to choose from multiple equally-optimal or near-optimal paths at crossroads, ensuring all viable routes are utilized in sequence without compromising core shortest-path score integrity. Action Items: Grid Class Initialization (self.cells properties) Ensure the nextPathChoiceIndex property exists on each cell object: cell.nextPathChoiceIndex: 0. This is currently correctly implemented. Grid.pathFind Method - processNode Function Logic 2.1. Introduce Path Divergence Tolerance Constant Instruction: Declare a new constant, PATH_DIVERGENCE_TOLERANCE, at a suitable scope (e.g., within the Grid class or globally if appropriate for constants). Note: Initialize PATH_DIVERGENCE_TOLERANCE to a small numerical value (e.g., 500 or 1000). This value should be less than the cost of a single cardinal step (10000) but large enough to include paths that are slightly longer than the absolute shortest. Experimentation will be required to find an optimal value for desired path diversity. 2.2. Modify node.targets Population within processNode Instruction: Locate the if (node.pathId < pathId || targetValue < node.score) block that sets node.targets = [targetNode];. This block should only trigger when a strictly shorter path to node is found or when node is processed for the first time in the current pathfinding cycle. Instruction: Modify the subsequent else if (node.pathId == pathId && targetValue == node.score) block. This condition should be expanded to include targetNode in node.targets if targetValue is equal to node.score OR if targetValue is greater than node.score but less than or equal to node.score + PATH_DIVERGENCE_TOLERANCE. Note: The primary node.score update logic (node.score = targetValue; etc.) must remain unchanged. node.score must always represent the absolute shortest distance from that cell to a goal. The PATH_DIVERGENCE_TOLERANCE is solely for populating node.targets with multiple acceptable next steps, not for altering the optimal path score. 2.3. Clear node.targets at Pathfinding Cycle Start Instruction: Within Grid.pathFind, at the beginning of the function, before the main while (toProcess.length) loop, ensure that for every cell (self.cells[i][j]), its targets array is re-initialized (e.g., self.cells[i][j].targets = [];). This guarantees that targets only reflect the current pathfinding cycle's valid paths, preventing accumulation from previous cycles. Grid.updateEnemy Method 3.1. Confirm Target Selection Logic: Instruction: Verify that the enemy's currentTarget selection correctly uses the cell.nextPathChoiceIndex to cycle through cell.targets (e.g., enemy.currentTarget = cell.targets[cell.nextPathChoiceIndex % cell.targets.length];). Instruction: Verify that cell.nextPathChoiceIndex is incremented and wrapped after a target is selected (e.g., cell.nextPathChoiceIndex = (cell.nextPathChoiceIndex + 1) % cell.targets.length;). Note: This logic appears to be correctly implemented already. The preceding modifications to pathFind will now ensure that cell.targets can contain more than one element at crossroads, making this cycling effective. 3.2. Target Validation Review Instruction: Confirm that target validation logic (if (enemy.currentTarget.type === 1 || enemy.currentTarget.type === 4 || enemy.currentTarget.pathId !== pathId)) correctly handles invalid targets (walls, tower slots, or paths from an old cycle) by setting enemy.currentTarget = undefined;, forcing a re-evaluation on the next update tick.
User prompt
Objective: Implement per-crossroad, round-robin path selection for ground enemies to ensure comprehensive utilization of equally optimal routes. Action Items: Grid Class - Cell Structure Modification Introduce a new property nextPathChoiceIndex to each cell object within the self.cells 2D array. 1.1. Grid Constructor Initialization Instruction: During the nested loop instantiation of self.cells[i][j] objects, initialize self.cells[i][j].nextPathChoiceIndex to 0. This will ensure each cell starts with the first path option. Grid.updateEnemy Method - Ground Enemy Path Selection Logic Modify the logic for ground enemies (!enemy.isFlying) when enemy.currentTarget is undefined. 2.1. Accessing Cell-Specific Path Choices Instruction: Replace the global self.nextPathSelectionIndex with the current cell.nextPathChoiceIndex when determining the index for cell.targets. Instruction: Update the enemy.currentTarget assignment to cell.targets[cell.nextPathChoiceIndex]. 2.2. Incrementing Cell-Specific Index Instruction: After assigning enemy.currentTarget, increment cell.nextPathChoiceIndex. Instruction: Implement a modulo operation on cell.nextPathChoiceIndex using cell.targets.length to ensure the index wraps around and cycles through all available paths for that specific cell. For example: cell.nextPathChoiceIndex = (cell.nextPathChoiceIndex + 1) % cell.targets.length; Note: This ensures that each distinct crossroad cell maintains its own internal state for path selection, allowing enemies to systematically explore all branches at that specific junction over time, rather than relying on a global sequence. 2.3. Path Validation Post-Recalculation Instruction: Retain the existing if (enemy.currentTarget.type === 1 || enemy.currentTarget.type === 4 || enemy.currentTarget.pathId !== pathId) validation check. This ensures that even if a nextPathChoiceIndex points to an invalid or outdated target due to path recalculation (e.g., tower placement), the currentTarget is reset, forcing a re-evaluation and selection of a valid path in the subsequent frame based on the updated cell.targets and the cycled nextPathChoiceIndex.
User prompt
Objective: Modify ground enemy pathfinding to utilize all equally optimal routes at path junctions in a round-robin sequence, rather than consistently selecting the first available target. Action Items: Grid Class Initialization Integrate a new state variable within the Grid class. 1.1. self.nextPathSelectionIndex Field Addition Instruction: Declare self.nextPathSelectionIndex as a property within the Grid constructor function. Instruction: Initialize self.nextPathSelectionIndex to 0. Note: This integer counter will manage the round-robin selection of target cells at path intersections for ground enemies. Grid.updateEnemy Method Refinement Adjust enemy target acquisition logic for ground-based units. 2.1. Target Assignment Modification Instruction: Locate the conditional block if (!enemy.currentTarget) within the Grid.updateEnemy method, specifically inside the if (!enemy.isFlying) scope. Instruction: Within this block, modify the assignment for enemy.currentTarget to select from cell.targets using self.nextPathSelectionIndex modulo cell.targets.length as the array index. Instruction: Increment self.nextPathSelectionIndex immediately after target assignment to prepare for the next enemy's selection. Note: This ensures that if cell.targets contains multiple equally scored valid next steps (representing a crossroad), enemies will sequentially choose each distinct path. 2.2. Invalidated Target Handling (Self-Correction) Instruction: Introduce a new conditional check immediately following the if (!enemy.currentTarget) block, still within the if (!enemy.isFlying) scope. Instruction: If enemy.currentTarget is currently assigned, verify its validity. Set enemy.currentTarget to undefined if the target cell's type is 1 (Wall) or 4 (Tower Slot), or if its pathId does not match the global pathId. Note: This robustifies enemy movement by forcing a re-evaluation of the path if the current target cell becomes impassable or if the overall pathfinding solution has changed due to grid modifications (e.g., tower placement).
/**** * Plugins ****/ var tween = LK.import("@upit/tween.v1"); /**** * Classes ****/ var Bullet = Container.expand(function (startX, startY, targetEnemy, damage, speed) { var self = Container.call(this); self.targetEnemy = targetEnemy; self.damage = damage || 10; self.speed = speed || 5; self.x = startX; self.y = startY; var bulletGraphics = self.attachAsset('bullet', { anchorX: 0.5, anchorY: 0.5 }); self.update = function () { if (!self.targetEnemy || !self.targetEnemy.parent) { self.destroy(); return; } var dx = self.targetEnemy.x - self.x; var dy = self.targetEnemy.y - self.y; var distance = Math.sqrt(dx * dx + dy * dy); if (distance < self.speed) { // Apply damage to target enemy self.targetEnemy.health -= self.damage; if (self.targetEnemy.health <= 0) { self.targetEnemy.health = 0; } else { self.targetEnemy.healthBar.width = self.targetEnemy.health / self.targetEnemy.maxHealth * 70; } // Apply special effects based on bullet type if (self.type === 'splash') { // Create visual splash effect var splashEffect = new EffectIndicator(self.targetEnemy.x, self.targetEnemy.y, 'splash'); game.addChild(splashEffect); // Splash damage to nearby enemies var splashRadius = CELL_SIZE * 1.5; for (var i = 0; i < enemies.length; i++) { var otherEnemy = enemies[i]; if (otherEnemy !== self.targetEnemy) { var splashDx = otherEnemy.x - self.targetEnemy.x; var splashDy = otherEnemy.y - self.targetEnemy.y; var splashDistance = Math.sqrt(splashDx * splashDx + splashDy * splashDy); if (splashDistance <= splashRadius) { // Apply splash damage (50% of original damage) otherEnemy.health -= self.damage * 0.5; if (otherEnemy.health <= 0) { otherEnemy.health = 0; } else { otherEnemy.healthBar.width = otherEnemy.health / otherEnemy.maxHealth * 70; } } } } } else if (self.type === 'slow') { // Prevent slow effect on immune enemies if (!self.targetEnemy.isImmune) { // Create visual slow effect var slowEffect = new EffectIndicator(self.targetEnemy.x, self.targetEnemy.y, 'slow'); game.addChild(slowEffect); // Apply slow effect // Make slow percentage scale with tower level (default 50%, up to 80% at max level) var slowPct = 0.5; if (self.sourceTowerLevel !== undefined) { // Scale: 50% at level 1, 60% at 2, 65% at 3, 70% at 4, 75% at 5, 80% at 6 var slowLevels = [0.5, 0.6, 0.65, 0.7, 0.75, 0.8]; var idx = Math.max(0, Math.min(5, self.sourceTowerLevel - 1)); slowPct = slowLevels[idx]; } if (!self.targetEnemy.slowed) { self.targetEnemy.originalSpeed = self.targetEnemy.speed; self.targetEnemy.speed *= 1 - slowPct; // Slow by X% self.targetEnemy.slowed = true; self.targetEnemy.slowDuration = 180; // 3 seconds at 60 FPS } else { self.targetEnemy.slowDuration = 180; // Reset duration } } } else if (self.type === 'poison') { // Prevent poison effect on immune enemies if (!self.targetEnemy.isImmune) { // Create visual poison effect var poisonEffect = new EffectIndicator(self.targetEnemy.x, self.targetEnemy.y, 'poison'); game.addChild(poisonEffect); // Apply poison effect self.targetEnemy.poisoned = true; self.targetEnemy.poisonDamage = self.damage * 0.2; // 20% of original damage per tick self.targetEnemy.poisonDuration = 300; // 5 seconds at 60 FPS } } else if (self.type === 'sniper') { // Create visual critical hit effect for sniper var sniperEffect = new EffectIndicator(self.targetEnemy.x, self.targetEnemy.y, 'sniper'); game.addChild(sniperEffect); } self.destroy(); } else { var angle = Math.atan2(dy, dx); self.x += Math.cos(angle) * self.speed; self.y += Math.sin(angle) * self.speed; } }; return self; }); var Coin = Container.expand(function (gridX, gridY) { var self = Container.call(this); self.gridX = gridX; self.gridY = gridY; var coinGraphics = self.attachAsset('coin', { anchorX: 0.5, anchorY: 0.5 }); // Position coin on grid self.x = grid.x + gridX * CELL_SIZE + CELL_SIZE / 2; self.y = grid.y + gridY * CELL_SIZE + CELL_SIZE / 2; // Add some visual flair self.alpha = 0; tween(self, { alpha: 1, scaleX: 1.2, scaleY: 1.2 }, { duration: 300, easing: tween.elasticOut }); return self; }); var DebugCell = Container.expand(function () { var self = Container.call(this); var cellGraphics = self.attachAsset('cell', { anchorX: 0.5, anchorY: 0.5 }); cellGraphics.tint = Math.random() * 0xffffff; var numberLabel = new Text2('0', { size: 30, fill: 0xFFFFFF, weight: 800 }); numberLabel.anchor.set(.5, .5); self.addChild(numberLabel); self.update = function () {}; self.down = function () { return; }; self.render = function (data) { numberLabel.visible = false; // Clear all children except numberLabel (first child) while (self.children.length > 1) { self.removeChild(self.children[self.children.length - 1]); } switch (data.type) { case GridItemType.PATH_CROSSROAD: case GridItemType.PATH_STRAIGHT_UP: case GridItemType.PATH_STRAIGHT_DOWN: case GridItemType.PATH_STRAIGHT_LEFT: case GridItemType.PATH_STRAIGHT_RIGHT: case GridItemType.PATH_CORNER_TOP_LEFT: case GridItemType.PATH_CORNER_TOP_RIGHT: case GridItemType.PATH_CORNER_BOTTOM_LEFT: case GridItemType.PATH_CORNER_BOTTOM_RIGHT: case GridItemType.SPAWN: { var towerInRangeHighlight = false; if (selectedTower && data.towersInRange && data.towersInRange.indexOf(selectedTower) !== -1) { towerInRangeHighlight = true; cellGraphics.tint = 0x0088ff; } else if (data.type === GridItemType.SPAWN) { cellGraphics.tint = 0x00ff00; } else { cellGraphics.tint = 0x008800; } cellGraphics.alpha = 0.1; // Add debug arrows for path visualization var arrowVectors = grid._getDebugArrowsForCell(data); for (var i = 0; i < arrowVectors.length; i++) { var vector = arrowVectors[i]; var arrow = LK.getAsset('arrow', { anchorX: -0.5, anchorY: 0.5 }); arrow.alpha = 0.5; arrow.rotation = Math.atan2(vector.y, vector.x); arrow.x = vector.x * 10; arrow.y = vector.y * 10; self.addChild(arrow); } break; } case GridItemType.WALL: { cellGraphics.tint = 0xaaaaaa; cellGraphics.alpha = 0; break; } case GridItemType.GOAL: { cellGraphics.tint = 0xff0000; cellGraphics.alpha = 0.1; break; } case GridItemType.TOWER_SLOT: { cellGraphics.tint = data.isOccupied ? 0x0088CC : 0x00BFFF; cellGraphics.alpha = 0.1; break; } default: { cellGraphics.tint = 0x880000; cellGraphics.alpha = 0.1; break; } } }; }); // This update method was incorrectly placed here and should be removed var EffectIndicator = Container.expand(function (x, y, type) { var self = Container.call(this); self.x = x; self.y = y; var effectGraphics = self.attachAsset('rangeCircle', { anchorX: 0.5, anchorY: 0.5 }); effectGraphics.blendMode = 1; switch (type) { case 'splash': effectGraphics.tint = 0x33CC00; effectGraphics.width = effectGraphics.height = CELL_SIZE * 1.5; break; case 'slow': effectGraphics.tint = 0x9900FF; effectGraphics.width = effectGraphics.height = CELL_SIZE; break; case 'poison': effectGraphics.tint = 0x00FFAA; effectGraphics.width = effectGraphics.height = CELL_SIZE; break; case 'sniper': effectGraphics.tint = 0xFF5500; effectGraphics.width = effectGraphics.height = CELL_SIZE; break; } effectGraphics.alpha = 0.7; self.alpha = 0; // Animate the effect tween(self, { alpha: 0.8, scaleX: 1.5, scaleY: 1.5 }, { duration: 200, easing: tween.easeOut, onFinish: function onFinish() { tween(self, { alpha: 0, scaleX: 2, scaleY: 2 }, { duration: 300, easing: tween.easeIn, onFinish: function onFinish() { self.destroy(); } }); } }); return self; }); // Base enemy class for common functionality var Enemy = Container.expand(function (type) { var self = Container.call(this); self.type = type || 'normal'; self.speed = .01; self.cellX = 0; self.cellY = 0; self.currentCellX = 0; self.currentCellY = 0; self.prevCellX = -1; self.prevCellY = -1; self.assignedPath = null; self.currentWaypointIndex = 0; self.maxHealth = 100; self.health = self.maxHealth; self.bulletsTargetingThis = []; self.waveNumber = currentWave; self.isFlying = false; self.isImmune = false; self.isBoss = false; // Check if this is a boss wave // Check if this is a boss wave // Apply different stats based on enemy type switch (self.type) { case 'fast': self.speed *= 2; // Twice as fast self.maxHealth = 100; break; case 'immune': self.isImmune = true; self.maxHealth = 80; break; case 'flying': self.isFlying = true; self.maxHealth = 80; break; case 'swarm': self.maxHealth = 50; // Weaker enemies break; case 'normal': default: // Normal enemy uses default values break; } if (currentWave % 10 === 0 && currentWave > 0 && type !== 'swarm') { self.isBoss = true; // Boss enemies have 20x health and are larger self.maxHealth *= 20; // Slower speed for bosses self.speed = self.speed * 0.7; } self.health = self.maxHealth; // Get appropriate asset for this enemy type var assetId = 'enemy'; if (self.type !== 'normal') { assetId = 'enemy_' + self.type; } var enemyGraphics = self.attachAsset(assetId, { anchorX: 0.5, anchorY: 0.5 }); // Scale up boss enemies if (self.isBoss) { enemyGraphics.scaleX = 1.8; enemyGraphics.scaleY = 1.8; } // Fall back to regular enemy asset if specific type asset not found // Apply tint to differentiate enemy types /*switch (self.type) { case 'fast': enemyGraphics.tint = 0x00AAFF; // Blue for fast enemies break; case 'immune': enemyGraphics.tint = 0xAA0000; // Red for immune enemies break; case 'flying': enemyGraphics.tint = 0xFFFF00; // Yellow for flying enemies break; case 'swarm': enemyGraphics.tint = 0xFF00FF; // Pink for swarm enemies break; }*/ // Create shadow for flying enemies if (self.isFlying) { // Create a shadow container that will be added to the shadow layer self.shadow = new Container(); // Clone the enemy graphics for the shadow var shadowGraphics = self.shadow.attachAsset(assetId || 'enemy', { anchorX: 0.5, anchorY: 0.5 }); // Apply shadow effect shadowGraphics.tint = 0x000000; // Black shadow shadowGraphics.alpha = 0.4; // Semi-transparent // If this is a boss, scale up the shadow to match if (self.isBoss) { shadowGraphics.scaleX = 1.8; shadowGraphics.scaleY = 1.8; } // Position shadow slightly offset self.shadow.x = 20; // Offset right self.shadow.y = 20; // Offset down // Ensure shadow has the same rotation as the enemy shadowGraphics.rotation = enemyGraphics.rotation; } var healthBarOutline = self.attachAsset('healthBarOutline', { anchorX: 0, anchorY: 0.5 }); var healthBarBG = self.attachAsset('healthBar', { anchorX: 0, anchorY: 0.5 }); var healthBar = self.attachAsset('healthBar', { anchorX: 0, anchorY: 0.5 }); healthBarBG.y = healthBarOutline.y = healthBar.y = -enemyGraphics.height / 2 - 10; healthBarOutline.x = -healthBarOutline.width / 2; healthBarBG.x = healthBar.x = -healthBar.width / 2 - .5; healthBar.tint = 0x00ff00; healthBarBG.tint = 0xff0000; self.healthBar = healthBar; self.update = function () { if (self.health <= 0) { self.health = 0; self.healthBar.width = 0; } // Handle slow effect if (self.isImmune) { // Immune enemies cannot be slowed or poisoned, clear any such effects self.slowed = false; self.slowEffect = false; self.poisoned = false; self.poisonEffect = false; // Reset speed to original if needed if (self.originalSpeed !== undefined) { self.speed = self.originalSpeed; } } else { // Handle slow effect if (self.slowed) { // Visual indication of slowed status if (!self.slowEffect) { self.slowEffect = true; } self.slowDuration--; if (self.slowDuration <= 0) { self.speed = self.originalSpeed; self.slowed = false; self.slowEffect = false; // Only reset tint if not poisoned if (!self.poisoned) { enemyGraphics.tint = 0xFFFFFF; // Reset tint } } } // Handle poison effect if (self.poisoned) { // Visual indication of poisoned status if (!self.poisonEffect) { self.poisonEffect = true; } // Apply poison damage every 30 frames (twice per second) if (LK.ticks % 30 === 0) { self.health -= self.poisonDamage; if (self.health <= 0) { self.health = 0; } self.healthBar.width = self.health / self.maxHealth * 70; } self.poisonDuration--; if (self.poisonDuration <= 0) { self.poisoned = false; self.poisonEffect = false; // Only reset tint if not slowed if (!self.slowed) { enemyGraphics.tint = 0xFFFFFF; // Reset tint } } } } // Set tint based on effect status if (self.isImmune) { enemyGraphics.tint = 0xFFFFFF; } else if (self.poisoned && self.slowed) { // Combine poison (0x00FFAA) and slow (0x9900FF) colors // Simple average: R: (0+153)/2=76, G: (255+0)/2=127, B: (170+255)/2=212 enemyGraphics.tint = 0x4C7FD4; } else if (self.poisoned) { enemyGraphics.tint = 0x00FFAA; } else if (self.slowed) { enemyGraphics.tint = 0x9900FF; } else { enemyGraphics.tint = 0xFFFFFF; } healthBarOutline.y = healthBarBG.y = healthBar.y = -enemyGraphics.height / 2 - 10; }; return self; }); var GoldIndicator = Container.expand(function (value, x, y) { var self = Container.call(this); var shadowText = new Text2("+" + value, { size: 45, fill: 0x000000, weight: 800 }); shadowText.anchor.set(0.5, 0.5); shadowText.x = 2; shadowText.y = 2; self.addChild(shadowText); var goldText = new Text2("+" + value, { size: 45, fill: 0xFFD700, weight: 800 }); goldText.anchor.set(0.5, 0.5); self.addChild(goldText); self.x = x; self.y = y; self.alpha = 0; self.scaleX = 0.5; self.scaleY = 0.5; tween(self, { alpha: 1, scaleX: 1.2, scaleY: 1.2, y: y - 40 }, { duration: 50, easing: tween.easeOut, onFinish: function onFinish() { tween(self, { alpha: 0, scaleX: 1.5, scaleY: 1.5, y: y - 80 }, { duration: 600, easing: tween.easeIn, delay: 800, onFinish: function onFinish() { self.destroy(); } }); } }); return self; }); var Grid = Container.expand(function (gridWidth, gridHeight) { var self = Container.call(this); self.cells = []; self.spawns = []; self.goals = []; self.allGroundPaths = []; self.nextPathAssignmentIndex = 0; for (var i = 0; i < gridWidth; i++) { self.cells[i] = []; for (var j = 0; j < gridHeight; j++) { self.cells[i][j] = { towersInRange: [], isOccupied: false }; } } /* Cell Types 0: Path (walkable by ground enemies) 1: Wall (impassable) 2: Spawn 3: Goal 4: Tower Slot (impassable by ground enemies, buildable) */ // Predefined map layout var mapLayout = [[9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 5, 3, 3, 3, 3, 3, 3, 8, 7, 4, 4, 4, 4, 4, 4, 6, 9, 9, 9, 9], [9, 9, 9, 9, 2, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 2, 9, 9, 9, 9], [9, 9, 9, 9, 2, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 2, 9, 9, 9, 9], [9, 9, 9, 9, 2, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 2, 9, 9, 9, 9], [9, 9, 9, 9, 7, 4, 4, 4, 4, 4, 4, 2, 2, 3, 3, 3, 3, 3, 3, 8, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 2, 2, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 11, 11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9], [9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]]; for (var i = 0; i < gridWidth; i++) { for (var j = 0; j < gridHeight; j++) { var cell = self.cells[i][j]; // Get cell type from map layout var cellType = 1; // Default to wall if (j < mapLayout.length && i < mapLayout[j].length) { cellType = mapLayout[j][i]; } // Add to appropriate arrays based on cell type if (cellType === GridItemType.SPAWN) { self.spawns.push(cell); } else if (cellType === GridItemType.GOAL) { self.goals.push(cell); } cell.type = cellType; cell.x = i; cell.y = j; if (j > 3 && j <= gridHeight - 4) { var debugCell = new DebugCell(); self.addChild(debugCell); debugCell.cell = cell; debugCell.x = i * CELL_SIZE; debugCell.y = j * CELL_SIZE; cell.debugCell = debugCell; } } } self.getCell = function (x, y) { return self.cells[x] && self.cells[x][y]; }; self.maxPathLength = gridWidth * gridHeight * 2; self.buildAllGroundPaths = function () { var before = new Date().getTime(); self.allGroundPaths = []; // Find all unique paths from spawn to goal for (var s = 0; s < self.spawns.length; s++) { var spawn = self.spawns[s]; var pathsFromSpawn = self.findPathsFromCell(spawn, []); self.allGroundPaths = self.allGroundPaths.concat(pathsFromSpawn); } console.log("Found", self.allGroundPaths.length, "ground paths in", new Date().getTime() - before, "ms"); }; self.findPathsFromCell = function (startCell, visitedCells) { var currentPath = visitedCells.slice(); // Clone visited cells // Add check for maximum path length to prevent infinite loops if (currentPath.length > self.maxPathLength) { return []; } var paths = []; currentPath.push({ x: startCell.x, y: startCell.y }); // Check if we reached a goal if (startCell.type === GridItemType.GOAL) { return [currentPath]; } // Get possible next cells var nextCells = self.getPossibleNextCellsForPath(startCell, visitedCells); for (var i = 0; i < nextCells.length; i++) { var nextCell = nextCells[i]; var nextCellObj = self.getCell(nextCell.x, nextCell.y); if (!nextCellObj) { continue; } // Check if already visited to prevent loops var alreadyVisited = false; for (var v = 0; v < currentPath.length; v++) { if (currentPath[v].x === nextCell.x && currentPath[v].y === nextCell.y) { alreadyVisited = true; break; } } if (!alreadyVisited) { var pathsFromNext = self.findPathsFromCell(nextCellObj, currentPath); paths = paths.concat(pathsFromNext); } } return paths; }; self.getPossibleNextCellsForPath = function (currentCell, visitedPath) { var possibleCells = []; var previousCell = null; // Get previous cell from path if (visitedPath.length > 0) { var prevCoords = visitedPath[visitedPath.length - 1]; previousCell = self.getCell(prevCoords.x, prevCoords.y); } // Handle different path types switch (currentCell.type) { case GridItemType.PATH_CROSSROAD: // Check all four adjacent cells var neighbors = [{ x: currentCell.x, y: currentCell.y - 1 }, // up { x: currentCell.x, y: currentCell.y + 1 }, // down { x: currentCell.x - 1, y: currentCell.y }, // left { x: currentCell.x + 1, y: currentCell.y } // right ]; for (var i = 0; i < neighbors.length; i++) { var neighbor = neighbors[i]; // Skip the previous cell to avoid backtracking if (previousCell && neighbor.x === previousCell.x && neighbor.y === previousCell.y) { continue; } var cell = self.getCell(neighbor.x, neighbor.y); if (cell && cell.type !== GridItemType.WALL && cell.type !== GridItemType.TOWER_SLOT) { possibleCells.push({ x: neighbor.x, y: neighbor.y }); } } break; case GridItemType.PATH_STRAIGHT_UP: possibleCells.push({ x: currentCell.x, y: currentCell.y - 1 }); break; case GridItemType.PATH_STRAIGHT_DOWN: possibleCells.push({ x: currentCell.x, y: currentCell.y + 1 }); break; case GridItemType.PATH_STRAIGHT_LEFT: possibleCells.push({ x: currentCell.x - 1, y: currentCell.y }); break; case GridItemType.PATH_STRAIGHT_RIGHT: possibleCells.push({ x: currentCell.x + 1, y: currentCell.y }); break; case GridItemType.PATH_CORNER_TOP_LEFT: if (previousCell) { var entryDirectionX = currentCell.x - previousCell.x; var entryDirectionY = currentCell.y - previousCell.y; if (entryDirectionY === 1) { // came from Top, exit Right possibleCells.push({ x: currentCell.x + 1, y: currentCell.y }); } else if (entryDirectionX === -1) { // came from Right, exit Bottom possibleCells.push({ x: currentCell.x, y: currentCell.y + 1 }); } } break; case GridItemType.PATH_CORNER_TOP_RIGHT: if (previousCell) { var entryDirectionX = currentCell.x - previousCell.x; var entryDirectionY = currentCell.y - previousCell.y; if (entryDirectionY === 1) { // came from Top, exit Left possibleCells.push({ x: currentCell.x - 1, y: currentCell.y }); } else if (entryDirectionX === 1) { // came from Left, exit Bottom possibleCells.push({ x: currentCell.x, y: currentCell.y + 1 }); } } break; case GridItemType.PATH_CORNER_BOTTOM_LEFT: if (previousCell) { var entryDirectionX = currentCell.x - previousCell.x; var entryDirectionY = currentCell.y - previousCell.y; if (entryDirectionY === -1) { // came from Bottom, exit Right possibleCells.push({ x: currentCell.x + 1, y: currentCell.y }); } else if (entryDirectionX === -1) { // came from Right, exit Top possibleCells.push({ x: currentCell.x, y: currentCell.y - 1 }); } } break; case GridItemType.PATH_CORNER_BOTTOM_RIGHT: if (previousCell) { var entryDirectionX = currentCell.x - previousCell.x; var entryDirectionY = currentCell.y - previousCell.y; if (entryDirectionY === -1) { // came from Bottom, exit Left possibleCells.push({ x: currentCell.x - 1, y: currentCell.y }); } else if (entryDirectionX === 1) { // came from Left, exit Top possibleCells.push({ x: currentCell.x, y: currentCell.y - 1 }); } } break; case GridItemType.SPAWN: // From spawn, find the first adjacent path cell var neighbors = [{ x: currentCell.x, y: currentCell.y - 1 }, // up { x: currentCell.x, y: currentCell.y + 1 }, // down { x: currentCell.x - 1, y: currentCell.y }, // left { x: currentCell.x + 1, y: currentCell.y } // right ]; for (var i = 0; i < neighbors.length; i++) { var neighbor = neighbors[i]; var cell = self.getCell(neighbor.x, neighbor.y); if (cell && cell.type !== GridItemType.WALL && cell.type !== GridItemType.TOWER_SLOT && cell.type !== GridItemType.SPAWN) { possibleCells.push({ x: neighbor.x, y: neighbor.y }); } } break; } return possibleCells; }; self._getDebugArrowsForCell = function (cell) { var arrowVectors = []; switch (cell.type) { case GridItemType.PATH_STRAIGHT_UP: arrowVectors.push({ x: 0, y: -1 }); break; case GridItemType.PATH_STRAIGHT_DOWN: arrowVectors.push({ x: 0, y: 1 }); break; case GridItemType.PATH_STRAIGHT_LEFT: arrowVectors.push({ x: -1, y: 0 }); break; case GridItemType.PATH_STRAIGHT_RIGHT: arrowVectors.push({ x: 1, y: 0 }); break; case GridItemType.PATH_CORNER_TOP_LEFT: arrowVectors.push({ x: 0, y: -1 }); arrowVectors.push({ x: -1, y: 0 }); break; case GridItemType.PATH_CORNER_TOP_RIGHT: arrowVectors.push({ x: 0, y: -1 }); arrowVectors.push({ x: 1, y: 0 }); break; case GridItemType.PATH_CORNER_BOTTOM_LEFT: arrowVectors.push({ x: 0, y: 1 }); arrowVectors.push({ x: -1, y: 0 }); break; case GridItemType.PATH_CORNER_BOTTOM_RIGHT: arrowVectors.push({ x: 0, y: 1 }); arrowVectors.push({ x: 1, y: 0 }); break; case GridItemType.PATH_CROSSROAD: arrowVectors.push({ x: 0, y: -1 }); arrowVectors.push({ x: 0, y: 1 }); arrowVectors.push({ x: -1, y: 0 }); arrowVectors.push({ x: 1, y: 0 }); break; case GridItemType.SPAWN: var nextCells = self.getPossibleNextCellsForPath(cell, []); for (var i = 0; i < nextCells.length; i++) { arrowVectors.push({ x: nextCells[i].x - cell.x, y: nextCells[i].y - cell.y }); } break; case GridItemType.GOAL: case GridItemType.WALL: case GridItemType.TOWER_SLOT: default: // No arrows for these types break; } return arrowVectors; }; self.renderDebug = function () { for (var i = 0; i < gridWidth; i++) { for (var j = 0; j < gridHeight; j++) { var debugCell = self.cells[i][j].debugCell; if (debugCell) { debugCell.render(self.cells[i][j]); } } } }; self.updateEnemy = function (enemy) { var cell = grid.getCell(enemy.cellX, enemy.cellY); if (cell && cell.type === GridItemType.GOAL) { return true; } if (enemy.isFlying && enemy.shadow) { enemy.shadow.x = enemy.x + 20; // Match enemy x-position + offset enemy.shadow.y = enemy.y + 20; // Match enemy y-position + offset // Match shadow rotation with enemy rotation if (enemy.children[0] && enemy.shadow.children[0]) { enemy.shadow.children[0].rotation = enemy.children[0].rotation; } } // Check if the enemy has reached the entry area (y position at spawn cell center) var hasReachedEntryArea = enemy.assignedPath && enemy.currentCellY >= enemy.assignedPath[0].y + 0.5; // If enemy hasn't reached the entry area yet, just move down vertically if (!hasReachedEntryArea) { // Move directly downward enemy.currentCellY += enemy.speed; // When reaching entry area for the first time, snap to center and initialize if (enemy.assignedPath && enemy.currentCellY >= enemy.assignedPath[0].y + 0.5) { enemy.currentCellY = enemy.assignedPath[0].y + 0.5; enemy.cellX = enemy.assignedPath[0].x; enemy.cellY = enemy.assignedPath[0].y; if (enemy.currentWaypointIndex === undefined) { enemy.currentWaypointIndex = 0; } } // Rotate enemy graphic to face downward (PI/2 radians = 90 degrees) var angle = Math.PI / 2; if (enemy.children[0] && enemy.children[0].targetRotation === undefined) { enemy.children[0].targetRotation = angle; enemy.children[0].rotation = angle; } else if (enemy.children[0]) { if (Math.abs(angle - enemy.children[0].targetRotation) > 0.05) { tween.stop(enemy.children[0], { rotation: true }); // Calculate the shortest angle to rotate var currentRotation = enemy.children[0].rotation; var angleDiff = angle - currentRotation; // Normalize angle difference to -PI to PI range for shortest path while (angleDiff > Math.PI) { angleDiff -= Math.PI * 2; } while (angleDiff < -Math.PI) { angleDiff += Math.PI * 2; } // Set target rotation and animate to it enemy.children[0].targetRotation = angle; tween(enemy.children[0], { rotation: currentRotation + angleDiff }, { duration: 250, easing: tween.easeOut }); } } // Update enemy's position enemy.x = grid.x + enemy.currentCellX * CELL_SIZE; enemy.y = grid.y + enemy.currentCellY * CELL_SIZE; return false; } // After reaching entry area, handle flying enemies differently if (enemy.isFlying) { // Flying enemies head straight to the closest goal if (!enemy.flyingTarget) { // Set flying target to a GOAL cell var goalCells = []; for (var i = 0; i < gridWidth; i++) { for (var j = 0; j < gridHeight; j++) { var cell = self.cells[i][j]; if (cell.type === GridItemType.GOAL) { goalCells.push(cell); } } } if (goalCells.length > 0) { enemy.flyingTarget = goalCells[0]; // Find closest goal if there are multiple if (goalCells.length > 1) { var closestDist = Infinity; for (var i = 0; i < goalCells.length; i++) { var goal = goalCells[i]; var dx = goal.x - enemy.cellX; var dy = goal.y - enemy.cellY; var dist = dx * dx + dy * dy; if (dist < closestDist) { closestDist = dist; enemy.flyingTarget = goal; } } } } } // Move directly toward the goal var ox = enemy.flyingTarget.x - enemy.currentCellX; var oy = enemy.flyingTarget.y - enemy.currentCellY; var dist = Math.sqrt(ox * ox + oy * oy); if (dist < enemy.speed) { // Reached the goal return true; } var angle = Math.atan2(oy, ox); // Rotate enemy graphic to match movement direction if (enemy.children[0] && enemy.children[0].targetRotation === undefined) { enemy.children[0].targetRotation = angle; enemy.children[0].rotation = angle; } else if (enemy.children[0]) { if (Math.abs(angle - enemy.children[0].targetRotation) > 0.05) { tween.stop(enemy.children[0], { rotation: true }); // Calculate the shortest angle to rotate var currentRotation = enemy.children[0].rotation; var angleDiff = angle - currentRotation; // Normalize angle difference to -PI to PI range for shortest path while (angleDiff > Math.PI) { angleDiff -= Math.PI * 2; } while (angleDiff < -Math.PI) { angleDiff += Math.PI * 2; } // Set target rotation and animate to it enemy.children[0].targetRotation = angle; tween(enemy.children[0], { rotation: currentRotation + angleDiff }, { duration: 250, easing: tween.easeOut }); } } // Update the cell position to track where the flying enemy is enemy.cellX = Math.round(enemy.currentCellX); enemy.cellY = Math.round(enemy.currentCellY); enemy.currentCellX += Math.cos(angle) * enemy.speed; enemy.currentCellY += Math.sin(angle) * enemy.speed; enemy.x = grid.x + enemy.currentCellX * CELL_SIZE; enemy.y = grid.y + enemy.currentCellY * CELL_SIZE; // Update shadow position if this is a flying enemy return false; } // Handle normal pathfinding enemies using assigned paths if (!enemy.assignedPath) { // This shouldn't happen in normal gameplay, but handle gracefully return true; } // Check if enemy has reached the end of their path if (enemy.currentWaypointIndex >= enemy.assignedPath.length - 1) { // Enemy reached the goal return true; } // Get current target waypoint var targetWaypoint = enemy.assignedPath[enemy.currentWaypointIndex + 1]; if (!targetWaypoint) { return true; } // Calculate movement vector from current position to target waypoint center var dx = targetWaypoint.x + 0.5 - enemy.currentCellX; var dy = targetWaypoint.y + 0.5 - enemy.currentCellY; var distToTarget = Math.sqrt(dx * dx + dy * dy); // Check if we've reached the current target waypoint (with buffer for smooth advancement) if (distToTarget < enemy.speed * 1.5) { // Snap to waypoint center and advance enemy.currentCellX = targetWaypoint.x + 0.5; enemy.currentCellY = targetWaypoint.y + 0.5; enemy.currentWaypointIndex++; enemy.cellX = targetWaypoint.x; enemy.cellY = targetWaypoint.y; // Check if we've reached the goal after advancing if (enemy.currentWaypointIndex >= enemy.assignedPath.length - 1) { return true; } } else { // Continue moving towards target var angle = Math.atan2(dy, dx); enemy.currentCellX += Math.cos(angle) * enemy.speed; enemy.currentCellY += Math.sin(angle) * enemy.speed; // Update rotation if (enemy.children[0]) { if (enemy.children[0].targetRotation === undefined) { enemy.children[0].targetRotation = angle; enemy.children[0].rotation = angle; } else if (Math.abs(angle - enemy.children[0].targetRotation) > 0.05) { tween.stop(enemy.children[0], { rotation: true }); var currentRotation = enemy.children[0].rotation; var angleDiff = angle - currentRotation; while (angleDiff > Math.PI) { angleDiff -= Math.PI * 2; } while (angleDiff < -Math.PI) { angleDiff += Math.PI * 2; } enemy.children[0].targetRotation = angle; tween(enemy.children[0], { rotation: currentRotation + angleDiff }, { duration: 250, easing: tween.easeOut }); } } } enemy.x = grid.x + enemy.currentCellX * CELL_SIZE; enemy.y = grid.y + enemy.currentCellY * CELL_SIZE; }; }); var NextWaveButton = Container.expand(function () { var self = Container.call(this); var buttonBackground = self.attachAsset('notification', { anchorX: 0.5, anchorY: 0.5 }); buttonBackground.width = 300; buttonBackground.height = 100; buttonBackground.tint = 0x0088FF; var buttonText = new Text2("Next Wave", { size: 50, fill: 0xFFFFFF, weight: 800 }); buttonText.anchor.set(0.5, 0.5); self.addChild(buttonText); self.enabled = false; self.visible = false; self.update = function () { if (waveIndicator && waveIndicator.gameStarted && currentWave < totalWaves) { self.enabled = true; self.visible = true; buttonBackground.tint = 0x0088FF; self.alpha = 1; } else { self.enabled = false; self.visible = false; buttonBackground.tint = 0x888888; self.alpha = 0.7; } }; self.down = function () { if (!self.enabled) { return; } if (waveIndicator.gameStarted && currentWave < totalWaves) { currentWave++; // Increment to the next wave directly waveTimer = 0; // Reset wave timer waveInProgress = true; waveSpawned = false; // Get the type of the current wave (which is now the next wave) var waveType = waveIndicator.getWaveTypeName(currentWave); var enemyCount = waveIndicator.getEnemyCount(currentWave); var notification = game.addChild(new Notification("Wave " + currentWave + " (" + waveType + " - " + enemyCount + " enemies) activated!")); notification.x = 2048 / 2; notification.y = grid.height - 150; } }; return self; }); var Notification = Container.expand(function (message) { var self = Container.call(this); var notificationGraphics = self.attachAsset('notification', { anchorX: 0.5, anchorY: 0.5 }); var notificationText = new Text2(message, { size: 50, fill: 0x000000, weight: 800 }); notificationText.anchor.set(0.5, 0.5); notificationGraphics.width = notificationText.width + 30; self.addChild(notificationText); self.alpha = 1; var fadeOutTime = 120; self.update = function () { if (fadeOutTime > 0) { fadeOutTime--; self.alpha = Math.min(fadeOutTime / 120 * 2, 1); } else { self.destroy(); } }; return self; }); var SourceTower = Container.expand(function (towerType) { var self = Container.call(this); self.towerType = towerType || 'default'; // Increase size of base for easier touch var baseGraphics = self.attachAsset('tower', { anchorX: 0.5, anchorY: 0.5, scaleX: 1.3, scaleY: 1.3 }); switch (self.towerType) { case 'rapid': baseGraphics.tint = 0x00AAFF; break; case 'sniper': baseGraphics.tint = 0xFF5500; break; case 'splash': baseGraphics.tint = 0x33CC00; break; case 'slow': baseGraphics.tint = 0x9900FF; break; case 'poison': baseGraphics.tint = 0x00FFAA; break; default: baseGraphics.tint = 0xAAAAAA; } var towerCost = getTowerCost(self.towerType); // Add shadow for tower type label var typeLabelShadow = new Text2(self.towerType.charAt(0).toUpperCase() + self.towerType.slice(1), { size: 50, fill: 0x000000, weight: 800 }); typeLabelShadow.anchor.set(0.5, 0.5); typeLabelShadow.x = 4; typeLabelShadow.y = -20 + 4; self.addChild(typeLabelShadow); // Add tower type label var typeLabel = new Text2(self.towerType.charAt(0).toUpperCase() + self.towerType.slice(1), { size: 50, fill: 0xFFFFFF, weight: 800 }); typeLabel.anchor.set(0.5, 0.5); typeLabel.y = -20; // Position above center of tower self.addChild(typeLabel); // Add cost shadow var costLabelShadow = new Text2(towerCost, { size: 50, fill: 0x000000, weight: 800 }); costLabelShadow.anchor.set(0.5, 0.5); costLabelShadow.x = 4; costLabelShadow.y = 24 + 12; self.addChild(costLabelShadow); // Add cost label var costLabel = new Text2(towerCost, { size: 50, fill: 0xFFD700, weight: 800 }); costLabel.anchor.set(0.5, 0.5); costLabel.y = 20 + 12; self.addChild(costLabel); self.update = function () { // Check if player can afford this tower var canAfford = gold >= getTowerCost(self.towerType); // Set opacity based on affordability self.alpha = canAfford ? 1 : 0.5; }; return self; }); var Tower = Container.expand(function (id) { var self = Container.call(this); self.id = id || 'default'; self.level = 1; self.maxLevel = 6; self.gridX = 0; self.gridY = 0; self.range = 3 * CELL_SIZE; // Standardized method to get the current range of the tower self.getRange = function () { // Always calculate range based on tower type and level switch (self.id) { case 'sniper': // Sniper: base 5, +0.8 per level, but final upgrade gets a huge boost if (self.level === self.maxLevel) { return 12 * CELL_SIZE; // Significantly increased range for max level } return (5 + (self.level - 1) * 0.8) * CELL_SIZE; case 'splash': // Splash: base 2, +0.2 per level (max ~4 blocks at max level) return (2 + (self.level - 1) * 0.2) * CELL_SIZE; case 'rapid': // Rapid: base 2.5, +0.5 per level return (2.5 + (self.level - 1) * 0.5) * CELL_SIZE; case 'slow': // Slow: base 3.5, +0.5 per level return (3.5 + (self.level - 1) * 0.5) * CELL_SIZE; case 'poison': // Poison: base 3.2, +0.5 per level return (3.2 + (self.level - 1) * 0.5) * CELL_SIZE; default: // Default: base 3, +0.5 per level return (3 + (self.level - 1) * 0.5) * CELL_SIZE; } }; self.cellsInRange = []; self.fireRate = 60; self.bulletSpeed = 5; self.damage = 10; self.lastFired = 0; self.targetEnemy = null; switch (self.id) { case 'rapid': self.fireRate = 30; self.damage = 5; self.range = 2.5 * CELL_SIZE; self.bulletSpeed = 7; break; case 'sniper': self.fireRate = 90; self.damage = 25; self.range = 5 * CELL_SIZE; self.bulletSpeed = 25; break; case 'splash': self.fireRate = 75; self.damage = 15; self.range = 2 * CELL_SIZE; self.bulletSpeed = 4; break; case 'slow': self.fireRate = 50; self.damage = 8; self.range = 3.5 * CELL_SIZE; self.bulletSpeed = 5; break; case 'poison': self.fireRate = 70; self.damage = 12; self.range = 3.2 * CELL_SIZE; self.bulletSpeed = 5; break; } var baseGraphics = self.attachAsset('tower', { anchorX: 0.5, anchorY: 0.5 }); switch (self.id) { case 'rapid': baseGraphics.tint = 0x00AAFF; break; case 'sniper': baseGraphics.tint = 0xFF5500; break; case 'splash': baseGraphics.tint = 0x33CC00; break; case 'slow': baseGraphics.tint = 0x9900FF; break; case 'poison': baseGraphics.tint = 0x00FFAA; break; default: baseGraphics.tint = 0xAAAAAA; } var levelIndicators = []; var maxDots = self.maxLevel; var dotSpacing = baseGraphics.width / (maxDots + 1); var dotSize = CELL_SIZE / 6; for (var i = 0; i < maxDots; i++) { var dot = new Container(); var outlineCircle = dot.attachAsset('towerLevelIndicator', { anchorX: 0.5, anchorY: 0.5 }); outlineCircle.width = dotSize + 4; outlineCircle.height = dotSize + 4; outlineCircle.tint = 0x000000; var towerLevelIndicator = dot.attachAsset('towerLevelIndicator', { anchorX: 0.5, anchorY: 0.5 }); towerLevelIndicator.width = dotSize; towerLevelIndicator.height = dotSize; towerLevelIndicator.tint = 0xCCCCCC; dot.x = -CELL_SIZE + dotSpacing * (i + 1); dot.y = CELL_SIZE * 0.7; self.addChild(dot); levelIndicators.push(dot); } var gunContainer = new Container(); self.addChild(gunContainer); var gunGraphics = gunContainer.attachAsset('defense', { anchorX: 0.5, anchorY: 0.5 }); self.updateLevelIndicators = function () { for (var i = 0; i < maxDots; i++) { var dot = levelIndicators[i]; var towerLevelIndicator = dot.children[1]; if (i < self.level) { towerLevelIndicator.tint = 0xFFFFFF; } else { switch (self.id) { case 'rapid': towerLevelIndicator.tint = 0x00AAFF; break; case 'sniper': towerLevelIndicator.tint = 0xFF5500; break; case 'splash': towerLevelIndicator.tint = 0x33CC00; break; case 'slow': towerLevelIndicator.tint = 0x9900FF; break; case 'poison': towerLevelIndicator.tint = 0x00FFAA; break; default: towerLevelIndicator.tint = 0xAAAAAA; } } } }; self.updateLevelIndicators(); self.refreshCellsInRange = function () { for (var i = 0; i < self.cellsInRange.length; i++) { var cell = self.cellsInRange[i]; var towerIndex = cell.towersInRange.indexOf(self); if (towerIndex !== -1) { cell.towersInRange.splice(towerIndex, 1); } } self.cellsInRange = []; var rangeRadius = self.getRange() / CELL_SIZE; var centerX = self.gridX + 1; var centerY = self.gridY + 1; var minI = Math.floor(centerX - rangeRadius - 0.5); var maxI = Math.ceil(centerX + rangeRadius + 0.5); var minJ = Math.floor(centerY - rangeRadius - 0.5); var maxJ = Math.ceil(centerY + rangeRadius + 0.5); for (var i = minI; i <= maxI; i++) { for (var j = minJ; j <= maxJ; j++) { var closestX = Math.max(i, Math.min(centerX, i + 1)); var closestY = Math.max(j, Math.min(centerY, j + 1)); var deltaX = closestX - centerX; var deltaY = closestY - centerY; var distanceSquared = deltaX * deltaX + deltaY * deltaY; if (distanceSquared <= rangeRadius * rangeRadius) { var cell = grid.getCell(i, j); if (cell) { self.cellsInRange.push(cell); cell.towersInRange.push(self); } } } } grid.renderDebug(); }; self.getTotalValue = function () { var baseTowerCost = getTowerCost(self.id); var totalInvestment = baseTowerCost; var baseUpgradeCost = baseTowerCost; // Upgrade cost now scales with base tower cost for (var i = 1; i < self.level; i++) { totalInvestment += Math.floor(baseUpgradeCost * Math.pow(2, i - 1)); } return totalInvestment; }; self.upgrade = function () { if (self.level < self.maxLevel) { // Exponential upgrade cost: base cost * (2 ^ (level-1)), scaled by tower base cost var baseUpgradeCost = getTowerCost(self.id); var upgradeCost; // Make last upgrade level extra expensive if (self.level === self.maxLevel - 1) { upgradeCost = Math.floor(baseUpgradeCost * Math.pow(2, self.level - 1) * 3.5 / 2); // Half the cost for final upgrade } else { upgradeCost = Math.floor(baseUpgradeCost * Math.pow(2, self.level - 1)); } if (gold >= upgradeCost) { setGold(gold - upgradeCost); self.level++; // No need to update self.range here; getRange() is now the source of truth // Apply tower-specific upgrades based on type if (self.id === 'rapid') { if (self.level === self.maxLevel) { // Extra powerful last upgrade (double the effect) self.fireRate = Math.max(4, 30 - self.level * 9); // double the effect self.damage = 5 + self.level * 10; // double the effect self.bulletSpeed = 7 + self.level * 2.4; // double the effect } else { self.fireRate = Math.max(15, 30 - self.level * 3); // Fast tower gets faster with upgrades self.damage = 5 + self.level * 3; self.bulletSpeed = 7 + self.level * 0.7; } } else { if (self.level === self.maxLevel) { // Extra powerful last upgrade for all other towers (double the effect) self.fireRate = Math.max(5, 60 - self.level * 24); // double the effect self.damage = 10 + self.level * 20; // double the effect self.bulletSpeed = 5 + self.level * 2.4; // double the effect } else { self.fireRate = Math.max(20, 60 - self.level * 8); self.damage = 10 + self.level * 5; self.bulletSpeed = 5 + self.level * 0.5; } } self.refreshCellsInRange(); self.updateLevelIndicators(); if (self.level > 1) { var levelDot = levelIndicators[self.level - 1].children[1]; tween(levelDot, { scaleX: 1.5, scaleY: 1.5 }, { duration: 300, easing: tween.elasticOut, onFinish: function onFinish() { tween(levelDot, { scaleX: 1, scaleY: 1 }, { duration: 200, easing: tween.easeOut }); } }); } return true; } else { var notification = game.addChild(new Notification("Not enough gold to upgrade!")); notification.x = 2048 / 2; notification.y = grid.height - 50; return false; } } return false; }; self.findTarget = function () { var closestEnemy = null; var closestScore = Infinity; // Get all goal cells for distance calculations var goalCells = []; for (var gx = 0; gx < grid.cells.length; gx++) { for (var gy = 0; gy < grid.cells[gx].length; gy++) { if (grid.cells[gx][gy] && grid.cells[gx][gy].type === GridItemType.GOAL) { goalCells.push(grid.cells[gx][gy]); } } } for (var i = 0; i < enemies.length; i++) { var enemy = enemies[i]; var dx = enemy.x - self.x; var dy = enemy.y - self.y; var distance = Math.sqrt(dx * dx + dy * dy); // Check if enemy is in range if (distance <= self.getRange()) { // Handle flying enemies differently - they can be targeted regardless of path if (enemy.isFlying) { // For flying enemies, prioritize by distance to the goal if (enemy.flyingTarget) { var goalX = enemy.flyingTarget.x; var goalY = enemy.flyingTarget.y; var distToGoal = Math.sqrt((goalX - enemy.cellX) * (goalX - enemy.cellX) + (goalY - enemy.cellY) * (goalY - enemy.cellY)); // Use distance to goal as score (lower is better) if (distToGoal < closestScore) { closestScore = distToGoal; closestEnemy = enemy; } } else { // If no flying target yet (shouldn't happen), prioritize by distance to tower if (distance < closestScore) { closestScore = distance; closestEnemy = enemy; } } } else { // For ground enemies, prioritize by path progress (higher waypoint index = closer to goal) var pathProgress = enemy.currentWaypointIndex || 0; if (enemy.assignedPath) { pathProgress = enemy.currentWaypointIndex / enemy.assignedPath.length; } // Use negative path progress as score so higher progress = lower score = higher priority var progressScore = -pathProgress; if (progressScore < closestScore) { closestScore = progressScore; closestEnemy = enemy; } } } } if (!closestEnemy) { self.targetEnemy = null; } return closestEnemy; }; self.update = function () { self.targetEnemy = self.findTarget(); if (self.targetEnemy) { var dx = self.targetEnemy.x - self.x; var dy = self.targetEnemy.y - self.y; var angle = Math.atan2(dy, dx); gunContainer.rotation = angle; if (LK.ticks - self.lastFired >= self.fireRate) { self.fire(); self.lastFired = LK.ticks; } } }; self.down = function (x, y, obj) { // Store drag start position dragStartX = x; dragStartY = y; draggedTower = self; var existingMenus = game.children.filter(function (child) { return child instanceof UpgradeMenu; }); var hasOwnMenu = false; var rangeCircle = null; for (var i = 0; i < game.children.length; i++) { if (game.children[i].isTowerRange && game.children[i].tower === self) { rangeCircle = game.children[i]; break; } } for (var i = 0; i < existingMenus.length; i++) { if (existingMenus[i].tower === self) { hasOwnMenu = true; break; } } if (hasOwnMenu) { for (var i = 0; i < existingMenus.length; i++) { if (existingMenus[i].tower === self) { hideUpgradeMenu(existingMenus[i]); } } if (rangeCircle) { game.removeChild(rangeCircle); } selectedTower = null; grid.renderDebug(); return; } // Close any existing menus when starting to drag for (var i = 0; i < existingMenus.length; i++) { existingMenus[i].destroy(); } // Remove all range indicators when starting to drag for (var i = game.children.length - 1; i >= 0; i--) { if (game.children[i].isTowerRange) { game.removeChild(game.children[i]); } } selectedTower = null; // Store original position for potential dragging draggedTowerOriginalX = self.gridX; draggedTowerOriginalY = self.gridY; // Don't clear grid cells here - only clear them when actually dragging starts }; self.isInRange = function (enemy) { if (!enemy) { return false; } var dx = enemy.x - self.x; var dy = enemy.y - self.y; var distance = Math.sqrt(dx * dx + dy * dy); return distance <= self.getRange(); }; self.fire = function () { if (self.targetEnemy) { var potentialDamage = 0; for (var i = 0; i < self.targetEnemy.bulletsTargetingThis.length; i++) { potentialDamage += self.targetEnemy.bulletsTargetingThis[i].damage; } if (self.targetEnemy.health > potentialDamage) { var bulletX = self.x + Math.cos(gunContainer.rotation) * 40; var bulletY = self.y + Math.sin(gunContainer.rotation) * 40; var bullet = new Bullet(bulletX, bulletY, self.targetEnemy, self.damage, self.bulletSpeed); // Set bullet type based on tower type bullet.type = self.id; // For slow tower, pass level for scaling slow effect if (self.id === 'slow') { bullet.sourceTowerLevel = self.level; } // Customize bullet appearance based on tower type switch (self.id) { case 'rapid': bullet.children[0].tint = 0x00AAFF; bullet.children[0].width = 20; bullet.children[0].height = 20; break; case 'sniper': bullet.children[0].tint = 0xFF5500; bullet.children[0].width = 15; bullet.children[0].height = 15; break; case 'splash': bullet.children[0].tint = 0x33CC00; bullet.children[0].width = 40; bullet.children[0].height = 40; break; case 'slow': bullet.children[0].tint = 0x9900FF; bullet.children[0].width = 35; bullet.children[0].height = 35; break; case 'poison': bullet.children[0].tint = 0x00FFAA; bullet.children[0].width = 35; bullet.children[0].height = 35; break; } game.addChild(bullet); bullets.push(bullet); self.targetEnemy.bulletsTargetingThis.push(bullet); // --- Fire recoil effect for gunContainer --- // Stop any ongoing recoil tweens before starting a new one tween.stop(gunContainer, { x: true, y: true, scaleX: true, scaleY: true }); // Always use the original resting position for recoil, never accumulate offset if (gunContainer._restX === undefined) { gunContainer._restX = 0; } if (gunContainer._restY === undefined) { gunContainer._restY = 0; } if (gunContainer._restScaleX === undefined) { gunContainer._restScaleX = 1; } if (gunContainer._restScaleY === undefined) { gunContainer._restScaleY = 1; } // Reset to resting position before animating (in case of interrupted tweens) gunContainer.x = gunContainer._restX; gunContainer.y = gunContainer._restY; gunContainer.scaleX = gunContainer._restScaleX; gunContainer.scaleY = gunContainer._restScaleY; // Calculate recoil offset (recoil back along the gun's rotation) var recoilDistance = 8; var recoilX = -Math.cos(gunContainer.rotation) * recoilDistance; var recoilY = -Math.sin(gunContainer.rotation) * recoilDistance; // Animate recoil back from the resting position tween(gunContainer, { x: gunContainer._restX + recoilX, y: gunContainer._restY + recoilY }, { duration: 60, easing: tween.cubicOut, onFinish: function onFinish() { // Animate return to original position/scale tween(gunContainer, { x: gunContainer._restX, y: gunContainer._restY }, { duration: 90, easing: tween.cubicIn }); } }); } } }; self.placeOnGrid = function (gridX, gridY) { self.gridX = gridX; self.gridY = gridY; self.x = grid.x + gridX * CELL_SIZE + CELL_SIZE / 2; self.y = grid.y + gridY * CELL_SIZE + CELL_SIZE / 2; // Mark all cells in the 2x2 tower area as occupied for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { var cell = grid.getCell(gridX + i, gridY + j); if (cell) { cell.isOccupied = true; } } } self.refreshCellsInRange(); }; return self; }); var TowerPreview = Container.expand(function () { var self = Container.call(this); var towerRange = 3; var rangeInPixels = towerRange * CELL_SIZE; self.towerType = 'default'; self.hasEnoughGold = true; var rangeIndicator = new Container(); self.addChild(rangeIndicator); var rangeGraphics = rangeIndicator.attachAsset('rangeCircle', { anchorX: 0.5, anchorY: 0.5 }); rangeGraphics.alpha = 0.3; var previewGraphics = self.attachAsset('tower', { anchorX: 0.5, anchorY: 0.5 }); previewGraphics.width = CELL_SIZE * 2; previewGraphics.height = CELL_SIZE * 2; self.canPlace = false; self.gridX = 0; self.gridY = 0; self.blockedByEnemy = false; self.update = function () { var previousHasEnoughGold = self.hasEnoughGold; self.hasEnoughGold = gold >= getTowerCost(self.towerType); // Only update appearance if the affordability status has changed if (previousHasEnoughGold !== self.hasEnoughGold) { self.updateAppearance(); } }; self.updateAppearance = function () { // Use Tower class to get the source of truth for range var tempTower = new Tower(self.towerType); var previewRange = tempTower.getRange(); // Clean up tempTower to avoid memory leaks if (tempTower && tempTower.destroy) { tempTower.destroy(); } // Set range indicator using unified range logic rangeGraphics.width = rangeGraphics.height = previewRange * 2; switch (self.towerType) { case 'rapid': previewGraphics.tint = 0x00AAFF; break; case 'sniper': previewGraphics.tint = 0xFF5500; break; case 'splash': previewGraphics.tint = 0x33CC00; break; case 'slow': previewGraphics.tint = 0x9900FF; break; case 'poison': previewGraphics.tint = 0x00FFAA; break; default: previewGraphics.tint = 0xAAAAAA; } if (!self.canPlace || !self.hasEnoughGold) { previewGraphics.tint = 0xFF0000; } }; self.updatePlacementStatus = function () { var validGridPlacement = true; if (self.gridY <= 4 || self.gridY + 1 >= grid.cells[0].length - 4) { validGridPlacement = false; } else { for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { var cell = grid.getCell(self.gridX + i, self.gridY + j); if (!cell || cell.type !== GridItemType.TOWER_SLOT || cell.isOccupied === true) { validGridPlacement = false; break; } } if (!validGridPlacement) { break; } } } self.blockedByEnemy = false; if (validGridPlacement) { for (var i = 0; i < enemies.length; i++) { var enemy = enemies[i]; if (enemy.currentCellY < 4) { continue; } // Only check non-flying enemies, flying enemies can pass over towers if (!enemy.isFlying) { if (enemy.cellX >= self.gridX && enemy.cellX < self.gridX + 2 && enemy.cellY >= self.gridY && enemy.cellY < self.gridY + 2) { self.blockedByEnemy = true; break; } if (enemy.currentTarget) { var targetX = enemy.currentTarget.x; var targetY = enemy.currentTarget.y; if (targetX >= self.gridX && targetX < self.gridX + 2 && targetY >= self.gridY && targetY < self.gridY + 2) { self.blockedByEnemy = true; break; } } } } } self.canPlace = validGridPlacement && !self.blockedByEnemy; self.hasEnoughGold = gold >= getTowerCost(self.towerType); self.updateAppearance(); }; self.checkPlacement = function () { self.updatePlacementStatus(); }; self.snapToGrid = function (x, y) { var gridPosX = x - grid.x; var gridPosY = y - grid.y; self.gridX = Math.floor(gridPosX / CELL_SIZE); self.gridY = Math.floor(gridPosY / CELL_SIZE); self.x = grid.x + self.gridX * CELL_SIZE + CELL_SIZE / 2; self.y = grid.y + self.gridY * CELL_SIZE + CELL_SIZE / 2; self.checkPlacement(); }; return self; }); var UpgradeMenu = Container.expand(function (tower) { var self = Container.call(this); self.tower = tower; self.y = 2732 + 225; var menuBackground = self.attachAsset('notification', { anchorX: 0.5, anchorY: 0.5 }); menuBackground.width = 2048; menuBackground.height = 500; menuBackground.tint = 0x444444; menuBackground.alpha = 0.9; var displayName = self.tower.id.charAt(0).toUpperCase() + self.tower.id.slice(1) + ' Tower'; var towerTypeText = new Text2(displayName, { size: 80, fill: 0xFFFFFF, weight: 800 }); towerTypeText.anchor.set(0, 0); towerTypeText.x = -840; towerTypeText.y = -160; self.addChild(towerTypeText); var statsText = new Text2('Level: ' + self.tower.level + '/' + self.tower.maxLevel + '\nDamage: ' + self.tower.damage + '\nFire Rate: ' + (60 / self.tower.fireRate).toFixed(1) + '/s', { size: 70, fill: 0xFFFFFF, weight: 400 }); statsText.anchor.set(0, 0.5); statsText.x = -840; statsText.y = 50; self.addChild(statsText); var buttonsContainer = new Container(); buttonsContainer.x = 500; self.addChild(buttonsContainer); var upgradeButton = new Container(); buttonsContainer.addChild(upgradeButton); var buttonBackground = upgradeButton.attachAsset('notification', { anchorX: 0.5, anchorY: 0.5 }); buttonBackground.width = 500; buttonBackground.height = 150; var isMaxLevel = self.tower.level >= self.tower.maxLevel; var buttonText; var upgradeCost; // For towers, show Upgrade button var baseUpgradeCost = getTowerCost(self.tower.id); if (isMaxLevel) { upgradeCost = 0; } else if (self.tower.level === self.tower.maxLevel - 1) { upgradeCost = Math.floor(baseUpgradeCost * Math.pow(2, self.tower.level - 1) * 3.5 / 2); } else { upgradeCost = Math.floor(baseUpgradeCost * Math.pow(2, self.tower.level - 1)); } buttonBackground.tint = isMaxLevel ? 0x888888 : gold >= upgradeCost ? 0x00AA00 : 0x888888; buttonText = new Text2(isMaxLevel ? 'Max Level' : 'Upgrade: ' + upgradeCost + ' gold', { size: 60, fill: 0xFFFFFF, weight: 800 }); buttonText.anchor.set(0.5, 0.5); upgradeButton.addChild(buttonText); // Add sell button for towers var sellButton; var sellButtonText; sellButton = new Container(); buttonsContainer.addChild(sellButton); var sellButtonBackground = sellButton.attachAsset('notification', { anchorX: 0.5, anchorY: 0.5 }); sellButtonBackground.width = 500; sellButtonBackground.height = 150; sellButtonBackground.tint = 0xCC0000; var totalInvestment = self.tower.getTotalValue ? self.tower.getTotalValue() : 0; var sellValue = getTowerSellValue(totalInvestment); sellButtonText = new Text2('Sell: +' + sellValue + ' gold', { size: 60, fill: 0xFFFFFF, weight: 800 }); sellButtonText.anchor.set(0.5, 0.5); sellButton.addChild(sellButtonText); upgradeButton.y = -85; sellButton.y = 85; var closeButton = new Container(); self.addChild(closeButton); var closeBackground = closeButton.attachAsset('notification', { anchorX: 0.5, anchorY: 0.5 }); closeBackground.width = 90; closeBackground.height = 90; closeBackground.tint = 0xAA0000; var closeText = new Text2('X', { size: 68, fill: 0xFFFFFF, weight: 800 }); closeText.anchor.set(0.5, 0.5); closeButton.addChild(closeText); closeButton.x = menuBackground.width / 2 - 57; closeButton.y = -menuBackground.height / 2 + 57; upgradeButton.down = function (x, y, obj) { // Handle tower upgrade if (self.tower.level >= self.tower.maxLevel) { var notification = game.addChild(new Notification("Tower is already at max level!")); notification.x = 2048 / 2; notification.y = grid.height - 50; return; } if (self.tower.upgrade()) { // Exponential upgrade cost: base cost * (2 ^ (level-1)), scaled by tower base cost var baseUpgradeCost = getTowerCost(self.tower.id); if (self.tower.level >= self.tower.maxLevel) { upgradeCost = 0; } else if (self.tower.level === self.tower.maxLevel - 1) { upgradeCost = Math.floor(baseUpgradeCost * Math.pow(2, self.tower.level - 1) * 3.5 / 2); } else { upgradeCost = Math.floor(baseUpgradeCost * Math.pow(2, self.tower.level - 1)); } statsText.setText('Level: ' + self.tower.level + '/' + self.tower.maxLevel + '\nDamage: ' + self.tower.damage + '\nFire Rate: ' + (60 / self.tower.fireRate).toFixed(1) + '/s'); buttonText.setText('Upgrade: ' + upgradeCost + ' gold'); var totalInvestment = self.tower.getTotalValue ? self.tower.getTotalValue() : 0; var sellValue = Math.floor(totalInvestment * 0.6); sellButtonText.setText('Sell: +' + sellValue + ' gold'); if (self.tower.level >= self.tower.maxLevel) { buttonBackground.tint = 0x888888; buttonText.setText('Max Level'); } var rangeCircle = null; for (var i = 0; i < game.children.length; i++) { if (game.children[i].isTowerRange && game.children[i].tower === self.tower) { rangeCircle = game.children[i]; break; } } if (rangeCircle) { var rangeGraphics = rangeCircle.children[0]; rangeGraphics.width = rangeGraphics.height = self.tower.getRange() * 2; } else { var newRangeIndicator = new Container(); newRangeIndicator.isTowerRange = true; newRangeIndicator.tower = self.tower; game.addChildAt(newRangeIndicator, 0); newRangeIndicator.x = self.tower.x; newRangeIndicator.y = self.tower.y; var rangeGraphics = newRangeIndicator.attachAsset('rangeCircle', { anchorX: 0.5, anchorY: 0.5 }); rangeGraphics.width = rangeGraphics.height = self.tower.getRange() * 2; rangeGraphics.alpha = 0.3; } tween(self, { scaleX: 1.05, scaleY: 1.05 }, { duration: 100, easing: tween.easeOut, onFinish: function onFinish() { tween(self, { scaleX: 1, scaleY: 1 }, { duration: 100, easing: tween.easeIn }); } }); } }; if (sellButton) { sellButton.down = function (x, y, obj) { var totalInvestment = self.tower.getTotalValue ? self.tower.getTotalValue() : 0; var sellValue = getTowerSellValue(totalInvestment); setGold(gold + sellValue); var notification = game.addChild(new Notification("Tower sold for " + sellValue + " gold!")); notification.x = 2048 / 2; notification.y = grid.height - 50; var gridX = self.tower.gridX; var gridY = self.tower.gridY; for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { var cell = grid.getCell(gridX + i, gridY + j); if (cell) { cell.isOccupied = false; var towerIndex = cell.towersInRange.indexOf(self.tower); if (towerIndex !== -1) { cell.towersInRange.splice(towerIndex, 1); } } } } if (selectedTower === self.tower) { selectedTower = null; } var towerIndex = towers.indexOf(self.tower); if (towerIndex !== -1) { towers.splice(towerIndex, 1); } towerLayer.removeChild(self.tower); grid.renderDebug(); self.destroy(); for (var i = 0; i < game.children.length; i++) { if (game.children[i].isTowerRange && game.children[i].tower === self.tower) { game.removeChild(game.children[i]); break; } } }; } closeButton.down = function (x, y, obj) { hideUpgradeMenu(self); selectedTower = null; grid.renderDebug(); }; self.update = function () { // For towers, handle upgrade logic if (self.tower.level >= self.tower.maxLevel) { if (buttonText.text !== 'Max Level') { buttonText.setText('Max Level'); buttonBackground.tint = 0x888888; } return; } // Exponential upgrade cost: base cost * (2 ^ (level-1)), scaled by tower base cost var baseUpgradeCost = getTowerCost(self.tower.id); var currentUpgradeCost; if (self.tower.level >= self.tower.maxLevel) { currentUpgradeCost = 0; } else if (self.tower.level === self.tower.maxLevel - 1) { currentUpgradeCost = Math.floor(baseUpgradeCost * Math.pow(2, self.tower.level - 1) * 3.5 / 2); } else { currentUpgradeCost = Math.floor(baseUpgradeCost * Math.pow(2, self.tower.level - 1)); } var canAfford = gold >= currentUpgradeCost; buttonBackground.tint = canAfford ? 0x00AA00 : 0x888888; var newText = 'Upgrade: ' + currentUpgradeCost + ' gold'; if (buttonText.text !== newText) { buttonText.setText(newText); } }; return self; }); var WaveIndicator = Container.expand(function () { var self = Container.call(this); self.gameStarted = false; self.waveMarkers = []; self.waveTypes = []; self.enemyCounts = []; self.indicatorWidth = 0; self.lastBossType = null; // Track the last boss type to avoid repeating var blockWidth = 400; var totalBlocksWidth = blockWidth * totalWaves; var startMarker = new Container(); var startBlock = startMarker.attachAsset('notification', { anchorX: 0.5, anchorY: 0.5 }); startBlock.width = blockWidth - 10; startBlock.height = 70 * 2; startBlock.tint = 0x00AA00; // Add shadow for start text var startTextShadow = new Text2("Start Game", { size: 50, fill: 0x000000, weight: 800 }); startTextShadow.anchor.set(0.5, 0.5); startTextShadow.x = 4; startTextShadow.y = 4; startMarker.addChild(startTextShadow); var startText = new Text2("Start Game", { size: 50, fill: 0xFFFFFF, weight: 800 }); startText.anchor.set(0.5, 0.5); startMarker.addChild(startText); startMarker.x = -self.indicatorWidth; self.addChild(startMarker); self.waveMarkers.push(startMarker); startMarker.down = function () { if (!self.gameStarted) { self.gameStarted = true; currentWave = 0; waveTimer = nextWaveTime; startBlock.tint = 0x00FF00; startText.setText("Started!"); startTextShadow.setText("Started!"); // Make sure shadow position remains correct after text change startTextShadow.x = 4; startTextShadow.y = 4; var notification = game.addChild(new Notification("Game started! Wave 1 incoming!")); notification.x = 2048 / 2; notification.y = grid.height - 150; } }; for (var i = 0; i < totalWaves; i++) { var marker = new Container(); var block = marker.attachAsset('notification', { anchorX: 0.5, anchorY: 0.5 }); block.width = blockWidth - 10; block.height = 70 * 2; // --- Begin new unified wave logic --- var waveType = "normal"; var enemyType = "normal"; var enemyCount = 10; var isBossWave = (i + 1) % 10 === 0; // Ensure all types appear in early waves if (i === 0) { block.tint = 0xAAAAAA; waveType = "Normal"; enemyType = "normal"; enemyCount = 10; } else if (i === 1) { block.tint = 0x00AAFF; waveType = "Fast"; enemyType = "fast"; enemyCount = 10; } else if (i === 2) { block.tint = 0xAA0000; waveType = "Immune"; enemyType = "immune"; enemyCount = 10; } else if (i === 3) { block.tint = 0xFFFF00; waveType = "Flying"; enemyType = "flying"; enemyCount = 10; } else if (i === 4) { block.tint = 0xFF00FF; waveType = "Swarm"; enemyType = "swarm"; enemyCount = 30; } else if (isBossWave) { // Boss waves: cycle through all boss types, last boss is always flying var bossTypes = ['normal', 'fast', 'immune', 'flying']; var bossTypeIndex = Math.floor((i + 1) / 10) - 1; if (i === totalWaves - 1) { // Last boss is always flying enemyType = 'flying'; waveType = "Boss Flying"; block.tint = 0xFFFF00; } else { enemyType = bossTypes[bossTypeIndex % bossTypes.length]; switch (enemyType) { case 'normal': block.tint = 0xAAAAAA; waveType = "Boss Normal"; break; case 'fast': block.tint = 0x00AAFF; waveType = "Boss Fast"; break; case 'immune': block.tint = 0xAA0000; waveType = "Boss Immune"; break; case 'flying': block.tint = 0xFFFF00; waveType = "Boss Flying"; break; } } enemyCount = 1; // Make the wave indicator for boss waves stand out // Set boss wave color to the color of the wave type switch (enemyType) { case 'normal': block.tint = 0xAAAAAA; break; case 'fast': block.tint = 0x00AAFF; break; case 'immune': block.tint = 0xAA0000; break; case 'flying': block.tint = 0xFFFF00; break; default: block.tint = 0xFF0000; break; } } else if ((i + 1) % 5 === 0) { // Every 5th non-boss wave is fast block.tint = 0x00AAFF; waveType = "Fast"; enemyType = "fast"; enemyCount = 10; } else if ((i + 1) % 4 === 0) { // Every 4th non-boss wave is immune block.tint = 0xAA0000; waveType = "Immune"; enemyType = "immune"; enemyCount = 10; } else if ((i + 1) % 7 === 0) { // Every 7th non-boss wave is flying block.tint = 0xFFFF00; waveType = "Flying"; enemyType = "flying"; enemyCount = 10; } else if ((i + 1) % 3 === 0) { // Every 3rd non-boss wave is swarm block.tint = 0xFF00FF; waveType = "Swarm"; enemyType = "swarm"; enemyCount = 30; } else { block.tint = 0xAAAAAA; waveType = "Normal"; enemyType = "normal"; enemyCount = 10; } // --- End new unified wave logic --- // Mark boss waves with a special visual indicator if (isBossWave && enemyType !== 'swarm') { // Add a crown or some indicator to the wave marker for boss waves var bossIndicator = marker.attachAsset('towerLevelIndicator', { anchorX: 0.5, anchorY: 0.5 }); bossIndicator.width = 30; bossIndicator.height = 30; bossIndicator.tint = 0xFFD700; // Gold color bossIndicator.y = -block.height / 2 - 15; // Change the wave type text to indicate boss waveType = "BOSS"; } // Store the wave type and enemy count self.waveTypes[i] = enemyType; self.enemyCounts[i] = enemyCount; // Add shadow for wave type - 30% smaller than before var waveTypeShadow = new Text2(waveType, { size: 56, fill: 0x000000, weight: 800 }); waveTypeShadow.anchor.set(0.5, 0.5); waveTypeShadow.x = 4; waveTypeShadow.y = 4; marker.addChild(waveTypeShadow); // Add wave type text - 30% smaller than before var waveTypeText = new Text2(waveType, { size: 56, fill: 0xFFFFFF, weight: 800 }); waveTypeText.anchor.set(0.5, 0.5); waveTypeText.y = 0; marker.addChild(waveTypeText); // Add shadow for wave number - 20% larger than before var waveNumShadow = new Text2((i + 1).toString(), { size: 48, fill: 0x000000, weight: 800 }); waveNumShadow.anchor.set(1.0, 1.0); waveNumShadow.x = blockWidth / 2 - 16 + 5; waveNumShadow.y = block.height / 2 - 12 + 5; marker.addChild(waveNumShadow); // Main wave number text - 20% larger than before var waveNum = new Text2((i + 1).toString(), { size: 48, fill: 0xFFFFFF, weight: 800 }); waveNum.anchor.set(1.0, 1.0); waveNum.x = blockWidth / 2 - 16; waveNum.y = block.height / 2 - 12; marker.addChild(waveNum); marker.x = -self.indicatorWidth + (i + 1) * blockWidth; self.addChild(marker); self.waveMarkers.push(marker); } // Get wave type for a specific wave number self.getWaveType = function (waveNumber) { if (waveNumber < 1 || waveNumber > totalWaves) { return "normal"; } // If this is a boss wave (waveNumber % 10 === 0), and the type is the same as lastBossType // then we should return a different boss type var waveType = self.waveTypes[waveNumber - 1]; return waveType; }; // Get enemy count for a specific wave number self.getEnemyCount = function (waveNumber) { if (waveNumber < 1 || waveNumber > totalWaves) { return 10; } return self.enemyCounts[waveNumber - 1]; }; // Get display name for a wave type self.getWaveTypeName = function (waveNumber) { var type = self.getWaveType(waveNumber); var typeName = type.charAt(0).toUpperCase() + type.slice(1); // Add boss prefix for boss waves (every 10th wave) if (waveNumber % 10 === 0 && waveNumber > 0 && type !== 'swarm') { typeName = "BOSS"; } return typeName; }; self.positionIndicator = new Container(); var indicator = self.positionIndicator.attachAsset('towerLevelIndicator', { anchorX: 0.5, anchorY: 0.5 }); indicator.width = blockWidth - 10; indicator.height = 16; indicator.tint = 0xffad0e; indicator.y = -65; var indicator2 = self.positionIndicator.attachAsset('towerLevelIndicator', { anchorX: 0.5, anchorY: 0.5 }); indicator2.width = blockWidth - 10; indicator2.height = 16; indicator2.tint = 0xffad0e; indicator2.y = 65; var leftWall = self.positionIndicator.attachAsset('towerLevelIndicator', { anchorX: 0.5, anchorY: 0.5 }); leftWall.width = 16; leftWall.height = 146; leftWall.tint = 0xffad0e; leftWall.x = -(blockWidth - 16) / 2; var rightWall = self.positionIndicator.attachAsset('towerLevelIndicator', { anchorX: 0.5, anchorY: 0.5 }); rightWall.width = 16; rightWall.height = 146; rightWall.tint = 0xffad0e; rightWall.x = (blockWidth - 16) / 2; self.addChild(self.positionIndicator); self.update = function () { var progress = waveTimer / nextWaveTime; var moveAmount = (progress + currentWave) * blockWidth; for (var i = 0; i < self.waveMarkers.length; i++) { var marker = self.waveMarkers[i]; marker.x = -moveAmount + i * blockWidth; } self.positionIndicator.x = 0; for (var i = 0; i < totalWaves + 1; i++) { var marker = self.waveMarkers[i]; if (i === 0) { continue; } var block = marker.children[0]; if (i - 1 < currentWave) { block.alpha = .5; } } self.handleWaveProgression = function () { if (!self.gameStarted) { return; } if (currentWave < totalWaves) { waveTimer++; if (waveTimer >= nextWaveTime) { waveTimer = 0; currentWave++; waveInProgress = true; waveSpawned = false; if (currentWave != 1) { var waveType = self.getWaveTypeName(currentWave); var enemyCount = self.getEnemyCount(currentWave); var notification = game.addChild(new Notification("Wave " + currentWave + " (" + waveType + " - " + enemyCount + " enemies) incoming!")); notification.x = 2048 / 2; notification.y = grid.height - 150; } } } }; self.handleWaveProgression(); }; return self; }); /**** * Initialize Game ****/ var game = new LK.Game({ backgroundColor: 0x333333 }); /**** * Game Code ****/ // Add Map_1 background without stretching var GridItemType = { PATH_CROSSROAD: 0, PATH_STRAIGHT_UP: 1, PATH_STRAIGHT_DOWN: 2, PATH_STRAIGHT_LEFT: 3, PATH_STRAIGHT_RIGHT: 4, PATH_CORNER_TOP_LEFT: 5, PATH_CORNER_TOP_RIGHT: 6, PATH_CORNER_BOTTOM_LEFT: 7, PATH_CORNER_BOTTOM_RIGHT: 8, WALL: 9, SPAWN: 10, GOAL: 11, TOWER_SLOT: 12 }; var backgroundMap = game.attachAsset('Map_1', { anchorX: 0, anchorY: 0, x: 0, y: 200 }); var isHidingUpgradeMenu = false; function hideUpgradeMenu(menu) { if (isHidingUpgradeMenu) { return; } isHidingUpgradeMenu = true; tween(menu, { y: 2732 + 225 }, { duration: 150, easing: tween.easeIn, onFinish: function onFinish() { menu.destroy(); isHidingUpgradeMenu = false; } }); } var CELL_SIZE = 76; var enemies = []; var towers = []; var bullets = []; var defenses = []; var coins = []; var selectedTower = null; var gold = 80; var lives = 20; var score = 0; var currentWave = 0; var totalWaves = 50; var waveTimer = 0; var waveInProgress = false; var waveSpawned = false; var nextWaveTime = 12000 / 2; var sourceTower = null; var enemiesToSpawn = 10; // Default number of enemies per wave var goldText = new Text2('Gold: ' + gold, { size: 60, fill: 0xFFD700, weight: 800 }); goldText.anchor.set(0.5, 0.5); var livesText = new Text2('Lives: ' + lives, { size: 60, fill: 0x00FF00, weight: 800 }); livesText.anchor.set(0.5, 0.5); var scoreText = new Text2('Score: ' + score, { size: 60, fill: 0xFF0000, weight: 800 }); scoreText.anchor.set(0.5, 0.5); var topMargin = 50; var centerX = 2048 / 2; var spacing = 400; LK.gui.top.addChild(goldText); LK.gui.top.addChild(livesText); LK.gui.top.addChild(scoreText); livesText.x = 0; livesText.y = topMargin; goldText.x = -spacing; goldText.y = topMargin; scoreText.x = spacing; scoreText.y = topMargin; function updateUI() { goldText.setText('Gold: ' + gold); livesText.setText('Lives: ' + lives); scoreText.setText('Score: ' + score); } function setGold(value) { gold = value; updateUI(); } var debugLayer = new Container(); var towerLayer = new Container(); // Create three separate layers for enemy hierarchy var enemyLayerBottom = new Container(); // For normal enemies var enemyLayerMiddle = new Container(); // For shadows var enemyLayerTop = new Container(); // For flying enemies var enemyLayer = new Container(); // Main container to hold all enemy layers // Add layers in correct order (bottom first, then middle for shadows, then top) enemyLayer.addChild(enemyLayerBottom); enemyLayer.addChild(enemyLayerMiddle); enemyLayer.addChild(enemyLayerTop); var grid = new Grid(24, 29 + 6); grid.x = 150; grid.y = 200 - CELL_SIZE * 4; // Initial blockers can be placed manually on specific tower slots if desired // For example: // var blocker = new Blocker(); // blocker.placeOnGrid(4, 8); // Place at tower slot coordinates // towerLayer.addChild(blocker); // blockers.push(blocker); grid.buildAllGroundPaths(); grid.renderDebug(); debugLayer.addChild(grid); game.addChild(debugLayer); game.addChild(towerLayer); game.addChild(enemyLayer); var offset = 0; var towerPreview = new TowerPreview(); game.addChild(towerPreview); towerPreview.visible = false; var isDragging = false; var draggedTower = null; var dragStartX = 0; var dragStartY = 0; var draggedTowerOriginalX = 0; var draggedTowerOriginalY = 0; function getTowerCost(towerType) { var cost = 5; switch (towerType) { case 'rapid': cost = 15; break; case 'sniper': cost = 25; break; case 'splash': cost = 35; break; case 'slow': cost = 45; break; case 'poison': cost = 55; break; } return cost; } function getTowerSellValue(totalValue) { return waveIndicator && waveIndicator.gameStarted ? Math.floor(totalValue * 0.6) : totalValue; } function placeTower(gridX, gridY, towerType) { var towerCost = getTowerCost(towerType); if (gold >= towerCost) { var tower = new Tower(towerType || 'default'); tower.placeOnGrid(gridX, gridY); towerLayer.addChild(tower); towers.push(tower); setGold(gold - towerCost); grid.renderDebug(); return true; } else { var notification = game.addChild(new Notification("Not enough gold!")); notification.x = 2048 / 2; notification.y = grid.height - 50; return false; } } game.down = function (x, y, obj) { var upgradeMenuVisible = game.children.some(function (child) { return child instanceof UpgradeMenu; }); if (upgradeMenuVisible) { return; } for (var i = 0; i < sourceTowers.length; i++) { var tower = sourceTowers[i]; if (x >= tower.x - tower.width / 2 && x <= tower.x + tower.width / 2 && y >= tower.y - tower.height / 2 && y <= tower.y + tower.height / 2) { towerPreview.visible = true; isDragging = true; towerPreview.towerType = tower.towerType; towerPreview.updateAppearance(); // Center the tower preview on the cursor position when starting drag towerPreview.snapToGrid(x, y); break; } } }; game.move = function (x, y, obj) { if (isDragging) { // Center the tower preview on the cursor position towerPreview.snapToGrid(x, y); } else if (draggedTower) { // Calculate distance moved to determine if this is a drag var dragDistance = Math.sqrt((x - dragStartX) * (x - dragStartX) + (y - dragStartY) * (y - dragStartY)); if (dragDistance > 20) { // Start dragging if moved more than 20 pixels isDragging = true; // Now clear the old tower position on the grid since we're actually dragging for (var i = 0; i < 2; i++) { for (var j = 0; j < 2; j++) { var cell = grid.getCell(draggedTower.gridX + i, draggedTower.gridY + j); if (cell) { cell.isOccupied = false; // Remove tower from cell's towersInRange array var towerIndex = cell.towersInRange.indexOf(draggedTower); if (towerIndex !== -1) { cell.towersInRange.splice(towerIndex, 1); } } } } grid.renderDebug(); // Update debug view towerPreview.visible = true; towerPreview.towerType = draggedTower.id; towerPreview.updateAppearance(); towerPreview.snapToGrid(x, y); // Hide the original tower while dragging draggedTower.visible = false; } } }; game.up = function (x, y, obj) { var clickedOnTower = false; for (var i = 0; i < towers.length; i++) { var tower = towers[i]; var towerLeft = tower.x - tower.width / 2; var towerRight = tower.x + tower.width / 2; var towerTop = tower.y - tower.height / 2; var towerBottom = tower.y + tower.height / 2; if (x >= towerLeft && x <= towerRight && y >= towerTop && y <= towerBottom) { clickedOnTower = true; break; } } var upgradeMenus = game.children.filter(function (child) { return child instanceof UpgradeMenu; }); if (upgradeMenus.length > 0 && !isDragging && !clickedOnTower) { var clickedOnMenu = false; for (var i = 0; i < upgradeMenus.length; i++) { var menu = upgradeMenus[i]; var menuWidth = 2048; var menuHeight = 450; var menuLeft = menu.x - menuWidth / 2; var menuRight = menu.x + menuWidth / 2; var menuTop = menu.y - menuHeight / 2; var menuBottom = menu.y + menuHeight / 2; if (x >= menuLeft && x <= menuRight && y >= menuTop && y <= menuBottom) { clickedOnMenu = true; break; } } if (!clickedOnMenu) { for (var i = 0; i < upgradeMenus.length; i++) { var menu = upgradeMenus[i]; hideUpgradeMenu(menu); } for (var i = game.children.length - 1; i >= 0; i--) { if (game.children[i].isTowerRange) { game.removeChild(game.children[i]); } } selectedTower = null; grid.renderDebug(); } } if (isDragging) { isDragging = false; if (draggedTower) { // Show the tower again draggedTower.visible = true; // Handle moving existing tower if (towerPreview.canPlace) { // Move tower to new position draggedTower.placeOnGrid(towerPreview.gridX, towerPreview.gridY); grid.renderDebug(); } else if (towerPreview.blockedByEnemy) { // Blocked by enemy, restore tower to original position draggedTower.placeOnGrid(draggedTowerOriginalX, draggedTowerOriginalY); var notification = game.addChild(new Notification("Cannot move: Enemy in the way!")); notification.x = 2048 / 2; notification.y = grid.height - 50; } else if (towerPreview.visible) { // Invalid placement, restore tower to original position draggedTower.placeOnGrid(draggedTowerOriginalX, draggedTowerOriginalY); var notification = game.addChild(new Notification("Cannot move here!")); notification.x = 2048 / 2; notification.y = grid.height - 50; } } else { // Handle placing new tower if (towerPreview.canPlace) { placeTower(towerPreview.gridX, towerPreview.gridY, towerPreview.towerType); } else if (towerPreview.blockedByEnemy) { var notification = game.addChild(new Notification("Cannot build: Enemy in the way!")); notification.x = 2048 / 2; notification.y = grid.height - 50; } else if (towerPreview.visible) { var notification = game.addChild(new Notification("Cannot build here!")); notification.x = 2048 / 2; notification.y = grid.height - 50; } } towerPreview.visible = false; draggedTower = null; // Close upgrade menus when dragging is complete var upgradeMenus = game.children.filter(function (child) { return child instanceof UpgradeMenu; }); for (var i = 0; i < upgradeMenus.length; i++) { upgradeMenus[i].destroy(); } } else if (draggedTower) { // Handle tap without drag - show upgrade menu var existingMenus = game.children.filter(function (child) { return child instanceof UpgradeMenu; }); for (var i = 0; i < existingMenus.length; i++) { existingMenus[i].destroy(); } for (var i = game.children.length - 1; i >= 0; i--) { if (game.children[i].isTowerRange) { game.removeChild(game.children[i]); } } selectedTower = draggedTower; var rangeIndicator = new Container(); rangeIndicator.isTowerRange = true; rangeIndicator.tower = draggedTower; game.addChild(rangeIndicator); rangeIndicator.x = draggedTower.x; rangeIndicator.y = draggedTower.y; var rangeGraphics = rangeIndicator.attachAsset('rangeCircle', { anchorX: 0.5, anchorY: 0.5 }); rangeGraphics.width = rangeGraphics.height = draggedTower.getRange() * 2; rangeGraphics.alpha = 0.3; var upgradeMenu = new UpgradeMenu(draggedTower); game.addChild(upgradeMenu); upgradeMenu.x = 2048 / 2; tween(upgradeMenu, { y: 2732 - 225 }, { duration: 200, easing: tween.backOut }); grid.renderDebug(); draggedTower = null; } }; var waveIndicator = new WaveIndicator(); waveIndicator.x = 2048 / 2; waveIndicator.y = 2732 - 80; game.addChild(waveIndicator); var nextWaveButtonContainer = new Container(); var nextWaveButton = new NextWaveButton(); nextWaveButton.x = 2048 - 200; nextWaveButton.y = 2732 - 100 + 20; nextWaveButtonContainer.addChild(nextWaveButton); game.addChild(nextWaveButtonContainer); var towerTypes = ['default', 'rapid', 'sniper', 'splash', 'slow', 'poison']; var sourceTowers = []; var towerSpacing = 300; // Increase spacing for larger towers var startX = 2048 / 2 - towerTypes.length * towerSpacing / 2 + towerSpacing / 2; var towerY = 2732 - CELL_SIZE * 3 - 90; for (var i = 0; i < towerTypes.length; i++) { var tower = new SourceTower(towerTypes[i]); tower.x = startX + i * towerSpacing; tower.y = towerY; towerLayer.addChild(tower); sourceTowers.push(tower); } sourceTower = null; enemiesToSpawn = 10; game.update = function () { if (waveInProgress) { if (!waveSpawned) { waveSpawned = true; // Get wave type and enemy count from the wave indicator var waveType = waveIndicator.getWaveType(currentWave); var enemyCount = waveIndicator.getEnemyCount(currentWave); // Check if this is a boss wave var isBossWave = currentWave % 10 === 0 && currentWave > 0; if (isBossWave && waveType !== 'swarm') { // Boss waves have just 1 enemy regardless of what the wave indicator says enemyCount = 1; // Show boss announcement var notification = game.addChild(new Notification("⚠️ BOSS WAVE! ⚠️")); notification.x = 2048 / 2; notification.y = grid.height - 200; } // Spawn the appropriate number of enemies for (var i = 0; i < enemyCount; i++) { var enemy = new Enemy(waveType); // Add enemy to the appropriate layer based on type if (enemy.isFlying) { // Add flying enemy to the top layer enemyLayerTop.addChild(enemy); // If it's a flying enemy, add its shadow to the middle layer if (enemy.shadow) { enemyLayerMiddle.addChild(enemy.shadow); } } else { // Add normal/ground enemies to the bottom layer enemyLayerBottom.addChild(enemy); } // Scale difficulty with wave number but don't apply to boss // as bosses already have their health multiplier // Use exponential scaling for health var healthMultiplier = Math.pow(1.12, currentWave); // ~20% increase per wave enemy.maxHealth = Math.round(enemy.maxHealth * healthMultiplier); enemy.health = enemy.maxHealth; // Increment speed slightly with wave number //enemy.speed = enemy.speed + currentWave * 0.002; // Select a random spawn point from the grid.spawns array var spawnCell = grid.spawns[Math.floor(Math.random() * grid.spawns.length)]; enemy.cellX = spawnCell.x; enemy.cellY = spawnCell.y; enemy.currentCellX = spawnCell.x + 0.5; enemy.currentCellY = spawnCell.y + 0.5 - (1 + Math.random() * 5); // Vertical offset for entry animation // Initialize prevCellX/prevCellY to spawn position enemy.prevCellX = enemy.cellX; enemy.prevCellY = enemy.cellY; // Assign path for ground enemies using round-robin if (!enemy.isFlying) { if (grid.allGroundPaths.length > 0) { enemy.assignedPath = grid.allGroundPaths[grid.nextPathAssignmentIndex % grid.allGroundPaths.length]; grid.nextPathAssignmentIndex++; enemy.currentWaypointIndex = 0; // Set enemy position to center of first cell in assigned path enemy.currentCellX = enemy.assignedPath[0].x + 0.5; enemy.currentCellY = enemy.assignedPath[0].y + 0.5; // Set initial target to first waypoint in path if (enemy.assignedPath.length > 0) { enemy.cellX = enemy.assignedPath[0].x; enemy.cellY = enemy.assignedPath[0].y; } } } enemy.waveNumber = currentWave; enemies.push(enemy); } } var currentWaveEnemiesRemaining = false; for (var i = 0; i < enemies.length; i++) { if (enemies[i].waveNumber === currentWave) { currentWaveEnemiesRemaining = true; break; } } if (waveSpawned && !currentWaveEnemiesRemaining) { waveInProgress = false; waveSpawned = false; } } for (var a = enemies.length - 1; a >= 0; a--) { var enemy = enemies[a]; if (enemy.health <= 0) { for (var i = 0; i < enemy.bulletsTargetingThis.length; i++) { var bullet = enemy.bulletsTargetingThis[i]; bullet.targetEnemy = null; } // Boss enemies give more gold and score var goldEarned = enemy.isBoss ? Math.floor(50 + (enemy.waveNumber - 1) * 5) : Math.floor(1 + (enemy.waveNumber - 1) * 0.5); var goldIndicator = new GoldIndicator(goldEarned, enemy.x, enemy.y); game.addChild(goldIndicator); setGold(gold + goldEarned); // Give more score for defeating a boss var scoreValue = enemy.isBoss ? 100 : 5; score += scoreValue; // Add a notification for boss defeat if (enemy.isBoss) { var notification = game.addChild(new Notification("Boss defeated! +" + goldEarned + " gold!")); notification.x = 2048 / 2; notification.y = grid.height - 150; } updateUI(); // Coin spawning removed // Clean up shadow if it's a flying enemy if (enemy.isFlying && enemy.shadow) { enemyLayerMiddle.removeChild(enemy.shadow); enemy.shadow = null; } // Remove enemy from the appropriate layer if (enemy.isFlying) { enemyLayerTop.removeChild(enemy); } else { enemyLayerBottom.removeChild(enemy); } enemies.splice(a, 1); continue; } if (grid.updateEnemy(enemy)) { // Clean up shadow if it's a flying enemy if (enemy.isFlying && enemy.shadow) { enemyLayerMiddle.removeChild(enemy.shadow); enemy.shadow = null; } // Remove enemy from the appropriate layer if (enemy.isFlying) { enemyLayerTop.removeChild(enemy); } else { enemyLayerBottom.removeChild(enemy); } enemies.splice(a, 1); lives = Math.max(0, lives - 1); updateUI(); if (lives <= 0) { LK.showGameOver(); } } } for (var i = bullets.length - 1; i >= 0; i--) { if (!bullets[i].parent) { if (bullets[i].targetEnemy) { var targetEnemy = bullets[i].targetEnemy; var bulletIndex = targetEnemy.bulletsTargetingThis.indexOf(bullets[i]); if (bulletIndex !== -1) { targetEnemy.bulletsTargetingThis.splice(bulletIndex, 1); } } bullets.splice(i, 1); } } if (towerPreview.visible) { towerPreview.checkPlacement(); } if (currentWave >= totalWaves && enemies.length === 0 && !waveInProgress) { LK.showYouWin(); } };
===================================================================
--- original.js
+++ change.js
@@ -699,78 +699,78 @@
});
break;
case GridItemType.PATH_CORNER_TOP_LEFT:
if (previousCell) {
- var dx = currentCell.x - previousCell.x;
- var dy = currentCell.y - previousCell.y;
- if (dx > 0) {
- // coming from left, go up
+ var entryDirectionX = currentCell.x - previousCell.x;
+ var entryDirectionY = currentCell.y - previousCell.y;
+ if (entryDirectionY === 1) {
+ // came from Top, exit Right
possibleCells.push({
- x: currentCell.x,
- y: currentCell.y - 1
+ x: currentCell.x + 1,
+ y: currentCell.y
});
- } else if (dy > 0) {
- // coming from top, go left
+ } else if (entryDirectionX === -1) {
+ // came from Right, exit Bottom
possibleCells.push({
- x: currentCell.x - 1,
- y: currentCell.y
+ x: currentCell.x,
+ y: currentCell.y + 1
});
}
}
break;
case GridItemType.PATH_CORNER_TOP_RIGHT:
if (previousCell) {
- var dx = currentCell.x - previousCell.x;
- var dy = currentCell.y - previousCell.y;
- if (dx < 0) {
- // coming from right, go up
+ var entryDirectionX = currentCell.x - previousCell.x;
+ var entryDirectionY = currentCell.y - previousCell.y;
+ if (entryDirectionY === 1) {
+ // came from Top, exit Left
possibleCells.push({
- x: currentCell.x,
- y: currentCell.y - 1
+ x: currentCell.x - 1,
+ y: currentCell.y
});
- } else if (dy > 0) {
- // coming from top, go right
+ } else if (entryDirectionX === 1) {
+ // came from Left, exit Bottom
possibleCells.push({
- x: currentCell.x + 1,
- y: currentCell.y
+ x: currentCell.x,
+ y: currentCell.y + 1
});
}
}
break;
case GridItemType.PATH_CORNER_BOTTOM_LEFT:
if (previousCell) {
- var dx = currentCell.x - previousCell.x;
- var dy = currentCell.y - previousCell.y;
- if (dx > 0) {
- // coming from left, go down
+ var entryDirectionX = currentCell.x - previousCell.x;
+ var entryDirectionY = currentCell.y - previousCell.y;
+ if (entryDirectionY === -1) {
+ // came from Bottom, exit Right
possibleCells.push({
- x: currentCell.x,
- y: currentCell.y + 1
+ x: currentCell.x + 1,
+ y: currentCell.y
});
- } else if (dy < 0) {
- // coming from bottom, go left
+ } else if (entryDirectionX === -1) {
+ // came from Right, exit Top
possibleCells.push({
- x: currentCell.x - 1,
- y: currentCell.y
+ x: currentCell.x,
+ y: currentCell.y - 1
});
}
}
break;
case GridItemType.PATH_CORNER_BOTTOM_RIGHT:
if (previousCell) {
- var dx = currentCell.x - previousCell.x;
- var dy = currentCell.y - previousCell.y;
- if (dx < 0) {
- // coming from right, go down
+ var entryDirectionX = currentCell.x - previousCell.x;
+ var entryDirectionY = currentCell.y - previousCell.y;
+ if (entryDirectionY === -1) {
+ // came from Bottom, exit Left
possibleCells.push({
- x: currentCell.x,
- y: currentCell.y + 1
+ x: currentCell.x - 1,
+ y: currentCell.y
});
- } else if (dy < 0) {
- // coming from bottom, go right
+ } else if (entryDirectionX === 1) {
+ // came from Left, exit Top
possibleCells.push({
- x: currentCell.x + 1,
- y: currentCell.y
+ x: currentCell.x,
+ y: currentCell.y - 1
});
}
}
break;
@@ -2955,8 +2955,11 @@
if (grid.allGroundPaths.length > 0) {
enemy.assignedPath = grid.allGroundPaths[grid.nextPathAssignmentIndex % grid.allGroundPaths.length];
grid.nextPathAssignmentIndex++;
enemy.currentWaypointIndex = 0;
+ // Set enemy position to center of first cell in assigned path
+ enemy.currentCellX = enemy.assignedPath[0].x + 0.5;
+ enemy.currentCellY = enemy.assignedPath[0].y + 0.5;
// Set initial target to first waypoint in path
if (enemy.assignedPath.length > 0) {
enemy.cellX = enemy.assignedPath[0].x;
enemy.cellY = enemy.assignedPath[0].y;
White circle with two eyes, seen from above.. In-Game asset. 2d. High contrast. No shadows
White simple circular enemy seen from above, black outline. Black eyes, with a single shield in-font of it. Black and white only. Blue background.
White circle with black outline. Blue background.. In-Game asset. 2d. High contrast. No shadows
A top-down orthographic view of a TD map. The focus is a single, continuous stone-paved path. This path is a long, serpentine line that twists and turns across the map in a strict grid pattern with sharp 90-degree angles. Crucially, the path never forks, branches, or intersects with itself; it is one unbroken line from start to finish. It enters at the top-center edge and exits at the bottom-center edge. The buildable areas next to the path are wide, flat, and empty grass. All decorative clutter, like mossy ruins and ancient trees, is kept exclusively on the outer perimeter of the map. Stylized and hand-painted. --no towers, no characters, no buildings, no crossroads, no forks. In-Game asset. 2d. High contrast. No shadows