Inheritance: Entity
 public void WriteTest(Tree<Cell> test, TestCounts counts)
 {
     var tables = (Parse) test.Branches[0];
     for (var table = tables; table != null; table = table.More) {
         CopyTable(table);
     }
 }
Example #2
0
File: Tree.cs Project: alxio/gen
 private Tree(int type, int value, Tree left, Tree right)
 {
     _type = type;
     _value = value;
     _left = left;
     _right = right;
 }
Example #3
0
        static void Main()
        {
            Tree<int> corner = new Tree<int>(0);
            int nodeCnts = int.Parse(Console.ReadLine());
            for (int i = 0; i < nodeCnts - 1; i++)
            {
                string[] edge = Console.ReadLine().Split(' ');
                int parentValue = int.Parse(edge[0]);
                Tree<int> parentNode = Tree<int>.GetTreeNodeByValue(parentValue);
                int childValue = int.Parse(edge[1]);
                Tree<int> childNode = Tree<int>.GetTreeNodeByValue(childValue);
                parentNode.Children.Add(childNode);
                childNode.Parent = parentNode;
                if (i == 0)
                {
                    corner = parentNode;
                }
            }

            int pathSum = int.Parse(Console.ReadLine());
            int subTreeSum = int.Parse(Console.ReadLine());

            Console.WriteLine();
            corner.Print();
        }
        public override void visit(Tree.MethodDefinition that)
        {
            // TODO: virtual, abstract methods
            var name = that.getIdentifier().getToken().getText().CSharpMethodName();

            base.visit(that);
        }
        public int Import(string filePath, int ownerId)
        {
            //Create GEDCOM Store
            var treeName = Path.GetFileNameWithoutExtension(filePath);
            var store = new GEDCOMStore(filePath);

            var treeService = _serviceFactory.CreateTreeService();

            var tree = new Tree() { Name = treeName, OwnerId = ownerId};
            treeService.Add(tree);

            _repositoryLookup = new Dictionary<int, int>();

            //Add Repositories
            ProcessRepositories(store.Repositories, tree.TreeId);

            _sourceLookup = new Dictionary<int, int>();

            //Add Sources
            ProcessSources(store.Sources, tree.TreeId);

            _individualLookup = new Dictionary<int, int>();

            //Add Individuals
            ProcessIndividuals(store.Individuals, tree.TreeId);

            //Add Families
            ProcessFamilies(store.Families, tree.TreeId);

            return tree.TreeId;
        }
Example #6
0
		public override void PopulateTree (Tree tree)
		{
			foreach(string TocFile in tocFiles) {
				XmlDocument doc = new XmlDocument();
				doc.Load (TocFile);

				XmlNodeList nodeList = doc.GetElementsByTagName("manpage");
				Node nodeToAddChildrenTo = tree.RootNode;
				var storage = nodeToAddChildrenTo.Tree.HelpSource.Storage;

				foreach (XmlNode node in nodeList) {

					XmlAttribute name = node.Attributes["name"];
					XmlAttribute page = node.Attributes["page"];

					if (name == null || page == null) continue;

					if (!File.Exists (page.Value))
						continue;

					string target = "man:" + name.Value;
					nodeToAddChildrenTo.CreateNode (name.Value, target);

					if (File.Exists (page.Value))
						using (var file = File.OpenRead (page.Value))
							storage.Store (name.Value, file);
				}
			}
		}
Example #7
0
		public override void PopulateTree (Tree tree)
		{
			XPathNavigator n = new XPathDocument (Path.Combine (basedir, "toc.xml")).CreateNavigator ();
			n.MoveToRoot ();
			n.MoveToFirstChild ();
			PopulateNode (n.SelectChildren ("node", ""), tree.RootNode);
		}
Example #8
0
        public override sealed Expression Compile(Tree<SyntaxToken> context)
        {
            var leaf = context.Leafs[0];
            var expression = leaf.Value.Compile(leaf);

            return Compile(expression);
        }
Example #9
0
        public override sealed double Evaluate(Tree<SyntaxToken> tree, EvaluationContext context)
        {
            var leaf = tree.Leafs[0];
            double value = leaf.Value.Evaluate(leaf, context);

            return Evaluate(value);
        }
        public static TreeNode CreateTreeNode(XElement element, Tree tree)
        {
            if (element.Name == TreeMarkupConstants.Namespace + "ElementRoot")
            {
                return BuildRootTreeNode(element, tree);
            }

            if (element.Name == TreeMarkupConstants.Namespace + "Element")
            {
                return BuildSimpleElementTreeNode(element, tree);
            }

            if (element.Name == TreeMarkupConstants.Namespace + "FunctionElementGenerator")
            {
                return BuildFunctionElementGeneratorTreeNode(element, tree);
            }

            if (element.Name == TreeMarkupConstants.Namespace + "DataElements")
            {
                return BuildDataElementsTreeNode(element, tree);
            }

            if (element.Name == TreeMarkupConstants.Namespace + "DataFolderElements")
            {
                return BuildDataFolderElementsTreeNode(element, tree);
            }
            
            tree.AddValidationError(element, "TreeValidationError.Common.UnknownElement", element.Name);
            return null;
        }
        // Constructor for creating a new representative table. We directly fill the table depending on the given sequence.
        public RepresentativeTable(Graph graph, Tree tree)
        {
            // Initialize the table
            _table = new Dictionary<BitSet, RepresentativeList>();

            Queue<BitSet> queue = new Queue<BitSet>();
            queue.Enqueue(tree.Root);
            _table[new BitSet(0, graph.Size)] = new RepresentativeList();

            int i = 0;

            while (queue.Count != 0)
            {
                BitSet node = queue.Dequeue();

                FillTable(graph, node);
                FillTable(graph, graph.Vertices - node);

                if (tree.LeftChild.ContainsKey(node))
                {
                    queue.Enqueue(tree.LeftChild[node]);
                }
                if (tree.RightChild.ContainsKey(node))
                {
                    queue.Enqueue(tree.RightChild[node]);
                }
            }
        }
Example #12
0
 public void SetLastIndex(Tree t)
 {
     lastIndex = 0;
     var iterator = t.Iterator();
     while (iterator.MoveNext())
     {
         var node = iterator.Current;
         /*foreach (Tree node in t) {*/
         string value = node.Label().Value();
         if (value != null)
         {
             var m = coindexationPattern.Match(value);
             if (m.Success)
             {
                 int thisIndex = 0;
                 try
                 {
                     thisIndex = int.Parse(m.Groups[1].Value);
                 }
                 catch (FormatException e)
                 {
                     // Ignore this exception.  This kind of exception can
                     // happen if there are nodes that happen to have the
                     // indexing character attached, even despite the attempt
                     // to ignore those nodes in the pattern above.
                 }
                 lastIndex = Math.Max(thisIndex, lastIndex);
             }
         }
     }
 }
Example #13
0
 public Tree TransformTree(Tree t)
 {
     TregexMatcher matcher = TregexMonthYear.Matcher(t);
     while (matcher.Find())
     {
         Tree root = matcher.GetNode("root");
         Tree month = matcher.GetNode("month");
         Tree year = matcher.GetNode("year");
         var children = new Tree[] {month, year};
         root.SetChildren(children);
         matcher = TregexMonthYear.Matcher(t);
     }
     matcher = TregexMonthDayYear.Matcher(t);
     while (matcher.Find())
     {
         Tree root = matcher.GetNode("root");
         Tree month = matcher.GetNode("month");
         Tree day = matcher.GetNode("day");
         Tree comma = matcher.GetNode("comma");
         Tree year = matcher.GetNode("year");
         var children = new Tree[] {month, day, comma, year};
         root.SetChildren(children);
         matcher = TregexMonthDayYear.Matcher(t);
     }
     return t;
 }
        public static void SaveTree(String TreeXml)
        {
            if (String.IsNullOrEmpty(TreeXml))
            {
                //创建一棵空树
                XElement root = new XElement("root");
                TreeXml = root.ToString();
            }

            using (InfocenterEntities context = new InfocenterEntities(DALConfig.ConnectString))
            {
               Tree treeObj = context.Trees.FirstOrDefault();
               if (treeObj != null)
               {
                   //更新树
                   treeObj.maintree = Encoding.UTF8.GetBytes(TreeXml);
                   context.SaveChanges();
               }
               else
               {
                   //正常情况下应该不会走到这个分支,但仍然写在这里,逻辑就完整了。
                   treeObj = new Tree();
                   treeObj.maintree = Encoding.UTF8.GetBytes(TreeXml);
                   context.Trees.Add(treeObj);
                   context.SaveChanges();
               }

            }
        }
Example #15
0
        public void WriteTable(Tree<Cell> table) {
            var tableResult = processor.ParseTree<Cell, StoryTableString>(table).ToString();
            if (string.IsNullOrEmpty(tableResult)) return;

            HandleTableResult(tableResult);
            writesTables = true;
        }
Example #16
0
 public World(Tree<Planet> planetTree)
 {
     planetStack = new Stack<TreeNode<Planet>>();
     this.planetTree = planetTree;
     _currentNode = this.planetTree.Root;
     currentNode = _currentNode;
 }
Example #17
0
    public void BuildTree_PrintTree_ShouldWorkCorrectly()
    {
        // Arrange
        var tree =
            new Tree<int>(7,
                new Tree<int>(19,
                    new Tree<int>(1),
                    new Tree<int>(12),
                    new Tree<int>(31)),
                new Tree<int>(21),
                new Tree<int>(14,
                    new Tree<int>(23),
                    new Tree<int>(6)));

        // Act
        var outputStream = new MemoryStream();
        using (var outputWriter = new StreamWriter(outputStream))
        {
            Console.SetOut(outputWriter);
            tree.Print();
        }
        var output = Encoding.UTF8.GetString(outputStream.ToArray());

        // Assert
        var expectedOutput = "7\n  19\n    1\n    12\n    31\n  21\n  14\n    23\n    6\n";
        output = output.Replace("\r\n", "\n");
        Assert.AreEqual(expectedOutput, output);
    }
Example #18
0
 static Tree<Cell> GetMethodCellRange(Tree<Cell> row , int excludedCellCount)
 {
     if (row.Branches.Count < 2) {
         throw new FitFailureException("Missing cells for embedded method");
     }
     return row.Skip(1).Take(row.Branches.Count -excludedCellCount - 1);
 }
        public void AddEmptyTree_Exception_Test()
        {
            dynamic obj1 = new { Name = "test" };
            var tree = new Tree<dynamic>(obj1);

            tree.Root.AddChild(null);
        }
Example #20
0
        private void bindPages( List<Page> list )
        {
            Tree<Page> tree = new Tree<Page>( list );

            IBlock block = getBlock( "list" );
            foreach (Page data in tree.GetAllOrdered()) {

                block.Set( "data.Id", data.Id );
                block.Set( "data.OrderId", data.OrderId );

                block.Set( "data.AddSubLink", to( AddSubPage, data.Id ) );

                int indentLength = tree.GetDepth( data.Id ) * 20;
                String indent = "padding-left:" + indentLength + "px";
                block.Set( "data.Indent", indent );

                block.Set( "data.Title", data.Title );
                block.Set( "data.Created", data.Created );
                block.Set( "data.Hits", data.Hits );
                block.Set( "data.ReplyCount", data.Replies );
                block.Set( "data.IsAllowReplyStr", data.IsAllowReplyStr );

                block.Set( "data.ViewUrl", to( ViewUrl, data.Id ) );

                block.Set( "data.LinkShow", plink( data.Id ) );
                block.Set( "data.LinkDelete", to( Delete, data.Id ) );
                block.Set( "data.LinkEdit", to( Edit, data.Id ) );

                block.Next();

            }
        }
Example #21
0
		public override void PopulateTree (Tree tree)
		{
			var storage = tree.HelpSource.Storage;
			var nsSummaries = new Dictionary<string, XElement> ();
			int resID = 0;

			foreach (var asm in directories) {
				var indexFilePath = Path.Combine (asm, "index.xml");
				if (!File.Exists (indexFilePath)) {
					Console.Error.WriteLine ("Warning: couldn't process directory `{0}' as it has no index.xml file", asm);
					continue;
				}

				EcmaDoc.PopulateTreeFromIndexFile (indexFilePath, EcmaHelpSource.EcmaPrefix, tree, storage, nsSummaries, _ => resID++.ToString ());
			}

			foreach (var summary in nsSummaries)
				storage.Store ("xml.summary." + summary.Key, summary.Value.ToString ());

			var masterSummary = new XElement ("elements",
			                                  directories
			                                  .SelectMany (d => Directory.EnumerateFiles (d, "ns-*.xml"))
			                                  .Select (ExtractNamespaceSummary));
			storage.Store ("mastersummary.xml", masterSummary.ToString ());
		}
Example #22
0
 private static Map Iterate(ConcurrentQueue<Tuple<Map, char>> queue, Tree tree)
 {
     Tuple<Map, char> var;
     while (!queue.TryDequeue(out var)) System.Threading.Thread.Sleep(5);
     var currentMap = var.Item1;
     var cars = currentMap.Parse();
       //Console.WriteLine("Checking:\n" + currentMap);
     if (cars.ContainsKey(Globals.TargetCar) && cars[Globals.TargetCar].Item1.Equals(targetLocation))
         return currentMap;
     foreach (var kvp in cars)
         if (kvp.Key != var.Item2) {
             Map move;
             bool horizontal = kvp.Value.Item3 == Direction.Right;
             for (int i = 1; i <= (horizontal ? kvp.Value.Item1.X : kvp.Value.Item1.Y); i++) {
                 move = currentMap.makeMove(kvp.Key, kvp.Value.Item1, kvp.Value.Item3.Invert(), kvp.Value.Item2, i);
                 if (move != null) {
                     NewMethod(queue, tree, currentMap, kvp, move);
                 }
                 else break;
             }
             for (int i = 1; i < (horizontal ? map.map.GetLength(0) - kvp.Value.Item1.X : map.map.GetLength(1) - kvp.Value.Item1.Y); i++) {
                 move = currentMap.makeMove(kvp.Key, kvp.Value.Item1, kvp.Value.Item3, kvp.Value.Item2, i);
                 if (move != null) {
                     NewMethod(queue, tree, currentMap, kvp, move);
                 }
                 else break;
             }
         }
     if (queue.Count == 0) return Globals.NoSolutions; // We don't have anything to add
     return null; // no solution found yet
 }
Example #23
0
        public static string ComputeId(Tree tree)
        {
            using (var md = new MessageDigest())
            {
                using (var ms = new MemoryStream())
                {
                    foreach (var item in tree.Items)
                    {
                        var data = Encoding.Default.GetBytes(string.Format("{0} {1}\0", item.Mode, item.Name));
                        ms.Write(data, 0, data.Length);

                        var id = Helper.IdToByteArray(item.Id);
                        ms.Write(id, 0, id.Length);
                    }

                    var header = Encoding.Default.GetBytes(string.Format("tree {0}\0", ms.Length));
                    ms.Position = 0;
                    md.Update(header);
                    md.Update(ms);
                }
                var digest = md.Digest();

                return Helper.ByteArrayToId(digest);
            }
        }
Example #24
0
        private static void DisplayTree(Tree<int> tree)
        {
            var serializer = new XmlSerializer(tree.GetType());
            serializer.Serialize(Console.Out, tree);

            Console.WriteLine();
        }
Example #25
0
		public void NonFullRootNodeTest ()
		{
			var tree = new Tree<int, string>(new TreeMemoryNodeManager<int, string>(2, Comparer<int>.Default),
				allowDuplicateKeys: true);

			tree.Insert (1, "1");

			Assert.AreEqual (0, (from node in tree.LargerThan(7) select node).Count());
			Assert.AreEqual (0, (from node in tree.LargerThanOrEqualTo(7) select node).Count());
			Assert.AreEqual (1, (from node in tree.LessThan(7) select node).FirstOrDefault().Item1);
			Assert.AreEqual (1, (from node in tree.LessThanOrEqualTo(7) select node).FirstOrDefault().Item1);
			Assert.AreEqual (1, (from node in tree.LessThanOrEqualTo(1) select node).FirstOrDefault().Item1);
			Assert.AreEqual (0, (from node in tree.LessThan(1) select node).Count());

			tree.Insert (5, "5");
			tree.Insert (9, "9");

			// 1,5,9

			Assert.IsTrue ((from node in tree.LessThanOrEqualTo(9) select node.Item1).SequenceEqual(new int[] { 9, 5, 1 }));
			Assert.IsTrue ((from node in tree.LessThan(9) select node.Item1).SequenceEqual(new int[] { 5, 1 }));
			Assert.IsTrue ((from node in tree.LargerThanOrEqualTo(5) select node.Item1).SequenceEqual(new int[] { 5, 9 }));
			Assert.IsTrue ((from node in tree.LargerThan(5) select node.Item1).SequenceEqual(new int[] { 9 }));


			Assert.DoesNotThrow(delegate {
				tree.Insert (5, "5.1");
			});

			// Iterating test
			var found = (from node in tree.LargerThanOrEqualTo(5) select node.Item2).ToList ();
			Assert.AreEqual (3, found.Count);
			Assert.IsTrue (found.Contains("5.1"));
			Assert.IsTrue (found.Contains("5"));
		}
Example #26
0
		public override void PopulateTree (Tree tree)
		{
			var doc = XDocument.Load (tocFile);
			var uls = doc.Descendants (ns + "body").First ().Elements (ns + "ul");
			foreach (var ul in uls)
				ParseUl (tree, tree.RootNode, ul);
		}
Example #27
0
 public static void DoTable(Tree<Cell> table, Interpreter activeFixture, bool inFlow)
 {
     var activeFlowFixture = activeFixture as FlowInterpreter;
     if (activeFlowFixture != null) activeFlowFixture.DoSetUp(table);
     activeFixture.Interpret(table);
     if (activeFlowFixture != null && !inFlow) activeFlowFixture.DoTearDown(table);
 }
        static void Main()
        {
            Tree<int> tree =
            new Tree<int>(3,
                          new Tree<int>(5,
                                        new Tree<int>(0),
                                        new Tree<int>(1),
                                        new Tree<int>(6)),
                          new Tree<int>(2,
                                        new Tree<int>(4)));

            Console.WriteLine("Depth-First Search (DFS) traversal (recursive):");
            tree.TraverseDFS();
            Console.WriteLine();

            Console.WriteLine("Breadth-First Search (BFS) traversal (with queue):");
            tree.TraverseBFS();
            Console.WriteLine();

            Console.WriteLine();
            Console.WriteLine("Depth-First Search (DFS) traversal (with stack):");
            tree.TraverseDFSWithStack();
            Console.WriteLine();

            Console.WriteLine("Root: {0}", tree.Root.Value);

            Console.Write("Leafs: ");
            tree.TraverseLeafs(tree.Root);
            Console.WriteLine();
        }
Example #29
0
 public void Interpret(CellProcessor processor, Tree<Cell> table)
 {
     new Traverse<Cell>()
         .Rows.Header(row => headerRow = row)
         .Rows.Rest(row => ComputeRow(processor, row))
         .VisitTable(table);
 }
Example #30
0
    static void Main()
    {
        Node<int> root = new Node<int>(5);
        Tree<int> tree = new Tree<int>(root);

        tree.Add(new Node<int>(7));
        tree.Add(new Node<int>(1));
        tree.Add(new Node<int>(2));
        tree.Add(new Node<int>(9));
        tree.Add(new Node<int>(4));
        tree.Add(new Node<int>(8));
        tree.Add(new Node<int>(0));
        tree.Add(new Node<int>(11));
        tree.Add(new Node<int>(-3));
        tree.Add(new Node<int>(-6));
        tree.Add(new Node<int>(-5));
        tree.Add(new Node<int>(-8));
        tree.Add(new Node<int>(5));
        tree.Add(new Node<int>(12));

        tree.Print();
        tree.FindLongestPath();

        Console.WriteLine("++++++++++++++++++++++++++++");

        var allSubTreessWithSum = tree.FindSubtreesWithSum(-10);

        foreach (var subTree in allSubTreessWithSum)
        {
            subTree.Print();
        }
    }
Example #31
0
 public virtual void AddTree(Tree tree)
 {
     Trees.Add(tree);
     tree.Site = this;
 }
Example #32
0
 /*********
 ** Public methods
 *********/
 /// <summary>Construct an instance.</summary>
 /// <param name="gameHelper">Provides utility methods for interacting with the game code.</param>
 /// <param name="tree">The lookup target.</param>
 /// <param name="tile">The tree's tile position.</param>
 /// <param name="translations">Provides translations stored in the mod folder.</param>
 public TreeSubject(GameHelper gameHelper, Tree tree, Vector2 tile, ITranslationHelper translations)
     : base(gameHelper, TreeSubject.GetName(translations, tree), null, translations.Get(L10n.Types.Tree), translations)
 {
     this.Target = tree;
     this.Tile   = tile;
 }
Example #33
0
 public void ResetToInitial()
 {
     transform.Set(OriginalTransform);
     AttachedToTree = null;
 }
Example #34
0
 public void OnDetached()
 {
     BeatSynchronizer.Instance.Stop(AudioSource);
     AttachedToTree = null;
 }
Example #35
0
 public TreeNodeClickedEvent(Tree tree, TreeNode node, bool isExpanded) : base(tree)
 {
     clickedNode     = node;
     this.isExpanded = isExpanded;
 }
Example #36
0
        public void Execute(IConsoleShell shell, string argStr, string[] args)
        {
            var window = new SS14Window {
                MinSize = (500, 400)
            };
            var tabContainer = new TabContainer();

            window.Contents.AddChild(tabContainer);
            var scroll = new ScrollContainer();

            tabContainer.AddChild(scroll);
            //scroll.SetAnchorAndMarginPreset(Control.LayoutPreset.Wide);
            var vBox = new BoxContainer
            {
                Orientation = LayoutOrientation.Vertical
            };

            scroll.AddChild(vBox);

            var progressBar = new ProgressBar {
                MaxValue = 10, Value = 5
            };

            vBox.AddChild(progressBar);

            var optionButton = new OptionButton();

            optionButton.AddItem("Honk");
            optionButton.AddItem("Foo");
            optionButton.AddItem("Bar");
            optionButton.AddItem("Baz");
            optionButton.OnItemSelected += eventArgs => optionButton.SelectId(eventArgs.Id);
            vBox.AddChild(optionButton);

            var tree = new Tree {
                VerticalExpand = true
            };
            var root = tree.CreateItem();

            root.Text = "Honk!";
            var child = tree.CreateItem();

            child.Text = "Foo";
            for (var i = 0; i < 20; i++)
            {
                child      = tree.CreateItem();
                child.Text = $"Bar {i}";
            }

            vBox.AddChild(tree);

            var rich    = new RichTextLabel();
            var message = new FormattedMessage.Builder();

            message.AddText("Foo\n");
            message.PushColor(Color.Red);
            message.AddText("Bar");
            message.Pop();
            rich.SetMessage(message.Build());
            vBox.AddChild(rich);

            var itemList = new ItemList();

            tabContainer.AddChild(itemList);
            for (var i = 0; i < 10; i++)
            {
                itemList.AddItem(i.ToString());
            }

            var grid = new GridContainer {
                Columns = 3
            };

            tabContainer.AddChild(grid);
            for (var y = 0; y < 3; y++)
            {
                for (var x = 0; x < 3; x++)
                {
                    grid.AddChild(new Button
                    {
                        MinSize = (50, 50),
                        Text    = $"{x}, {y}"
                    });
Example #37
0
        private Tree GetTreeFromInputStream()
        {
            int wordIndex = 0;

            // FSA
            //label:
            while (tokenizer.HasNext())
            {
                string token = tokenizer.Next();

                switch (token)
                {
                case LeftParen:

                    // cdm 20100225: This next line used to have "" instead of null, but the traditional and current tree normalizers depend on the label being null not "" when there is no label on a tree (like the outermost English PTB level)
                    string label = (tokenizer.Peek().Equals(LeftParen)) ? null : tokenizer.Next();
                    if (RightParen.Equals(label))
                    {
                        //Skip past empty trees
                        continue;
                    }
                    else if (treeNormalizer != null)
                    {
                        label = treeNormalizer.NormalizeNonterminal(label);
                    }

                    if (label != null)
                    {
                        label = StarPattern.Replace(label, "*");
                        label = SlashPattern.Replace(label, "/");
                    }

                    Tree newTree = treeFactory.NewTreeNode(label, null);     // dtrs are added below

                    if (currentTree == null)
                    {
                        stack.Add(newTree);
                    }
                    else
                    {
                        currentTree.AddChild(newTree);
                        stack.Add(currentTree);
                    }

                    currentTree = newTree;

                    break;

                case RightParen:
                    if (!stack.Any())
                    {
                        // Warn that file has too many right parens
                        //break label;
                        goto post_while_label;
                    }

                    //Accept
                    currentTree = stack.Last();
                    stack.RemoveAt(stack.Count - 1);     // i.e., stack.pop()

                    if (!stack.Any())
                    {
                        return(currentTree);
                    }

                    break;

                default:

                    if (currentTree == null)
                    {
                        // A careful Reader should warn here, but it's kind of useful to
                        // suppress this because then the TreeReader doesn't print a ton of
                        // messages if there is a README file in a directory of Trees.
                        //break label;
                        goto post_while_label;
                    }

                    string terminal = (treeNormalizer == null) ? token : treeNormalizer.NormalizeTerminal(token);
                    terminal = StarPattern.Replace(terminal, "*");
                    terminal = SlashPattern.Replace(terminal, "/");
                    Tree leaf = treeFactory.NewLeaf(terminal);
                    if (leaf.Label() is IHasIndex)
                    {
                        var hi = (IHasIndex)leaf.Label();
                        hi.SetIndex(wordIndex);
                    }
                    if (leaf.Label() is IHasWord)
                    {
                        var hw = (IHasWord)leaf.Label();
                        hw.SetWord(leaf.Label().Value());
                    }
                    wordIndex++;

                    currentTree.AddChild(leaf);
                    // cdm: Note: this implementation just isn't as efficient as the old recursive descent parser (see 2008 code), where all the daughters are gathered before the tree is made....
                    break;
                }
            }
post_while_label:
            {
            }

            //Reject
            return(null);
        }
Example #38
0
        public void doMagic(bool playedToday)
        {
            if (Game1.currentLocation.isOutdoors)
            {
                List <Vector2> treetiles = new List <Vector2>();


                GameLocation gls = Game1.currentLocation;

                foreach (var keyV in gls.terrainFeatures.Keys)
                {
                    if (gls.terrainFeatures[keyV] is Tree || gls.terrainFeatures[keyV] is FruitTree || gls.terrainFeatures[keyV] is Grass || gls.terrainFeatures[keyV] is Bush)
                    {
                        treetiles.Add(keyV);
                    }
                }


                for (int i = 0; i < treetiles.Count(); i++)
                {
                    if (gls.terrainFeatures[treetiles[i]] is Tree)
                    {
                        if (!playedToday)
                        {
                            Tree tree = gls.terrainFeatures[treetiles[i]] as Tree;
                            tree.growthStage = (tree.growthStage < 4) ? tree.growthStage + 1 : tree.growthStage;
                            gls.terrainFeatures[treetiles[i]] = tree;
                        }
                        (gls.terrainFeatures[treetiles[i]] as Tree).performUseAction(treetiles[i]);
                    }

                    if (gls.terrainFeatures[treetiles[i]] is FruitTree)
                    {
                        if (!playedToday)
                        {
                            FruitTree tree = (gls.terrainFeatures[treetiles[i]] as FruitTree);
                            tree.growthStage     = (tree.growthStage <= 4) ? tree.growthStage + 1 : tree.growthStage;
                            tree.daysUntilMature = tree.daysUntilMature - 7;
                            gls.terrainFeatures[treetiles[i]] = tree;
                        }
                        (gls.terrainFeatures[treetiles[i]] as FruitTree).performUseAction(treetiles[i]);
                    }

                    if (gls.terrainFeatures[treetiles[i]] is Grass)
                    {
                        if (!playedToday)
                        {
                            Grass grass = (gls.terrainFeatures[treetiles[i]] as Grass);
                            grass.numberOfWeeds = Math.Min(grass.numberOfWeeds + Game1.random.Next(1, 4), 4);
                            gls.terrainFeatures[treetiles[i]] = grass;
                        }
                        (gls.terrainFeatures[treetiles[i]] as Grass).doCollisionAction(gls.terrainFeatures[treetiles[i]].getBoundingBox(treetiles[i]), 3, treetiles[i], Game1.player, Game1.currentLocation);
                    }

                    if (gls.terrainFeatures[treetiles[i]] is Bush)
                    {
                        (gls.terrainFeatures[treetiles[i]] as Bush).performUseAction(treetiles[i]);
                    }
                }
                priorRadius = Game1.player.magneticRadius;
                Game1.player.magneticRadius += 2000;

                DelayedAction resetAction = new DelayedAction(8000);
                resetAction.behavior = new DelayedAction.delayedBehavior(resetRadius);

                Game1.delayedActions.Add(resetAction);
            }
        }
Example #39
0
 public bool CanParse(Type type, TypedValue instance, Tree <Cell> parameters)
 {
     return(type == typeof(bool));
 }
Example #40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ImportFilesDialog"/> class.
        /// </summary>
        /// <param name="entries">The entries to edit settings.</param>
        public ImportFilesDialog(List <ImportFileEntry> entries)
            : base("Import files settings")
        {
            if (entries == null || entries.Count < 1)
            {
                throw new ArgumentNullException();
            }

            const float TotalWidth   = 920;
            const float EditorHeight = 450;

            Width = TotalWidth;

            // Header and help description
            var headerLabel = new Label(0, 0, TotalWidth, 40)
            {
                Text      = "Import settings",
                DockStyle = DockStyle.Top,
                Parent    = this,
                Font      = new FontReference(Style.Current.FontTitle)
            };
            var infoLabel = new Label(10, headerLabel.Bottom + 5, TotalWidth - 20, 40)
            {
                Text = "Specify options for importing files. Every file can have different settings. Select entries on the left panel to modify them.\nPro Tip: hold CTRL key and select entries to edit multiple at once.",
                HorizontalAlignment = TextAlignment.Near,
                Margin    = new Margin(7),
                DockStyle = DockStyle.Top,
                Parent    = this
            };

            // Buttons
            const float ButtonsWidth  = 60;
            const float ButtonsMargin = 8;
            var         importButton  = new Button(TotalWidth - ButtonsMargin - ButtonsWidth, infoLabel.Bottom - 30, ButtonsWidth)
            {
                Text        = "Import",
                AnchorStyle = AnchorStyle.UpperRight,
                Parent      = this
            };

            importButton.Clicked += OnImport;
            var cancelButton = new Button(importButton.Left - ButtonsMargin - ButtonsWidth, importButton.Y, ButtonsWidth)
            {
                Text        = "Cancel",
                AnchorStyle = AnchorStyle.UpperRight,
                Parent      = this
            };

            cancelButton.Clicked += OnCancel;

            // Split panel for entries list and settings editor
            var splitPanel = new SplitPanel(Orientation.Horizontal, ScrollBars.Vertical, ScrollBars.Vertical)
            {
                Y         = infoLabel.Bottom,
                Size      = new Vector2(TotalWidth, EditorHeight),
                DockStyle = DockStyle.Fill,
                Parent    = this
            };

            // Settings editor
            _settingsEditor = new CustomEditorPresenter(null);
            _settingsEditor.Panel.Parent = splitPanel.Panel2;

            // Setup tree
            var tree = new Tree(true);

            tree.Parent      = splitPanel.Panel1;
            tree.RightClick += OnTreeRightClick;
            _rootNode        = new TreeNode(false);
            for (int i = 0; i < entries.Count; i++)
            {
                var entry = entries[i];

                // TODO: add icons for textures/models/etc from FileEntry to tree node??
                var node = new ItemNode(entry)
                {
                    Parent = _rootNode
                };
            }
            _rootNode.Expand();
            _rootNode.ChildrenIndent = 0;
            _rootNode.Parent         = tree;
            tree.Margin           = new Margin(0.0f, 0.0f, -14.0f, 2.0f); // Hide root node
            tree.SelectedChanged += OnSelectedChanged;

            // Select the first item
            tree.Select(_rootNode.Children[0] as TreeNode);

            Size = new Vector2(TotalWidth, splitPanel.Bottom);
        }
Example #41
0
 private CollectionOfBloomFilters(Mode mode, Tree tree, TransactionOperationContext context)
 {
     _mode    = mode;
     _context = context;
     _tree    = tree;
 }
Example #42
0
 /// <summary>
 /// Create a new <code>TreeGraphNode</code> having the same tree
 /// structure and label values as an existing tree (but no shared storage)
 /// </summary>
 /// <param name="t">the tree to copy</param>
 /// <param name="graph">the graph of which this node is a part</param>
 public TreeGraphNode(Tree t, GrammaticalStructure graph) :
     this(t, (TreeGraphNode)null)
 {
     this.SetTreeGraph(graph);
 }
Example #43
0
 private static void SetRelations(Tree <int> currentParrent, Tree <int> currentChild)
 {
     currentParrent.AddNewChild(currentChild);
     currentChild.SetParent(currentParrent);
 }
Example #44
0
    static void Main()
    {
        Node a = new Node("a");
        Node b = new Node("b");
        Node c = new Node("c");
        Node d = new Node("d");
        Node e = new Node("e");
        Node f = new Node("f");

        Graph graph = new Graph();

        a.Add(b, 4);
        a.Add(c, 5);
        a.Add(d, 9);
        graph.Add(a);

        b.Add(a, 4);
        b.Add(d, 2);
        graph.Add(b);

        c.Add(a, 5);
        c.Add(d, 20);
        c.Add(e, 7);
        graph.Add(c);

        d.Add(b, 2);
        d.Add(c, 20);
        d.Add(a, 9);
        d.Add(e, 8);
        graph.Add(d);

        e.Add(c, 7);
        e.Add(d, 8);
        e.Add(f, 12);
        graph.Add(e);

        f.Add(e, 12);
        graph.Add(f);

        PriorityQueue <Link> q = new PriorityQueue <Link>();
        Tree tree = new Tree(new Node("a"));

        foreach (var child in a)
        {
            Link currentLink = new Link(a, child, a.GetDistance(child.Id));
            q.Enqueue(currentLink);
        }

        while (q.Count > 0)
        {
            Link currentLink = q.Dequeue();

            if (tree.Search(currentLink.Child.Id))
            {
                continue;
            }

            tree.Add(new Node(currentLink.Child.Id));
            //Console.WriteLine(currentLink.Child.Id+" distance => "+ currentLink.Distance+" parent id => "+currentLink.Parent.Id);
            tree.GetChild(currentLink.Parent.Id).Add(currentLink.Child, currentLink.Distance);
            //5 Console.WriteLine("pass");

            foreach (var linkage in currentLink.Child)
            {
                if (!tree.Search(linkage.Id))
                {
                    Link link = new Link(currentLink.Child, linkage, currentLink.Child.GetDistance(linkage.Id));
                    q.Enqueue(link);
                }
            }
        }

        int shortestDistance = 0;

        foreach (var child in tree)
        {
            foreach (var subChild in child)
            {
                shortestDistance += child.GetDistance(subChild.Id);
            }
        }

        Console.WriteLine(shortestDistance);
    }
Example #45
0
 public void AddChild(Tree <T> child)
 {
     children.Add(child);
 }
Example #46
0
 public BloomFilter64(int key, Tree tree, bool writable, ByteStringContext allocator)
     : base(key, tree, writable, M, PtrSize, MaxCapacity, allocator)
 {
 }
            public void WriteTree(Tree blTree)
            {
                int max_count;                               /* max repeat count */
                int min_count;                               /* min repeat count */
                int count;                                   /* repeat count of the current code */
                int curlen = -1;                             /* length of current code */

                int i = 0;

                while (i < numCodes)
                {
                    count = 1;
                    int nextlen = length[i];
                    if (nextlen == 0)
                    {
                        max_count = 138;
                        min_count = 3;
                    }
                    else
                    {
                        max_count = 6;
                        min_count = 3;
                        if (curlen != nextlen)
                        {
                            blTree.WriteSymbol(nextlen);
                            count = 0;
                        }
                    }
                    curlen = nextlen;
                    i++;

                    while (i < numCodes && curlen == length[i])
                    {
                        i++;
                        if (++count >= max_count)
                        {
                            break;
                        }
                    }

                    if (count < min_count)
                    {
                        while (count-- > 0)
                        {
                            blTree.WriteSymbol(curlen);
                        }
                    }
                    else if (curlen != 0)
                    {
                        blTree.WriteSymbol(REP_3_6);
                        dh.pending.WriteBits(count - 3, 2);
                    }
                    else if (count <= 10)
                    {
                        blTree.WriteSymbol(REP_3_10);
                        dh.pending.WriteBits(count - 3, 3);
                    }
                    else
                    {
                        blTree.WriteSymbol(REP_11_138);
                        dh.pending.WriteBits(count - 11, 7);
                    }
                }
            }
Example #48
0
 public void RemoveChild(Tree <T> child)
 {
     children.Remove(child);
 }
Example #49
0
 public override void MouseDoubleClick(TreeNodeAdvMouseEventArgs args)
 {
     Tree.AutoSizeColumn(Column);
 }
Example #50
0
    public void AddChild(T child)
    {
        Tree <T> node = new Tree <T>(child);

        children.Add(node);
    }
Example #51
0
        private string dataString(TreeNode <NodeData> node)
        {
            string data = string.Empty;

            if (node.Data.Type == FTN.Common.DMSType.ENEGRYSOURCE)
            {
                EnergySource energySource = (EnergySource)node.Data.IdentifiedObject;
                data += "GID: " + energySource.GlobalId + "\n";
                data += "Name:" + energySource.Name + "\n";
                data += "Position: " + energySource.Latitude + ", " + energySource.Longitude + "\n";
                data += "Active power: " + energySource.ActivePower + "\n";

                foreach (long gid in energySource.Measurements)
                {
                    TreeNode <NodeData> measurement = Tree.Where(x => x.Data.IdentifiedObject.GlobalId == gid && x.Data.Type == FTN.Common.DMSType.ANALOG).First();
                    if (measurement != null)
                    {
                        Analog analogMeas = (Analog)measurement.Data.IdentifiedObject;
                        data += "Measurement value: " + analogMeas.NormalValue + "\n";
                    }
                }
            }
            else if (node.Data.Type == FTN.Common.DMSType.ENERGYCONSUMER)
            {
                EnergyConsumer energyConsumer = (EnergyConsumer)node.Data.IdentifiedObject;
                data += "GID: " + energyConsumer.GlobalId + "\n";
                data += "Position: " + energyConsumer.Latitude + ", " + energyConsumer.Longitude + "\n";
                data += "Name: " + energyConsumer.Name + "\n";
                data += "PFixed: " + energyConsumer.PFixed + "\n";
                data += "QFixed: " + energyConsumer.QFixed + "\n";

                foreach (long gid in energyConsumer.Measurements)
                {
                    TreeNode <NodeData> measurement = Tree.Where(x => x.Data.IdentifiedObject.GlobalId == gid && x.Data.Type == FTN.Common.DMSType.ANALOG).First();
                    if (measurement != null)
                    {
                        Analog analogMeas = (Analog)measurement.Data.IdentifiedObject;
                        data += "Measurement value: " + analogMeas.NormalValue + "\n";
                    }
                }
            }
            else if (node.Data.Type == FTN.Common.DMSType.GENERATOR)
            {
                Generator generator = (Generator)node.Data.IdentifiedObject;
                data += "GID: " + generator.GlobalId + "\n";
                data += "Position: " + generator.Latitude + ", " + generator.Longitude + "\n";
                data += "Name: " + generator.Name + "\n";
                data += "Type: " + generator.GeneratorType.ToString() + "\n";

                foreach (long gid in generator.Measurements)
                {
                    TreeNode <NodeData> measurement = Tree.Where(x => x.Data.IdentifiedObject.GlobalId == gid && x.Data.Type == FTN.Common.DMSType.ANALOG).First();
                    if (measurement != null)
                    {
                        Analog analogMeas = (Analog)measurement.Data.IdentifiedObject;
                        data += "Measurement " + analogMeas.Mrid + "= " + analogMeas.NormalValue + " kW\n";
                    }
                }
            }
            return(data);
        }
Example #52
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SceneTreeWindow"/> class.
        /// </summary>
        /// <param name="editor">The editor.</param>
        public SceneTreeWindow(Editor editor)
            : base(editor, true, ScrollBars.Both)
        {
            Title = "Scene";

            // Create scene structure tree
            var root = editor.Scene.Root;

            root.TreeNode.ChildrenIndent = 0;
            root.TreeNode.Expand();
            _tree        = new Tree(true);
            _tree.Margin = new Margin(0.0f, 0.0f, -14.0f, 0.0f); // Hide root node
            _tree.AddChild(root.TreeNode);
            _tree.SelectedChanged += Tree_OnSelectedChanged;
            _tree.RightClick      += Tree_OnRightClick;
            _tree.Parent           = this;

            // Spawnable actors (groups with single entry are inlined without a child menu)
            var groups = new[]
            {
                new ActorsGroup
                {
                    Types = new[] { new KeyValuePair <string, Type>("Actor", typeof(EmptyActor)) }
                },
                new ActorsGroup
                {
                    Types = new[] { new KeyValuePair <string, Type>("Model", typeof(ModelActor)) }
                },
                new ActorsGroup
                {
                    Types = new[] { new KeyValuePair <string, Type>("Camera", typeof(Camera)) }
                },
                new ActorsGroup
                {
                    Name  = "Lights",
                    Types = new[]
                    {
                        new KeyValuePair <string, Type>("Directional Light", typeof(DirectionalLight)),
                        new KeyValuePair <string, Type>("Point Light", typeof(PointLight)),
                        new KeyValuePair <string, Type>("Spot Light", typeof(SpotLight)),
                        new KeyValuePair <string, Type>("Sky Light", typeof(SkyLight)),
                    }
                },
                new ActorsGroup
                {
                    Name  = "Visuals",
                    Types = new[]
                    {
                        new KeyValuePair <string, Type>("Environment Probe", typeof(EnvironmentProbe)),
                        new KeyValuePair <string, Type>("Sky", typeof(Sky)),
                        new KeyValuePair <string, Type>("Skybox", typeof(Skybox)),
                        new KeyValuePair <string, Type>("Exponential Height Fog", typeof(ExponentialHeightFog)),
                        new KeyValuePair <string, Type>("PostFx Volume", typeof(PostFxVolume)),
                        new KeyValuePair <string, Type>("Decal", typeof(Decal)),
                    }
                },
                new ActorsGroup
                {
                    Name  = "Physics",
                    Types = new[]
                    {
                        new KeyValuePair <string, Type>("Rigid Body", typeof(RigidBody)),
                        new KeyValuePair <string, Type>("Character Controller", typeof(CharacterController)),
                        new KeyValuePair <string, Type>("Box Collider", typeof(BoxCollider)),
                        new KeyValuePair <string, Type>("Sphere Collider", typeof(SphereCollider)),
                        new KeyValuePair <string, Type>("Capsule Collider", typeof(CapsuleCollider)),
                        new KeyValuePair <string, Type>("Mesh Collider", typeof(MeshCollider)),
                        new KeyValuePair <string, Type>("Fixed Joint", typeof(FixedJoint)),
                        new KeyValuePair <string, Type>("Distance Joint", typeof(DistanceJoint)),
                        new KeyValuePair <string, Type>("Slider Joint", typeof(SliderJoint)),
                        new KeyValuePair <string, Type>("Spherical Joint", typeof(SphericalJoint)),
                        new KeyValuePair <string, Type>("Hinge Joint", typeof(HingeJoint)),
                        new KeyValuePair <string, Type>("D6 Joint", typeof(D6Joint)),
                    }
                },
                new ActorsGroup
                {
                    Name  = "Other",
                    Types = new[]
                    {
                        new KeyValuePair <string, Type>("Animated Model", typeof(AnimatedModel)),
                        new KeyValuePair <string, Type>("Bone Socket", typeof(BoneSocket)),
                        new KeyValuePair <string, Type>("CSG Box Brush", typeof(BoxBrush)),
                        new KeyValuePair <string, Type>("Audio Source", typeof(AudioSource)),
                        new KeyValuePair <string, Type>("Audio Listener", typeof(AudioListener)),
                    }
                },
                new ActorsGroup
                {
                    Name  = "GUI",
                    Types = new[]
                    {
                        new KeyValuePair <string, Type>("UI Control", typeof(UIControl)),
                        new KeyValuePair <string, Type>("UI Canvas", typeof(UICanvas)),
                        new KeyValuePair <string, Type>("Text Render", typeof(TextRender)),
                    }
                },
            };

            // Create context menu
            _contextMenu = new ContextMenu();
            _contextMenu.MinimumWidth = 120;
            _cmRename    = _contextMenu.AddButton("Rename", Rename);
            _cmDuplicate = _contextMenu.AddButton("Duplicate", Editor.SceneEditing.Duplicate);
            _cmDelete    = _contextMenu.AddButton("Delete", Editor.SceneEditing.Delete);
            _contextMenu.AddSeparator();
            _cmCopy = _contextMenu.AddButton("Copy", Editor.SceneEditing.Copy);
            _contextMenu.AddButton("Paste", Editor.SceneEditing.Paste);
            _cmCut = _contextMenu.AddButton("Cut", Editor.SceneEditing.Cut);
            _contextMenu.AddSeparator();
            _spawnMenu = _contextMenu.AddChildMenu("New");
            var newActorCm = _spawnMenu.ContextMenu;

            for (int i = 0; i < groups.Length; i++)
            {
                var group = groups[i];

                if (group.Types.Length == 1)
                {
                    var type = group.Types[0].Value;
                    newActorCm.AddButton(group.Types[0].Key, () => Spawn(type));
                }
                else
                {
                    var groupCm = newActorCm.AddChildMenu(group.Name).ContextMenu;
                    for (int j = 0; j < group.Types.Length; j++)
                    {
                        var type = group.Types[j].Value;
                        groupCm.AddButton(group.Types[j].Key, () => Spawn(type));
                    }
                }
            }

            _contextMenu.VisibleChanged += ContextMenuOnVisibleChanged;
        }
Example #53
0
 public PostfixEnumerator(Tree <T> tree) => throw new TreeException("PostfixEnumerator: Not implemented");
Example #54
0
 public override bool MouseMove(MouseEventArgs args)
 {
     Column.Width = _initWidth + args.Location.X - _initLocation.X;
     Tree.UpdateView();
     return(true);
 }
Example #55
0
        /// <summary>
        /// "hook" of performToolAction in StardewValley.TerrainFeatures.Tree
        /// </summary>
        /// <returns><c>true</c> proceed to game code <c>false</c> stop game code</returns>
        /// <param name="__instance"> reference to access variables in Tree.</param>
        /// <param name="t">Tool used</param>
        /// <param name="explosion">Explosion.</param>
        /// <param name="tileLocation">Tile location.</param>
        /// <param name="location">Location where action is performed</param>
        private static bool performToolAction_Prefix2(Tree __instance, Tool t, int explosion, Vector2 tileLocation, GameLocation location)
        {
            //Don't do anything if Mod isn't active
            if (!IsModActive)
            {
                return(true);
            }
            ModMonitor.Log($"Prefix2 called with: t:{t} explosion:{explosion} tileLocation: {tileLocation} location: {location}");
            try
            {
                //iterates through all terrain features at the location
                foreach (KeyValuePair <Vector2, TerrainFeature> pair in location.terrainFeatures.Pairs)
                {
                    if (pair.Key == tileLocation)
                    {
                        ModMonitor.Log($"found {pair.Value}!", LogLevel.Trace);
                        if (pair.Value is Tree)
                        {
                            ModMonitor.Log("It's a tree!", LogLevel.Trace);
                            tree = (Tree)pair.Value;
                        }
                    }
                }
                //NOTE: Using net types will *totally* not f**k up everything in multiplayer
                NetBool  tapped      = tree.tapped;
                NetFloat health      = tree.health;
                NetInt   growthStage = tree.growthStage;
                NetBool  stump       = tree.stump;
                //NetInt treeType = tree.treeType;

                ModMonitor.Log($"Tree properties: growthStage: {tree.growthStage} stump: {tree.stump} tapped: {tree.tapped} treeType: {tree.treeType} shakeLeft: {tree.shakeLeft}");

                if (location == null)
                {
                    location = Game1.currentLocation;
                }
                if (explosion > 0)
                {
                    tapped.Value = false;
                }

                if ((bool)tapped)
                {
                    return(true);
                }
                if ((float)health <= -99f)
                {
                    return(true);
                }

                if ((int)growthStage >= 5)
                {
                    if (t != null && t is Axe)
                    {
                        //location.playSound("axchop", NetAudio.SoundContext.Default);
                        //lastPlayerToHit.Value = t.getLastFarmerToUse().UniqueMultiplayerID;
                        //location.debris.Add(new Debris(12, Game1.random.Next(1, 3), t.getLastFarmerToUse().GetToolLocation(false) + new Vector2(16f, 0f), t.getLastFarmerToUse().Position, 0, ((int)treeType == 7) ? 10000 : (-1)));

                        /*
                         * // try to create secret note
                         * if (!(bool)stump && t.getLastFarmerToUse() != null && t.getLastFarmerToUse().hasMagnifyingGlass && Game1.random.NextDouble() < 0.005)
                         * {
                         *  Object @object = location.tryToCreateUnseenSecretNote(t.getLastFarmerToUse());
                         *  if (@object != null)
                         *  {
                         *      Game1.createItemDebris(@object, new Vector2(tileLocation.X, tileLocation.Y - 3f) * 64f, -1, location, Game1.player.getStandingY() - 32);
                         *  }
                         * }
                         */
                    }
                    else if (explosion <= 0)
                    {
                        return(true);
                    }
                    //shake(tileLocation, true, location);
                    float num = 1f;
                    if (explosion > 0)
                    {
                        num = (float)explosion;
                    }
                    else
                    {
                        if (t == null)
                        {
                            return(true);
                        }
                        switch ((int)t.upgradeLevel)
                        {
                        //Starter tool
                        case 0:
                            num = 1f;
                            break;

                        //Copper tool
                        case 1:
                            num = 1.25f;
                            break;

                        //Steel (Iron) Tool
                        case 2:
                            num = 1.67f;
                            break;

                        //Gold tool
                        case 3:
                            num = 2.5f;
                            break;

                        //Iridium tool
                        case 4:
                            num = 5f;
                            break;
                        }
                    }
                    health.Value -= num;
                    if ((float)health <= 0f && performTreeFall(t, explosion, tileLocation, location))
                    {
                        return(true);
                    }
                    health.Value += num;
                }
                else if ((int)growthStage >= 3)
                {
                    if (t != null && t.BaseName.Contains("Ax"))
                    {
                        /*
                         * NetCollection<Debris> debris = location.debris;
                         * int numberOfChunks = Game1.random.Next((int)t.upgradeLevel * 2, (int)t.upgradeLevel * 4);
                         * Vector2 debrisOrigin = t.getLastFarmerToUse().GetToolLocation(false) + new Vector2(16f, 0f);
                         * Rectangle boundingBox = t.getLastFarmerToUse().GetBoundingBox();
                         * float x = (float)boundingBox.Center.X;
                         * boundingBox = t.getLastFarmerToUse().GetBoundingBox();
                         * debris.Add(new Debris(12, numberOfChunks, debrisOrigin, new Vector2(x, (float)boundingBox.Center.Y), 0, -1));
                         */
                    }
                    else if (explosion <= 0)
                    {
                        return(true);
                    }
                    //shake(tileLocation, true, location);
                    float num2 = 1f;

                    /*
                     * if (Game1.IsMultiplayer)
                     * {
                     *  Random recentMultiplayerRandom = Game1.recentMultiplayerRandom;
                     * }
                     * else
                     * {
                     *  new Random((int)((float)(double)Game1.uniqueIDForThisGame + tileLocation.X * 7f + tileLocation.Y * 11f + (float)(double)Game1.stats.DaysPlayed + (float)health));
                     * }
                     */
                    if (explosion <= 0)
                    {
                        switch ((int)t.upgradeLevel)
                        {
                        case 0:
                            num2 = 2f;
                            break;

                        case 1:
                            num2 = 2.5f;
                            break;

                        case 2:
                            num2 = 3.34f;
                            break;

                        case 3:
                            num2 = 5f;
                            break;

                        case 4:
                            num2 = 10f;
                            break;
                        }
                    }
                    else
                    {
                        num2 = (float)explosion;
                    }
                    health.Value -= num2;
                    if ((float)health <= 0f)
                    {
                        performBushDestroy(tileLocation, location);
                        return(true);
                    }
                    health.Value += num2;
                }
                else if ((int)growthStage >= 1)
                {
                    /*
                     * if (explosion > 0)
                     * {
                     *  location.playSound("cut", NetAudio.SoundContext.Default);
                     *  return true;
                     * }
                     * if (t != null && t.BaseName.Contains("Axe"))
                     * {
                     *  location.playSound("axchop", NetAudio.SoundContext.Default);
                     *  Game1.createRadialDebris(location, 12, (int)tileLocation.X, (int)tileLocation.Y, Game1.random.Next(10, 20), false, -1, false, -1);
                     * }
                     */
                    if (t is Axe || t is Pickaxe || t is Hoe || t is MeleeWeapon)
                    {
                        performSproutDestroy(t, tileLocation, location);
                        return(true);
                    }
                }
                else
                {
                    if (explosion > 0)
                    {
                        return(true);
                    }
                    if (t.BaseName.Contains("Axe") || t.BaseName.Contains("Pick") || t.BaseName.Contains("Hoe"))
                    {
                        performSeedDestroy(t, tileLocation, location);
                        return(true);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                ModMonitor.Log($"Failed in {nameof(performToolAction_Prefix2)}:\n{ex}", LogLevel.Error);
                return(true); // run original logic
            }
        }
Example #56
0
        private void FilterCommandExecute(object paremeter)
        {
            TreeNode <NodeData> element = null;

            if (SelectedCriteria == "Name")
            {
                try
                {
                    element = Tree.Where(x => x.Data.IdentifiedObject.Name == SearchParameter).First();
                }
                catch
                {
                }

                if (element == null)
                {
                    NetworkModelItems = new ObservableCollection <NetworkModelViewClass>();
                    OnPropertyChanged("NetworkModelItems");
                    return;
                }
            }
            else if (SelectedCriteria == "Gid")
            {
                try
                {
                    element = Tree.Where(x => x.Data.IdentifiedObject.GlobalId.ToString() == SearchParameter).First();
                }
                catch
                {
                }
                if (element == null)
                {
                    NetworkModelItems = new ObservableCollection <NetworkModelViewClass>();
                    OnPropertyChanged("NetworkModelItems");
                    return;
                }
            }

            if (element.Data.Type == FTN.Common.DMSType.ACLINESEGMENT || element.Data.Type == FTN.Common.DMSType.ANALOG || element.Data.Type == FTN.Common.DMSType.BREAKER ||
                element.Data.Type == FTN.Common.DMSType.CONNECTIVITYNODE || element.Data.Type == FTN.Common.DMSType.DISCRETE || element.Data.Type == FTN.Common.DMSType.TERMINAL
                )
            {
                return;
            }

            NetworkModelItems = new ObservableCollection <NetworkModelViewClass>();
            if (element.Data.Type == FTN.Common.DMSType.ENEGRYSOURCE || element.Data.Type == FTN.Common.DMSType.ENERGYCONSUMER || element.Data.Type == FTN.Common.DMSType.GENERATOR)
            {
                if (element.Data.Type == FTN.Common.DMSType.ENEGRYSOURCE)
                {
                    string infoString = dataString(element);
                    NetworkModelItems.Add(new NetworkModelViewClass(Brushes.LightGreen, PackIconKind.TransmissionTower, "Energy source " + element.Data.IdentifiedObject.Name, infoString));
                }
                else
                {
                    DealWithChildren(element);
                }
            }
            else
            {
                foreach (TreeNode <NodeData> node in element.Children)
                {
                    DealWithChildren(node);
                }
            }
            OnPropertyChanged("NetworkModelItems");
        }
Example #57
0
 public void RemoveTree(Tree tree)
 {
     TreeList.Remove(tree);
 }
Example #58
0
 public InfixEnumerator(Tree <T> t)
 {
     _currNode = null; // NB: needs to start with -1;
     _root     = t.Root;
     _stack    = new Stack();
 }
 private void ShowStartingLocationChoices()
 {
     if ((UnityEngine.Object)titleText != (UnityEngine.Object)null)
     {
         titleText.text = "Choose Starting Location";
     }
     startNodes = worldGen.WorldLayout.GetStartNodes();
     startNodes.Shuffle();
     if (startNodes.Count > 0)
     {
         ChooseBaseLocation(startNodes[0]);
     }
     else
     {
         List <SubWorld> list = new List <SubWorld>();
         for (int i = 0; i < startNodes.Count; i++)
         {
             Tree tree = startNodes[i] as Tree;
             if (tree == null)
             {
                 tree = worldGen.GetOverworldForNode(startNodes[i] as Leaf);
                 if (tree == null)
                 {
                     continue;
                 }
             }
             SubWorld subWorldForNode = worldGen.GetSubWorldForNode(tree);
             if (subWorldForNode != null && !list.Contains(subWorldForNode))
             {
                 list.Add(subWorldForNode);
                 GameObject    gameObject = UnityEngine.Object.Instantiate(locationButtonPrefab);
                 RectTransform component  = gameObject.GetComponent <RectTransform>();
                 component.SetParent(chooseLocationPanel);
                 component.localScale = Vector3.one;
                 Text     componentInChildren = gameObject.GetComponentInChildren <Text>();
                 SubWorld subWorld            = null;
                 Tree     parent = startNodes[i].parent;
                 while (subWorld == null && parent != null)
                 {
                     subWorld = worldGen.GetSubWorldForNode(parent);
                     if (subWorld == null)
                     {
                         parent = parent.parent;
                     }
                 }
                 TagSet tagSet = new TagSet(startNodes[i].tags);
                 tagSet.Remove(WorldGenTags.Feature);
                 tagSet.Remove(WorldGenTags.StartLocation);
                 tagSet.Remove(WorldGenTags.IgnoreCaveOverride);
                 componentInChildren.text = tagSet.ToString();
                 int idx = i;
                 Button.ButtonClickedEvent buttonClickedEvent = new Button.ButtonClickedEvent();
                 buttonClickedEvent.AddListener(delegate
                 {
                     ChooseBaseLocation(startNodes[idx]);
                 });
                 Button component2 = gameObject.GetComponent <Button>();
                 component2.onClick = buttonClickedEvent;
             }
         }
     }
 }
Example #60
0
 public void AddTree(Tree tree)
 {
     TreeList.Add(tree);
 }