using System;
using System.Collections.Generic;
using System.Linq;
namespace StardewModdingAPI.Utilities
{
/// Manages a separate value for each player in split-screen mode. This can safely be used in non-split-screen mode too, it'll just have a single state in that case.
/// The state class.
public class PerScreen
{
/*********
** Fields
*********/
/// Create the initial value for a player.
private readonly Func CreateNewState;
/// The tracked values for each player.
private readonly IDictionary States = new Dictionary();
/// The last value for which this instance was updated.
private int LastRemovedScreenId;
/*********
** Accessors
*********/
/// The value for the current player.
/// The value is initialized the first time it's requested for that player, unless it's set manually first.
public T Value
{
get
{
this.RemoveDeadPlayers();
return this.States.TryGetValue(Context.ScreenId, out T state)
? state
: this.States[Context.ScreenId] = this.CreateNewState();
}
set
{
this.RemoveDeadPlayers();
this.States[Context.ScreenId] = value;
}
}
/*********
** Public methods
*********/
/// Construct an instance.
public PerScreen()
: this(null) { }
/// Construct an instance.
/// Create the initial state for a player screen.
public PerScreen(Func createNewState)
{
this.CreateNewState = createNewState ?? (() => default);
}
/*********
** Private methods
*********/
/// Remove players who are no longer have a split-screen index.
/// Returns whether any players were removed.
private void RemoveDeadPlayers()
{
if (this.LastRemovedScreenId == Context.LastRemovedScreenId)
return;
this.LastRemovedScreenId = Context.LastRemovedScreenId;
foreach (int id in this.States.Keys.ToArray())
{
if (!Context.HasScreenId(id))
this.States.Remove(id);
}
}
}
}