Skip to content

Refactor StallUpgradeManager for efficiency and simplicity#128

Merged
candour merged 2 commits into
mainfrom
refactor-stall-upgrade-manager-7076087423520579259
May 7, 2026
Merged

Refactor StallUpgradeManager for efficiency and simplicity#128
candour merged 2 commits into
mainfrom
refactor-stall-upgrade-manager-7076087423520579259

Conversation

@candour
Copy link
Copy Markdown
Owner

@candour candour commented May 6, 2026

This PR refactors the stat calculation logic in StallUpgradeManager.kt. The previous O(level) iterative loop has been replaced with an idiomatic Kotlin fold operation, and a thread-safe ConcurrentHashMap has been introduced to cache calculated values, significantly improving performance for repeated stat lookups. Redundant imports and unrelated compilation issues in GridUtils and MainViewModel have also been resolved.


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

Summary by CodeRabbit

  • Performance Improvements

    • Optimized stall upgrade calculations with caching to enhance responsiveness.
  • Enhancements

    • Improved legendary-tier stall mechanics including enhanced naming logic and progression handling.
  • Bug Fixes

    • Refactored upgrade computation to fix edge cases in stall stat calculations.

- Introduced ConcurrentHashMap for caching calculated stat values.
- Replaced iterative loop with fold operation in calculateValue.
- Cleaned up redundant imports and fixed compilation errors in MainViewModel.
- Updated fixes.md to record the refactoring.

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 6, 2026

Warning

Rate limit exceeded

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

To continue reviewing without waiting, purchase usage credits 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: ca8378f7-4443-40e0-b221-65b3cb292606

📥 Commits

Reviewing files that changed from the base of the PR and between 49e4b73 and 6b311bb.

📒 Files selected for processing (2)
  • app/src/main/java/com/messark/hawker/MainViewModel.kt
  • app/src/main/java/com/messark/hawker/utils/StallUpgradeManager.kt
📝 Walkthrough

Walkthrough

This PR refactors the stall upgrade calculation system to use canonicalized stat names and caching, introduces a BoostResult data class in MainViewModel, and changes the calculateStatBoost method signature from accepting GameState to accepting a hexes map. The upgrade pipeline now features centralized value computation with concurrent caching and Legendary naming logic at level 10.

Changes

Stall Upgrade System Refactoring

Layer / File(s) Summary
Data Structures
app/src/main/java/com/messark/hawker/MainViewModel.kt, app/src/main/java/com/messark/hawker/utils/StallUpgradeManager.kt
BoostResult data class added to MainViewModel with multiplier and providerCoords fields. CacheKey data class introduced in StallUpgradeManager to key cached upgrade values by stall type, stat, base value, and level.
Canonical Stat Mapping
app/src/main/java/com/messark/hawker/utils/StallUpgradeManager.kt
New getCanonicalStat() function maps UI stat names (e.g., "Grab Rate", "Cleaning Time") to canonical internal keys for consistent upgrade computation.
Upgrade Value Calculation
app/src/main/java/com/messark/hawker/utils/StallUpgradeManager.kt
calculateValue() function introduced with level-based incremental progression, milestone logic, and concurrent value caching. Replaces ad-hoc per-stat calculations.
Upgrade Application Pipeline
app/src/main/java/com/messark/hawker/utils/StallUpgradeManager.kt
applyUpgrade() refactored to normalize alias levels via canonical keys, compute new levels, and apply Legendary naming logic when reaching level 10 (including name prefix/suffix and category updates). Returns updated Stall with all stats recalculated via calculateValue(), upgraded counts, and investment totals.
Method Signature & Integration
app/src/main/java/com/messark/hawker/MainViewModel.kt
calculateStatBoost() signature changed from (AxialCoordinate, GameState) to (AxialCoordinate, Map<AxialCoordinate, HexTile>). Import reorganized to use wildcard import for com.messark.hawker.utils.*.
Utility Imports
app/src/main/java/com/messark/hawker/utils/GridUtils.kt
Imports updated: added PreciseAxialCoordinate and kotlin.math.abs; removed direct AxialCoordinate import.
Documentation
fixes.md
New entry REF-001 documents refactoring of StallUpgradeManager to use caching and fold operations for optimized stat calculation.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • candour/towerpower#116: Modifies StallUpgradeManager to canonicalize stat names and centralize stat computation with similar patterns (calculateValue and canonical mapping).
  • candour/towerpower#126: Directly related—modifies the same MainViewModel boost logic (BoostResult and calculateStatBoost signature) and shares GridUtils adjacency updates.
  • candour/towerpower#119: Updates upgrade logic in StallUpgradeManager and adds related guards/changes in MainViewModel's upgrade flow.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main refactoring work in StallUpgradeManager.kt, addressing both efficiency (caching via ConcurrentHashMap) and simplicity (fold operation replacing iterative loops).
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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-stall-upgrade-manager-7076087423520579259

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

github-actions Bot commented May 6, 2026

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/src/main/java/com/messark/hawker/utils/StallUpgradeManager.kt (1)

129-177: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Canonicalize all persisted stat metadata before recomputing upgrades.

This block only merges the Uncle aliases. Bak Kut Teh can still carry "Damage" metadata, but Line 165 recomputes its level from "Boost" only, so that saved boost level drops back to base on the next upgrade/copy. namingCategories has the same inconsistency because it still stores raw statName, which can let one logical stat count twice under mixed aliases.

Proposed fix
-        // Normalize aliases
-        listOf("Grab Rate", "Cleaning Time").forEach { alias ->
-            val canonical = getCanonicalStat(alias)
-            val level = max(mutableUpgrades.getOrDefault(alias, 0), mutableUpgrades.getOrDefault(canonical, 0))
+        // Normalize aliases before reading levels or legendary categories.
+        val aliasPairs = buildList {
+            add("Grab Rate" to "Rate")
+            add("Cleaning Time" to "Duration")
+            if (stall.stallType == StallType.BAK_KUT_TEH) add("Damage" to "Boost")
+        }
+        aliasPairs.forEach { (alias, canonical) ->
+            val level = max(
+                mutableUpgrades.getOrDefault(alias, 0),
+                mutableUpgrades.getOrDefault(canonical, 0)
+            )
             if (level > 0) {
                 mutableUpgrades[alias] = level
                 mutableUpgrades[canonical] = level
             }
         }
@@
-        val newNamingCategories = stall.namingCategories.toMutableList()
+        val newNamingCategories = stall.namingCategories
+            .map {
+                if (stall.stallType == StallType.BAK_KUT_TEH && it == "Damage") "Boost"
+                else getCanonicalStat(it)
+            }
+            .toMutableList()
@@
-        if (newLevelForStat == 10 && !stall.namingCategories.contains(statName)) {
+        if (newLevelForStat == 10 && !newNamingCategories.contains(canonicalStat)) {
             val legendaryCat = canonicalStat
-            if (stall.namingCategories.isEmpty()) {
+            if (newNamingCategories.isEmpty()) {
                 newSuffix = LegendaryNames.getRandomSuffix(legendaryCat)
-                newNamingCategories.add(statName)
+                newNamingCategories.add(canonicalStat)
             } else if (stall.namingCategories.size == 1) {
                 newPrefix = LegendaryNames.getRandomPrefix(legendaryCat)
-                newNamingCategories.add(statName)
+                newNamingCategories.add(canonicalStat)
             }
         }

As per coding guidelines, Use StallUpgradeManager to normalize stat aliasing mappings (e.g., 'Grab Rate' → 'Rate') upfront to prevent state-resetting bugs.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 8743c2c0-2159-4eb8-864e-9c8bbf815062

📥 Commits

Reviewing files that changed from the base of the PR and between 4d67159 and 49e4b73.

📒 Files selected for processing (4)
  • app/src/main/java/com/messark/hawker/MainViewModel.kt
  • app/src/main/java/com/messark/hawker/utils/GridUtils.kt
  • app/src/main/java/com/messark/hawker/utils/StallUpgradeManager.kt
  • fixes.md
💤 Files with no reviewable changes (1)
  • app/src/main/java/com/messark/hawker/utils/GridUtils.kt

@candour
Copy link
Copy Markdown
Owner Author

candour commented May 6, 2026

stall has type Stall? (from tile?.stall). The condition stall?.stallType == StallType.BAK_KUT_TEH uses a safe-call equality, which does not trigger Kotlin smart cast. As a result, both stall.disabledWaves (line 1223) and stall.damage (line 1224) are non-null member accesses on a nullable type, causing a compile error.

Add an explicit stall != null guard to enable smart cast for subsequent accesses

Also Canonicalize all persisted stat metadata before recomputing upgrades.

This block only merges the Uncle aliases. Bak Kut Teh can still carry "Damage" metadata, but Line 165 recomputes its level from "Boost" only, so that saved boost level drops back to base on the next upgrade/copy. namingCategories has the same inconsistency because it still stores raw statName, which can let one logical stat count twice under mixed aliases.

@google-labs-jules
Copy link
Copy Markdown
Contributor

stall has type Stall? (from tile?.stall). The condition stall?.stallType == StallType.BAK_KUT_TEH uses a safe-call equality, which does not trigger Kotlin smart cast. As a result, both stall.disabledWaves (line 1223) and stall.damage (line 1224) are non-null member accesses on a nullable type, causing a compile error.

Add an explicit stall != null guard to enable smart cast for subsequent accesses

Also Canonicalize all persisted stat metadata before recomputing upgrades.

This block only merges the Uncle aliases. Bak Kut Teh can still carry "Damage" metadata, but Line 165 recomputes its level from "Boost" only, so that saved boost level drops back to base on the next upgrade/copy. namingCategories has the same inconsistency because it still stores raw statName, which can let one logical stat count twice under mixed aliases.

I've implemented the requested changes:

  1. Fixed the compile error in calculateStatBoost by adding an explicit stall != null guard to enable smart casting.
  2. Generalized the getCanonicalStat function and improved stat normalization in applyUpgrade to handle all aliased and stall-specific stats (like 'Damage' vs 'Boost' for Bak Kut Teh).
  3. Updated the legendary naming logic to use canonical stat categories, preventing duplicate logical entries in namingCategories.

- Fixed compile error in calculateStatBoost with explicit null guard.
- Generalized stat normalization and canonicalization in StallUpgradeManager.
- Fixed inconsistent namingCategories logic by using canonical stat names.

Co-authored-by: candour <4670475+candour@users.noreply.github.com>
@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 6, 2026

Build Successful! 🚀

Download APK

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

@candour candour merged commit 142f5d4 into main May 7, 2026
3 checks passed
@candour candour deleted the refactor-stall-upgrade-manager-7076087423520579259 branch May 7, 2026 00:22
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