From e64a1220e309e8fc83e20833b8849de1721ec469 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Wed, 1 Jan 2020 18:52:24 -0500 Subject: unify item diff logic for players & chests --- src/SMAPI/Framework/SnapshotItemListDiff.cs | 66 +++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/SMAPI/Framework/SnapshotItemListDiff.cs (limited to 'src/SMAPI/Framework/SnapshotItemListDiff.cs') diff --git a/src/SMAPI/Framework/SnapshotItemListDiff.cs b/src/SMAPI/Framework/SnapshotItemListDiff.cs new file mode 100644 index 00000000..e8ab1b1e --- /dev/null +++ b/src/SMAPI/Framework/SnapshotItemListDiff.cs @@ -0,0 +1,66 @@ +using System.Collections.Generic; +using System.Linq; +using StardewModdingAPI.Events; +using StardewValley; + +namespace StardewModdingAPI.Framework +{ + /// A snapshot of a tracked item list. + internal class SnapshotItemListDiff + { + /********* + ** Accessors + *********/ + /// Whether the item list changed. + public bool IsChanged { get; } + + /// The removed values. + public Item[] Removed { get; } + + /// The added values. + public Item[] Added { get; } + + /// The items whose stack sizes changed. + public ItemStackSizeChange[] QuantityChanged { get; } + + + /********* + ** Public methods + *********/ + /// Update the snapshot. + /// The added values. + /// The removed values. + /// The items whose stack sizes changed. + public SnapshotItemListDiff(Item[] added, Item[] removed, ItemStackSizeChange[] sizesChanged) + { + this.Removed = removed; + this.Added = added; + this.QuantityChanged = sizesChanged; + + this.IsChanged = removed.Length > 0 || added.Length > 0 || sizesChanged.Length > 0; + } + + /// Get a snapshot diff if anything changed in the given data. + /// The added item stacks. + /// The removed item stacks. + /// The items with their previous stack sizes. + /// The inventory changes, or null if nothing changed. + /// Returns whether anything changed. + public static bool TryGetChanges(ISet added, ISet removed, IDictionary stackSizes, out SnapshotItemListDiff changes) + { + KeyValuePair[] sizesChanged = stackSizes.Where(p => p.Key.Stack != p.Value).ToArray(); + if (sizesChanged.Any() || added.Any() || removed.Any()) + { + changes = new SnapshotItemListDiff( + added: added.ToArray(), + removed: removed.ToArray(), + sizesChanged: sizesChanged.Select(p => new ItemStackSizeChange(p.Key, p.Value, p.Key.Stack)).ToArray() + ); + return true; + } + + changes = null; + return false; + } + } +} -- cgit