Inventory
Each use picks up a random item. It goes into the player's bag (a List<string>), its points go into the player's
score (a Dictionary<string, int>) and its count into a tally. The label shows the bag, the item counts and the top
three players. The state is local to each player. See Lists and dictionaries.
Inventory.cs
using System.Collections.Generic;
using StageTime.SDK;
using TMPro;
using UnityEngine;
/// <summary>
/// An inventory and a leaderboard kept in a List and Dictionaries. Each use picks up a random item: it goes into the
/// player's bag (List<string>), its points into the player's score (Dictionary<string, int>) and its count
/// into a tally (Dictionary<string, int>). The label shows the bag, the item counts and the top three players.
/// The state is local to each player (Guestbook shows a [Synced, MaxLength] list shared by everyone).
/// </summary>
public class Inventory : StageTimeBehaviour
{
public TMP_Text label;
public int maxBagSize = 8;
private readonly string[] itemNames = { "Apple", "Gem", "Key", "Coin", "Map" };
private readonly int[] itemPoints = { 1, 5, 3, 2, 4 };
private List<string> bag = new List<string>();
private Dictionary<string, int> tally = new Dictionary<string, int>();
private Dictionary<string, int> scores = new Dictionary<string, int>();
private void Start() => Refresh();
public override void Interact()
{
int pick = Random.Range(0, itemNames.Length);
string item = itemNames[pick];
// The bag keeps the newest items: drop the oldest when it is full.
if (bag.Count >= maxBagSize) bag.RemoveAt(0);
bag.Add(item);
tally.TryGetValue(item, out int count);
tally[item] = count + 1;
string player = Networking.LocalPlayer != null ? Networking.LocalPlayer.displayName : "Player";
if (!scores.ContainsKey(player)) scores.Add(player, 0);
scores[player] += itemPoints[pick];
Refresh();
}
/// <summary>Empties the bag but keeps the scores.</summary>
public void ClearBag()
{
bag.Clear();
tally.Clear();
Refresh();
}
private void Refresh()
{
if (label == null) return;
string text = $"Bag ({bag.Count}/{maxBagSize}): ";
for (int i = 0; i < bag.Count; i++) text += (i > 0 ? ", " : "") + bag[i];
var names = new List<string>(tally.Count);
foreach (string name in tally.Keys) names.Add(name);
names.Sort();
text += "\nFound:";
foreach (string name in names) text += $" {name} x{tally[name]}";
text += "\nTop players:";
List<string> top = TopPlayers(3);
for (int i = 0; i < top.Count; i++) text += $"\n{i + 1}. {top[i]} - {scores[top[i]]}";
if (top.Count == 0) text += " none yet";
label.text = text;
}
/// <summary>The players with the highest scores, best first.</summary>
private List<string> TopPlayers(int count)
{
var top = new List<string>();
foreach (var entry in scores)
{
int at = 0;
while (at < top.Count && scores[top[at]] >= entry.Value) at++;
if (at < count) top.Insert(at, entry.Key);
if (top.Count > count) top.RemoveAt(count);
}
return top;
}
}