Beispiel #1
0
 internal Arg(string text)
 {
     this.text      = text;
     this.type      = ArgType.text;
     this.scope     = Regex.Scope.invalid;
     this.stringInt = null;
 }
Beispiel #2
0
        private StringInt evaluateList(string firstBuffer, string s, int i)
        {
            //lists can contain variables
            List <string> buffers = new List <string>()
            {
                firstBuffer, string.Empty
            };

            while (i < s.Length && s[i] != ')')
            {
                if (s[i] == '(')
                {
                    StringInt evaluated = evaluateSingle(s, i + 1);
                    buffers[buffers.Count - 1] += evaluated.s;
                    i = evaluated.i;
                }
                else
                {
                    if (s[i] == LIST_DELIMITER)
                    {
                        buffers.Add(string.Empty);
                    }
                    else
                    {
                        buffers[buffers.Count - 1] += s[i];
                    }
                }
                i++;
            }

            int randomIndex = _indexForListEvaluation % buffers.Count;

            return(new StringInt(evaluateSingle(buffers[randomIndex], 0).s, i));
        }
Beispiel #3
0
        private StringInt evaluateEquality(string firstBuffer, string s, int i)
        {
            //http://stackoverflow.com/questions/14952113/how-can-i-match-nested-brackets-using-regex
            //ranges can contain variables and brackets
            string[] buffers = new string[2];
            buffers[0] = firstBuffer;

            while (i < s.Length && s[i] != ')')
            {
                //if { concat next expression to current buffer
                if (s[i] == '(')
                {
                    StringInt evaluated = evaluateBracketed(s, i + 1);
                    buffers[1] += evaluated.s;
                    i           = evaluated.i;
                }
                else
                {
                    if (s[i].isAlpha())
                    {
                        StringInt evaluated = evaluateLetters(s, i);
                        buffers[1] += evaluated.s;
                        i           = evaluated.i;
                    }
                    else
                    {
                        buffers[1] += s[i];
                    }
                }
                i++;
            }

            return(new StringInt(compareWithinError(buffers[0], buffers[1]).ToString(), i));
        }
Beispiel #4
0
        public void Run(TestConfig config)
        {
            int count = config.Count;
            var res   = new TestResult();

            config.Result = res;
            IDatabase db = config.GetDatabase();
            IIndex <string, StringInt> root = (IIndex <string, StringInt>)db.Root;

            Tests.Assert(null == root);
            root    = db.CreateIndex <string, StringInt>(IndexType.Unique);
            db.Root = root;

            string[] strs = new string[] { "one", "two", "three", "four" };
            int      no   = 1;

            for (var i = 0; i < count; i++)
            {
                foreach (string s in strs)
                {
                    var s2 = String.Format("{0}-{1}", s, i);
                    var o  = new StringInt(s, no++);
                    root[s2] = o;
                }
            }

            CheckStrings(root, strs, count);
            db.Close();

            db   = config.GetDatabase(false);
            root = (IIndex <string, StringInt>)db.Root;
            Tests.Assert(null != root);
            CheckStrings(root, strs, count);
            db.Close();
        }
Beispiel #5
0
        public void Run(TestConfig config)
        {
            int count = config.Count;
            var res = new TestResult();
            config.Result = res;
            IDatabase db = config.GetDatabase();
            IIndex<string, StringInt> root = (IIndex<string, StringInt>)db.Root;
            Tests.Assert(null == root);
            root = db.CreateIndex<string, StringInt>(IndexType.Unique);
            db.Root = root;

            string[] strs = new string[] { "one", "two", "three", "four" };
            int no = 1;
            for (var i = 0; i < count; i++)
            {
                foreach (string s in strs)
                {
                    var s2 = String.Format("{0}-{1}", s, i);
                    var o = new StringInt(s, no++);
                    root[s2] = o;
                }
            }

            CheckStrings(root, strs, count);
            db.Close();

            db = config.GetDatabase(false);
            root = (IIndex<string, StringInt>)db.Root;
            Tests.Assert(null != root);
            CheckStrings(root, strs, count);
            db.Close();
        }
Beispiel #6
0
 public Arg(Regex.Scope scope, int resultNumber)
 {
     this.type         = ArgType.regex;
     this.text         = null;
     this.scope        = scope;
     this.resultNumber = resultNumber;
     this.stringInt    = null;
 }
Beispiel #7
0
        static void Main(string[] args)
        {
            StringInt result = new StringInt();

            foreach (var addMe in addMes)
            {
                result += addMe;
            }

            Console.WriteLine(result.Value.Substring(0, 10));
            Console.ReadKey();
        }
Beispiel #8
0
        public static void CheckStrings(IIndex <string, StringInt> root, string[] strs, int count)
        {
            int no = 1;

            for (var i = 0; i < count; i++)
            {
                foreach (string s in strs)
                {
                    var       s2 = String.Format("{0}-{1}", s, i);
                    StringInt o  = root[s2];
                    Tests.Assert(o.no == no++);
                }
            }
        }
Beispiel #9
0
    private void ConditionTest(object sender, StringInt str)
    {
        //Debug.Log ("run condition test");
        if (str.conditionnum < -50)
        {
            GameOver();
            return;
        }

        unfinishedsuccessconditions -= str.conditionnum;
        if (unfinishedsuccessconditions == 0)
        {
            Success();
        }
    }
Beispiel #10
0
        private StringInt evaluateRange(string firstBuffer, string s, int i)
        {
            //ranges can contain variables and brackets
            string[] buffers = new string[2];
            buffers[0] = evaluateSingle(firstBuffer, 0).s;

            while (i < s.Length && s[i] != ')')
            {
                if (s[i] == '(')
                {
                    StringInt evaluated = evaluateSingle(s, i + 1);
                    buffers[1] += evaluated.s;
                    i           = evaluated.i;
                }
                else
                {
                    buffers[1] += s[i];
                }
                i++;
            }

            String  minString  = evaluateSingle(buffers[0], 0).s;
            String  maxString  = evaluateSingle(buffers[1], 0).s;
            Decimal decimalmin = 0;
            Decimal decimalmax = 0;

            if (!Decimal.TryParse(minString, out decimalmin) || !Decimal.TryParse(maxString, out decimalmax))
            {
                throw new RowException(RowException.ErrorCode.BAD_RANGE_EXPRESSION);
            }
            int min = (int)Math.Ceiling(decimalmin);
            int max = (int)Math.Floor(decimalmax);

            if (min > max)
            {
                int tempSwapMinandMax = min;
                min = max;
                max = tempSwapMinandMax;
            }

            int temp = min == max ? min : min + _random.Next(max - min + 1);

            return(new StringInt(temp.ToString(), i));
        }
Beispiel #11
0
                    internal static Arg Create(string text)
                    {
                        Rule.Regex.Scope scope = Regex.Scope.invalid;
                        // eh, simple if'ology would be sufficient
                        if (text.StartsWith("$s"))
                        {
                            scope = Regex.Scope.subject;
                        }
                        else if (text.StartsWith("$b"))
                        {
                            scope = Regex.Scope.body;
                        }
                        else if (text.StartsWith("$t"))
                        {
                            scope = Regex.Scope.to;
                        }
                        else if (text.StartsWith("$f"))
                        {
                            scope = Regex.Scope.from;
                        }
                        else if (text.StartsWith("$c"))
                        {
                            scope = Regex.Scope.cc;
                        }
                        else
                        {
                            return(new Arg(text));
                        }

                        var separator = text.IndexOf('.');

                        int       resultNumber;
                        StringInt stringInt = null;

                        if (separator < 0)
                        {
                            // $cN - Nth match, implicit 0th group
                            if (!int.TryParse(text.Substring(2, text.Length - 2), out resultNumber))
                            {
                                return(null);
                            }
                            return(new Arg(scope, resultNumber));
                        }
                        else if (separator <= 2)
                        {
                            // $c. .. just nope
                            return(null);
                        }
                        else
                        {
                            if (!int.TryParse(text.Substring(2, separator - 2), out resultNumber))
                            {
                                return(null);
                            }

                            int    group;
                            string group_sub = text.Substring(separator + 1, text.Length - separator - 1);
                            if (!int.TryParse(group_sub, out group))
                            {
                                // $cN.groupname
                                stringInt = new StringInt(group_sub);
                            }
                            else
                            {
                                // $cN.M - Nth match Mth group
                                stringInt = new StringInt(group);
                            }

                            return(new Arg(scope, resultNumber, stringInt));
                        }
                    }
Beispiel #12
0
    public static void Generate()
    {
        DirectoryInfo d = new DirectoryInfo(Application.dataPath + @"\Textures\objects\hydroponics\growing");

        FileInfo[] Files                 = d.GetFiles("*.png");// \\Getting Text files
        var        ListFiles             = new List <string>();
        var        PlantDictionary       = new Dictionary <string, DefaultPlantData>();
        var        PlantDictionaryObject = new Dictionary <string, System.Object>();

        foreach (FileInfo file in Files)
        {
            ListFiles.Add(file.Name);
        }

        var food  = (Resources.Load(@"Prefabs\Items\Botany\food") as GameObject);
        var json  = (Resources.Load(@"Metadata\plants") as TextAsset).ToString();
        var plats = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(json);

        foreach (var plat in plats)
        {
            //\\foreach (var Datapiece in plat)
            //\\{
            //\\	Logger.Log(Datapiece.Key);
            //\\}

            var plantdata = new PlantData();
            plantdata.ProduceObject = food;
            plantdata.Name          = plat["name"] as string;
            if (plat.ContainsKey("plantname"))
            {
                plantdata.Plantname = plat["plantname"] as string;
            }
            plantdata.Description = plat["Description"] as string;
            var seed_packet = "";
            if (plat.ContainsKey("species"))
            {
                seed_packet = (plat["species"] as string);
            }
            else
            {
                seed_packet = (plat["seed_packet"] as string);
                if (seed_packet.Contains("seed-"))
                {
                    seed_packet = seed_packet.Replace("seed-", "");
                }
                else if (seed_packet.Contains("mycelium-"))
                {
                    seed_packet = seed_packet.Replace("mycelium-", "");
                }
            }

            //
            Logger.Log(seed_packet);
            //Logger.Log(plat["seed_packet"] as string);
            //Logger.Log("harvest_" + seed_packet);

            plantdata.PacketsSprite         = new SpriteSheetAndData();
            plantdata.PacketsSprite.Texture = (AssetDatabase.LoadAssetAtPath(@"Assets\textures\objects\hydroponics\seeds\seeds_" + (plat["seed_packet"] as string) + ".png", typeof(Texture2D)) as Texture2D);
            plantdata.PacketsSprite.setSprites();

            plantdata.ProduceSprite         = new SpriteSheetAndData();
            plantdata.ProduceSprite.Texture = (AssetDatabase.LoadAssetAtPath(@"Assets\textures\objects\hydroponics\harvest\harvest_" + seed_packet + ".png", typeof(Texture2D)) as Texture2D);

            //Application.dataPath
            if (plantdata.ProduceSprite.Texture == null)
            {
                plantdata.ProduceSprite.Texture = (AssetDatabase.LoadAssetAtPath(@"Assets\textures\objects\hydroponics\harvest\harvest_" + seed_packet + "pile" + ".png", typeof(Texture2D)) as Texture2D);
            }
            if (plantdata.ProduceSprite.Texture == null)
            {
                var EEEseed_packet = (plat["seed_packet"] as string);
                if (EEEseed_packet.Contains("seed-"))
                {
                    EEEseed_packet = EEEseed_packet.Replace("seed-", "");
                }
                else if (EEEseed_packet.Contains("mycelium-"))
                {
                    EEEseed_packet = EEEseed_packet.Replace("mycelium-", "");
                }
                plantdata.ProduceSprite.Texture = (AssetDatabase.LoadAssetAtPath(@"Assets\textures\objects\hydroponics\harvest\harvest_" + EEEseed_packet + ".png", typeof(Texture2D)) as Texture2D);
                if (plantdata.ProduceSprite.Texture == null)
                {
                    plantdata.ProduceSprite.Texture = (AssetDatabase.LoadAssetAtPath(@"Assets\textures\objects\hydroponics\harvest\harvest_" + EEEseed_packet + "s" + ".png", typeof(Texture2D)) as Texture2D);
                }
                if (plantdata.ProduceSprite.Texture == null)
                {
                    plantdata.ProduceSprite.Texture = (AssetDatabase.LoadAssetAtPath(@"Assets\textures\objects\hydroponics\harvest\harvest_" + seed_packet + "s" + ".png", typeof(Texture2D)) as Texture2D);
                }
            }
            plantdata.ProduceSprite.setSprites();

            plantdata.GrowthSprites = new List <SpriteSheetAndData>();
            //var Growingsprites = new List<string>();
            foreach (var ListFile in ListFiles)
            {
                if (ListFile.Contains(seed_packet))
                {
                    var Namecheck = ListFile;
                    Namecheck = Namecheck.Replace("growing_flowers_", "");
                    Namecheck = Namecheck.Replace("growing_fruits_", "");
                    Namecheck = Namecheck.Replace("growing_mushrooms_", "");
                    Namecheck = Namecheck.Replace("growing_vegetables_", "");
                    Namecheck = Namecheck.Replace("growing_", "");
                    Namecheck = Namecheck.Split('-')[0];

                    if (Namecheck == seed_packet)
                    {
                        if (!ListFile.Contains("-dead"))
                        {
                            if (!ListFile.Contains("-harvest"))
                            {
                                //var _ListFile = ListFile.Replace(".png", "");
                                //\\Growingsprites.Add(ListFile);
                                //\Assets\Resources\textures\objects\hydroponics\growing\growing_ambrosia_gaia-grow6.png
                                var _SpriteSheetAndData = new SpriteSheetAndData();
                                _SpriteSheetAndData.Texture = (AssetDatabase.LoadAssetAtPath(@"Assets\textures\objects\hydroponics\growing\" + ListFile, typeof(Texture2D)) as Texture2D);
                                _SpriteSheetAndData.setSprites();
                                plantdata.GrowthSprites.Add(_SpriteSheetAndData);

                                //\\If not found do at end
                            }
                            else
                            {
                                //Logger.Log("got harvest");

                                var _SpriteSheetAndData = new SpriteSheetAndData();
                                _SpriteSheetAndData.Texture = (AssetDatabase.LoadAssetAtPath(@"Assets\textures\objects\hydroponics\growing\" + ListFile, typeof(Texture2D)) as Texture2D);
                                _SpriteSheetAndData.setSprites();
                                plantdata.FullyGrownSprite = _SpriteSheetAndData;
                            }
                        }
                        else
                        {
                            //Logger.Log("got DeadSprite");

                            //var _ListFile = ListFile.Replace(".png", "");
                            var _SpriteSheetAndData = new SpriteSheetAndData();
                            _SpriteSheetAndData.Texture = (AssetDatabase.LoadAssetAtPath(@"Assets\textures\objects\hydroponics\growing\" + ListFile, typeof(Texture2D)) as Texture2D);
                            _SpriteSheetAndData.setSprites();
                            plantdata.DeadSprite = _SpriteSheetAndData;
                        }
                    }
                }
                if (plantdata.FullyGrownSprite == null)
                {
                    if (plantdata.GrowthSprites.Count > 0)
                    {
                        plantdata.FullyGrownSprite = plantdata.GrowthSprites[plantdata.GrowthSprites.Count - 1];
                    }
                }
            }
            plantdata.WeedResistance = int.Parse(plat["weed_resistance"].ToString());
            plantdata.WeedGrowthRate = int.Parse(plat["weed_growth_rate"].ToString());
            plantdata.Potency        = int.Parse(plat["potency"].ToString());
            plantdata.Endurance      = int.Parse(plat["endurance"].ToString());
            plantdata.Yield          = int.Parse(plat["plant_yield"].ToString());
            plantdata.Lifespan       = int.Parse(plat["lifespan"].ToString());
            plantdata.GrowthSpeed    = int.Parse(plat["production"].ToString());

            if (plat.ContainsKey("genes"))
            {
                var genes = JsonConvert.DeserializeObject <List <string> >(plat["genes"].ToString());

                foreach (var gene in genes)
                {
                    if (gene == "Perennial_Growth")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Perennial_Growth);
                    }
                    else if (gene == "Fungal Vitality")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Fungal_Vitality);
                    }
                    else if (gene == "Liquid Contents")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Liquid_Content);
                    }
                    else if (gene == "Slippery Skin")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Slippery_Skin);
                    }
                    else if (gene == "Bluespace Activity")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Bluespace_Activity);
                    }
                    else if (gene == "Densified Chemicals")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Densified_Chemicals);
                    }
                    else if (gene == "Capacitive Cell Production")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Capacitive_Cell_Production);
                    }
                    else if (gene == "Weed Adaptation")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Weed_Adaptation);
                    }
                    else if (gene == "Hypodermic Prickles")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Hypodermic_Needles);
                    }
                    else if (gene == "Shadow Emission")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Shadow_Emission);
                    }
                    else if (gene == "Red Electrical Glow")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Red_Electrical_Glow);
                    }
                    else if (gene == "Electrical Activity")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Electrical_Activity);
                    }
                    else if (gene == "Strong Bioluminescence")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Strong_Bioluminescence);
                    }
                    else if (gene == "Bioluminescence")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Bioluminescence);
                    }
                    else if (gene == "Separated Chemicals")
                    {
                        plantdata.PlantTrays.Add(PlantTrays.Separated_Chemicals);
                    }
                }
            }
            if (plat.ContainsKey("reagents_add"))
            {
                var Chemicals = JsonConvert.DeserializeObject <Dictionary <string, float> >(plat["reagents_add"].ToString());

                foreach (var Chemical in Chemicals)
                {
                    var SInt = new StringInt();
                    SInt.Int    = (int)(Chemical.Value * 100);
                    SInt.String = Chemical.Key;
                    plantdata.ReagentProduction.Add(SInt);
                }
            }

            var DefaultPlantData = new DefaultPlantData();
            //\\ Creates the folder path
            DefaultPlantData.plantData = plantdata;


            //\\ Creates the file in the folder path
            Logger.Log(plantdata.Name + " < PlantDictionary");
            PlantDictionary[plantdata.Name] = DefaultPlantData;

            if (plat.ContainsKey("mutates_into"))
            {
                PlantDictionaryObject[plantdata.Name] = plat["mutates_into"];
            }


            //\\Logger.Log(plantdata.GrowthSprites.Count.ToString());
        }


        foreach (var pant in PlantDictionary)
        {
            if (PlantDictionaryObject.ContainsKey(pant.Value.plantData.Name))
            {
                var Mutations = JsonConvert.DeserializeObject <List <string> >(PlantDictionaryObject[pant.Value.plantData.Name].ToString());
                foreach (var Mutation in Mutations)
                {
                    if (Mutation.Length != 0)
                    {
                        if (PlantDictionary[Mutation] != null)
                        {
                            MutationComparison(pant.Value, PlantDictionary[Mutation]);
                            pant.Value.plantData.MutatesInTo.Add(PlantDictionary[Mutation]);
                        }



                        if (PlantDictionary[Mutation].plantData.DeadSprite?.Texture == null)
                        {
                            if (pant.Value.plantData.DeadSprite?.Texture != null)
                            {
                                PlantDictionary[Mutation].plantData.DeadSprite         = new SpriteSheetAndData();
                                PlantDictionary[Mutation].plantData.DeadSprite.Texture = pant.Value.plantData.DeadSprite.Texture;
                                PlantDictionary[Mutation].plantData.DeadSprite.setSprites();
                            }
                        }

                        if (PlantDictionary[Mutation].plantData.GrowthSprites.Count == 0)
                        {
                            PlantDictionary[Mutation].plantData.GrowthSprites = pant.Value.plantData.GrowthSprites;
                        }
                    }
                }
            }
        }
        foreach (var pant in PlantDictionary)
        {
            AssetDatabase.CreateAsset(pant.Value, @"Assets\Resources\ScriptableObjects\Plant default\" + pant.Value.plantData.Name + ".asset");
        }
    }
Beispiel #13
0
        private StringInt evaluateBracketed(string s, int i)
        {
            //anything in brackets
            //http://stackoverflow.com/questions/14952113/how-can-i-match-nested-brackets-using-regex
            string buffer = string.Empty;

            while (i < s.Length && s[i] != ')')
            {
                //if ( concat next expression to current buffer
                if (s[i] == '(')
                {
                    StringInt evaluated = evaluateBracketed(s, i + 1);
                    buffer += evaluated.s;
                    i       = evaluated.i;
                }
                else
                {
                    if (s[i].isAlpha())
                    {
                        StringInt evaluated = evaluateLetters(s, i);
                        buffer += evaluated.s;
                        i       = evaluated.i;
                    }
                    else
                    {
                        if (s[i] == '=')
                        {
                            return(evaluateEquality(buffer, s, i + 1));
                        }
                        else
                        {
                            if (s[i] == '$')
                            {
                                StringInt evaluated = evaluateDollar(s, i + 1);
                                buffer += evaluated.s;
                                i       = evaluated.i;
                            }
                            else
                            {
                                buffer += s[i];
                            }
                        }
                    }
                }
                i++;
            }

            //end of string or }
            if (haltOnEmptyField)
            {
                return(new StringInt("", i));
            }
            Expression e = new Expression(buffer, EvaluateOptions.IgnoreCase);

            e.Options |= EvaluateOptions.RoundAwayFromZero;

            string retVal = string.Empty;

            try
            {
                object evaluated = e.Evaluate();
                if (evaluated != null)
                {
                    retVal = evaluated.ToString();
                }
            }
            catch (EvaluationException err)
            {
                retVal = buffer;
            }
            return(new StringInt(retVal, i));
        }
Beispiel #14
0
        //http://stackoverflow.com/questions/333737/evaluating-string-342-yield-int-18
        private StringInt evaluateSingle(string s, int i)
        {
            //anything in brackets
            //http://stackoverflow.com/questions/14952113/how-can-i-match-nested-brackets-using-regex
            string buffer = string.Empty;

            while (i < s.Length && s[i] != ')')
            {
                if (overflowCounter++ > OVERFLOW_LIMIT)
                {
                    throw new RowException(RowException.ErrorCode.INFINITE_LOOP_ERROR);
                }
                //if ( concat next expression to current buffer
                if (s[i] == '(')
                {
                    StringInt evaluated = evaluateSingle(s, i + 1);
                    buffer += evaluated.s;
                    i       = evaluated.i;
                }
                else
                {
                    if (s[i].isAlpha())
                    {
                        StringInt evaluated = evaluateLetters(s, i);
                        buffer += evaluated.s;
                        i       = evaluated.i;
                    }
                    else
                    {
                        if (s[i] == 'π')
                        {
                            buffer += "3.14159265359";
                        }
                        else
                        {
                            if (i + 1 < s.Length && s.Substring(i, 2) == RANGE_DELIMITER)
                            {
                                return(evaluateRange(buffer, s, i + 2));
                            }
                            else
                            {
                                if (s[i] == LIST_DELIMITER)
                                {
                                    return(evaluateList(buffer, s, i + 1));
                                }
                                else
                                {
                                    if (s[i] == QUOTE)
                                    {
                                        return(evaluateQuote(s, i));
                                    }
                                    else
                                    {
                                        if (s[i] == DOLLAR)
                                        {
                                            StringInt evaluated = evaluateDollar(s, i + 1);
                                            buffer += evaluated.s;
                                            i       = evaluated.i;
                                        }
                                        else
                                        {
                                            buffer += s[i];
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                i++;
            }

            if (string.IsNullOrWhiteSpace(buffer))
            {
                return(new StringInt(string.Empty, i));
            }
            if (buffer[0] == '"')
            {
                return(new StringInt(buffer.Trim('"'), i)); //allow quotes to  pass through
            }
            Expression e = new Expression(buffer, EvaluateOptions.IgnoreCase);

            e.Options |= EvaluateOptions.RoundAwayFromZero;
            return(new StringInt(e.Evaluate().ToString(), i));
        }
Beispiel #15
0
        private StringInt evaluateFunction(string functionName, string s, int i)
        {
            string functionNameLower = functionName.ToLower();

            //starts after first bracket
            List <string> parameters = new List <string>()
            {
                string.Empty
            };

            while (i < s.Length && s[i] != ')')
            {
                if (s[i] == '(')
                {
                    StringInt evaluated = evaluateSingle(s, i + 1);
                    parameters[parameters.Count - 1] += evaluated.s;
                    i = evaluated.i;
                }
                else
                {
                    if (s[i] == ',')
                    {
                        parameters.Add(string.Empty);
                    }
                    else
                    {
                        parameters[parameters.Count - 1] += s[i];
                    }
                }
                i++;
            }


            if (functionNameLower == "if")
            {
                return(new StringInt(
                           bool.Parse(evaluateSingle(parameters[0], 0).s) ?
                           evaluateSingle(parameters[1], 0).s :
                           evaluateSingle(parameters[2], 0).s,
                           i));
            }

            //evaluate functions
            List <decimal> evaluatedParameters = parameters.Select(p => decimal.Parse(evaluateSingle(p, 0).s, System.Globalization.NumberStyles.Float)).ToList();


            if (functionNameLower == "exponent")
            {
                string asExponent = evaluatedParameters[0].ToString("E");
                int    Eindex     = asExponent.IndexOf('E');
                return(new StringInt("0" + asExponent.Substring(Eindex + 1), i));
            }

            if (functionNameLower == "mantissa")
            {
                string asExponent = evaluatedParameters[0].ToString("E");
                int    Eindex     = asExponent.IndexOf('E');
                return(new StringInt(asExponent.Substring(0, Eindex), i));
            }

            if (functionNameLower == "maxlength")
            {
                int max = Math.Min((int)evaluatedParameters[1], evaluatedParameters[0].ToString().Length);
                return(new StringInt(evaluatedParameters[0].ToString().Substring(0, max), i));
            }
            if (functionNameLower == "padleftzeroes")
            {
                return(new StringInt('"' + evaluatedParameters[0].ToString().PadLeft((int)evaluatedParameters[1], '0'), i));
            }
            if (functionNameLower == "padrightzeroes")
            {
                string str = evaluatedParameters[0].ToString();
                if (!str.Contains('.'))
                {
                    str += '.';
                }
                return(new StringInt('"' + str.PadRight((int)evaluatedParameters[1], '0'), i));
            }

            if (functionNameLower == "getdigit")
            {
                int        n      = (int)evaluatedParameters[0];
                List <int> digits = n.digits().ToList();
                int        index  = digits.Count - 1 - (int)Math.Log10((double)evaluatedParameters[1]);
                return(new StringInt(digits[index].ToString(), i));
            }
            if (functionNameLower == "abs")
            {
                return(new StringInt(Math.Abs(evaluatedParameters[0]).ToString(), i));
            }
            if (functionNameLower == "mean")
            {
                return(new StringInt(evaluatedParameters.Average().ToString(), i));
            }
            if (functionNameLower == "median")
            {
                return(new StringInt(evaluatedParameters.Median().ToString(), i));
            }
            if (functionNameLower == "mode")
            {
                return(new StringInt(evaluatedParameters.Mode().ToString(), i));
            }
            if (functionNameLower == "max")
            {
                return(new StringInt(evaluatedParameters.Max().ToString(), i));
            }
            if (functionNameLower == "min")
            {
                return(new StringInt(evaluatedParameters.Min().ToString(), i));
            }
            if (functionNameLower == "hcf")
            {
                return(new StringInt(Helpers.HCF((int)evaluatedParameters[0], (int)evaluatedParameters[1]).ToString(), i));
            }
            if (functionNameLower == "coprime")
            {
                int denom = (int)evaluatedParameters[0];
                if (denom < 2)
                {
                    return(new StringInt("0", i));
                }
                int guess = _random.Next(denom);
                while (Helpers.HCF(denom, guess) > 1)
                {
                    guess = _random.Next(denom);
                }
                return(new StringInt(guess.ToString(), i));
            }
            if (functionNameLower == "includesign")
            {
                if (evaluatedParameters[0] > 0)
                {
                    return(new StringInt(String.Format(@"""+ {0}""", evaluatedParameters[0].ToString()), i));
                }
                return(new StringInt(String.Format(@"""- {0}""", (-1 * evaluatedParameters[0]).ToString()), i));
            }
            if (functionNameLower == "includeoppsign")
            {
                if (evaluatedParameters[0] > 0)
                {
                    return(new StringInt(String.Format(@"""- {0}""", evaluatedParameters[0].ToString()), i));
                }
                return(new StringInt(String.Format(@"""+ {0}""", (-1 * evaluatedParameters[0]).ToString()), i));
            }

            return(new StringInt(new Expression(
                                     functionName + '(' + string.Join(",", parameters.Select(p => evaluateSingle(p, 0).s)) + ')', EvaluateOptions.IgnoreCase
                                     ).Evaluate().ToString(), i)); //leave anything else for ncalc
        }
Beispiel #16
0
        //--------------------------------------------------------------
        // group best roll... roll the three highest of those present
        //
        void gbest_cmd(string args)
        {
            if (args == "")
            {
                dumpCommandHelp();
                return;
            }

            var present = getpresent();

            var rollers = new List <StringInt>();

            foreach (string s in present)
            {
                roller = s;

                try
                {
                    int val = eval_roll(args);

                    var p = new StringInt();
                    p.key = s;
                    p.val = val;

                    if (val <= 0)
                    {
                        continue;
                    }

                    rollers.Add(p);
                }
                catch (ParseException)
                {
                }
            }

            if (rollers.Count < 1)
            {
                sbOut.Append("Nobody has a skill that is positive\n");
                return;
            }

            string roll = args + "%";

            rollers.Sort((t1, t2) =>
            {
                if (t1.val < t2.val)
                {
                    return(1);                      // sort bigget to smallest
                }
                if (t1.val > t2.val)
                {
                    return(-1);
                }
                return(0);
            });

            for (int i = 0; i < 3 && i < rollers.Count; i++)
            {
                roller = rollers[i].key;

                try
                {
                    int result = eval_roll(roll);
                    sbOut.AppendFormat("{0}: {1}\n", roller, sb2.ToString());
                }
                catch (ParseException)
                {
                }
            }
        }
Beispiel #17
0
 private void PutOutFire(object sender, StringInt str)
 {
     putOutFire = true;
     Destroy(GetComponent <TouchableStatic> ());
 }
Beispiel #18
0
        private StringInt evaluateFunction(string functionName, string s, int i)
        {
            string functionNameLower = functionName.ToLower();

            //one parameter one char can be done now - also remove the haltonblankfield check
            if (functionNameLower == "isfull" || functionNameLower == "full" ||
                functionNameLower == "isfilled" || functionNameLower == "filled" ||
                functionNameLower == "isempty" || functionNameLower == "empty")
            {
                StringInt evaluated = evaluateVariable(s, i, false); //skip the first bracket
                bool      result    = (functionNameLower == "isfull" || functionNameLower == "full" ||
                                       functionNameLower == "isfilled" || functionNameLower == "filled") == !string.IsNullOrEmpty(evaluated.s);
                return(new StringInt(result.ToString(), evaluated.i + 1)); //skip the end bracket
            }
            if (functionNameLower == "countfull" || functionNameLower == "countempty")
            {
                //starts after first bracket
                List <string> parameters2 = new List <string>()
                {
                    string.Empty
                };
                while (i < s.Length && s[i] != ')')
                {
                    if (s[i] == ',')
                    {
                        parameters2.Add(string.Empty);
                    }
                    else
                    {
                        parameters2[parameters2.Count - 1] += s[i];
                    }
                    i++;
                }
                int result = parameters2.Count(p =>
                                               (functionNameLower == "countfull") == !string.IsNullOrEmpty(evaluateVariable(p, 0, false).s));
                return(new StringInt(result.ToString(), i)); //skip the end bracket
            }

            //starts after first bracket
            List <string> parameters = new List <string>()
            {
                string.Empty
            };

            while (i < s.Length && s[i] != ')')
            {
                //if { concat next expression to current buffer
                if (s[i] == '(')
                {
                    StringInt evaluated = evaluateBracketed(s, i + 1);
                    parameters[parameters.Count - 1] += evaluated.s;
                    i = evaluated.i;
                }
                else
                {
                    if (s[i] == ',')
                    {
                        parameters.Add(string.Empty);
                    }
                    else
                    {
                        if (s[i].isAlpha())
                        {
                            StringInt evaluated = evaluateLetters(s, i);
                            parameters[parameters.Count - 1] += evaluated.s;
                            i = evaluated.i;
                        }
                        else
                        {
                            parameters[parameters.Count - 1] += s[i];
                        }
                    }
                }
                i++;
            }

            //evaluate functions
            if (functionNameLower == "mean")
            {
                return(new StringInt(parameters.Select(p => decimal.Parse(evaluateBracketed(p, 0).s)).Average().ToString(), i));
            }
            if (functionNameLower == "median")
            {
                return(new StringInt(parameters.Select(p => decimal.Parse(evaluateBracketed(p, 0).s)).Median().ToString(), i));
            }
            if (functionNameLower == "mode")
            {
                return(new StringInt(parameters.Select(p => decimal.Parse(evaluateBracketed(p, 0).s)).Mode().ToString(), i));
            }
            if (functionNameLower == "max")
            {
                return(new StringInt(parameters.Select(p => decimal.Parse(evaluateBracketed(p, 0).s)).Max().ToString(), i));
            }
            if (functionNameLower == "min")
            {
                return(new StringInt(parameters.Select(p => decimal.Parse(evaluateBracketed(p, 0).s)).Min().ToString(), i));
            }
            if (functionNameLower == "in")
            {
                string[] evaluatedParameters = parameters.Select(p => evaluateBracketed(p, 0).s).ToArray();
                return(new StringInt(evaluatedParameters.Skip(1).Any(p => compareWithinError(p, evaluatedParameters[0])).ToString(), i));
            }
            if (functionNameLower == "python")
            {
                return(new StringInt(doPython(
                                         parameters[0],
                                         parameters.Skip(1).Select(p => evaluateBracketed(p, 0).s).ToArray()), i));
            }

            return(new StringInt(new Expression(
                                     functionName + '(' + string.Join(",", parameters) + ')', EvaluateOptions.IgnoreCase
                                     ).Evaluate().ToString(), i)); //leave anything else for ncalc
        }