reworking chest event handler

This commit is contained in:
wartech0 2019-12-31 01:36:18 -06:00 committed by Jesse Plamondon-Willard
parent 1286a90ec2
commit 2894b43223
No known key found for this signature in database
GPG Key ID: CF8B1456B3E29F49
2 changed files with 80 additions and 1 deletions

View File

@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
using StardewModdingAPI.Enums;
using StardewModdingAPI.Events;
using StardewModdingAPI.Framework.StateTracking.FieldWatchers;
using StardewValley;
using ChangeType = StardewModdingAPI.Events.ChangeType;
using Chest = StardewValley.Objects.Chest;
namespace StardewModdingAPI.Framework.StateTracking
{
internal class ChestTracker
{
/*********
** Fields
*********/
/// <summary>The chest's inventory as of the last reset.</summary>
private IDictionary<Item, int> PreviousInventory;
/// <summary>The chest's inventory change as of the last update.</summary>
private IDictionary<Item, int> CurrentInventory;
/*********
** Accessors
*********/
/// <summary>The chest being tracked</summary>
public Chest Chest { get; }
/*********
** Public methods
*********/
public ChestTracker(Chest chest)
{
this.Chest = chest;
this.PreviousInventory = this.GetInventory();
}
public void Update()
{
this.CurrentInventory = this.GetInventory();
}
public void Reset()
{
this.PreviousInventory = this.CurrentInventory;
}
public IEnumerable<ItemStackChange> GetInventoryChanges()
{
IDictionary<Item, int> previous = this.PreviousInventory;
Console.WriteLine(previous.Count);
IDictionary<Item, int> current = this.GetInventory();
Console.WriteLine(current.Count);
foreach (Item item in previous.Keys.Union(current.Keys))
{
if (!previous.TryGetValue(item, out int prevStack))
yield return new ItemStackChange { Item = item, StackChange = item.Stack, ChangeType = ChangeType.Added };
else if (!current.TryGetValue(item, out int newStack))
yield return new ItemStackChange { Item = item, StackChange = -item.Stack, ChangeType = ChangeType.Removed };
else if (prevStack != newStack)
yield return new ItemStackChange { Item = item, StackChange = newStack - prevStack, ChangeType = ChangeType.StackChange };
}
}
/*********
** Private methods
*********/
private IDictionary<Item, int> GetInventory()
{
return this.Chest.items
.Where(n => n != null)
.Distinct()
.ToDictionary(n => n, n => n.Stack);
}
}
}

View File

@ -43,7 +43,7 @@ namespace StardewModdingAPI.Framework.StateTracking.Snapshots
foreach (LocationTracker locationWatcher in watcher.Locations)
{
if (!this.LocationsDict.TryGetValue(locationWatcher.Location, out LocationSnapshot snapshot))
this.LocationsDict[locationWatcher.Location] = snapshot = new LocationSnapshot(locationWatcher.Location);
this.LocationsDict[locationWatcher.Location] = snapshot = new LocationSnapshot(locationWatcher);
snapshot.Update(locationWatcher);
}