Exemple #1
0
        /// <summary>
        /// Loads all the bean information by the given configuration class.
        /// </summary>
        /// <param name="configType">Configuration class.</param>
        private void LoadConfigurationClass(Type configType)
        {
            if (configurationInstances.ContainsKey(configType))
            {
                return;                                                 // Already loaded.
            }
            configType
            .GetMethods()
            .ToList()
            .ForEach(x =>
            {
                BeanAttribute beanAttr       = x.GetCustomAttribute <BeanAttribute>();
                PrimaryAttribute primaryAttr = x.GetCustomAttribute <PrimaryAttribute>();

                if (beanAttr == null)
                {
                    return;
                }

                if (!beanInfo.ContainsKey(x.ReturnType))
                {
                    beanInfo.Add(x.ReturnType, new TypeContainer(this, x.ReturnType));
                }

                string beanName = beanAttr.Name ?? x.Name;

                beanInfo[x.ReturnType].AddBean(beanName, x, primaryAttr != null, beanAttr.InitMethod);
            });

            object configInstance = Activator.CreateInstance(configType);

            configurationInstances.Add(configType, configInstance);

            // TODO: Add beans declared as properties.
        }
        public void PrimaryAttribute_Correctly_Increases_With_Float_When_Type_Is_Float(float inc)
        {
            _mockAttr = Substitute.ForPartsOf <PrimaryAttribute>(AttributeType.Float, _dfValue);
            _mockAttr.Increase(inc);

            Assert.AreEqual(inc + _dfValue, _mockAttr.CurrentValue);
        }
Exemple #3
0
 void CreatePrimaryAttribute()
 {
     priAttributes = new PrimaryAttribute[(int)PrimaryAttributeName.Count];
     for (int i = 0; i < priAttributes.Length; i++)
     {
         priAttributes[i] = new PrimaryAttribute((PrimaryAttributeName)i);
     }
 }
        public void PrimaryAttribute_Correctly_Decreases_With_Float_When_Type_Is_Integer(int startingVal, float dec, int expected)
        {
            _mockAttr = Substitute.ForPartsOf <PrimaryAttribute>(AttributeType.Integer, _dfValue);
            _mockAttr.Increase(startingVal - _dfValue);

            _mockAttr.Decrease(dec);
            Assert.AreEqual((float)expected, _mockAttr.CurrentValue);
        }
        public void PrimaryAttribute_Correctly_Decreases_With_Float_When_Type_Is_Float(float startingVal, float dec, float expected)
        {
            _mockAttr = Substitute.ForPartsOf <PrimaryAttribute>(AttributeType.Float, _dfValue);
            _mockAttr.Increase(startingVal - _dfValue);

            _mockAttr.Decrease(dec);
            // Need to check range instead of value since there's floating point imprecision
            Assert.IsTrue(InRange(_mockAttr.CurrentValue, expected));
        }
Exemple #6
0
 /// <summary>
 /// Gets the primary attribute if present.
 /// </summary>
 /// <returns>The primary attribute if present.</returns>
 public PrimaryAttribute GetPrimaryAttribute()
 {
     if (m_isPrimaryAttributeWasSet)
     {
         return(m_primaryAttribute);
     }
     m_isPrimaryAttributeWasSet = true;
     return(m_primaryAttribute = PropertyInfo.GetCustomAttribute(typeof(PrimaryAttribute)) as PrimaryAttribute);
 }
Exemple #7
0
 /// <summary>
 /// Gets the <see cref="PrimaryAttribute"/> if present.
 /// </summary>
 /// <returns>The instance of <see cref="PrimaryAttribute"/>.</returns>
 public PrimaryAttribute GetPrimaryAttribute()
 {
     if (m_isPrimaryAttributeWasSet)
     {
         return(m_primaryAttribute);
     }
     m_isPrimaryAttributeWasSet = true;
     return(m_primaryAttribute = PropertyInfo.GetCustomAttribute <PrimaryAttribute>() ??
                                 (PropertyInfo.GetCustomAttribute <KeyAttribute>() != null ? new PrimaryAttribute() : null));
 }
 public void AddRatio(PrimaryAttribute attr, float ratio)
 {
     if (sourceRatio.ContainsKey(attr))
     {
         sourceRatio[attr] += ratio;
     }
     else
     {
         sourceRatio.Add(attr, ratio);
     }
 }
Exemple #9
0
        public void SerializationTest()
        {
            Assert.IsTrue(typeof(PrimaryAttribute).IsSerializable);
            Assert.IsTrue(typeof(SecondaryAttribute).IsSerializable);
            Assert.IsTrue(typeof(VolumeAttribute).IsSerializable);

            var random = new Random();

            // Serialize a PrimaryAttribute
            Body.Value    = random.Next(10, 500);
            Body.MinValue = random.Next(0, 9);
            Body.MaxValue = random.Next(501, 999);
            Body.AddModifier(new TimeBasedModifier("Test", 10, 10));
            BinarySerialize(Body);

            // Binary deserialization of PrimaryAttribute
            PrimaryAttribute binarySerializedBody = (PrimaryAttribute)BinaryDeserialize(Body);

            Assert.AreEqual(Body.Value, binarySerializedBody.Value);
            Assert.AreEqual(Body.MinValue, binarySerializedBody.MinValue);
            Assert.AreEqual(Body.MaxValue, binarySerializedBody.MaxValue);
            PrimaryAttributeTest(binarySerializedBody);

            // Serialize a SecondaryAttribute
            Experience.Value = 100;
            BinarySerialize(Level);

            // Binary deserialization of SecondaryAttribute
            SecondaryAttribute binarySerializedLevel = (SecondaryAttribute)BinaryDeserialize(Level);

            Assert.AreEqual(Level.Value, binarySerializedLevel.Value);
            Assert.AreEqual(1, binarySerializedLevel.Attributes.Length);
            Experience.Value = 0;
            binarySerializedLevel.Attributes = new BaseAttribute[] { Experience };
            binarySerializedLevel.Value      = binarySerializedLevel.MaxValue;
            SecondaryAttributeTest(binarySerializedLevel);

            // Serialize a VolumeAttribute
            Body.MinValue = 0;
            Body.MaxValue = 999;
            Body.Value    = 0;
            Life.Value    = random.Next(0, 23);
            BinarySerialize(Life);

            // Binary deserialization of VolumeAttribute
            VolumeAttribute binarySerializedLife = (VolumeAttribute)BinaryDeserialize(Life);

            Assert.AreEqual(Life.Value, binarySerializedLife.Value);
            Assert.AreEqual(2, binarySerializedLife.Attributes.Length);
            Body.Value = 0;
            binarySerializedLife.Attributes = new BaseAttribute[] { Level, Body };
            binarySerializedLife.Value      = binarySerializedLife.MaxValue;
            VolumeTest(binarySerializedLife);
        }
        public void ExecFilter()
        {
            //フィルターに値をセット
            PrimaryAttribute att = new PrimaryAttribute();

            //filter.set

            //フィルターを実行
            System.Windows.Forms.ListView.ListViewItemCollection col = heroListView.Items;
            //filter.ExecFilter();
        }
 public void RemoveRatio(PrimaryAttribute attr, float ratio)
 {
     if (sourceRatio.ContainsKey(attr))
     {
         if (sourceRatio[attr] > ratio)
         {
             sourceRatio[attr] -= ratio;
         }
         else
         {
             sourceRatio.Remove(attr);
         }
     }
 }
Exemple #12
0
        private void PrimaryAttributeTest(PrimaryAttribute attr)
        {
            GameTime.time = 0;
            // Set some values
            attr.Value = attr.MinValue;
            Assert.AreEqual(attr.Value, attr.MinValue);
            attr.Value = float.MaxValue;
            Assert.AreEqual(attr.Value, attr.MaxValue);
            attr.Value = float.MinValue;
            Assert.AreEqual(attr.Value, attr.MinValue);

            // Add a modifier
            attr.AddModifier(new TimeBasedModifier("StrengthBuff", 10, 10));
            Assert.AreEqual(attr.MinValue + 10, attr.Value);

            attr.BaseValue += 1;
            Assert.AreEqual(attr.MinValue + 11, attr.Value);
            attr.BaseValue -= 1;

            // Advance in time
            for (int i = 0; i < 10; i++)
            {
                GameTime.time = i;
                Assert.AreEqual(attr.MinValue + 10, attr.Value);
            }
            // Until the modifier's life cycle is over
            GameTime.time += 1;
            Assert.AreEqual(attr.MinValue, attr.Value);

            // Add some more modifiers and advance time
            GameTime.time = 0;
            attr.AddModifier(new TimeBasedModifier("StrengthBuff", 10, 10));
            attr.AddModifier(new TimeBasedModifier("AnotherStrengthBuff", 20, 5));
            Assert.AreEqual(attr.MinValue + 30, attr.Value);

            GameTime.time = 5;
            Assert.AreEqual(attr.MinValue + 10, attr.Value);
            Assert.AreEqual(1, attr.Modifiers.Count);
            Assert.IsTrue(attr.IsModified);

            GameTime.time = 10;
            Assert.AreEqual(attr.MinValue, attr.Value);
            Assert.AreEqual(0, attr.Modifiers.Count);
            Assert.IsFalse(attr.IsModified);

            attr.Value = attr.MaxValue;
            attr.Reset();
            Assert.AreEqual(attr.MinValue, attr.Value);
        }
Exemple #13
0
 public void SetUp()
 {
     GameTime.Reset();
     Body                  = new PrimaryAttribute("Body", 0, 999, 10);
     Experience            = new PrimaryAttribute("Experience", 0);
     MagicRegenerationRate = new PrimaryAttribute("MagicRegenerationRate", 0, 99, 1);
     Level                 = new SecondaryAttribute("Level",
                                                    x => (int)(Math.Sqrt(x[0].Value / 100)) * 1f,
                                                    new BaseAttribute[] { Experience }, 0, 99);
     Life = new VolumeAttribute("Life",
                                x => (int)(20 + 5 * x[0].Value + x[1].Value / 3) * 1f,
                                new BaseAttribute[] { Level, Body }, 0, 999);
     Magic = new VolumeAttribute("Magic",
                                 x => (int)(20 + 5 * x[0].Value + x[1].Value / 3) * 1f,
                                 new BaseAttribute[] { Level, Body }, 0, 999);
     Energy = new SimpleVolumeAttribute("Energy", 0, 999, 0);
 }
Exemple #14
0
 public EnemyStats()
 {
     Body                  = new PrimaryAttribute("Body", 0, 999, 0);
     Mind                  = new PrimaryAttribute("Mind", 0, 999, 0);
     Soul                  = new PrimaryAttribute("Soul", 0, 999, 0);
     Experience            = new PrimaryAttribute("Experience", 0, 980100, 0);
     Level                 = new PrimaryAttribute("Level", 0, 99, 0);
     Life                  = new PrimaryAttribute("Life", 0, 999, 0);
     MagicRegenerationRate = new PrimaryAttribute("MagicRegenerationRate", 0, 2, 0);
     LifeRegenerationRate  = new PrimaryAttribute("LifeRegenerationRate", 0, 2, 0);
     Magic                 = new PrimaryAttribute("Magic", 0, 999, 0);
     AlertnessRange        = new PrimaryAttribute("AlertnessRange", 2, 999, 2);
     Damage                = new PrimaryAttribute("Damage", 0, 999, 0);
     AttackRange           = new PrimaryAttribute("AttackRange", 1, 999, 1);
     MovementSpeed         = new PrimaryAttribute("MovementSpeed", 1, 10, 1);
     Alertness             = new PrimaryAttribute("Alertness", 0, 10, 0);
     ChasePersistency      = new PrimaryAttribute("ChasePersistency", 0, 100, 0);
     AssignAttributesToDict();
 }
Exemple #15
0
        public PlayerStats()
        {
            // Primary Attributes
            Body             = new PrimaryAttribute("Body", 0, 999, 0);
            Mind             = new PrimaryAttribute("Mind", 0, 999, 0);
            Soul             = new PrimaryAttribute("Soul", 0, 999, 0);
            Experience       = new PrimaryAttribute("Experience", 0, 980100, 0);
            AlertnessRange   = new PrimaryAttribute("AlertnessRange", 2, 999, 2);
            AttackRange      = new PrimaryAttribute("AttackRange", 1, 999, 1);
            Damage           = new PrimaryAttribute("Damage", 0, 999, 0);
            MovementSpeed    = new PrimaryAttribute("MovementSpeed", 1, 10, 1);
            Alertness        = new PrimaryAttribute("Alertness", 0, 10, 0);
            ChasePersistency = new PrimaryAttribute("ChasePersistency", 0, 100, 0);

            // Secondary Attributes
            Level = new SecondaryAttribute("Level",
                                           x => (int)(Math.Sqrt(x[0].Value / 100)) * 1f,
                                           new BaseAttribute[] { Experience }, 0, 99);
            MagicRegenerationRate = new SecondaryAttribute(
                "MagicRegenerationRate",
                x => 1 + (x[0].Value / 1000),
                new BaseAttribute[] { Mind }, 0, 99);
            LifeRegenerationRate = new SecondaryAttribute(
                "LifeRegenerationRate",
                x => 1 + (x[0].Value / 1000),
                new BaseAttribute[] { Body }, 0, 99);

            // Volume Attributes
            Life = new VolumeAttribute("Life",
                                       x => (int)(20 + 5 * x[0].Value + x[1].Value / 3) * 1f,
                                       new BaseAttribute[] { Level, Body }, 0, 999);
            Magic = new VolumeAttribute("Magic",
                                        x => (int)(20 + 5 * x[0].Value + x[1].Value / 3) * 1f,
                                        new BaseAttribute[] { Level, Soul }, 0, 999);

            AssignAttributesToDict();
        }
        public void Setup()
        {
            _changed  = false;
            _mockAttr = Substitute.ForPartsOf <PrimaryAttribute>(AttributeType.Float, _dfValue, _maxValue);
            _mockAttr.onAttributeChanged += () => _changed = true;
            _mockAttr.When(x => x.CalculateMods()).Do(x => {
                float total = 0;
                foreach (var pctMod in _mockAttr.PercentMods)
                {
                    total += pctMod.ValueAsFloat();
                }
                foreach (var flatMod in _mockAttr.FlatMods)
                {
                    total += flatMod.ValueAsFloat();
                }

                if (total < 0)
                {
                    total = 0;
                }

                _mockAttr.ModsValue.Returns(total);
            });
        }
Exemple #17
0
        public bool Init(DbHolder holder)
        {
            try {
                if (!File.Exists(_file))
                {
                    return(false);
                }

                string   dbRawName = Path.GetFileNameWithoutExtension(_file);
                string   dbName    = _toDbName(dbRawName.Replace("_db", ""));
                string[] lines     = File.ReadAllLines(_file);
                string[] itemsRaw  = null;
                bool     waitOne   = false;

                foreach (string line in lines)
                {
                    string t = line;

                    string[] raw = t.Replace("[,", ",[").Replace("{,", ",{").Split(',');

                    if (waitOne && raw.Length <= 1)
                    {
                        break;
                    }

                    if (waitOne)
                    {
                        raw[0]   = raw[0].TrimStart('/', ' ', '\t');
                        itemsRaw = itemsRaw.Concat(raw).ToArray();
                    }
                    else
                    {
                        itemsRaw = raw;
                    }

                    if (itemsRaw.Length > 1)
                    {
                        int end = itemsRaw.Length - 1;
                        itemsRaw[end] = itemsRaw[end].Contains("//") ? itemsRaw[end].Substring(0, itemsRaw[end].IndexOf("//", StringComparison.Ordinal)) : itemsRaw[end];
                        waitOne       = true;
                    }
                }

                if (itemsRaw == null || itemsRaw.Length <= 1)
                {
                    return(false);
                }

                Dictionary <int, string> comments = new Dictionary <int, string>();

                foreach (string line in lines)
                {
                    if (!line.StartsWith("//"))
                    {
                        break;
                    }

                    string bufLine = line.Trim('/', ' ');

                    if (bufLine.Length > 2 && bufLine[2] == '.')
                    {
                        int ival;

                        if (Int32.TryParse(bufLine.Substring(0, 2), out ival))
                        {
                            string t = bufLine.Substring(3).Trim(' ', '\t');

                            int index = t.LastIndexOf("  ", StringComparison.Ordinal);

                            if (index > -1)
                            {
                                t = t.Substring(index);
                            }
                            else
                            {
                                index = t.LastIndexOf("\t\t", StringComparison.Ordinal);

                                if (index > -1)
                                {
                                    t = t.Substring(index);
                                }
                            }

                            comments[ival] = t.Trim(' ', '\t');
                        }
                    }
                }

                List <string> items = itemsRaw.ToList();

                items[0] = items[0].TrimStart('/', ' ');
                items    = items.ToList().Select(p => p.Trim(' ')).ToList();
                HashSet <int> variable = new HashSet <int>();

                if (items.Any(p => p == "..."))
                {
                    // Find the longest line

                    if (_hasLogic(items, variable))
                    {
                    }
                    else
                    {
                        int        itemIndex = items.IndexOf("...");
                        List <int> count     = lines.Select(line => line.Split(',').Length).ToList();

                        int missingArguments = count.Max(p => p) - items.Count;

                        if (missingArguments == 0)
                        {
                            items[itemIndex] = "Unknown";
                        }
                        else if (missingArguments < 0)
                        {
                            items.RemoveAt(itemIndex);
                        }
                        else
                        {
                            items.RemoveAt(itemIndex);

                            for (int i = 0; i < missingArguments; i++)
                            {
                                items.Insert(itemIndex, "Variable");
                                variable.Add(itemIndex + i);
                            }
                        }
                    }
                }

                if (items.Any(p => p.Contains('[')) || items.Any(p => p.Contains('{')))
                {
                    bool begin = false;

                    for (int i = 0; i < items.Count; i++)
                    {
                        if (items[i].StartsWith("[") || items[i].StartsWith("{"))
                        {
                            if (items[i] != "{}")
                            {
                                begin = true;
                            }
                        }

                        if (begin)
                        {
                            variable.Add(i);
                        }

                        if (items[i].EndsWith("]") || items[i].EndsWith("}"))
                        {
                            begin = false;
                        }
                    }
                }

                items = items.Select(p => p.Trim('[', ']', '{', '}')).ToList();

                AttributeList list = new AttributeList();

                IntLineStream reader = new IntLineStream(_file);
                Type          dbType = typeof(int);

                bool?duplicates = reader.HasDuplicateIds();

                if (duplicates == null || duplicates == true)
                {
                    dbType = typeof(string);
                }

                bool        first            = true;
                DbAttribute bindingAttribute = null;

                for (int i = 0; i < items.Count; i++)
                {
                    string      value     = items[i];
                    string      desc      = null;
                    string      toDisplay = _toDisplay(value);
                    DbAttribute att;

                    if (comments.ContainsKey(i + 1))
                    {
                        desc = comments[i + 1];
                    }

                    if (i == 0 && first)
                    {
                        if (duplicates == null)
                        {
                            att = new PrimaryAttribute(value, dbType, 0, toDisplay);
                        }
                        else if (duplicates == true)
                        {
                            att   = new PrimaryAttribute("RealId", dbType, "");
                            first = false;
                            i--;
                        }
                        else
                        {
                            att = new PrimaryAttribute(value, dbType, 0, toDisplay);
                        }
                    }
                    else
                    {
                        string          toLower = value.ToLower();
                        CustomAttribute custom  = new CustomAttribute(value, typeof(string), "", toDisplay, desc);
                        att = custom;

                        if (toLower.Contains("skillid"))
                        {
                            att.AttachedObject = ServerDbs.Skills;
                            custom.SetDataType(dbType == typeof(int) ? typeof(SelectTupleProperty <int>) : typeof(SelectTupleProperty <string>));
                            if (i == 1)
                            {
                                bindingAttribute = new DbAttribute("Elements", typeof(SkillBinding), duplicates == true ? 2 : 1)
                                {
                                    IsDisplayAttribute = true, Visibility = VisibleState.Hidden
                                }
                            }
                            ;
                        }

                        if (toLower.Contains("mobid"))
                        {
                            att.AttachedObject = ServerDbs.Mobs;
                            custom.SetDataType(dbType == typeof(int) ? typeof(SelectTupleProperty <int>) : typeof(SelectTupleProperty <string>));
                            if (i == 1)
                            {
                                bindingAttribute = new DbAttribute("Elements", typeof(MobBinding), duplicates == true ? 2 : 1)
                                {
                                    IsDisplayAttribute = true, Visibility = VisibleState.Hidden
                                }
                            }
                            ;
                        }

                        if (toLower.Contains("itemid"))
                        {
                            att.AttachedObject = ServerDbs.Items;
                            custom.SetDataType(dbType == typeof(int) ? typeof(SelectTupleProperty <int>) : typeof(SelectTupleProperty <string>));
                            if (i == 1)
                            {
                                bindingAttribute = new DbAttribute("Elements", typeof(ItemBinding), duplicates == true ? 2 : 1)
                                {
                                    IsDisplayAttribute = true, Visibility = VisibleState.Hidden
                                }
                            }
                            ;
                        }

                        if (variable.Contains(i))
                        {
                            att.IsSkippable = true;
                        }
                    }

                    list.Add(att);
                }

                if (bindingAttribute != null)
                {
                    list.Add(bindingAttribute);
                }
                else
                {
                    string toLower = items[0].ToLower();

                    if (toLower.Contains("skillid"))
                    {
                        bindingAttribute = new DbAttribute("Elements", typeof(SkillBinding), duplicates == true ? 2 : 1)
                        {
                            IsDisplayAttribute = true, Visibility = VisibleState.Hidden
                        };
                    }

                    if (toLower.Contains("mobid"))
                    {
                        bindingAttribute = new DbAttribute("Elements", typeof(MobBinding), duplicates == true ? 2 : 1)
                        {
                            IsDisplayAttribute = true, Visibility = VisibleState.Hidden
                        };
                    }

                    if (toLower.Contains("itemid"))
                    {
                        bindingAttribute = new DbAttribute("Elements", typeof(ItemBinding), duplicates == true ? 2 : 1)
                        {
                            IsDisplayAttribute = true, Visibility = VisibleState.Hidden
                        };
                    }

                    if (bindingAttribute != null)
                    {
                        list.Add(bindingAttribute);
                    }
                }


                if (dbType == typeof(int))
                {
                    _adb = new DummyDb <int>();

                    _adb.To <int>().TabGenerator.OnSetCustomCommands += GTabsMaker.SelectFromMobDb;
                    _adb.To <int>().TabGenerator.OnSetCustomCommands += GTabsMaker.SelectFromItemDb;
                    _adb.To <int>().TabGenerator.OnSetCustomCommands += GTabsMaker.SelectFromSkillDb;
                }
                else
                {
                    _adb = new DummyDb <string>();

                    var db = _adb.To <string>();

                    if (duplicates == true)
                    {
                        db.LayoutIndexes = new int[] {
                            1, list.Attributes.Count
                        };

                        db.DbLoader = DbLoaderMethods.DbUniqueLoader;
                        db.DbWriter = DbWriterMethods.DbUniqueWriter;

                        db.TabGenerator.OnInitSettings += delegate(GDbTabWrapper <string, ReadableTuple <string> > tab, GTabSettings <string, ReadableTuple <string> > settings, BaseDb gdb) {
                            settings.CanChangeId         = false;
                            settings.CustomAddItemMethod = delegate {
                                try {
                                    string id = Methods.RandomString(32);

                                    ReadableTuple <string> item = new ReadableTuple <string>(id, settings.AttributeList);
                                    item.Added = true;

                                    db.Table.Commands.StoreAndExecute(new AddTuple <string, ReadableTuple <string> >(id, item));
                                    tab._listView.ScrollToCenterOfView(item);
                                }
                                catch (KeyInvalidException) {
                                }
                                catch (Exception err) {
                                    ErrorHandler.HandleException(err);
                                }
                            };
                        };
                        db.TabGenerator.StartIndexInCustomMethods = 1;
                        db.TabGenerator.OnInitSettings           += delegate(GDbTabWrapper <string, ReadableTuple <string> > tab, GTabSettings <string, ReadableTuple <string> > settings, BaseDb gdb) {
                            settings.AttributeList = gdb.AttributeList;
                            settings.AttId         = gdb.AttributeList.Attributes[1];
                            settings.AttDisplay    = gdb.AttributeList.Attributes.FirstOrDefault(p => p.IsDisplayAttribute) ?? gdb.AttributeList.Attributes[2];
                            settings.AttIdWidth    = 60;
                        };
                        db.TabGenerator.OnSetCustomCommands += GTabsMaker.SelectFromMobDbString;
                        db.TabGenerator.OnSetCustomCommands += GTabsMaker.SelectFromSkillDbString;
                    }
                    else if (duplicates == null)
                    {
                        db.UnsafeContext = true;
                        db.DbWriter      = DbWriterMethods.DbStringCommaWriter;
                    }
                }

                ServerDbs sdb = ServerDbs.Instantiate(dbRawName, dbName, FileType.Txt);

                if (bindingAttribute != null)
                {
                    bindingAttribute.AttachedObject = _adb;
                }

                _adb.IsCustom      = true;
                _adb.DbSource      = sdb;
                _adb.AttributeList = list;

                return(true);
            }
            catch { }
            return(false);
        }
 public void PrimaryAttribute_Wont_Clamp_When_Increasing_Without_Max_Val()
 {
     _mockAttr = Substitute.ForPartsOf <PrimaryAttribute>(AttributeType.Float, _dfValue);
     _mockAttr.Increase(300f);
     Assert.AreEqual(300f + _dfValue, _mockAttr.CurrentValue);
 }
Exemple #19
0
		public bool Init(DbHolder holder) {
			try {
				if (!File.Exists(_file)) return false;

				string dbRawName = Path.GetFileNameWithoutExtension(_file);
				string dbName = _toDbName(dbRawName.Replace("_db", ""));
				string[] lines = File.ReadAllLines(_file);
				string[] itemsRaw = null;
				bool waitOne = false;

				foreach (string line in lines) {
					string t = line;

					string[] raw = t.Replace("[,", ",[").Replace("{,", ",{").Split(',');

					if (waitOne && raw.Length <= 1) break;

					if (waitOne) {
						raw[0] = raw[0].TrimStart('/', ' ', '\t');
						itemsRaw = itemsRaw.Concat(raw).ToArray();
					}
					else {
						itemsRaw = raw;
					}

					if (itemsRaw.Length > 1) {
						int end = itemsRaw.Length - 1;
						itemsRaw[end] = itemsRaw[end].Contains("//") ? itemsRaw[end].Substring(0, itemsRaw[end].IndexOf("//", StringComparison.Ordinal)) : itemsRaw[end];
						waitOne = true;
					}
				}

				if (itemsRaw == null || itemsRaw.Length <= 1) return false;

				Dictionary<int, string> comments = new Dictionary<int, string>();

				foreach (string line in lines) {
					if (!line.StartsWith("//")) break;

					string bufLine = line.Trim('/', ' ');

					if (bufLine.Length > 2 && bufLine[2] == '.') {
						int ival;

						if (Int32.TryParse(bufLine.Substring(0, 2), out ival)) {
							string t = bufLine.Substring(3).Trim(' ', '\t');

							int index = t.LastIndexOf("  ", StringComparison.Ordinal);

							if (index > -1) {
								t = t.Substring(index);
							}
							else {
								index = t.LastIndexOf("\t\t", StringComparison.Ordinal);

								if (index > -1) {
									t = t.Substring(index);
								}
							}

							comments[ival] = t.Trim(' ', '\t');
						}
					}
				}

				List<string> items = itemsRaw.ToList();

				items[0] = items[0].TrimStart('/', ' ');
				items = items.ToList().Select(p => p.Trim(' ')).ToList();
				HashSet<int> variable = new HashSet<int>();

				if (items.Any(p => p == "...")) {
					// Find the longest line

					if (_hasLogic(items, variable)) { }
					else {
						int itemIndex = items.IndexOf("...");
						List<int> count = lines.Select(line => line.Split(',').Length).ToList();

						int missingArguments = count.Max(p => p) - items.Count;

						if (missingArguments == 0) {
							items[itemIndex] = "Unknown";
						}
						else if (missingArguments < 0) {
							items.RemoveAt(itemIndex);
						}
						else {
							items.RemoveAt(itemIndex);

							for (int i = 0; i < missingArguments; i++) {
								items.Insert(itemIndex, "Variable");
								variable.Add(itemIndex + i);
							}
						}
					}
				}

				if (items.Any(p => p.Contains('[')) || items.Any(p => p.Contains('{'))) {
					bool begin = false;

					for (int i = 0; i < items.Count; i++) {
						if (items[i].StartsWith("[") || items[i].StartsWith("{")) {
							if (items[i] != "{}")
								begin = true;
						}

						if (begin) {
							variable.Add(i);
						}

						if (items[i].EndsWith("]") || items[i].EndsWith("}")) {
							begin = false;
						}
					}
				}

				items = items.Select(p => p.Trim('[', ']', '{', '}')).ToList();

				AttributeList list = new AttributeList();

				IntLineStream reader = new IntLineStream(_file);
				Type dbType = typeof (int);

				bool? duplicates = reader.HasDuplicateIds();

				if (duplicates == null || duplicates == true) {
					dbType = typeof (string);
				}

				bool first = true;
				DbAttribute bindingAttribute = null;

				for (int i = 0; i < items.Count; i++) {
					string value = items[i];
					string desc = null;
					string toDisplay = _toDisplay(value);
					DbAttribute att;

					if (comments.ContainsKey(i + 1))
						desc = comments[i + 1];

					if (i == 0 && first) {
						if (duplicates == null) {
							att = new PrimaryAttribute(value, dbType, 0, toDisplay);
						}
						else if (duplicates == true) {
							att = new PrimaryAttribute("RealId", dbType, "");
							first = false;
							i--;
						}
						else {
							att = new PrimaryAttribute(value, dbType, 0, toDisplay);
						}
					}
					else {
						string toLower = value.ToLower();
						CustomAttribute custom = new CustomAttribute(value, typeof(string), "", toDisplay, desc);
						att = custom;

						if (toLower.Contains("skillid")) {
							att.AttachedObject = ServerDbs.Skills;
							custom.SetDataType(dbType == typeof(int) ? typeof(SelectTupleProperty<int>) : typeof(SelectTupleProperty<string>));
							if (i == 1) bindingAttribute = new DbAttribute("Elements", typeof(SkillBinding), duplicates == true ? 2 : 1) { IsDisplayAttribute = true, Visibility = VisibleState.Hidden };
						}

						if (toLower.Contains("mobid")) {
							att.AttachedObject = ServerDbs.Mobs;
							custom.SetDataType(dbType == typeof(int) ? typeof(SelectTupleProperty<int>) : typeof(SelectTupleProperty<string>));
							if (i == 1) bindingAttribute = new DbAttribute("Elements", typeof(MobBinding), duplicates == true ? 2 : 1) { IsDisplayAttribute = true, Visibility = VisibleState.Hidden };
						}

						if (toLower.Contains("itemid")) {
							att.AttachedObject = ServerDbs.Items;
							custom.SetDataType(dbType == typeof(int) ? typeof(SelectTupleProperty<int>) : typeof(SelectTupleProperty<string>));
							if (i == 1) bindingAttribute = new DbAttribute("Elements", typeof(ItemBinding), duplicates == true ? 2 : 1) { IsDisplayAttribute = true, Visibility = VisibleState.Hidden };
						}

						if (variable.Contains(i))
							att.IsSkippable = true;
					}

					list.Add(att);
				}

				if (bindingAttribute != null)
					list.Add(bindingAttribute);
				else {
					string toLower = items[0].ToLower();

					if (toLower.Contains("skillid")) {
						bindingAttribute = new DbAttribute("Elements", typeof(SkillBinding), duplicates == true ? 2 : 1) { IsDisplayAttribute = true, Visibility = VisibleState.Hidden };
					}

					if (toLower.Contains("mobid")) {
						bindingAttribute = new DbAttribute("Elements", typeof(MobBinding), duplicates == true ? 2 : 1) { IsDisplayAttribute = true, Visibility = VisibleState.Hidden };
					}

					if (toLower.Contains("itemid")) {
						bindingAttribute = new DbAttribute("Elements", typeof(ItemBinding), duplicates == true ? 2 : 1) { IsDisplayAttribute = true, Visibility = VisibleState.Hidden };
					}

					if (bindingAttribute != null)
						list.Add(bindingAttribute);
				}


				if (dbType == typeof(int)) {
					_adb = new DummyDb<int>();

					_adb.To<int>().TabGenerator.OnSetCustomCommands += GTabsMaker.SelectFromMobDb;
					_adb.To<int>().TabGenerator.OnSetCustomCommands += GTabsMaker.SelectFromItemDb;
					_adb.To<int>().TabGenerator.OnSetCustomCommands += GTabsMaker.SelectFromSkillDb;
				}
				else {
					_adb = new DummyDb<string>();

					var db = _adb.To<string>();

					if (duplicates == true) {
						db.LayoutIndexes = new int[] {
							1, list.Attributes.Count
						};

						db.DbLoader = DbLoaderMethods.DbUniqueLoader;
						db.DbWriter = DbWriterMethods.DbUniqueWriter;

						db.TabGenerator.OnInitSettings += delegate(GDbTabWrapper<string, ReadableTuple<string>> tab, GTabSettings<string, ReadableTuple<string>> settings, BaseDb gdb) {
							settings.CanChangeId = false;
							settings.CustomAddItemMethod = delegate {
								try {
									string id = Methods.RandomString(32);

									ReadableTuple<string> item = new ReadableTuple<string>(id, settings.AttributeList);
									item.Added = true;

									db.Table.Commands.StoreAndExecute(new AddTuple<string, ReadableTuple<string>>(id, item));
									tab._listView.ScrollToCenterOfView(item);
								}
								catch (KeyInvalidException) {
								}
								catch (Exception err) {
									ErrorHandler.HandleException(err);
								}
							};
						};
						db.TabGenerator.StartIndexInCustomMethods = 1;
						db.TabGenerator.OnInitSettings += delegate(GDbTabWrapper<string, ReadableTuple<string>> tab, GTabSettings<string, ReadableTuple<string>> settings, BaseDb gdb) {
							settings.AttributeList = gdb.AttributeList;
							settings.AttId = gdb.AttributeList.Attributes[1];
							settings.AttDisplay = gdb.AttributeList.Attributes.FirstOrDefault(p => p.IsDisplayAttribute) ?? gdb.AttributeList.Attributes[2];
							settings.AttIdWidth = 60;
						};
						db.TabGenerator.OnSetCustomCommands += GTabsMaker.SelectFromMobDbString;
						db.TabGenerator.OnSetCustomCommands += GTabsMaker.SelectFromSkillDbString;
					}
					else if (duplicates == null) {
						db.UnsafeContext = true;
						db.DbWriter = DbWriterMethods.DbStringCommaWriter;
					}
				}

				ServerDbs sdb = ServerDbs.Instantiate(dbRawName, dbName, FileType.Txt);

				if (bindingAttribute != null)
					bindingAttribute.AttachedObject = _adb;

				_adb.IsCustom = true;
				_adb.DbSource = sdb;
				_adb.AttributeList = list;

				return true;
			}
			catch { }
			return false;
		}