Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- namespace NovaEngineFramework.Framework.Probability
- {
- public class LootTable
- {
- private readonly List<string> _lootTable;
- private readonly Dictionary<string , uint> _cachedLoot;
- private readonly Random _rngInstance;
- private bool _isRebuildRequired;
- public LootTable()
- {
- _rngInstance = new Random();
- _cachedLoot = new Dictionary<string , uint>();
- _lootTable = new List<string>();
- }
- public LootTable( Random random )
- {
- this._rngInstance = random;
- _cachedLoot = new Dictionary<string , uint>();
- _lootTable = new List<string>();
- }
- public void AddLoot( uint probability , string name )
- {
- if( !_cachedLoot.ContainsKey( name ) )
- {
- this._cachedLoot.Add( name , probability );
- _isRebuildRequired = true;
- }
- else
- {
- throw new Exception( "Item: " + name + " Already Exists!" );
- }
- }
- public void DeleteLoot( string name )
- {
- if( _cachedLoot.ContainsKey( name ) )
- {
- this._cachedLoot.Remove( name );
- _isRebuildRequired = true;
- }
- else
- {
- throw new Exception( "Item: " + name + " Did not exist!" );
- }
- }
- public double CalculateProbability( string name )
- {
- if( _cachedLoot.ContainsKey( name ) )
- {
- double total = _cachedLoot.Values.Sum( n => ( int )n );
- double percent = _cachedLoot[ name ] / total;
- return Math.Round( percent * 100 , 2 );
- }
- throw new Exception( "Item: " + name + " Does not exist." );
- }
- public uint CheckRarity( string name )
- {
- if( _cachedLoot.ContainsKey( name ) )
- {
- return _cachedLoot[ name ];
- }
- throw new Exception( "Item: " + name + " Does not exist." );
- }
- public List<string> CheckLoot()
- {
- return this._cachedLoot.Keys.ToList();
- }
- public void EditLoot( string name , uint newProbability )
- {
- if( _cachedLoot.ContainsKey( name ) )
- {
- this._cachedLoot[ name ] = newProbability;
- _isRebuildRequired = true;
- }
- else
- {
- throw new Exception( "Item: " + name + " Does not exist." );
- }
- }
- public void ClearAllLoot()
- {
- this._cachedLoot.Clear();
- this._isRebuildRequired = true;
- }
- private void Build()
- {
- _lootTable.Clear();
- foreach( KeyValuePair<string , uint> pair in _cachedLoot )
- {
- for( int i = 0; i < pair.Value; i++ )
- {
- _lootTable.Add( pair.Key );
- }
- }
- _isRebuildRequired = false;
- }
- public string NextRandomItem()
- {
- if( !_isRebuildRequired )
- {
- return _lootTable[ _rngInstance.Next( _lootTable.Count ) ];
- }
- this.Build(); // A rebuild is needed, let's go ahead and take care of it!
- return _lootTable[ _rngInstance.Next( _lootTable.Count ) ];
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment