根据权重随机。
怪物死亡时掉落的物品有些掉落概率大一些有些概率小一些。
using System;
using System.Collections.Generic;
public class WeightedRandom<T>
{
private readonly Dictionary<T, int> m_items;
private readonly Random m_random = new Random();
private int m_totalWeight;
public WeightedRandom()
{
m_items = new Dictionary<T, int>();
}
public void Add(T item, int weight)
{
if (weight <= 0)
return;
m_totalWeight += weight;
if (m_items.ContainsKey(item))
m_items[item] += weight;
else
m_items.Add(item, weight);
}
public void Clear()
{
m_totalWeight = 0;
m_items.Clear();
}
public T Next()
{
if (m_totalWeight == 0)
throw new InvalidOperationException("Items is empty.");
var weight = m_random.Next(1, m_totalWeight + 1);
var counter = 0;
foreach (var item in m_items)
{
counter += item.Value;
if (counter >= weight)
return item.Key;
}
throw new InvalidOperationException();
}
public IEnumerable<T> Next(int count)
{
if (count <= 0)
throw new ArgumentOutOfRangeException("count");
for (var i = 0; i < count; i++)
yield return Next();
}
public void Remove(T item)
{
if (!m_items.ContainsKey(item))
return;
m_totalWeight -= m_items[item];
m_items.Remove(item);
}
}
0o0oo