Skip to content

Offense Stat Line Limitations - #306

Merged
AngeloTadeucci merged 5 commits into
MS2Community:masterfrom
Zintixx:statlines
Feb 9, 2025
Merged

Offense Stat Line Limitations#306
AngeloTadeucci merged 5 commits into
MS2Community:masterfrom
Zintixx:statlines

Conversation

@Zintixx

@Zintixx Zintixx commented Feb 9, 2025

Copy link
Copy Markdown
Collaborator

Needs testing/verification

Summary by CodeRabbit

  • New Features
    • Introduced configurable offense attribute management with a threshold to control item statistic options.
    • Added validation checks to ensure offense attribute limits aren’t exceeded during option generation.
  • Refactor
    • Updated key routines to accept additional parameters, enabling more precise handling of item options based on offense attributes.
    • Enhanced organization of offense attributes through new static lists for better management.

@coderabbitai

coderabbitai Bot commented Feb 9, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This pull request updates the offense attribute handling in the ItemStatsCalculator class. It introduces a new constant to define the offense line threshold and adds three static lists to categorize offense attributes. Method signatures for GetStaticOption and GetRandomOption are modified to include additional parameters for stats type and item type. A new private method, IsValidStat, is implemented to enforce the threshold, and the RandomItemOption method is revised to integrate validation checks for offense attributes before returning an option.

Changes

File Change Summary
Maple2.Server.Game/.../ItemStatsCalculator.cs • Introduced OFFENSE_LINE_MAX_THRESHOLD constant and offenseBasicAttributes, offenseSpecialAttributes, damageTypeAttributes lists.
• Updated GetStaticOption signature to include ItemStats.Type parameter.
• Updated GetRandomOption to add ItemType and ItemStats.Type parameters.
• Added IsValidStat method and integrated threshold checks.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant ISC as ItemStatsCalculator
    Caller->>ISC: GetStaticOption(item, job, statsType, pick)
    ISC-->>Caller: Return Option or Failure
Loading
sequenceDiagram
    participant Caller as Caller
    participant ISC as ItemStatsCalculator
    participant IV as IsValidStat
    Caller->>ISC: GetRandomOption(itemOption, itemType, statsType, count, presets)
    ISC->>IV: Validate offense stat count
    IV-->>ISC: Validity result
    ISC-->>Caller: Return random option
Loading

Possibly related PRs

  • Differentiate Random Stats by Random Make Type #302: The changes in the main PR are related to the modifications in the ItemStatsCalculator class, specifically the updates to the GetRandomOption method signature and its internal logic, which align with the changes made in the retrieved PR regarding randomization handling and type casting.
  • Fix: Stats #242: The changes in the main PR are related to the modifications in the ItemStatsCalculator class, specifically the updates to the GetStats and RandomizeValues methods, which also involve handling the MultiplyFactor introduced in the retrieved PR.

Suggested reviewers

  • AngeloTadeucci

Poem

I'm a rabbit with a joyful beat,
Hopping through the code, so neat.
New constants, lists, and checks in line,
Offense attributes now finely defined.
Carrots and code, together we cheer,
For these changes that make our app clear!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (1)

472-503: Prevent potential infinite loop when no valid stat can be added.
Because the code continues looping until statResult.Count + specialResult.Count == total, but skips offense stats when IsValidStat fails, there's a risk of never exiting if all candidates are invalid.

Consider adding a maximum iteration safeguard. For example:

 while (statResult.Count + specialResult.Count < total) {
+    const int maxAttempts = 1000;
+    int attempts = 0;
+
+    // ...
+    while (statResult.Count + specialResult.Count < total && attempts < maxAttempts) {
+        attempts++;
         ItemOption.Entry entry = option.Entries.Random();
         if (statsType == ItemStats.Type.Random
             && itemType.IsArmor
             && !IsValidStat(total, statResult, specialResult, entry)) {
             continue;
         }
         // ...
+    }
+    if (attempts >= maxAttempts) {
+       Log.Warning("Reached maximum iteration attempts while filling item stats.");
+       break;
+    }
 }

This ensures the code eventually exits, even if no valid offense attributes remain.

🧹 Nitpick comments (2)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (2)

365-373: Consider renaming or refactoring for clarity.
Invoking “RandomItemOption” from “GetStaticOption” could be confusing for future maintainers, as “RandomItemOption” is also used for truly random scenarios. A more neutral helper name (e.g., “GenerateItemOption”) could reduce confusion.


394-396: Simplify or remove the pass-through function.
GetRandomOption immediately delegates to RandomItemOption, adding a minor layer of indirection. If no extra logic is planned, consider removing it in favor of calling RandomItemOption directly.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5cbe0df and 6c1005a.

📒 Files selected for processing (1)
  • Maple2.Server.Game/Util/ItemStatsCalculator.cs (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (4)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (4)

88-90: Looks good.
Using the new parameter (ItemStats.Type.Static) on GetStaticOption appears consistent with the method signature update.


94-94: No issues found.
Passing ItemStats.Type.Random here matches the intended usage for random options.


139-139: No issues found.
The additional parameters for GetRandomOption appear consistent with the rest of the changes.


544-559: Confirm intended inequality for the offense line threshold.
The code uses “< OFFENSE_LINE_MAX_THRESHOLD,” allowing fewer than 50% offense stats but rejecting exactly 50%. This blocks one offense line on a 2-line item and two offense lines on a 4-line item, etc.

Is it your intention to disallow exactly 50% offense lines? If not, consider using “≤” to permit up to half the lines as offense lines.

Comment thread Maple2.Server.Game/Util/ItemStatsCalculator.cs

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (1)

556-583: Optimize the validation logic with early returns.

The method can be simplified for better readability:

 private static bool IsValidStat(ItemType itemType, int statLineCount, IDictionary<BasicAttribute, BasicOption> statDict, IDictionary<SpecialAttribute, SpecialOption> specialDict, ItemOption.Entry entry) {
-    if (itemType.IsAccessory) {
-        int currentElementalStats = specialDict.Keys.Count(stat => elementalDamageAttributes.Contains(stat));
-        if (entry.SpecialAttribute != null && elementalDamageAttributes.Contains((SpecialAttribute) entry.SpecialAttribute)) {
-            currentElementalStats++;
-        }
-        return currentElementalStats < 2;
-    }
+    // Early return for non-armor/accessory items
+    if (!itemType.IsArmor && !itemType.IsAccessory) {
+        return true;
+    }
 
-    if (itemType.IsArmor) {
-        int offenseStatCount = statDict.Keys.Count(stat => offenseBasicAttributes.Contains(stat));
-        offenseStatCount += specialDict.Keys.Count(stat => offenseSpecialAttributes.Contains(stat));
+    // Handle accessories
+    if (itemType.IsAccessory) {
+        int currentElementalStats = specialDict.Keys.Count(stat => elementalDamageAttributes.Contains(stat));
+        return !(entry.SpecialAttribute != null && 
+                elementalDamageAttributes.Contains((SpecialAttribute)entry.SpecialAttribute) && 
+                currentElementalStats >= 1);
+    }
 
-        if (entry.BasicAttribute != null && offenseBasicAttributes.Contains((BasicAttribute) entry.BasicAttribute)) {
-            offenseStatCount++;
-        } else if (entry.SpecialAttribute != null && offenseSpecialAttributes.Contains((SpecialAttribute) entry.SpecialAttribute)) {
-            offenseStatCount++;
-        }
+    // Handle armor
+    int offenseStatCount = statDict.Keys.Count(stat => offenseBasicAttributes.Contains(stat)) +
+                          specialDict.Keys.Count(stat => offenseSpecialAttributes.Contains(stat));
 
-        return (float) offenseStatCount / statLineCount <= OFFENSE_LINE_MAX_THRESHOLD;
+    if (entry.BasicAttribute != null && offenseBasicAttributes.Contains((BasicAttribute)entry.BasicAttribute)) {
+        offenseStatCount++;
+    } else if (entry.SpecialAttribute != null && offenseSpecialAttributes.Contains((SpecialAttribute)entry.SpecialAttribute)) {
+        offenseStatCount++;
     }
 
-    return true;
+    return (float)offenseStatCount / statLineCount <= OFFENSE_LINE_MAX_THRESHOLD;
 }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 63d4839 and cd3fe24.

📒 Files selected for processing (1)
  • Maple2.Server.Game/Util/ItemStatsCalculator.cs (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (2)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (2)

23-86: Use valid C# initialization syntax for offense attributes.

The current collection expression syntax ([...]) requires C# 12. For better compatibility, use standard collection initializers.


377-409: LGTM! Method signature changes are well-structured.

The addition of itemType and statsType parameters provides necessary context for offense line validation.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (2)

416-418: Consider reordering parameters for better readability.

The parameter order could be improved by grouping related parameters together. Consider moving count next to presets since they're both optional parameters.

-private ItemStats.Option GetRandomOption(ItemOption itemOption, in ItemType itemType, ItemStats.Type statsType, int count = -1, params LockOption[] presets)
+private ItemStats.Option GetRandomOption(ItemOption itemOption, in ItemType itemType, ItemStats.Type statsType, params LockOption[] presets, int count = -1)

565-590: Improve method documentation and readability.

  1. Add parameter documentation to explain the purpose of each parameter.
  2. Consider extracting the offense stat count calculation into a separate method for better readability.
     /// <summary>
     /// Verifies if the new attribute being added meets the offense line threshold.
     /// </summary>
+    /// <param name="itemType">The type of item being validated</param>
+    /// <param name="statLineCount">Total number of stat lines</param>
+    /// <param name="statDict">Dictionary of basic attributes</param>
+    /// <param name="specialDict">Dictionary of special attributes</param>
+    /// <param name="entry">The new entry being validated</param>
+    /// <returns>True if the stat is valid according to offense line limitations</returns>
     private static bool IsValidStat(ItemType itemType, int statLineCount, IDictionary<BasicAttribute, BasicOption> statDict, IDictionary<SpecialAttribute, SpecialOption> specialDict, ItemOption.Entry entry) {
         int damageTypeStatCount = specialDict.Keys.Count(stat => damageTypeAttributes.Contains(stat));
         if (entry.SpecialAttribute != null && damageTypeAttributes.Contains((SpecialAttribute) entry.SpecialAttribute)) {
             return damageTypeStatCount < 1;
         }

         if (!itemType.IsCombatPet && !itemType.IsWeapon && !itemType.IsAccessory) {
-            int offenseStatCount = statDict.Keys.Count(stat => offenseBasicAttributes.Contains(stat));
-            offenseStatCount += specialDict.Keys.Count(stat => offenseSpecialAttributes.Contains(stat));
-
-            if (entry.BasicAttribute != null && offenseBasicAttributes.Contains((BasicAttribute) entry.BasicAttribute)) {
-                offenseStatCount++;
-            } else if (entry.SpecialAttribute != null && offenseSpecialAttributes.Contains((SpecialAttribute) entry.SpecialAttribute)) {
-                offenseStatCount++;
-            }
+            int offenseStatCount = CalculateOffenseStatCount(statDict, specialDict, entry);
+            return (float)offenseStatCount / statLineCount <= OFFENSE_LINE_MAX_THRESHOLD;
         }

         return true;
     }

+    private static int CalculateOffenseStatCount(
+        IDictionary<BasicAttribute, BasicOption> statDict,
+        IDictionary<SpecialAttribute, SpecialOption> specialDict,
+        ItemOption.Entry entry)
+    {
+        int count = statDict.Keys.Count(stat => offenseBasicAttributes.Contains(stat));
+        count += specialDict.Keys.Count(stat => offenseSpecialAttributes.Contains(stat));
+
+        if (entry.BasicAttribute != null && offenseBasicAttributes.Contains((BasicAttribute)entry.BasicAttribute))
+        {
+            count++;
+        }
+        else if (entry.SpecialAttribute != null && offenseSpecialAttributes.Contains((SpecialAttribute)entry.SpecialAttribute))
+        {
+            count++;
+        }
+
+        return count;
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cd3fe24 and 1937826.

📒 Files selected for processing (1)
  • Maple2.Server.Game/Util/ItemStatsCalculator.cs (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (1)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (1)

23-95: Add XML documentation for attribute lists.

Consider adding XML documentation to explain the purpose and usage of each list, especially the distinction between offenseBasicAttributes, offenseSpecialAttributes, and damageTypeAttributes.

Comment thread Maple2.Server.Game/Util/ItemStatsCalculator.cs Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (2)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (2)

22-22: Consider making the threshold configurable.

The offense line threshold is currently hardcoded. Consider making it configurable through game settings or configuration files for easier tuning.


571-574: Document the damage type attribute limitation.

Add a comment explaining why only one damage type attribute is allowed per item. This will help future maintainers understand the game design decision.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1937826 and 13f7169.

📒 Files selected for processing (1)
  • Maple2.Server.Game/Util/ItemStatsCalculator.cs (8 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (3)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (3)

23-40: LGTM! Well-organized attribute categorization.

The attributes are logically grouped into offense basic attributes, offense special attributes, and damage type attributes. The categorization appears comprehensive and accurate.

Also applies to: 41-78, 79-95


386-418: LGTM! Method signature changes are consistent.

The addition of ItemStats.Type and ItemType parameters enables proper validation of offense attributes. All callers have been updated accordingly.


565-590: ⚠️ Potential issue

Fix the logical condition for item type validation.

The condition itemType is { IsCombatPet: false, IsWeapon: false, IsAccessory: false } is incorrect. It will skip offense line validation for items that should have it applied.

Apply this fix:

-        if (itemType is { IsCombatPet: false, IsWeapon: false, IsAccessory: false }) {
+        if (!itemType.IsCombatPet && !itemType.IsWeapon && !itemType.IsAccessory) {

Additionally, consider adding a comment explaining which item types should have offense line validation applied.

Likely invalid or redundant comment.

@AngeloTadeucci AngeloTadeucci left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM

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.

3 participants