Skip to content

Refactor Game Engine Pipeline and Targeting Logic#164

Merged
candour merged 2 commits into
mainfrom
refactor-game-engine-pipeline-14640828118690784622
May 17, 2026
Merged

Refactor Game Engine Pipeline and Targeting Logic#164
candour merged 2 commits into
mainfrom
refactor-game-engine-pipeline-14640828118690784622

Conversation

@candour
Copy link
Copy Markdown
Owner

@candour candour commented May 17, 2026

Refactored the game engine update pipeline and targeting logic in MainViewModel.kt and Registry.kt for improved performance and code clarity. The update reorders the pipeline steps, pre-calculates expensive engine data (boosts, targeting lists), optimizes CLOSEST target selection via SpatialIndex, and consolidates state updates to minimize memory overhead from redundant GameState copies. Unit tests confirm correct behavior and performance gains.


PR created automatically by Jules for task 14640828118690784622 started by @candour

Summary by CodeRabbit

  • Refactor
    • Optimized game engine data processing pipeline for improved efficiency in enemy targeting and stall firing calculations.
    • Streamlined health loss application and state updates during enemy movement handling.
    • Enhanced adjacency tracking and unique target accounting for stall firing interactions.

Review Change Stack

This commit optimizes the core game tick update in `MainViewModel.kt` and
the stall targeting logic in `Registry.kt`. Key improvements include:

1.  **Optimized Pipeline Order:** Reordered the `updateGame` loop to build
    the `SpatialIndex<Enemy>` after movement, ensuring targeting and
    collisions use the most up-to-date coordinates.
2.  **Engine Data Pre-calculation:** Pre-calculating Bak Kut Teh boosts
    and sorted targeting lists (`FIRST`, `STRONGEST`, `WEAKEST`) once per
    tick to eliminate redundant calculations inside the stall loop.
3.  **Targeting Efficiency:** Updated `StallBehavior.selectTarget` to use
    `SpatialIndex.findNearby` for `CLOSEST` mode targeting, reducing
    complexity from $O(E)$ to $O(1)$.
4.  **State Update Consolidation:** Refactored `handleEnemyMovement` and
    hit tracking to batch `GameState` and `HexTile` map copies, reducing
    memory allocation overhead.

These changes result in a more efficient and maintainable game engine.
Record added to `fixes.md` as `REF-011`.

Co-authored-by: candour <4670475+candour@users.noreply.github.com>
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 17, 2026

Warning

Rate limit exceeded

@candour has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 35 minutes and 31 seconds before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f827a2a1-3951-4966-8997-a73deee8bc06

📥 Commits

Reviewing files that changed from the base of the PR and between 33ef76b and 22ee280.

📒 Files selected for processing (1)
  • fixes.md
📝 Walkthrough

Walkthrough

The game engine tick is refactored to pre-compute targeting infrastructure after enemy movement, consolidate health mutations, batch Bak Kut Teh adjacency updates, and optimize projectile hit accounting. The StallBehavior.selectTarget contract is updated to use spatial indices for efficient enemy candidate sourcing.

Changes

Engine Pipeline and Targeting Refactor

Layer / File(s) Summary
Targeting contract and spatial index adoption
app/src/main/java/com/messark/hawker/registry/Registry.kt
StallBehavior.selectTarget signature changes to accept enemySpatialIndex: SpatialIndex<Enemy> instead of allEnemies: List<Enemy>. DefaultStallBehavior.selectTarget uses enemySpatialIndex.findNearby(...) to source TargetMode.CLOSEST candidates instead of filtering the full list.
Engine data pre-calculation in tick orchestration
app/src/main/java/com/messark/hawker/MainViewModel.kt
After enemy movement, updateGame builds a spatial index, pre-sorts enemies by targeting mode, pre-filters eligible firing stalls, and pre-calculates Bak Kut Teh boosts; this precomputed data is passed into handleStallFiring.
Enemy movement with deferred health loss accumulation
app/src/main/java/com/messark/hawker/MainViewModel.kt
handleEnemyMovement introduces a healthLoss accumulator to defer health mutations. Health loss is collected during path-completion processing and applied once after movement completes; stall-unique-target updates are then derived and applied.
Stall firing with precomputed data and batched Bak Kut Teh updates
app/src/main/java/com/messark/hawker/MainViewModel.kt
handleStallFiring accepts precomputed spatial index, per-mode sorted enemy lists, and pre-calculated boosts. Bak Kut Teh adjacency updates are collected in a map during firing and applied in a single batch after all stall decisions.
Projectile hit accounting with conditional state writes
app/src/main/java/com/messark/hawker/MainViewModel.kt
Projectile hit resolution now computes newUniqueTargets and conditionally writes back to stall state only when kills or the unique-target set size actually changes.
Engine refactor registry documentation
fixes.md
New REF-011 registry entry documents pre-calculation of engine data, spatial indexing adoption, and consolidated state updates.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~22 minutes

Possibly related PRs

  • candour/towerpower#125: Main PR's refactor of Bak Kut Teh boost pre-calculation and handleEnemyMovement health/buff logic overlaps with the original introduction of BoostResult and calculateStatBoost system.
  • candour/towerpower#156: Both PRs refactor stall targeting in MainViewModel.handleStallFiring and update Registry.kt's StallBehavior.selectTarget contract; main PR further adopts spatial indexing.
  • candour/towerpower#158: Both PRs refactor MainViewModel to use SpatialIndex-based nearby enemy queries in the core tick flow, especially around movement and firing phases.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main refactoring effort: restructuring the game engine pipeline and optimizing targeting logic with SpatialIndex, matching the core changes across MainViewModel.kt and Registry.kt.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor-game-engine-pipeline-14640828118690784622

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions
Copy link
Copy Markdown

Build Successful! 🚀

Download APK

Note: This link will be removed when the PR is closed.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a18a6f95-806d-4579-b1f8-5f3e1682fafe

📥 Commits

Reviewing files that changed from the base of the PR and between 4bb5e4a and 33ef76b.

📒 Files selected for processing (3)
  • app/src/main/java/com/messark/hawker/MainViewModel.kt
  • app/src/main/java/com/messark/hawker/registry/Registry.kt
  • fixes.md

Comment thread fixes.md Outdated
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
@github-actions
Copy link
Copy Markdown

Build Successful! 🚀

Download APK

Note: This link will be removed when the PR is closed.

@candour candour merged commit 6803d1f into main May 17, 2026
3 checks passed
@candour candour deleted the refactor-game-engine-pipeline-14640828118690784622 branch May 17, 2026 23:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant