WXMC/.svn/pristine/cf/cfdc623aa1f3229a5628bf993693caa41472007d.svn-base
2024-12-04 16:18:46 +08:00

85 lines
2.3 KiB
Plaintext

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)
{
// 计算总权重
float totalWeight = list.Sum(x => x.Weight);
// 根据总权重随机选择一个值
float randomPoint = Random.Range(0, totalWeight);
// 根据随机值选择项目
float currentPoint = 0f;
foreach (var item in list)
{
currentPoint += item.Weight;
if (randomPoint <= currentPoint)
{
return item;
}
}
throw new System.Exception($"Nothing to chose from");
}
}