User prompt
Objective: Transition the game's pathfinding system from A* to an explicit waypoint-following model, updating grid data, rendering, and entity movement accordingly. **Action Items:** 1. **Grid System Refactor** * Integrate explicit path types and the waypoint generation mechanism. * **1.1. `GridItemType` Enum Definition** * Declare `const GridItemType` at global scope with the provided values. * **1.2. `Grid` Class Constructor Modifications** * Update `mapLayout` array elements to use `GridItemType` enum values instead of raw numbers. * Remove `self.spawns` and `self.goals` array initializations. * Remove `cell.score`, `cell.pathId`, `cell.targets` property assignments. * Remove `cell.upLeft`, `cell.up`, `cell.upRight`, `cell.left`, `cell.right`, `cell.downLeft`, `cell.down`, `cell.downRight`, and `cell.neighbors` property assignments. * Remove instantiation of `DebugCell` within the `Grid` constructor. `DebugCell` instances will be managed and added by `Game`'s initialization if `debugLayer` is active. * Add a call to `self.waypointPath = self.generateWaypointPath();` at the end of the constructor. * **1.3. `Grid` Class Method Implementations** * Remove the entire `self.pathFind` method. * Add `self.findTile` method as per the provided pseudocode. It should take `tileType` as an argument and iterate over `self.cells`. * Add `self.findFirstStep` method as per the provided pseudocode. It should take `startPos` as an argument and iterate over `self.cells`. * Add `self.getNextWaypoint` method as per the provided pseudocode. It should take `currentPos`, `prevPos` as arguments and iterate over `self.cells`. * Add `self.generateWaypointPath` method (renamed from `buildWaypointPath` for consistency) as per the provided pseudocode. This method should internally call `self.findTile`, `self.findFirstStep`, and `self.getNextWaypoint`. * Modify `self.updateEnemy` method: * Retain only the goal check: `if (cell.type == GridItemType.GOAL)` return true. * Remove all enemy movement, rotation, and `currentTarget` logic. This responsibility shifts to `Enemy.update`. * Retain `enemy.isFlying` and `enemy.shadow` updates to ensure shadow synchronization. * Modify `self.renderDebug` method: * Loop through all cells and call `debugCell.render(cell)`. * Remove the hardcoded `j > 3 && j <= gridHeight - 4` condition for `debugCell` existence in `Grid` constructor, as `DebugCell` will now be created for all relevant cells. * `DebugCell` instances need to be created earlier in the `Grid` constructor for all cells where `mapLayout[j][i]` is not `GridItemType.EMPTY` or `GridItemType.TOWER_SLOT`. * `DebugCell` creation logic needs to be moved to the Grid constructor. 2. **`DebugCell` Class Refactor** * Update rendering logic to reflect new explicit path types. * **2.1. `DebugCell` Constructor Modifications** * Remove `numberLabel` instantiation and `self.addChild(numberLabel)`. * **2.2. `DebugCell.render` Method Modifications** * Remove `numberLabel.setText` and `numberLabel.visible` calls. * Remove `if (data.pathId != pathId)` and related logic. * Remove `tint` calculation based on `data.score` and `maxScore`. * Remove `towerInRangeHighlight` logic. * Replace the entire `switch (data.type)` block's `case 0: case 2:` section with logic that utilizes the `getArrowRotationsForCell` function. * Implement `getArrowRotationsForCell` function globally or within `DebugCell` scope using the provided pseudocode and `GridItemType` enum. * Adjust `tint` for each `GridItemType`: * `PATH_*`: Base color for path, arrows provide direction. * `SPAWN`: Unique tint (e.g., 0x00FF00 for green). * `GOAL`: Unique tint (e.g., 0xFF0000 for red). * `TOWER_SLOT`: Keep existing tint and `isOccupied` logic. * `EMPTY`: Set `cellGraphics.alpha = 0;` (transparent). * Ensure `self.removeArrows()` is called before adding new arrows. * The loop over `data.targets` and all related `debugArrows[a].rotation = angle;` logic must be removed. 3. **`Enemy` Class Refactor** * Implement waypoint-based movement. * **3.1. `Enemy` Class Property Changes** * Remove `self.cellX`, `self.cellY`, `self.currentCellX`, `self.currentCellY`, `self.currentTarget` properties. * Add `self.currentWaypointIndex = 0;`. * Add `self.waypointPath`. This will be assigned at spawn. * Add `self.pixelPosition = { x: 0, y: 0 };`. * **3.2. `Enemy` Constructor Modifications** * Remove assignment of `self.cellX`, `self.cellY`, `self.currentCellX`, `self.currentCellY`. * Initialize `self.waypointPath = grid.waypointPath;`. * Initialize `self.pixelPosition` using `convertGridToPixels(self.waypointPath[0])`. * Set `self.x = self.pixelPosition.x;` and `self.y = self.pixelPosition.y;`. * **3.3. `Enemy.update` Method Modifications** * Remove all previous movement logic including `if (!hasReachedEntryArea)` and `if (self.currentTarget)`. * Implement the waypoint following logic as provided in the prompt's `Enemy` class pseudocode: * Check if `self.currentWaypointIndex` is out of bounds. If so, indicate goal reached (e.g., by setting a flag or returning true). * Get `targetWaypoint` from `self.waypointPath`. * Calculate `targetPixelPosition` using `convertGridToPixels`. * Move `self.pixelPosition` towards `targetPixelPosition` based on `self.speed`. * Update `self.x = self.pixelPosition.x;` and `self.y = self.pixelPosition.y;`. * Implement snap-to-waypoint logic and increment `self.currentWaypointIndex`. * Re-implement the enemy graphic rotation logic from `Grid.updateEnemy` (the `tween` based rotation) here in `Enemy.update`, using `targetPixelPosition` for angle calculation. * Retain `healthBarOutline.y`, `healthBarBG.y`, `healthBar.y` updates. * Retain all `isImmune`, `slowed`, `poisoned` status management and tinting logic. * **3.4. Global Helper `convertGridToPixels`** * Define `function convertGridToPixels(gridPos)` globally, taking `gridPos` ({x, y}) and returning pixel coordinates, incorporating `CELL_SIZE` and `grid.x`, `grid.y` offsets. 4. **`Tower` Class Refactor** * Update target acquisition to use enemy waypoint progress. * **4.1. `Tower.findTarget` Method Modifications** * For ground enemies: * Change `closestScore` initialization to `-Infinity`. * Replace `if (cell && cell.pathId === pathId)` check with a simple `if (enemy.waypointPath)` check. * Prioritize enemies by their `enemy.currentWaypointIndex`. `closestScore` should be updated if `enemy.currentWaypointIndex` is *greater* than the current `closestScore`. * Retain flying enemy targeting logic (distance to goal from `flyingTarget`). 5. **Game State and Interaction Logic Refactor** * Remove obsolete A* related variables and calls. * **5.1. Global Variable Removals** * Remove `var pathId = 1;` and `var maxScore = 0;`. * **5.2. `game.update` Method Modifications** * Replace `if (grid.updateEnemy(enemy))` with `var reachedGoal = grid.updateEnemy(enemy);`. * The enemy removal logic within the loop should check `if (enemy.health <= 0 || reachedGoal)`. * **5.3. Tower Placement/Selling Logic Modifications** * In `placeTower` function, remove `grid.pathFind()` and `grid.renderDebug()` calls. * In `Tower.placeOnGrid`, remove `grid.pathFind()` and `grid.renderDebug()` calls. * In `Tower.upgrade`, remove `grid.pathFind()` and `grid.renderDebug()` calls. * In `UpgradeMenu.sellButton.down`, remove `grid.pathFind()` and `grid.renderDebug()` calls. * In `game.move` (for draggedTower), remove `grid.pathFind()` and `grid.renderDebug()` calls. * In `game.up` (for placing/moving towers), remove `grid.pathFind()` and `grid.renderDebug()` calls. * **5.4. Initial Game Setup** * Remove `grid.pathFind()` and `grid.renderDebug()` calls at game initialization. These are now handled within the `Grid` constructor. 6. **`TowerPreview` Class Refactor** * Adjust placement validation for the new path system. * **6.1. `TowerPreview.updatePlacementStatus` Method Modifications** * Remove all `enemy.currentTarget` checks. * The check `enemy.cellX >= self.gridX && enemy.cellX < self.gridX + 2 && enemy.cellY >= self.gridY && enemy.cellY < self.gridY + 2` for `blockedByEnemy` should remain but based on the enemy's `pixelPosition` converted to grid coordinates, not `enemy.cellX/Y` directly. Or simply use `enemy.x` and `enemy.y` and check intersection with tower preview bounding box in world coordinates. For simplicity, convert enemy's current pixel position to grid cell. * Ensure the `enemy.currentCellY < 4` check remains for initial spawn area.
Code edit (1 edits merged)
Please save this source code
User prompt
**Objective:** Refactor game's core enemy pathfinding system from a dynamic A* implementation to a static, explicit waypoint-following model based on pre-defined `GridItemType` data. **Action Items:** 1. **Grid Data Model & Path Generation** * Implement the `GridItemType` enum, mapping integer values to their descriptive names as provided in the "Grid Implementation & Migration Guide." * **1.1. Grid Class Constructor (`Grid.expand`)** * **Instruction:** Within the `Grid` class constructor, modify the `mapLayout` processing loop. * **Instruction:** Translate the integer values from the existing `mapLayout` (0, 1, 2, 3, 4) into their corresponding `GridItemType` enum values before assigning them to `cell.type`. Use `GridItemType.PATH_STRAIGHT_DOWN` for original `mapLayout` values of `0`. * **Instruction:** Remove initialization of `cell.upLeft`, `cell.up`, `cell.upRight`, `cell.left`, `cell.right`, `cell.downLeft`, `cell.down`, `cell.downRight`, and `cell.neighbors`. These are no longer required for pathfinding. * **Instruction:** Remove `cell.score`, `cell.pathId`, and `cell.targets` properties from `Grid` cell objects. * **Instruction:** Initialize a new `self.waypoints` array property on the `Grid` instance to store the generated path. * **1.2. Pathfinding Logic Replacement** * **Instruction:** Implement `buildWaypointPath(gridInstance)` as a method within the `Grid` class. This method will orchestrate the path generation. * **Instruction:** Implement `findTile(tileType)` as a method within the `Grid` class, operating on `self.cells`. * **Instruction:** Implement `findFirstStep(startPos)` as a method within the `Grid` class, operating on `self.cells`. * **Instruction:** Implement `getNextWaypoint(currentPos, prevPos)` as a method within the `Grid` class, operating on `self.cells`. * **Instruction:** In `Grid.pathFind`, remove all existing A* algorithm logic, including the `toProcess` queue, `processNode` function, and all related score and path ID assignments. * **Instruction:** In `Grid.pathFind`, invoke the new `self.buildWaypointPath()` method and assign its result to `self.waypoints`. * **Instruction:** Update the path validity checks in `Grid.pathFind` (`console.warn("Spawn blocked")`, `console.warn("Enemy blocked")`) to assess path completeness based on `self.waypoints` (e.g., if the path reaches a `GOAL` tile). * **Note:** The `Grid.pathFind` method is called when towers are placed or sold. Ensure that the new `buildWaypointPath` appropriately re-generates the path if the `TOWER_SLOT` occupancy changes. However, for an explicit path, tower placement on `TOWER_SLOT`s should not break the path. The check might only be relevant for initial map validation. 2. **Enemy Movement Refactor** * **2.1. Enemy Class (`Enemy.expand`)** * **Instruction:** Add `self.waypoints` and `self.targetWaypointIndex` properties to the `Enemy` instance. Initialize `self.targetWaypointIndex` to `1` (assuming waypoint `0` is the spawn cell itself). * **Instruction:** Remove `self.currentTarget` property. * **2.2. Grid Update Enemy (`Grid.updateEnemy`)** * **Instruction:** Remove all existing ground enemy pathfinding logic (e.g., `if (!enemy.currentTarget)`, `var ox = enemy.currentTarget.x - enemy.currentCellX`). * **Instruction:** Implement logic to retrieve the next target waypoint from `enemy.waypoints` using `enemy.targetWaypointIndex`. * **Instruction:** Calculate movement direction and update `enemy.currentCellX` and `enemy.currentCellY` towards the current target waypoint. * **Instruction:** Increment `enemy.targetWaypointIndex` when the enemy reaches the current target waypoint (within a small threshold). * **Instruction:** If `enemy.targetWaypointIndex` exceeds the bounds of `enemy.waypoints`, assume the enemy has reached the goal and return `true`. * **Instruction:** Maintain existing rotation logic for `enemy.children[0]` but ensure the `angle` is derived from the new target waypoint. * **Instruction:** Retain `enemy.isFlying` logic which independently moves flying enemies towards `enemy.flyingTarget` (the closest `GOAL` cell). 3. **Debug & Targeting Systems Alignment** * **3.1. Global Variables Cleanup** * **Instruction:** Remove global variables `pathId` and `maxScore`. * **3.2. DebugCell Class (`DebugCell.expand`)** * **Instruction:** In `DebugCell.render`, remove all branches and logic related to `data.score`, `data.pathId`, and `data.towersInRange`. * **Instruction:** Modify `DebugCell.render` to tint `cellGraphics` based solely on `data.type` (the new `GridItemType` enum values). * **Instruction:** Adjust `DebugCell.render` to visualize `self.cell.targets` if these are re-purposed to show the next waypoint for path cells, or remove `debugArrows` if no longer relevant. * **Instruction:** Remove `numberLabel.setText("")` from `DebugCell.render` after `switch` statement. * **3.3. Tower Targeting (`Tower.findTarget`)** * **Instruction:** For ground enemies (`!enemy.isFlying`), modify the target prioritization logic. Instead of using `cell.score`, prioritize enemies based on their `enemy.targetWaypointIndex`. A higher `targetWaypointIndex` indicates the enemy is further along the path and closer to the goal. * **Instruction:** Ensure flying enemy targeting logic remains independent of the waypoint path. * **3.4. Tower Range Display** * **Instruction:** In `Tower.refreshCellsInRange`, remove any logic that modifies `cell.towersInRange` for cells within range. The `towersInRange` property is no longer used for pathfinding. * **Instruction:** Update `Tower.prototype.placeOnGrid` to ensure `cell.isOccupied` is set correctly for `TOWER_SLOT` cells (as it currently does). * **3.5. `TowerPreview`** * **Instruction:** In `TowerPreview.updatePlacementStatus`, verify that the checks for `cell.type !== 4` (now `GridItemType.TOWER_SLOT`) and `cell.isOccupied === true` remain correct.
User prompt
Objective: Refactor enemy spawning, pathing, and debug visualization to align with explicit path-following, ensuring accurate movement and comprehensive visual feedback. **Action Items:** 1. **GRID_ITEM_TYPE Enum Alignment** * **Instruction:** Verify `GRID_ITEM_TYPE` enum members match the specified numerical values and names from the design guide in `Game Code` section. * **Note:** This ensures correct interpretation of map layout data. 2. **Grid Class (`Grid`)** * A core system component responsible for map data and path calculation. * **2.1. Constructor Initialization (`Grid`)** * **Instruction:** Remove the `self.spawns` and `self.goals` arrays. These are implicitly handled by `buildWaypointPath`. * **Instruction:** Modify the nested loop creating `self.cells[i][j]` objects. Ensure `cell.visualCell` (a `Container` with an attached 'cell' asset) is instantiated for *every* grid cell (`0` to `gridWidth-1` for `x`, `0` to `gridHeight-1` for `y`) during grid initialization. * **Instruction:** Set `cell.visualCell.x` to `i * CELL_SIZE` and `cell.visualCell.y` to `j * CELL_SIZE`. Add `cell.visualCell` to the `Grid` instance (`self.addChild(visualCell)`). * **Instruction:** Remove the conditional `if (j > 3 && j <= gridHeight - 4)` around `visualCell` creation, ensuring all cells have a visual representation. * **2.2. Waypoint Path Generation (`Grid.buildWaypointPath`)** * **Instruction:** Replace the existing `self.getNextWaypoint` function logic entirely with the one provided in the "Migration Guide: Step 3: Implement the Helper Functions - The Core Logic: `getNextWaypoint`" section. * **Note:** Pay close attention to the `entryDir` calculation and the precise conditional logic within the `switch (cellType)` for `PATH_STRAIGHT`, `PATH_CORNER`, and `PATH_CROSSROAD` types. The current implementation in Version 4 for corner detection is incorrect and must be replaced directly with the guide's logic. * **Instruction:** Ensure `self.waypoints` is cleared (`self.waypoints = [];`) at the start of `buildWaypointPath` to prevent accumulation from multiple calls. * **2.3. Debug Rendering (`Grid.renderDebug`)** * **Instruction:** Modify the primary rendering loop (`for (var i = 0; i < gridWidth; i++) { for (var j = 0; j < gridHeight; j++) { ... } }`) to iterate over *all* `self.cells[i][j]`, not just a visible subset. * **Instruction:** For each `cell.visualCell`, clear any existing arrow children by iterating `for (var c = visualCell.children.length - 1; c >= 0; c--)` and removing children identified by `child.isArrow` property. * **Instruction:** Update the `cellGraphics.tint` and `cellGraphics.alpha` properties within the `switch (cell.type)` block to correctly represent all `GRID_ITEM_TYPE`s: * `PATH_CROSSROAD`, `PATH_STRAIGHT_UP/DOWN/LEFT/RIGHT`, `PATH_CORNER_TOP/BOTTOM_LEFT/RIGHT`: `tint = 0x00FF00`, `alpha = 0.3`. * `SPAWN`: `tint = 0x00CC00`, `alpha = 0.5`. * `GOAL`: `tint = 0xFF0000`, `alpha = 0.5`. * `WALL`: `tint = 0xAAAAAA`, `alpha = 0`. * `TOWER_SLOT`: `tint = cell.isOccupied ? 0x0088CC : 0x00BFFF`, `alpha = 0.1`. * **Instruction:** Implement a new loop *after* the cell tinting logic to draw directional arrows: * Iterate from `w = 0` to `self.waypoints.length - 2` (stopping one before the last waypoint). * For each `waypoint = self.waypoints[w]` and `nextWaypoint = self.waypoints[w+1]`: * Retrieve `cell = self.getCell(waypoint.x, waypoint.y)`. * If `cell` and `cell.visualCell` exist: * Create a new 'arrow' asset, set `isArrow = true`, and attach it to `cell.visualCell`. * Calculate `dx = nextWaypoint.x - waypoint.x` and `dy = nextWaypoint.y - waypoint.y`. * Set `arrowGraphics.rotation = Math.atan2(dy, dx)`. * Set `arrowGraphics.alpha = 0.8` and `arrowGraphics.tint = 0x000000` (black for visibility). * **Instruction:** Additionally, after the `waypoints` loop, iterate through `self.waypoints` again. For each `waypoint`, if `cell.visualCell` exists, attach a small circle (e.g., `LK.init.shape('waypointDot', {width:10, height:10, color:0xFFFFFF, shape:'ellipse'})`) to `cell.visualCell` at its center, with `isWaypointDot = true`. Clear existing `isWaypointDot` elements at the beginning of `renderDebug`. * **Note:** This provides clear visual markers for each waypoint. * **2.4. Enemy Update Logic (`Grid.updateEnemy`)** * **Instruction:** Remove the `hasReachedEntryArea` check and its associated vertical movement logic. The enemy's initial position should be handled by its constructor (see Enemy Class). * **Instruction:** For ground enemies, modify the `dist < enemy.speed` check. If `dist` is less than `enemy.speed`, directly set `enemy.currentCellX = enemy.currentTarget.x` and `enemy.currentCellY = enemy.currentTarget.y` before incrementing `enemy.targetWaypointIndex`. This ensures enemies land precisely on waypoints. * **Instruction:** Adjust the goal collection condition: `if (enemy.targetWaypointIndex >= enemy.path.length)` (remove `-1`). This ensures enemies are marked as reached goal *after* processing the last waypoint, providing more accurate visual progression. 3. **Enemy Class (`Enemy`)** * Defines enemy properties and movement. * **3.1. Constructor Initialization (`Enemy`)** * **Instruction:** Initialize `self.currentCellY` with a vertical offset to create an entry animation: `self.currentCellY = self.path[0].y - (1 + Math.random() * 5);` * **Instruction:** Initialize `self.currentCellX` to `self.path[0].x`. * **Instruction:** Adjust `self.x` and `self.y` in the constructor to use `self.currentCellX` and `self.currentCellY` for their initial pixel positions, maintaining consistency with the offset. `self.x = grid.x + self.currentCellX * CELL_SIZE + CELL_SIZE / 2;` `self.y = grid.y + self.currentCellY * CELL_SIZE + CELL_SIZE / 2;` * **3.2. Update Method (`Enemy.update`)** * **Instruction:** Remove any `currentTarget` rotation logic from `Enemy.update`. Enemy rotation should now be handled in `Grid.updateEnemy` for both flying and ground enemies when calculating movement direction. * **Note:** This centralizes enemy rotation updates based on their movement vectors. 4. **Game Update Loop (`game.update`)** * **4.1. Enemy Spawning Logic** * **Instruction:** In the `game.update` loop, within the `if (!waveSpawned)` block, remove the lines that re-initialize `enemy.currentCellX` and `enemy.currentCellY` after the `Enemy` instance is created: `enemy.currentCellX = spawnPoint.x;` `enemy.currentCellY = spawnPoint.y;` * **Note:** The `Enemy` constructor now handles the initial spawn point and offset correctly, ensuring the entry animation works. * **Instruction:** Verify that `enemyCount` logic is correctly providing the desired number of enemies per wave. The current logic `var enemyCount = waveIndicator.getEnemyCount(currentWave);` and its override for boss waves (`enemyCount = 1;`) are the only places `enemyCount` is set. The problem of "only 1 enemy spawning" implies `currentWave` is interpreted as a boss wave. No code changes for `enemyCount` are required based on provided logic. * **4.2. Life Deduction** * **Instruction:** Confirm that the line `lives = Math.max(0, lives - 1);` remains unchanged. The current code correctly subtracts 1 life per enemy reaching the goal. 5. **Tower Placement & Selling (`Tower.placeOnGrid`, `UpgradeMenu.sellButton.down`)** * **Instruction:** Remove calls to `grid.pathFind()` from `Tower.placeOnGrid` and `UpgradeMenu.sellButton.down`. Pathfinding is now static and performed only once at game initialization. * **Note:** `grid.renderDebug()` calls should remain to update visual highlights. 6. **Tower Preview (`TowerPreview.updatePlacementStatus`)** * **Instruction:** Update the placement check in `TowerPreview.updatePlacementStatus` to specifically check `cell.type !== GRID_ITEM_TYPE.TOWER_SLOT` instead of `cell.type !== 4`. This ensures consistency with the new enum. 7. **Initial Grid Setup (`Game Code` section)** * **Instruction:** Remove the `grid.pathFind();` call. `grid.buildWaypointPath();` already performs the necessary initialization. These actions will address the pathing errors, correct the debug visualizations, and refine enemy spawning behavior.
User prompt
Objective: Correct path-following logic, enemy spawning, goal detection, and re-implement path visualization. **Action Items:** 1. **Grid Item Type Synchronization** * Ensure `GRID_ITEM_TYPE` enum accurately reflects the provided documentation for all path, spawn, goal, and special tile values. * **1.1. Constants Definition** * **Instruction:** Verify `GRID_ITEM_TYPE` object defines the following mappings: * `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` 2. **Grid Pathing Logic (`Grid` Class)** * Refine waypoint generation and traversal to accurately follow explicit path types, especially corners. * **2.1. `Grid.findFirstStep` Method Refinement** * **Instruction:** Update the `findFirstStep(startPos)` method. The condition `cell.type >= GRID_ITEM_TYPE.PATH_CROSSROAD && cell.type <= 8` is currently too broad. * **Instruction:** Change the condition to specifically check for `cell.type >= GRID_ITEM_TYPE.PATH_CROSSROAD && cell.type <= GRID_ITEM_TYPE.PATH_CORNER_BOTTOM_RIGHT`. This ensures only valid path tiles are considered as a first step. * **Note:** This method will return the first valid path tile adjacent to the *single* `SPAWN` point identified by `findTile()`. The current setup generates one primary path. If multiple independent paths from different spawn points are intended, further architectural changes would be required. * **2.2. `Grid.getNextWaypoint` Method Re-implementation** * **Instruction:** Overhaul the `getNextWaypoint(currentPos, prevPos)` method to precisely match the logic provided in the "Migration Guide: Step 3: The Core Logic: `getNextWaypoint`" section. * **Instruction:** Calculate `entryDir` as `{ x: currentPos.x - prevPos.x, y: currentPos.y - prevPos.y }`. * **Instruction:** Implement the `switch (cellType)` block to return the exact next `(x, y)` coordinates based on `cellType` and `entryDir.x`/`entryDir.y` for all `PATH_STRAIGHT`, `PATH_CORNER`, and `PATH_CROSSROAD` types. Do not use the `directions` array and `entryDir` index-based calculations for `nextX`, `nextY` within the `switch` statement for corners; instead, directly compute `nextX = currentPos.x + entryDir.x_for_exit` and `nextY = currentPos.y + entryDir.y_for_exit`. * **Example (Conceptual for `PATH_CORNER_TOP_LEFT`):** ```javascript case GRID_ITEM_TYPE.PATH_CORNER_TOP_LEFT: // ┌, connects Bottom and Right if (entryDir.y === -1) { return { x: currentPos.x + 1, y: currentPos.y }; } // Entered from Bottom, exit Right if (entryDir.x === -1) { return { x: currentPos.x, y: currentPos.y + 1 }; } // Entered from Right, exit Bottom break; // ... similar precise logic for other corner types ... case GRID_ITEM_TYPE.PATH_CROSSROAD: return { x: currentPos.x + entryDir.x, y: currentPos.y + entryDir.y }; // Continues straight ``` * **Note:** The current `getNextWaypoint` in version 3 incorrectly infers the exit direction from `entryDir` as if path segments were always connected to `prevPos` + `directions[i]` for the next step, rather than interpreting the specific corner type. 3. **Enemy Movement (`Enemy` Class)** * Ensure enemies initiate movement correctly from the spawn point and accurately detect goal arrival. * **3.1. Initial Spawn Position** * **Instruction:** In the `Enemy` constructor, remove the vertical offset from `currentCellY` initialization. * **Instruction:** Set `self.currentCellY` and `self.y` directly based on the *first waypoint* (which is the spawn point), ensuring enemies start precisely on the grid cell. * **Instruction:** Remove the entire "Check if the enemy has reached the entry area" and "If enemy hasn't reached the entry area yet" conditional block within `Grid.updateEnemy(enemy)`. This initial entry animation logic is obsolete with pre-calculated paths. * **Instruction:** In `game.update`, when spawning new enemies, set `enemy.currentCellY` directly to `spawnPoint.y` (the y-coordinate of the first waypoint in `grid.waypoints`). Remove the `-(1 + Math.random() * 5)` offset. * **3.2. Goal Detection** * **Instruction:** In `Grid.updateEnemy(enemy)`, modify the condition for reaching the goal: `if (enemy.targetWaypointIndex >= enemy.path.length)`. * **Instruction:** Change this to `if (enemy.targetWaypointIndex >= enemy.path.length - 1)`. This signifies the enemy has reached or passed the *last* waypoint, which corresponds to the `GOAL` tile. 4. **Debug Visualization (`Grid` Class and Global Scope)** * Re-introduce visual arrows to depict the calculated path. * **4.1. Re-introduce `DebugCell` if desired, or integrate into `Grid.renderDebug`** * **Instruction:** Since `DebugCell` was removed, we will re-integrate arrow drawing directly into `Grid.renderDebug`. * **Instruction:** Modify `Grid.renderDebug()` to iterate through `self.waypoints`. For each pair of consecutive waypoints, calculate the direction vector, angle, and draw an `arrow` asset in the `visualCell` representing the first waypoint of the pair. * **Instruction:** For each cell in the grid that is part of the `self.waypoints` array, create/update its `visualCell` container. * **Instruction:** For each `visualCell` corresponding to a waypoint, clear any existing arrows and then add a new `arrow` asset. * **Instruction:** Position the `arrow` asset at the center of the `visualCell` and rotate it to point from the current waypoint towards the next waypoint in `self.waypoints`. * **Instruction:** Adjust `cellGraphics.alpha` values for path tiles (including corners) to be more visible (e.g., `0.3` or `0.5`) to allow arrows to overlay them. * **4.2. Update `Tower.findTarget` Priority** * **Instruction:** The `Tower.findTarget` method correctly uses `enemy.targetWaypointIndex` for prioritizing ground enemies. Ensure `closestScore` is initialized to a sufficiently low value (e.g., `-Infinity`) if higher `targetWaypointIndex` means "closer to goal". * **Instruction:** The current logic `var priority = enemy.targetWaypointIndex * 1000; priority -= distToTarget; if (priority > closestScore)` correctly prioritizes higher `targetWaypointIndex` first, then uses `distToTarget` as a tie-breaker (subtracting `distToTarget` means smaller `distToTarget` gives higher `priority`). This logic is acceptable.
User prompt
Objective: Refactor the grid and enemy movement systems to correctly implement the explicit waypoint path-following framework, addressing current pathing and rendering discrepancies. Action Items: 1. **Grid System Core Logic Update** * Implement the explicit path-following mechanism as per the provided specification. * **1.1. `GRID_ITEM_TYPE` Definition** * **Instruction:** Update the global `GRID_ITEM_TYPE` object to include all specified enum values (0-12) with their corresponding integer values. * **Instruction:** Ensure `PATH_CROSSROAD` is 0, `PATH_STRAIGHT_UP` is 1, `PATH_STRAIGHT_DOWN` is 2, `PATH_STRAIGHT_LEFT` is 3, `PATH_STRAIGHT_RIGHT` is 4, `PATH_CORNER_TOP_LEFT` is 5, `PATH_CORNER_TOP_RIGHT` is 6, `PATH_CORNER_BOTTOM_LEFT` is 7, `PATH_CORNER_BOTTOM_RIGHT` is 8, `WALL` is 9, `SPAWN` is 10, `GOAL` is 11, and `TOWER_SLOT` is 12. * **1.2. `Grid` Class Constructor (`Container.expand(function (gridWidth, gridHeight)`)** * **Instruction:** Remove `self.spawns` and `self.goals` arrays. These are no longer needed for path tracking. `self.flyingGoal` is retained for flying enemies. * **Instruction:** Initialize `cell.type` directly from `mapLayout[j][i]` using the updated `GRID_ITEM_TYPE` values for all conditions (e.g., `cellType === GRID_ITEM_TYPE.SPAWN`). * **Instruction:** Remove `cell.score`, `cell.pathId`, `cell.upLeft`, `cell.up`, `cell.upRight`, `cell.left`, `cell.right`, `cell.downLeft`, `cell.down`, `cell.downRight`, `cell.neighbors`, and `cell.targets` properties from `self.cells[i][j]` initialization. These are artifacts of the previous A* system. * **Instruction:** Remove all `DebugCell` instantiation and related logic within the `Grid` constructor. Debug rendering will be handled directly by `Grid.renderDebug`. * **1.3. `Grid.findTile` Method** * **Instruction:** No changes required; this method is correctly implemented for its purpose. * **1.4. `Grid.findFirstStep` Method** * **Instruction:** No changes required; this method is correctly implemented for its purpose. * **1.5. `Grid.getNextWaypoint` Method** * **Instruction:** Completely rewrite the internal logic of this method to strictly adhere to the `getNextWaypoint` pseudocode provided in the framework guide. * **Instruction:** Calculate `entryDir` based on `currentPos` and `prevPos`. * **Instruction:** Implement a `switch` statement on `cellType` (from `grid[y][x]`) to determine the next position based on `entryDir` for `PATH_CROSSROAD`, all `PATH_STRAIGHT_*`, and all `PATH_CORNER_*` types. * **Note:** This is the most critical fix for path following and corner handling. * **1.6. `Grid.buildWaypointPath` Method** * **Instruction:** No changes required to the overall flow; it correctly uses `findTile`, `findFirstStep`, and the (now corrected) `getNextWaypoint`. * **Instruction:** Retain `self.flyingGoal = self.findTile(GRID_ITEM_TYPE.GOAL);` as it's needed for flying enemy targeting. * **1.7. `Grid.pathFind` Method** * **Instruction:** Simplify `self.pathFind` to exclusively call `self.buildWaypointPath()`. * **Instruction:** Remove all remaining path validation loops and console warnings related to "Spawn blocked" or "Enemy blocked". The new system implicitly validates the path during generation; a broken path will result in `getNextWaypoint` returning `null` during `buildWaypointPath`. * **Instruction:** Remove `pathId` and `maxScore` variable declarations from the global scope, as well as `pathId += 1;` increments. These are deprecated. * **1.8. `Grid.renderDebug` Method** * **Instruction:** Remove all references to `debugCell` and the `DebugCell` class. * **Instruction:** Iterate through `self.cells` directly. For each cell within the visible range (`j` from 4 to `gridHeight - 4`), ensure a graphical `Container` (e.g., using `cellGraphics = debugCell.attachAsset('cell', { ... });`) is created and added to `self` if `cell.debugCell` (now `cell.visualCell`) does not exist. Store this graphical object in `cell.visualCell`. * **Instruction:** Update the `cellGraphics.tint` and `cellGraphics.alpha` based on the *new* `GRID_ITEM_TYPE` for each `cell.type`. * `PATH_CROSSROAD` (0), `PATH_STRAIGHT_*` (1-4), `PATH_CORNER_*` (5-8): Use a distinct path color (e.g., `0x00FF00` or a light yellow/beige as shown in user's image) with `alpha = 0.1`. * `WALL` (9): `tint = 0xaaaaaa`, `alpha = 0`. * `SPAWN` (10): Use a distinct color (e.g., `0x00CC00`) with `alpha = 0.5`. * `GOAL` (11): Use a distinct color (e.g., `0xFF0000`) with `alpha = 0.5`. * `TOWER_SLOT` (12): Tint based on `cell.isOccupied` (`0x0088CC` if occupied, `0x00BFFF` if not) with `alpha = 0.1`. * **Instruction:** Remove the `if (selectedTower && cell.towersInRange ...)` highlighting logic from `renderDebug`. Tower range is visualized by a separate range circle. 2. **Enemy Movement Refactor** * Ensure enemies accurately follow the pre-calculated waypoint path. * **2.1. `Enemy` Class Constructor (`Container.expand(function (type)`)** * **Instruction:** After `self.health = self.maxHealth;`, set `self.path = grid.waypoints;` and `self.targetWaypointIndex = 1;`. * **Instruction:** Initialize enemy position: `self.x = grid.x + self.path[0].x * CELL_SIZE + CELL_SIZE / 2;` and `self.y = grid.y + self.path[0].y * CELL_SIZE + CELL_SIZE / 2;`. * **Instruction:** Initialize `self.currentCellX = self.path[0].x;` and `self.currentCellY = self.path[0].y;`. * **Instruction:** Remove `self.cellX = 0;`, `self.cellY = 0;`, and `self.currentTarget = undefined;` as properties that are explicitly set to default values. * **2.2. `Enemy.update` Method** * **Instruction:** Remove the entire "entry area" movement logic (`if (!hasReachedEntryArea) { ... }`) for all enemy types. Enemies should now start precisely at the spawn waypoint. * **Instruction:** In the `if (enemy.isFlying)` block, simplify `enemy.flyingTarget` assignment to `enemy.flyingTarget = grid.flyingGoal;`. Remove the loop that finds the closest goal, as there should only be one designated `GOAL` for flying enemies. * **Instruction:** In the "Handle ground enemies with waypoint following" block, update `enemy.currentTarget` to `enemy.path[enemy.targetWaypointIndex]`. * **Instruction:** Ensure `enemy.currentCellX` and `enemy.currentCellY` are updated based on movement towards `enemy.currentTarget`. * **Instruction:** Update `enemy.cellX` and `enemy.cellY` to `Math.round(enemy.currentCellX)` and `Math.round(enemy.currentCellY)` after movement to keep them aligned with grid cells. * **Instruction:** Ensure the `enemyGraphics.rotation` logic (for `angle` and `tween`) is applied for both flying and ground enemies, based on their movement direction towards their respective `targetPosition` or `currentTarget`. 3. **Tower Targeting and Placement Logic Update** * Adjust tower logic to align with the new grid system. * **3.1. `Tower.findTarget` Method** * **Instruction:** In the `else` block (for ground enemies), replace all logic relying on `cell.score` and `cell.pathId` with prioritization based on `enemy.targetWaypointIndex`. * **Instruction:** Prioritize ground enemies that have a *higher* `enemy.targetWaypointIndex` (meaning they are further along the path). As a tie-breaker, prioritize enemies closer to their *current* target waypoint. * **3.2. `Tower.placeOnGrid` Method** * **Instruction:** Remove the `grid.pathFind();` call. Pathfinding is now pre-calculated and static. * **3.3. `UpgradeMenu.sellButton.down` Method** * **Instruction:** Remove the `grid.pathFind();` call. Pathfinding is now pre-calculated and static. 4. **Game Initialization Clean-up** * Streamline main game initialization to reflect the new system. * **4.1. Global Variables** * **Instruction:** Remove `pathId` and `maxScore` global variables. * **4.2. `grid` Initialization** * **Instruction:** In the main game code, replace the call `grid.pathFind();` with `grid.buildWaypointPath();` to generate the waypoints once at game start.
Code edit (1 edits merged)
Please save this source code
User prompt
Please fix the bug: 'Cannot read properties of undefined (reading 'json')' in or related to this line: 'LK.init.json('Grid_Layout_1', [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 1, 1, 1], [1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1], [1, 1, 1, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 1, 1, 1], [1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 4, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 4, 4, 0, 0, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 4, 4, 0, 0, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 4, 4, 0, 0, 4, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]);' Line Number: 2181
User prompt
Objective: Transition the game's pathfinding system from A* to an explicit waypoint-based path-following model utilizing predefined grid layouts. Action Items: 1. **Grid Data & Constants Setup** * Introduce `GridItemType` enum constants for clarity and type safety. * **1.1. Asset Initialization** * **Instruction:** Add a `LK.init.json` declaration for the new grid layout data. Use `Grid_Layout_1` as the asset ID. The JSON content will be the provided `mapLayout` array. * **1.2. Global Constants** * **Instruction:** Define a `GRID_ITEM_TYPE` constant object mapping integer values (0-12) to descriptive string names (e.g., `PATH_CROSSROAD`, `WALL`, `SPAWN`, `GOAL`, `TOWER_SLOT`). * **1.3. `Grid` Constructor Refactor** * **Instruction:** Modify the `Grid` class constructor to load the grid data using `LK.json('Grid_Layout_1')`. * **Instruction:** For each cell in the grid, assign its `type` property based on the loaded `Grid_Layout_1` value, mapping it to the appropriate `GRID_ITEM_TYPE`. * **Instruction:** Populate `self.spawns` and `self.goals` arrays by iterating the loaded `mapLayout` and identifying cells with `GRID_ITEM_TYPE.SPAWN` and `GRID_ITEM_TYPE.GOAL` respectively. * **Instruction:** Remove the hardcoded `mapLayout` array. * **Instruction:** Remove the assignment of diagonal and cardinal neighbors (`upLeft`, `up`, `upRight`, `left`, `right`, `downLeft`, `down`, `downRight`, `neighbors`). These are obsolete. * **Instruction:** Remove the instantiation of `DebugCell` and assignment to `cell.debugCell`. This class is being deprecated. * **Instruction:** Initialize `self.waypoints = [];` and `self.flyingGoal = null;` within the `Grid` constructor. 2. **Path Generation & Deprecations** * Implement the explicit path-following logic. * **2.1. `Grid.findTile` Method** * **Instruction:** Add a private helper method `self.findTile(tileType)` to the `Grid` class that iterates through `self.cells` to find and return the first `{x, y}` coordinate matching `tileType`. Return `null` if not found. * **2.2. `Grid.findFirstStep` Method** * **Instruction:** Add a private helper method `self.findFirstStep(startPos)` to the `Grid` class that, given a `startPos`, checks its cardinal neighbors and returns the `{x, y}` coordinate of the first valid path tile (types 0-8). Return `null` if no path tile is found. * **2.3. `Grid.getNextWaypoint` Method** * **Instruction:** Add a private helper method `self.getNextWaypoint(currentPos, prevPos)` to the `Grid` class that implements the core logic for determining the next waypoint based on `currentPos`'s `GridItemType` and the `entryDir` derived from `prevPos`. Return `{x, y}` for the next waypoint or `null` if the path is broken. * **2.4. `Grid.buildWaypointPath` Method** * **Instruction:** Implement `self.buildWaypointPath()` within the `Grid` class. This method will: * Call `self.findTile` to locate the `GRID_ITEM_TYPE.SPAWN` point. * Initialize `self.waypoints` with the spawn point. * Call `self.findFirstStep` to get the initial path segment from the spawn. * Loop, calling `self.getNextWaypoint` to trace the path until `GRID_ITEM_TYPE.GOAL` is reached. * Include a `MAX_PATH_LENGTH` safety break to prevent infinite loops. * Assign the resulting ordered list of waypoints to `self.waypoints`. * Assign the `GRID_ITEM_TYPE.GOAL` coordinates to `self.flyingGoal`. * **2.5. `Grid.pathFind` Method Refactor** * **Instruction:** Remove all A*-specific pathfinding logic (score calculation, `toProcess` queue, `processNode`, `pathId`, `maxScore`) from `Grid.pathFind`. * **Instruction:** Update `Grid.pathFind` to execute `self.buildWaypointPath()` instead of the A* algorithm. * **Instruction:** Remove the path blockage checks (`console.warn("Spawn blocked")`, `console.warn("Enemy blocked")`) from `Grid.pathFind`. Path validity is handled during `buildWaypointPath`. * **2.6. Global Variable Clean-up** * **Instruction:** Remove the global variables `pathId` and `maxScore`. 3. **Enemy Movement Adaptation** * Modify enemy movement to follow the new waypoint path. * **3.1. `Enemy` Class Constructor** * **Instruction:** Add `self.path = null;` and `self.targetWaypointIndex = 0;` to the `Enemy` constructor. * **3.2. `Grid.updateEnemy` Method Refactor** * **Instruction:** Remove enemy rotation logic from `Grid.updateEnemy`. This will be handled in `Enemy.update`. * **Instruction:** For ground enemies (`!enemy.isFlying`), refactor the movement logic: * If `enemy.targetWaypointIndex` is beyond `enemy.path.length - 1`, return `true` (reached goal). * Set `enemy.currentTarget` to `enemy.path[enemy.targetWaypointIndex]`. * Move `enemy.currentCellX` and `enemy.currentCellY` towards `enemy.currentTarget`. * If the enemy is sufficiently close to `enemy.currentTarget` (e.g., distance < `enemy.speed`), increment `enemy.targetWaypointIndex` and update `enemy.cellX`, `enemy.cellY` to `enemy.currentTarget`'s integer coordinates. * **Instruction:** For flying enemies (`enemy.isFlying`), refactor the movement logic: * Set `enemy.flyingTarget` to `grid.flyingGoal`. * Move `enemy.currentCellX` and `enemy.currentCellY` directly towards `enemy.flyingTarget`. * If the enemy is sufficiently close to `enemy.flyingTarget`, return `true` (reached goal). * **Instruction:** Remove all checks related to `cell.score` and `cell.targets` within `Grid.updateEnemy`. * **Instruction:** Ensure `enemy.currentCellY >= 4` (entry animation complete) is still handled before applying pathing logic for ground enemies, and `enemy.path` is initialized. * **3.3. `Enemy.update` Method Refactor** * **Instruction:** Remove `if (self.currentTarget)` block related to `enemyGraphics.targetRotation` and `tween` for rotation. This responsibility now falls to `Grid.updateEnemy` for enemy movement and orientation. (Self-correction: As per prior thought, the rotation should remain in `Enemy.update` for enemies themselves, based on `self.currentTarget`, which is *now* the next waypoint). * **Instruction:** Ensure the `enemyGraphics.targetRotation` and `tween` logic in `Enemy.update` correctly rotates the enemy towards `self.currentTarget` (which will be populated by `Grid.updateEnemy` as the next waypoint). 4. **Tower Targeting Adaptation** * Modify tower targeting to work with the new path data. * **4.1. `Tower.findTarget` Method Refactor** * **Instruction:** For ground enemies (`!enemy.isFlying`): * Replace `cell.score < closestScore` with a prioritization based on path progression. Prioritize enemies further along the path. A higher `enemy.targetWaypointIndex` indicates further progress. If indices are equal, then use distance to the current target waypoint. * **Instruction:** For flying enemies (`enemy.isFlying`): * Retain existing logic prioritizing by distance to `enemy.flyingTarget`. 5. **Cleanup & Final Validation** * Remove unused code and ensure integrity. * **5.1. `DebugCell` Removal** * **Instruction:** Delete the entire `DebugCell` class definition. * **Instruction:** Remove all references to `DebugCell` (e.g., in `Grid` constructor, `grid.renderDebug`). * **5.2. `Grid.renderDebug` Method Refactor** * **Instruction:** Update `Grid.renderDebug` to remove any rendering logic related to `score`, `pathId`, `targets`, or `debugArrows`. It should only render cells based on `cell.type` (e.g., `WALL`, `TOWER_SLOT`) and `cell.isOccupied`, and highlight `cell.towersInRange`. * **5.3. `Bullet` Class Review** * **Instruction:** In `Bullet.update`, ensure that when `self.targetEnemy.health <= 0`, `self.targetEnemy.healthBar.width` is set to `0` and no further health bar updates occur for that enemy. * **Instruction:** In `Bullet.update` and `game.update` loop for bullets, ensure bullets correctly remove themselves from `targetEnemy.bulletsTargetingThis` when they are destroyed or their target dies. * **5.4. `game.update` Initialisation** * **Instruction:** Call `grid.buildWaypointPath()` directly after the `grid` instantiation. * **Instruction:** Remove any calls to `grid.pathFind()` from `game.update` or any other update loops where it was called per frame or event. It should only be called once at initialization and upon tower placement/removal. * **5.5. `SourceTower` Placement** * **Instruction:** Update the `sourceTowers` loop at the end of the script to ensure `tower.y` is appropriate given potential UI layout changes or to be consistent. Current `towerY` looks fine.
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.
/**** * 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 debugArrows = []; self.update = function () {}; self.down = function () { return; if (self.cell.type == 0 || self.cell.type == 1) { self.cell.type = self.cell.type == 1 ? 0 : 1; if (grid.pathFind()) { self.cell.type = self.cell.type == 1 ? 0 : 1; grid.pathFind(); var notification = game.addChild(new Notification("Path is blocked!")); notification.x = 2048 / 2; notification.y = grid.height - 50; } grid.renderDebug(); } }; self.removeArrows = function () { while (debugArrows.length) { self.removeChild(debugArrows.pop()); } }; self.render = function (data) { self.removeArrows(); switch (data.type) { case GridItemType.PATH_HORIZONTAL: case GridItemType.PATH_VERTICAL: case GridItemType.PATH_TURN_NE: case GridItemType.PATH_TURN_NW: case GridItemType.PATH_TURN_SE: case GridItemType.PATH_TURN_SW: case GridItemType.PATH_JUNCTION: { var towerInRangeHighlight = false; if (selectedTower && data.towersInRange && data.towersInRange.indexOf(selectedTower) !== -1) { towerInRangeHighlight = true; cellGraphics.tint = 0x0088ff; } else { cellGraphics.tint = 0x888888; // Base path color } cellGraphics.alpha = 0.1; // Add arrows based on path type var rotations = getArrowRotationsForCell(data, grid); for (var a = 0; a < rotations.length; a++) { var arrow = LK.getAsset('arrow', { anchorX: -.5, anchorY: 0.5 }); arrow.alpha = .5; arrow.rotation = rotations[a]; self.addChildAt(arrow, 1); debugArrows.push(arrow); } break; } case GridItemType.EMPTY: { cellGraphics.tint = 0xaaaaaa; cellGraphics.alpha = 0; break; } case GridItemType.SPAWN: { cellGraphics.tint = 0x00FF00; // Green for spawn cellGraphics.alpha = 0.1; break; } case GridItemType.GOAL: { cellGraphics.tint = 0xFF0000; // Red for goal cellGraphics.alpha = 0.1; break; } case GridItemType.TOWER_SLOT: { cellGraphics.tint = data.isOccupied ? 0x0088CC : 0x00BFFF; 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.currentWaypointIndex = 0; self.waypointPath = []; self.pixelPosition = { x: 0, y: 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; // Initialize waypoint path and position self.waypointPath = grid.waypointPath; if (self.waypointPath.length > 0) { self.pixelPosition = convertGridToPixels(self.waypointPath[0]); self.x = self.pixelPosition.x; self.y = self.pixelPosition.y; } // 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; } // Waypoint-based movement if (self.currentWaypointIndex >= self.waypointPath.length) { // Reached the end of the path (goal) return; } var targetWaypoint = self.waypointPath[self.currentWaypointIndex]; var targetPixelPosition = convertGridToPixels(targetWaypoint); // Calculate direction to target var dx = targetPixelPosition.x - self.pixelPosition.x; var dy = targetPixelPosition.y - self.pixelPosition.y; var distance = Math.sqrt(dx * dx + dy * dy); // Move towards target if (distance > self.speed) { var moveX = dx / distance * self.speed; var moveY = dy / distance * self.speed; self.pixelPosition.x += moveX; self.pixelPosition.y += moveY; } else { // Snap to waypoint and move to next one self.pixelPosition.x = targetPixelPosition.x; self.pixelPosition.y = targetPixelPosition.y; self.currentWaypointIndex++; } // Update display position self.x = self.pixelPosition.x; self.y = self.pixelPosition.y; // Rotate enemy to face movement direction if (dx !== 0 || dy !== 0) { var angle = Math.atan2(dy, dx); if (enemyGraphics.targetRotation === undefined) { enemyGraphics.targetRotation = angle; enemyGraphics.rotation = angle; } else { if (Math.abs(angle - enemyGraphics.targetRotation) > 0.05) { tween.stop(enemyGraphics, { rotation: true }); // Calculate the shortest angle to rotate var currentRotation = enemyGraphics.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; } enemyGraphics.targetRotation = angle; tween(enemyGraphics, { rotation: currentRotation + angleDiff }, { duration: 250, easing: tween.easeOut }); } } } 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 = []; 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 using GridItemType enum: EMPTY: 1 (Wall/impassable) SPAWN: 2 (Enemy spawn points) GOAL: 3 (Enemy goal points) TOWER_SLOT: 4 (Buildable tower locations) PATH_*: Various path types for waypoint following */ // Predefined map layout using GridItemType enum var mapLayout = [[GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.SPAWN, GridItemType.SPAWN, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_VERTICAL, GridItemType.PATH_VERTICAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_VERTICAL, GridItemType.PATH_VERTICAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_VERTICAL, GridItemType.PATH_VERTICAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.GOAL, GridItemType.GOAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY]]; 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 = GridItemType.EMPTY; // Default to empty/wall if (j < mapLayout.length && i < mapLayout[j].length) { cellType = mapLayout[j][i]; } cell.type = cellType; cell.x = i; cell.y = j; // Create debug cells for visible gameplay area if (j > 3 && j <= gridHeight - 4 && cellType !== GridItemType.EMPTY) { var debugCell = new DebugCell(); self.addChild(debugCell); debugCell.cell = cell; debugCell.x = i * CELL_SIZE; debugCell.y = j * CELL_SIZE; cell.debugCell = debugCell; } } } // Generate waypoint path after cells are created self.waypointPath = self.generateWaypointPath(); self.getCell = function (x, y) { return self.cells[x] && self.cells[x][y]; }; self.findTile = function (tileType) { for (var i = 0; i < self.cells.length; i++) { for (var j = 0; j < self.cells[i].length; j++) { if (self.cells[i][j].type === tileType) { return { x: i, y: j }; } } } return null; }; self.findFirstStep = function (startPos) { // Find the first walkable tile after spawn for (var i = 0; i < self.cells.length; i++) { for (var j = 0; j < self.cells[i].length; j++) { var cell = self.cells[i][j]; if (cell.type === GridItemType.PATH_VERTICAL || cell.type === GridItemType.PATH_HORIZONTAL || cell.type === GridItemType.PATH_TURN_NE || cell.type === GridItemType.PATH_TURN_NW || cell.type === GridItemType.PATH_TURN_SE || cell.type === GridItemType.PATH_TURN_SW || cell.type === GridItemType.PATH_JUNCTION) { return { x: i, y: j }; } } } return null; }; self.getNextWaypoint = function (currentPos, prevPos) { var currentCell = self.getCell(currentPos.x, currentPos.y); if (!currentCell) return null; // Simple pathfinding along the predefined path var nextX = currentPos.x; var nextY = currentPos.y; if (currentCell.type === GridItemType.PATH_HORIZONTAL) { nextX += 1; // Move right } else if (currentCell.type === GridItemType.PATH_VERTICAL) { nextY += 1; // Move down } var nextCell = self.getCell(nextX, nextY); if (nextCell && (nextCell.type === GridItemType.PATH_HORIZONTAL || nextCell.type === GridItemType.PATH_VERTICAL || nextCell.type === GridItemType.GOAL)) { return { x: nextX, y: nextY }; } return null; }; self.generateWaypointPath = function () { var path = []; var spawn = self.findTile(GridItemType.SPAWN); if (!spawn) return path; path.push(spawn); var firstStep = self.findFirstStep(spawn); if (!firstStep) return path; var current = firstStep; var prev = spawn; path.push(current); while (current) { var next = self.getNextWaypoint(current, prev); if (!next) break; path.push(next); prev = current; current = next; // Stop if we reach the goal var cell = self.getCell(current.x, current.y); if (cell && cell.type === GridItemType.GOAL) { break; } } return path; }; 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(Math.round(enemy.x / CELL_SIZE), Math.round(enemy.y / CELL_SIZE)); if (cell && cell.type == GridItemType.GOAL) { return true; } // Update shadow position for flying enemies 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; } } return false; }; }); 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; 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 closer to goal) if (distToGoal < closestScore || closestScore === -Infinity) { closestScore = distToGoal; closestEnemy = enemy; } } else { // If no flying target yet (shouldn't happen), prioritize by distance to tower if (distance < closestScore || closestScore === -Infinity) { closestScore = distance; closestEnemy = enemy; } } } else { // For ground enemies, use waypoint progress for prioritization if (enemy.waypointPath) { // Prioritize enemies that are further along the path if (enemy.currentWaypointIndex > closestScore) { closestScore = enemy.currentWaypointIndex; 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 !== 4 || 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.y < grid.y + 4 * CELL_SIZE) { continue; } // Only check non-flying enemies, flying enemies can pass over towers if (!enemy.isFlying) { // Convert enemy pixel position to grid coordinates var enemyGridX = Math.floor((enemy.x - grid.x) / CELL_SIZE); var enemyGridY = Math.floor((enemy.y - grid.y) / CELL_SIZE); if (enemyGridX >= self.gridX && enemyGridX < self.gridX + 2 && enemyGridY >= self.gridY && enemyGridY < 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 ****/ // GridItemType enum definition // Add Map_1 background without stretching var GridItemType = { EMPTY: 1, PATH_START: 2, PATH_HORIZONTAL: 3, PATH_VERTICAL: 4, PATH_TURN_NE: 5, PATH_TURN_NW: 6, PATH_TURN_SE: 7, PATH_TURN_SW: 8, PATH_JUNCTION: 9, SPAWN: 2, GOAL: 3, TOWER_SLOT: 4 }; // Global helper function to convert grid coordinates to pixel coordinates function convertGridToPixels(gridPos) { return { x: grid.x + gridPos.x * CELL_SIZE + CELL_SIZE / 2, y: grid.y + gridPos.y * CELL_SIZE + CELL_SIZE / 2 }; } // Global helper function to get arrow rotations for a cell function getArrowRotationsForCell(cell, grid) { var rotations = []; if (cell.type === GridItemType.PATH_HORIZONTAL) { rotations.push(0); // Right arrow } else if (cell.type === GridItemType.PATH_VERTICAL) { rotations.push(Math.PI / 2); // Down arrow } else if (cell.type === GridItemType.PATH_TURN_NE) { rotations.push(-Math.PI / 2); // Up arrow rotations.push(0); // Right arrow } else if (cell.type === GridItemType.PATH_TURN_NW) { rotations.push(-Math.PI / 2); // Up arrow rotations.push(Math.PI); // Left arrow } else if (cell.type === GridItemType.PATH_TURN_SE) { rotations.push(Math.PI / 2); // Down arrow rotations.push(0); // Right arrow } else if (cell.type === GridItemType.PATH_TURN_SW) { rotations.push(Math.PI / 2); // Down arrow rotations.push(Math.PI); // Left arrow } else if (cell.type === GridItemType.PATH_JUNCTION) { rotations.push(0); // Right arrow rotations.push(Math.PI / 2); // Down arrow } return rotations; } 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.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; enemy.currentCellY = spawnCell.y - (1 + Math.random() * 5); // Vertical offset for entry animation 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]; var reachedGoal = grid.updateEnemy(enemy); if (enemy.health <= 0 || reachedGoal) { 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
@@ -136,15 +136,8 @@
anchorY: 0.5
});
cellGraphics.tint = Math.random() * 0xffffff;
var debugArrows = [];
- 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;
if (self.cell.type == 0 || self.cell.type == 1) {
@@ -164,40 +157,62 @@
self.removeChild(debugArrows.pop());
}
};
self.render = function (data) {
+ self.removeArrows();
switch (data.type) {
- case GridItemType.PATH_STRAIGHT_DOWN:
- case GridItemType.SPAWN:
+ case GridItemType.PATH_HORIZONTAL:
+ case GridItemType.PATH_VERTICAL:
+ case GridItemType.PATH_TURN_NE:
+ case GridItemType.PATH_TURN_NW:
+ case GridItemType.PATH_TURN_SE:
+ case GridItemType.PATH_TURN_SW:
+ case GridItemType.PATH_JUNCTION:
{
- self.removeArrows();
- cellGraphics.tint = 0x880000;
+ var towerInRangeHighlight = false;
+ if (selectedTower && data.towersInRange && data.towersInRange.indexOf(selectedTower) !== -1) {
+ towerInRangeHighlight = true;
+ cellGraphics.tint = 0x0088ff;
+ } else {
+ cellGraphics.tint = 0x888888; // Base path color
+ }
cellGraphics.alpha = 0.1;
- numberLabel.visible = false;
+ // Add arrows based on path type
+ var rotations = getArrowRotationsForCell(data, grid);
+ for (var a = 0; a < rotations.length; a++) {
+ var arrow = LK.getAsset('arrow', {
+ anchorX: -.5,
+ anchorY: 0.5
+ });
+ arrow.alpha = .5;
+ arrow.rotation = rotations[a];
+ self.addChildAt(arrow, 1);
+ debugArrows.push(arrow);
+ }
break;
}
- case GridItemType.WALL:
+ case GridItemType.EMPTY:
{
- self.removeArrows();
cellGraphics.tint = 0xaaaaaa;
cellGraphics.alpha = 0;
- numberLabel.visible = false;
break;
}
+ case GridItemType.SPAWN:
+ {
+ cellGraphics.tint = 0x00FF00; // Green for spawn
+ cellGraphics.alpha = 0.1;
+ break;
+ }
case GridItemType.GOAL:
{
- self.removeArrows();
- cellGraphics.tint = 0x008800;
+ cellGraphics.tint = 0xFF0000; // Red for goal
cellGraphics.alpha = 0.1;
- numberLabel.visible = false;
break;
}
case GridItemType.TOWER_SLOT:
{
- self.removeArrows();
cellGraphics.tint = data.isOccupied ? 0x0088CC : 0x00BFFF;
cellGraphics.alpha = 0.1;
- numberLabel.visible = false;
break;
}
}
};
@@ -260,14 +275,14 @@
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.waypoints = [];
- self.targetWaypointIndex = 1;
+ self.currentWaypointIndex = 0;
+ self.waypointPath = [];
+ self.pixelPosition = {
+ x: 0,
+ y: 0
+ };
self.maxHealth = 100;
self.health = self.maxHealth;
self.bulletsTargetingThis = [];
self.waveNumber = currentWave;
@@ -305,8 +320,15 @@
// Slower speed for bosses
self.speed = self.speed * 0.7;
}
self.health = self.maxHealth;
+ // Initialize waypoint path and position
+ self.waypointPath = grid.waypointPath;
+ if (self.waypointPath.length > 0) {
+ self.pixelPosition = convertGridToPixels(self.waypointPath[0]);
+ self.x = self.pixelPosition.x;
+ self.y = self.pixelPosition.y;
+ }
// Get appropriate asset for this enemy type
var assetId = 'enemy';
if (self.type !== 'normal') {
assetId = 'enemy_' + self.type;
@@ -449,39 +471,62 @@
enemyGraphics.tint = 0x9900FF;
} else {
enemyGraphics.tint = 0xFFFFFF;
}
- if (self.currentTarget) {
- var ox = self.currentTarget.x - self.currentCellX;
- var oy = self.currentTarget.y - self.currentCellY;
- if (ox !== 0 || oy !== 0) {
- var angle = Math.atan2(oy, ox);
- if (enemyGraphics.targetRotation === undefined) {
- enemyGraphics.targetRotation = angle;
- enemyGraphics.rotation = angle;
- } else {
- if (Math.abs(angle - enemyGraphics.targetRotation) > 0.05) {
- tween.stop(enemyGraphics, {
- rotation: true
- });
- // Calculate the shortest angle to rotate
- var currentRotation = enemyGraphics.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;
- }
- enemyGraphics.targetRotation = angle;
- tween(enemyGraphics, {
- rotation: currentRotation + angleDiff
- }, {
- duration: 250,
- easing: tween.easeOut
- });
+ // Waypoint-based movement
+ if (self.currentWaypointIndex >= self.waypointPath.length) {
+ // Reached the end of the path (goal)
+ return;
+ }
+ var targetWaypoint = self.waypointPath[self.currentWaypointIndex];
+ var targetPixelPosition = convertGridToPixels(targetWaypoint);
+ // Calculate direction to target
+ var dx = targetPixelPosition.x - self.pixelPosition.x;
+ var dy = targetPixelPosition.y - self.pixelPosition.y;
+ var distance = Math.sqrt(dx * dx + dy * dy);
+ // Move towards target
+ if (distance > self.speed) {
+ var moveX = dx / distance * self.speed;
+ var moveY = dy / distance * self.speed;
+ self.pixelPosition.x += moveX;
+ self.pixelPosition.y += moveY;
+ } else {
+ // Snap to waypoint and move to next one
+ self.pixelPosition.x = targetPixelPosition.x;
+ self.pixelPosition.y = targetPixelPosition.y;
+ self.currentWaypointIndex++;
+ }
+ // Update display position
+ self.x = self.pixelPosition.x;
+ self.y = self.pixelPosition.y;
+ // Rotate enemy to face movement direction
+ if (dx !== 0 || dy !== 0) {
+ var angle = Math.atan2(dy, dx);
+ if (enemyGraphics.targetRotation === undefined) {
+ enemyGraphics.targetRotation = angle;
+ enemyGraphics.rotation = angle;
+ } else {
+ if (Math.abs(angle - enemyGraphics.targetRotation) > 0.05) {
+ tween.stop(enemyGraphics, {
+ rotation: true
+ });
+ // Calculate the shortest angle to rotate
+ var currentRotation = enemyGraphics.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;
+ }
+ enemyGraphics.targetRotation = angle;
+ tween(enemyGraphics, {
+ rotation: currentRotation + angleDiff
+ }, {
+ duration: 250,
+ easing: tween.easeOut
+ });
}
}
}
healthBarOutline.y = healthBarBG.y = healthBar.y = -enemyGraphics.height / 2 - 10;
@@ -536,15 +581,11 @@
}
});
return self;
});
-// GridItemType enum
var Grid = Container.expand(function (gridWidth, gridHeight) {
var self = Container.call(this);
self.cells = [];
- self.spawns = [];
- self.goals = [];
- self.waypoints = [];
for (var i = 0; i < gridWidth; i++) {
self.cells[i] = [];
for (var j = 0; j < gridHeight; j++) {
self.cells[i][j] = {
@@ -553,53 +594,30 @@
};
}
}
/*
- Cell Types
- 0: Path (walkable by ground enemies)
- 1: Wall (impassable)
- 2: Spawn
- 3: Goal
- 4: Tower Slot (impassable by ground enemies, buildable)
+ Cell Types using GridItemType enum:
+ EMPTY: 1 (Wall/impassable)
+ SPAWN: 2 (Enemy spawn points)
+ GOAL: 3 (Enemy goal points)
+ TOWER_SLOT: 4 (Buildable tower locations)
+ PATH_*: Various path types for waypoint following
*/
- // Predefined map layout
- var mapLayout = [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 1, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 1, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 1, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 1, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1], [1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 1, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 1, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 1, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 1, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1], [1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 1, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 1, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 1, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 1, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 4, 4, 4, 4, 4, 4, 0, 0, 4, 4, 4, 4, 4, 4, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]];
+ // Predefined map layout using GridItemType enum
+ var mapLayout = [[GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.SPAWN, GridItemType.SPAWN, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_VERTICAL, GridItemType.PATH_VERTICAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_VERTICAL, GridItemType.PATH_VERTICAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.PATH_HORIZONTAL, GridItemType.PATH_HORIZONTAL, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.TOWER_SLOT, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.PATH_VERTICAL, GridItemType.PATH_VERTICAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.GOAL, GridItemType.GOAL, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY], [GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY, GridItemType.EMPTY]];
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 = GridItemType.WALL; // Default to wall
+ var cellType = GridItemType.EMPTY; // Default to empty/wall
if (j < mapLayout.length && i < mapLayout[j].length) {
- var mapValue = mapLayout[j][i];
- // Translate map values to GridItemType enum
- switch (mapValue) {
- case 0:
- cellType = GridItemType.PATH_STRAIGHT_DOWN;
- break;
- case 1:
- cellType = GridItemType.WALL;
- break;
- case 2:
- cellType = GridItemType.SPAWN;
- break;
- case 3:
- cellType = GridItemType.GOAL;
- break;
- case 4:
- cellType = GridItemType.TOWER_SLOT;
- break;
- }
+ 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) {
+ // Create debug cells for visible gameplay area
+ if (j > 3 && j <= gridHeight - 4 && cellType !== GridItemType.EMPTY) {
var debugCell = new DebugCell();
self.addChild(debugCell);
debugCell.cell = cell;
debugCell.x = i * CELL_SIZE;
@@ -607,111 +625,85 @@
cell.debugCell = debugCell;
}
}
}
+ // Generate waypoint path after cells are created
+ self.waypointPath = self.generateWaypointPath();
self.getCell = function (x, y) {
return self.cells[x] && self.cells[x][y];
};
self.findTile = function (tileType) {
- for (var i = 0; i < gridWidth; i++) {
- for (var j = 0; j < gridHeight; j++) {
+ for (var i = 0; i < self.cells.length; i++) {
+ for (var j = 0; j < self.cells[i].length; j++) {
if (self.cells[i][j].type === tileType) {
- return self.cells[i][j];
+ return {
+ x: i,
+ y: j
+ };
}
}
}
return null;
};
self.findFirstStep = function (startPos) {
- // Look for the first PATH_STRAIGHT_DOWN tile below spawn
- var x = startPos.x;
- for (var y = startPos.y + 1; y < gridHeight; y++) {
- var cell = self.getCell(x, y);
- if (cell && cell.type === GridItemType.PATH_STRAIGHT_DOWN) {
- return cell;
+ // Find the first walkable tile after spawn
+ for (var i = 0; i < self.cells.length; i++) {
+ for (var j = 0; j < self.cells[i].length; j++) {
+ var cell = self.cells[i][j];
+ if (cell.type === GridItemType.PATH_VERTICAL || cell.type === GridItemType.PATH_HORIZONTAL || cell.type === GridItemType.PATH_TURN_NE || cell.type === GridItemType.PATH_TURN_NW || cell.type === GridItemType.PATH_TURN_SE || cell.type === GridItemType.PATH_TURN_SW || cell.type === GridItemType.PATH_JUNCTION) {
+ return {
+ x: i,
+ y: j
+ };
+ }
}
}
return null;
};
self.getNextWaypoint = function (currentPos, prevPos) {
- var x = currentPos.x;
- var y = currentPos.y;
- // Check all 4 directions for next path
- var directions = [{
- dx: 0,
- dy: 1
- },
- // down
- {
- dx: 1,
- dy: 0
- },
- // right
- {
- dx: 0,
- dy: -1
- },
- // up
- {
- dx: -1,
- dy: 0
- } // left
- ];
- for (var i = 0; i < directions.length; i++) {
- var dir = directions[i];
- var nextX = x + dir.dx;
- var nextY = y + dir.dy;
- var nextCell = self.getCell(nextX, nextY);
- if (nextCell && (nextCell.type === GridItemType.PATH_STRAIGHT_DOWN || nextCell.type === GridItemType.GOAL) && (!prevPos || nextX !== prevPos.x || nextY !== prevPos.y)) {
- return nextCell;
- }
+ var currentCell = self.getCell(currentPos.x, currentPos.y);
+ if (!currentCell) return null;
+ // Simple pathfinding along the predefined path
+ var nextX = currentPos.x;
+ var nextY = currentPos.y;
+ if (currentCell.type === GridItemType.PATH_HORIZONTAL) {
+ nextX += 1; // Move right
+ } else if (currentCell.type === GridItemType.PATH_VERTICAL) {
+ nextY += 1; // Move down
}
+ var nextCell = self.getCell(nextX, nextY);
+ if (nextCell && (nextCell.type === GridItemType.PATH_HORIZONTAL || nextCell.type === GridItemType.PATH_VERTICAL || nextCell.type === GridItemType.GOAL)) {
+ return {
+ x: nextX,
+ y: nextY
+ };
+ }
return null;
};
- self.buildWaypointPath = function () {
- // Find spawn tile
- var spawnTile = self.findTile(GridItemType.SPAWN);
- if (!spawnTile) {
- console.warn("No spawn tile found");
- return [];
- }
- var waypoints = [spawnTile];
- var currentPos = spawnTile;
- var prevPos = null;
- // Find first step from spawn
- var firstStep = self.findFirstStep(spawnTile);
- if (!firstStep) {
- console.warn("No path from spawn");
- return waypoints;
- }
- waypoints.push(firstStep);
- prevPos = currentPos;
- currentPos = firstStep;
- // Follow path until we reach goal
- while (currentPos.type !== GridItemType.GOAL) {
- var nextWaypoint = self.getNextWaypoint(currentPos, prevPos);
- if (!nextWaypoint) {
- console.warn("Path broken at", currentPos.x, currentPos.y);
+ self.generateWaypointPath = function () {
+ var path = [];
+ var spawn = self.findTile(GridItemType.SPAWN);
+ if (!spawn) return path;
+ path.push(spawn);
+ var firstStep = self.findFirstStep(spawn);
+ if (!firstStep) return path;
+ var current = firstStep;
+ var prev = spawn;
+ path.push(current);
+ while (current) {
+ var next = self.getNextWaypoint(current, prev);
+ if (!next) break;
+ path.push(next);
+ prev = current;
+ current = next;
+ // Stop if we reach the goal
+ var cell = self.getCell(current.x, current.y);
+ if (cell && cell.type === GridItemType.GOAL) {
break;
}
- waypoints.push(nextWaypoint);
- prevPos = currentPos;
- currentPos = nextWaypoint;
}
- return waypoints;
+ return path;
};
- self.pathFind = function () {
- var before = new Date().getTime();
- // Generate waypoint path
- self.waypoints = self.buildWaypointPath();
- // Check if path is complete (reaches goal)
- if (self.waypoints.length > 0 && self.waypoints[self.waypoints.length - 1].type === GridItemType.GOAL) {
- console.log("Path generation complete, waypoints:", self.waypoints.length);
- } else {
- console.warn("Path generation incomplete");
- }
- console.log("Speed", new Date().getTime() - before);
- };
self.renderDebug = function () {
for (var i = 0; i < gridWidth; i++) {
for (var j = 0; j < gridHeight; j++) {
var debugCell = self.cells[i][j].debugCell;
@@ -721,163 +713,22 @@
}
}
};
self.updateEnemy = function (enemy) {
- var cell = grid.getCell(enemy.cellX, enemy.cellY);
- if (cell.type == 3) {
+ var cell = grid.getCell(Math.round(enemy.x / CELL_SIZE), Math.round(enemy.y / CELL_SIZE));
+ if (cell && cell.type == GridItemType.GOAL) {
return true;
}
+ // Update shadow position for flying enemies
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 is at least 5)
- var hasReachedEntryArea = enemy.currentCellY >= 4;
- // If enemy hasn't reached the entry area yet, just move down vertically
- if (!hasReachedEntryArea) {
- // Move directly downward
- enemy.currentCellY += enemy.speed;
- // 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;
- // If enemy has now reached the entry area, update cell coordinates
- if (enemy.currentCellY >= 4) {
- enemy.cellX = Math.round(enemy.currentCellX);
- enemy.cellY = Math.round(enemy.currentCellY);
- }
- 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 the closest goal
- enemy.flyingTarget = self.goals[0];
- // Find closest goal if there are multiple
- if (self.goals.length > 1) {
- var closestDist = Infinity;
- for (var i = 0; i < self.goals.length; i++) {
- var goal = self.goals[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 waypoint-based pathfinding enemies
- if (enemy.waypoints.length === 0) {
- enemy.waypoints = self.waypoints;
- }
- if (enemy.targetWaypointIndex >= enemy.waypoints.length) {
- // Reached end of path
- return true;
- }
- var targetWaypoint = enemy.waypoints[enemy.targetWaypointIndex];
- if (targetWaypoint) {
- var ox = targetWaypoint.x - enemy.currentCellX;
- var oy = targetWaypoint.y - enemy.currentCellY;
- var dist = Math.sqrt(ox * ox + oy * oy);
- if (dist < enemy.speed) {
- enemy.cellX = Math.round(enemy.currentCellX);
- enemy.cellY = Math.round(enemy.currentCellY);
- enemy.targetWaypointIndex++;
- if (enemy.targetWaypointIndex >= enemy.waypoints.length) {
- return true;
- }
- return;
- }
- var angle = Math.atan2(oy, ox);
- 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;
+ return false;
};
});
var NextWaveButton = Container.expand(function () {
var self = Container.call(this);
@@ -1302,9 +1153,9 @@
return false;
};
self.findTarget = function () {
var closestEnemy = null;
- var closestScore = Infinity;
+ var closestScore = -Infinity;
for (var i = 0; i < enemies.length; i++) {
var enemy = enemies[i];
var dx = enemy.x - self.x;
var dy = enemy.y - self.y;
@@ -1317,26 +1168,28 @@
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
- if (distToGoal < closestScore) {
+ // Use distance to goal as score (lower is closer to goal)
+ if (distToGoal < closestScore || closestScore === -Infinity) {
closestScore = distToGoal;
closestEnemy = enemy;
}
} else {
// If no flying target yet (shouldn't happen), prioritize by distance to tower
- if (distance < closestScore) {
+ if (distance < closestScore || closestScore === -Infinity) {
closestScore = distance;
closestEnemy = enemy;
}
}
} else {
- // For ground enemies, prioritize by waypoint progress
- // Higher targetWaypointIndex means closer to goal
- if (enemy.targetWaypointIndex > closestScore) {
- closestScore = enemy.targetWaypointIndex;
- closestEnemy = enemy;
+ // For ground enemies, use waypoint progress for prioritization
+ if (enemy.waypointPath) {
+ // Prioritize enemies that are further along the path
+ if (enemy.currentWaypointIndex > closestScore) {
+ closestScore = enemy.currentWaypointIndex;
+ closestEnemy = enemy;
+ }
}
}
}
}
@@ -1529,10 +1382,8 @@
cell.isOccupied = true;
}
}
}
- // Recalculate pathfinding after placing tower to ensure paths are updated
- grid.pathFind();
self.refreshCellsInRange();
};
return self;
});
@@ -1607,9 +1458,9 @@
} 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) {
+ if (!cell || cell.type !== 4 || cell.isOccupied === true) {
validGridPlacement = false;
break;
}
}
@@ -1621,25 +1472,20 @@
self.blockedByEnemy = false;
if (validGridPlacement) {
for (var i = 0; i < enemies.length; i++) {
var enemy = enemies[i];
- if (enemy.currentCellY < 4) {
+ if (enemy.y < grid.y + 4 * CELL_SIZE) {
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) {
+ // Convert enemy pixel position to grid coordinates
+ var enemyGridX = Math.floor((enemy.x - grid.x) / CELL_SIZE);
+ var enemyGridY = Math.floor((enemy.y - grid.y) / CELL_SIZE);
+ if (enemyGridX >= self.gridX && enemyGridX < self.gridX + 2 && enemyGridY >= self.gridY && enemyGridY < 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;
@@ -1861,9 +1707,8 @@
if (towerIndex !== -1) {
towers.splice(towerIndex, 1);
}
towerLayer.removeChild(self.tower);
- grid.pathFind();
grid.renderDebug();
self.destroy();
for (var i = 0; i < game.children.length; i++) {
if (game.children[i].isTowerRange && game.children[i].tower === self.tower) {
@@ -2254,17 +2099,56 @@
/****
* Game Code
****/
-// GridItemType enum
+// GridItemType enum definition
// Add Map_1 background without stretching
var GridItemType = {
- PATH_STRAIGHT_DOWN: 0,
- WALL: 1,
+ EMPTY: 1,
+ PATH_START: 2,
+ PATH_HORIZONTAL: 3,
+ PATH_VERTICAL: 4,
+ PATH_TURN_NE: 5,
+ PATH_TURN_NW: 6,
+ PATH_TURN_SE: 7,
+ PATH_TURN_SW: 8,
+ PATH_JUNCTION: 9,
SPAWN: 2,
GOAL: 3,
TOWER_SLOT: 4
};
+// Global helper function to convert grid coordinates to pixel coordinates
+function convertGridToPixels(gridPos) {
+ return {
+ x: grid.x + gridPos.x * CELL_SIZE + CELL_SIZE / 2,
+ y: grid.y + gridPos.y * CELL_SIZE + CELL_SIZE / 2
+ };
+}
+// Global helper function to get arrow rotations for a cell
+function getArrowRotationsForCell(cell, grid) {
+ var rotations = [];
+ if (cell.type === GridItemType.PATH_HORIZONTAL) {
+ rotations.push(0); // Right arrow
+ } else if (cell.type === GridItemType.PATH_VERTICAL) {
+ rotations.push(Math.PI / 2); // Down arrow
+ } else if (cell.type === GridItemType.PATH_TURN_NE) {
+ rotations.push(-Math.PI / 2); // Up arrow
+ rotations.push(0); // Right arrow
+ } else if (cell.type === GridItemType.PATH_TURN_NW) {
+ rotations.push(-Math.PI / 2); // Up arrow
+ rotations.push(Math.PI); // Left arrow
+ } else if (cell.type === GridItemType.PATH_TURN_SE) {
+ rotations.push(Math.PI / 2); // Down arrow
+ rotations.push(0); // Right arrow
+ } else if (cell.type === GridItemType.PATH_TURN_SW) {
+ rotations.push(Math.PI / 2); // Down arrow
+ rotations.push(Math.PI); // Left arrow
+ } else if (cell.type === GridItemType.PATH_JUNCTION) {
+ rotations.push(0); // Right arrow
+ rotations.push(Math.PI / 2); // Down arrow
+ }
+ return rotations;
+}
var backgroundMap = game.attachAsset('Map_1', {
anchorX: 0,
anchorY: 0,
x: 0,
@@ -2363,9 +2247,8 @@
// var blocker = new Blocker();
// blocker.placeOnGrid(4, 8); // Place at tower slot coordinates
// towerLayer.addChild(blocker);
// blockers.push(blocker);
-grid.pathFind();
grid.renderDebug();
debugLayer.addChild(grid);
game.addChild(debugLayer);
game.addChild(towerLayer);
@@ -2411,9 +2294,8 @@
tower.placeOnGrid(gridX, gridY);
towerLayer.addChild(tower);
towers.push(tower);
setGold(gold - towerCost);
- grid.pathFind();
grid.renderDebug();
return true;
} else {
var notification = game.addChild(new Notification("Not enough gold!"));
@@ -2465,9 +2347,8 @@
}
}
}
}
- grid.pathFind(); // Recalculate path after removing tower
grid.renderDebug(); // Update debug view
towerPreview.visible = true;
towerPreview.towerType = draggedTower.id;
towerPreview.updateAppearance();
@@ -2530,9 +2411,8 @@
// Handle moving existing tower
if (towerPreview.canPlace) {
// Move tower to new position
draggedTower.placeOnGrid(towerPreview.gridX, towerPreview.gridY);
- grid.pathFind();
grid.renderDebug();
} else if (towerPreview.blockedByEnemy) {
// Blocked by enemy, restore tower to original position
draggedTower.placeOnGrid(draggedTowerOriginalX, draggedTowerOriginalY);
@@ -2695,9 +2575,10 @@
}
}
for (var a = enemies.length - 1; a >= 0; a--) {
var enemy = enemies[a];
- if (enemy.health <= 0) {
+ var reachedGoal = grid.updateEnemy(enemy);
+ if (enemy.health <= 0 || reachedGoal) {
for (var i = 0; i < enemy.bulletsTargetingThis.length; i++) {
var bullet = enemy.bulletsTargetingThis[i];
bullet.targetEnemy = null;
}
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
Top-down map asset for a TD game. Imagine a single, contiguous ribbon laid across a canyon floor; this ribbon is the path. It is a unicursal maze, meaning it's a single, non-branching route that twists through the map in a complex, grid-like pattern. The path has absolutely no junctions or alternative routes. The path starts at the top-middle edge and the very same path ends at the bottom-middle edge. The path is flanked by wide, flat, sandy plateaus that are completely barren for building. The map is framed by large, decorative sandstone formations pushed to the far edges, which do not intrude on the central play area. Semi-realistic style. --no towers, no buildings, no characters, no junctions. In-Game asset. 2d. High contrast. No shadows