WXMC/.svn/pristine/cf/cfdc623aa1f3229a5628bf993693caa41472007d.svn-base

85 lines
2.3 KiB
Plaintext
Raw Normal View History

2024-12-04 16:18:46 +08:00
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
[CreateAssetMenu(fileName = "GrantPool", menuName = "ScriptableObject/NodeGrantPool", order = 1)]
public class NodeGrantPool : ScriptableObject
{
public List<PHomePush.NodeChoseItem> AllItems;
public Sprite DesImage;
public PHomePush.NodeChoseItem GetOneItemRandom()
{
return GetOneItemRandomFromList(AllItems);
}
public IEnumerable<PHomePush.NodeChoseItem> GetItemsRandom(int count = 1, bool allowRepeat = false)
{
if (count <= 0)
{
yield break;
}
if (allowRepeat)
{
for (int i = 0; i < count; i++)
{
yield return GetOneItemRandom();
}
}
else
{
if (AllItems.Count < count)
{
throw new System.Exception($"Item pool only contains {AllItems.Count} items, but trying to get {count}");
}
if (count == 1)
{
yield return GetOneItemRandom();
yield break;
}
else if (count == AllItems.Count)
{
foreach (var item in AllItems)
{
yield return item;
}
yield break;
}
List<PHomePush.NodeChoseItem> availableItems = new List<PHomePush.NodeChoseItem>(AllItems);
for (int i = 0; i < count; i++)
{
var item = GetOneItemRandomFromList(availableItems);
availableItems.Remove(item);
yield return item;
}
}
}
public static PHomePush.NodeChoseItem GetOneItemRandomFromList(List<PHomePush.NodeChoseItem> list)
{
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ȩ<EFBFBD><C8A8>
float totalWeight = list.Sum(x => x.Weight);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ȩ<EFBFBD><C8A8><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1>һ<EFBFBD><D2BB>ֵ
float randomPoint = Random.Range(0, totalWeight);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ֵѡ<D6B5><D1A1><EFBFBD><EFBFBD>Ŀ
float currentPoint = 0f;
foreach (var item in list)
{
currentPoint += item.Weight;
if (randomPoint <= currentPoint)
{
return item;
}
}
throw new System.Exception($"Nothing to chose from");
}
}