Skip to content

Roll-max multiple item fix - #495

Merged
AngeloTadeucci merged 1 commit into
MS2Community:masterfrom
Dreary:rollmax
Jun 18, 2025
Merged

Roll-max multiple item fix#495
AngeloTadeucci merged 1 commit into
MS2Community:masterfrom
Dreary:rollmax

Conversation

@Dreary

@Dreary Dreary commented Jun 18, 2025

Copy link
Copy Markdown
Contributor

Fixes it so roll-max applies to multiple items rather than just 1

Summary by CodeRabbit

  • Refactor
    • Improved item handling logic for better clarity and extended functionality when processing items.
    • Enhanced error handling and messaging during item creation and processing.

Fixes it so roll-max applies to multiple items rather than just 1
@coderabbitai

coderabbitai Bot commented Jun 18, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The Handle method in ItemCommand.cs was refactored to clarify item handling logic and extend its capabilities. A new helper method, ProcessSingleItem, was introduced to encapsulate item processing, including inventory addition and item dropping, with improved error handling and exit code management.

Changes

File(s) Change Summary
Maple2.Server.Game/Commands/ItemCommand.cs Refactored item handling logic in Handle; added ProcessSingleItem helper; improved error handling.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ItemCommand
    participant ItemFactory
    participant Inventory
    participant World

    User->>ItemCommand: Invoke Handle()
    ItemCommand->>ItemFactory: Create Item(s)
    alt Item is currency
        ItemCommand->>Inventory: Add currency
    else Non-currency
        alt Non-stackable or rollMax
            loop For each item
                ItemCommand->>ItemFactory: Create Item
                ItemCommand->>ItemCommand: ProcessSingleItem()
            end
        else
            ItemCommand->>ItemCommand: ProcessSingleItem()
        end
    end
    ItemCommand->>User: Set exit code (0 or 1)
Loading

Possibly related PRs

  • AngeloTadeucci/Maple2#242: Refactors item creation and processing logic in ItemCommand.cs and introduces a helper method, overlapping with changes to the Handle method and command options in this PR.

Poem

A hop and a skip, a refactor anew,
With ProcessSingleItem, our logic grew!
Stackable, non-stackable, handled with care,
Errors are caught, no bugs to spare.
In inventories or on the ground,
Every item finds its place, safe and sound!
🥕

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @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: 4

🧹 Nitpick comments (1)
Maple2.Server.Game/Commands/ItemCommand.cs (1)

59-64: SlotMax == 0 path clamps only the lower bound.

Math.Clamp(amount, 1, int.MaxValue) does nothing except force a minimum of 1.
If the caller mistakenly passes a negative value the earlier check already covers it; otherwise the call is redundant.
You can drop the clamp (or clamp to a reasonable upper bound, e.g. player inventory slots).

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c180183 and 41e2192.

📒 Files selected for processing (1)
  • Maple2.Server.Game/Commands/ItemCommand.cs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: format
  • GitHub Check: build
  • GitHub Check: build

Comment on lines +91 to +98
if (drop && session.Field != null) {
FieldItem fieldItem = session.Field.SpawnItem(session.Player, item);
session.Field.Broadcast(FieldPacket.DropItem(fieldItem));
} else if (!session.Item.Inventory.Add(item, true)) {
session.Item.Inventory.Discard(item);
ctx.Console.Error.WriteLine($"Failed to add item:{item.Id} to inventory");
ctx.ExitCode = 1;
}

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.

🛠️ Refactor suggestion

Early-exit after inventory failure to prevent partial success confusion.

If adding to inventory fails, the command keeps processing subsequent items, producing a mix of success & failure with a single exit code.
Consider aborting once an error is detected.

-            session.Item.Inventory.Discard(item);
-            ctx.Console.Error.WriteLine($"Failed to add item:{item.Id} to inventory");
-            ctx.ExitCode = 1;
+            session.Item.Inventory.Discard(item);
+            ctx.Console.Error.WriteLine($"Failed to add item:{item.Id} to inventory");
+            ctx.ExitCode = 1;
+            return; // stop further processing
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (drop && session.Field != null) {
FieldItem fieldItem = session.Field.SpawnItem(session.Player, item);
session.Field.Broadcast(FieldPacket.DropItem(fieldItem));
} else if (!session.Item.Inventory.Add(item, true)) {
session.Item.Inventory.Discard(item);
ctx.Console.Error.WriteLine($"Failed to add item:{item.Id} to inventory");
ctx.ExitCode = 1;
}
if (drop && session.Field != null) {
FieldItem fieldItem = session.Field.SpawnItem(session.Player, item);
session.Field.Broadcast(FieldPacket.DropItem(fieldItem));
} else if (!session.Item.Inventory.Add(item, true)) {
session.Item.Inventory.Discard(item);
ctx.Console.Error.WriteLine($"Failed to add item:{item.Id} to inventory");
ctx.ExitCode = 1;
return; // stop further processing
}
🤖 Prompt for AI Agents
In Maple2.Server.Game/Commands/ItemCommand.cs around lines 91 to 98, after
failing to add an item to the inventory, the code continues processing further
items, causing mixed success and failure states. To fix this, add an early exit
(e.g., return or break) immediately after setting the error exit code and
logging the failure to stop further processing and avoid partial success
confusion.

Comment on lines +47 to +48
Item? firstItem = session.Field.ItemDrop.CreateItem(itemId, rarity, rollMax: rollMax);
if (firstItem == null) {

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.

⚠️ Potential issue

Possible NullReferenceException when session.Field is null.

session.Field.ItemDrop.CreateItem(...) dereferences session.Field unconditionally.
While the command is usually executed in-field, a GM can trigger it from a lobby / loading screen, making session.Field null and crashing the server.

+if (session.Field == null) {
+    ctx.Console.Error.WriteLine("Cannot spawn items: player is not in a field.");
+    ctx.ExitCode = 1;
+    return;
+}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Item? firstItem = session.Field.ItemDrop.CreateItem(itemId, rarity, rollMax: rollMax);
if (firstItem == null) {
if (session.Field == null) {
ctx.Console.Error.WriteLine("Cannot spawn items: player is not in a field.");
ctx.ExitCode = 1;
return;
}
Item? firstItem = session.Field.ItemDrop.CreateItem(itemId, rarity, rollMax: rollMax);
if (firstItem == null) {
🤖 Prompt for AI Agents
In Maple2.Server.Game/Commands/ItemCommand.cs around lines 47 to 48, the code
accesses session.Field without checking if it is null, which can cause a
NullReferenceException when the command is triggered outside a field context.
Add a null check for session.Field before accessing ItemDrop.CreateItem, and
handle the case where session.Field is null gracefully, such as by returning
early or sending an error message to prevent the server crash.

Comment on lines +53 to 56
if (firstItem.IsCurrency()) {
firstItem.Amount = amount;
ProcessSingleItem(ctx, firstItem, drop);
return;

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.

⚠️ Potential issue

Validate amount for currency items.

firstItem.Amount = amount; accepts negative or zero values, silently minting / removing mesos.
Add a sanity-check to reject non-positive amounts.

-if (firstItem.IsCurrency()) {
-    firstItem.Amount = amount;
+if (firstItem.IsCurrency()) {
+    if (amount <= 0) {
+        ctx.Console.Error.WriteLine("Amount must be positive.");
+        ctx.ExitCode = 1;
+        return;
+    }
+    firstItem.Amount = amount;
🤖 Prompt for AI Agents
In Maple2.Server.Game/Commands/ItemCommand.cs around lines 53 to 56, the
assignment of amount to firstItem.Amount allows zero or negative values, which
can incorrectly mint or remove currency. Add a validation check before this
assignment to ensure amount is positive, and reject or handle cases where amount
is zero or negative to prevent unintended currency manipulation.

Comment on lines +66 to +78
if (isNonStackable || (rollMax && amount > 1)) {
ProcessSingleItem(ctx, firstItem, drop);

for (int i = 1; i < amount; i++) {
Item? additionalItem = session.Field.ItemDrop.CreateItem(itemId, rarity, rollMax: rollMax);
if (additionalItem == null) {
ctx.Console.Error.WriteLine($"Failed to create additional item {i + 1}/{amount}");
continue;
}

ProcessSingleItem(ctx, additionalItem, drop);
}
} else {

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.

⚠️ Potential issue

Error propagation from ProcessSingleItem is lost.

When ProcessSingleItem sets ctx.ExitCode = 1, it is overwritten by the unconditional
ctx.ExitCode = 0 at line 83.
A batch spawn in which a single item fails still reports success.

-            ctx.ExitCode = 0;
+            // Preserve a non-zero exit code set by ProcessSingleItem
+            if (ctx.ExitCode == 0)
+                ctx.ExitCode = 0; // success only if no previous failure

Or simply delete line 83 and rely on the default exit code (0) unless an error was signalled.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In Maple2.Server.Game/Commands/ItemCommand.cs around lines 66 to 78, the exit
code set by ProcessSingleItem to indicate failure is overwritten later by an
unconditional ctx.ExitCode = 0 at line 83, causing errors to be ignored. To fix
this, modify the code to preserve any non-zero exit code set by
ProcessSingleItem by only setting ctx.ExitCode to 0 if it is not already an
error code, or remove the line 83 assignment entirely to rely on the default
exit code unless an error occurs.

@AngeloTadeucci
AngeloTadeucci merged commit 875ea2a into MS2Community:master Jun 18, 2025
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