/// Entry point into console application.
    static void Main()
    {
        // Create a tree structure
        Composite root = new Composite("root");
        root.Add(new Leaf("Leaf A"));
        root.Add(new Leaf("Leaf B"));

        Composite comp1 = new Composite("Composite X");
        comp1.Add(new Leaf("Leaf XA"));
        comp1.Add(new Leaf("Leaf XB"));
        root.Add(comp1);

        Composite comp2 = new Composite("Composite Y");
        comp2.Add(new Leaf("Leaf YA"));
        comp2.Add(new Leaf("Leaf YB"));
        root.Add(comp2);

        Composite comp3 = new Composite("Composite Z");
        comp3.Add(new Leaf("Leaf ZA"));
        comp3.Add(new Leaf("Leaf ZB"));
        comp2.Add(comp3);

        root.Add(new Leaf("Leaf C"));

        // Add and remove a leaf
        Leaf leaf = new Leaf("Leaf D");
        root.Add(leaf);
        root.Remove(leaf);

        // Recursively display tree
        root.Display(1);

        // Wait for user
        Console.ReadKey();
    }
    private static void Main()
    {
        // Create a tree structure
        Composite root = new Composite("root");
        root.Add(new Leaf("Leaf A"));
        root.Add(new Leaf("Leaf B"));

        Composite comp = new Composite("Composite X");
        comp.Add(new Leaf("Leaf XA"));
        comp.Add(new Leaf("Leaf XB"));

        root.Add(comp);
        root.Add(new Leaf("Leaf C"));

        // Add and remove a leaf
        Leaf leaf = new Leaf("Leaf D");
        root.Add(leaf);
        root.Remove(leaf);

        // Recursively display tree
        root.Display(1);

        // Wait for user
        Console.Read();
    }
Esempio n. 3
0
        static void Main(string[] args)
        {
            Composite comp = new Composite();
            comp.Text = "first";
            Leaf leaf = new Leaf();

            comp.add(leaf);
            comp.draw();
        }
Esempio n. 4
0
 public Leaf(Bspt bspt, Leaf leaf, int countToKeep)
     : this(bspt)
 {
     for (int i = countToKeep; i < Bspt.leafCountMax; ++i)
     {
         tuples[count++] = leaf.tuples[i];
         leaf.tuples[i] = null;
     }
     leaf.count = countToKeep;
 }
	void UnitTest2 () {
		
		// 根節點
		IComponent theRoot = new Composite("Root");

		// 產生一最終節點
		IComponent theLeaf1 = new Leaf("Leaf1");

		// 加入節點
		theLeaf1.Add ( new Leaf("Leaf2") );  // 錯誤

			
	}
Esempio n. 6
0
 /**
  * initialize to return all points within the sphere defined
  * by center and radius
  *
  * @param center
  * @param radius
  */
 public void initialize(Tuple center, float radius)
 {
     this.center = center;
     this.radius = radius;
     this.radius2 = radius * radius;
     this.tHemisphere = false;
     for (int dim = bspt.dimMax; --dim >= 0; )
         centerValues[dim] = center.getDimensionValue(dim);
     leaf = null;
     stack[0] = bspt.eleRoot;
     sp = 1;
     findLeftLeaf();
 }
Esempio n. 7
0
        public static void Blow(Leaf leaf)
        {
            Rectangle mousePos = new Rectangle(Mouse.GetState().X,Mouse.GetState().Y,0,0);

            if (blowStrength < 5)
            {
                blowStrength = Mouse.GetState().ScrollWheelValue / 120;
            }

            if (Mouse.GetState().LeftButton == ButtonState.Pressed && // if mouse is
                leaf.collisionBox.Contains(mousePos) &&
                leaf.isOnTree == false)
            {
                //if the mouse is below the leaves, blow up/left/right
                if (leaf.drawPos.Y < Mouse.GetState().Y)
                {
                    leaf.drawPos.Y -= blowStrength;
                }
                if (leaf.drawPos.X < Mouse.GetState().X)
                {
                    leaf.drawPos.X -= blowStrength;
                }
                if (leaf.drawPos.X > Mouse.GetState().X)
                {
                    leaf.drawPos.X += blowStrength;
                }

                //prevents from going off screen
                if (leaf.drawPos.X < 5)
                {
                    leaf.drawPos.X += blowStrength;
                }
                if (leaf.drawPos.X > 785)
                {
                    leaf.drawPos.X -= blowStrength;
                }
                if (leaf.drawPos.Y < 5)
                {
                    leaf.drawPos.Y += blowStrength;
                }
                if (leaf.drawPos.Y > 395)
                {
                    leaf.drawPos.Y -= blowStrength;
                }

                //if(Mouse.GetState().Y < leaf.drawPos.Y && leaf.drawPos == )
            }
        }
    public Leaf root;           //start with root in our BSPtree

    #region Recursive Map Building
    public Leaf buildDungeonMap(Leaf root)  //recursive method that builds map based on BSPtree
    {
        if (root != null)
        {
            if (root.leftChild != null || root.rightChild != null)
            {
                if (root.leftChild != null) //if we don't have childs - we got to the leaf level
                {
                    buildDungeonMap(root.leftChild);
                }
                if (root.rightChild != null)    //if we don't have childs - we got to the leaf level
                {
                    buildDungeonMap(root.rightChild);
                }
            }
            else
            {
                //Debug.Log("Leaf " + roomCount + ": " + root.startX + " " + root.endX + " " + root.startY + " "
                //    + root.endY + " " + root.width + " " + root.height);
                createTiles(root.startX, root.endX, root.startY, root.endY, 0);
                if (root.room != null)
                {
                    //Debug.Log("Room " + roomCount + ": " + root.room.startX + " " + root.room.endX + " "
                    //    + root.room.startY + " " + root.room.endY);
                    createTiles(root.room.startX, root.room.endX, root.room.startY, root.room.endY, 1);
                    if (!playerCreated) //we have to create it after the room so it won't be deleted
                    {
                        GameObject gm = Instantiate(player, new Vector2(root.room.startX, root.room.startY),
                            Quaternion.identity) as GameObject;
                        playerCreated = true;
                        gm.transform.parent = boardManager;
                        gm = Instantiate(enemies[Random.Range(0, 2)], new Vector2(root.room.endX, root.room.endY),
                            Quaternion.identity) as GameObject;
                        gm.transform.parent = boardManager;
                    }
                }
                roomCount++;	//leaf and room shares same count
                return root;
            }
            foreach (EdgeRect er in root.halls)
            {
                //Debug.Log("Hall " + hallCount + ": " + er.startX + " " + er.endX + " " + er.startY + " " + er.endY);
                createTiles(er.startX, er.endX, er.startY, er.endY, 2);
                hallCount++;	//seprate count for halls;
            }
        }
        return null;
    }
Esempio n. 9
0
        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";

             for (int i = 0; i < numberOfLeaves; i++)
            {
                Leaf myLeaf = new Leaf();
                leaves.Add(myLeaf);
             }

             for (int i = 0; i < numberOfLeaves; i++)
             {
                 TreePoint tp = new TreePoint();
                 treePoints.Add(tp);
             }
        }
        public static void Main()
        {
            var root = new Composite("root");
            root.AddChild(new Leaf("Leaf 1"));
            root.AddChild(new Leaf("Leaf 2"));

            var comp = new Composite("Composite C");
            comp.AddChild(new Leaf("Leaf C.1"));
            comp.AddChild(new Leaf("Leaf C.2"));

            root.AddChild(comp);
            root.AddChild(new Leaf("Leaf 3"));

            var leaf = new Leaf("Leaf 4");
            root.AddChild(leaf);
            root.RemoveChild(leaf);

            root.Display(1);
        }
Esempio n. 11
0
        public static void Demo()
        {
            // Create a tree structure
            Composite root = new Composite("root");
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));

            Composite comp = new Composite("Composite X");
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB"));

            root.Add(comp);
            root.Add(new Leaf("Leaf C"));

            // Add and remove a leaf
            Leaf leaf = new Leaf("Leaf D");
            root.Add(leaf);
            root.Remove(leaf);

            // Recursively display tree
            root.Display(1);
        }
Esempio n. 12
0
 // Primitive : CharClassExpr | NamedRegexReference | "." | escapedChar | char ;
 internal RegExTree Primitive()
 {
     RegExTree tmp;
     if (!esc && chr == '[')
         tmp = CharClassExpr();
     else if (!esc && chr == '{' && !Char.IsDigit( peek() ))
         tmp = UseRegexRef();
     else if (!esc && chr == '.') {
         Leaf leaf = new Leaf( RegOp.charClass );
         leaf.rangeLit = new RangeLiteral( true );
         scan();
         leaf.rangeLit.list.Add( new CharRange( '\n' ) );
         tmp = leaf;
     }
     // Remaining cases are:
     //  1. escaped character (maybe beyond ffff limit)
     //  2. ordinary unicode character
     //  3. maybe a surrogate pair in future
     else if (esc) {
         tmp = new Leaf( EscapedChar() );
         scan();
     }
     else {
         tmp = new Leaf( chr );
         scan();
     }
     return tmp;
 }
Esempio n. 13
0
        //Leafを編集する権限があるか
        //引数1:アクセスユーザ
        //引数2:DB
        //引数3:編集するleaf
        //戻り値:true 編集可能、false 不可能
        public static async Task <bool> authEditLeaf(ClaimsPrincipal user, ExchaDContext9 context, Leaf leaf)
        {
            bool flag = false;                                           //戻り値:編集可不可フラグ

            Diary diary = await context.diaries.FindAsync(leaf.diaryId); //日記を取得

            if (diary == null)
            {
                return(false);                              //日記がないとき、不可能
            }
            //最新のleafの日時を取得する
            DateTime latest = await context.leaves
                              .Where(l => l.diaryId == leaf.diaryId)
                              .MaxAsync(l => l.time);

            //Leafを編集する権限があるか、確認する
            // 持ち主、かつ、交換中でない、かつ、最新leaf、かつ、コメント者なし、ならば可能

            //未ログインか
            if (!user.Identity.IsAuthenticated)
            {
                //未ログインのとき、不可能
            }                                                                    //ログイン中のとき
            else if (
                (diary.Id == user.FindFirst(ClaimTypes.NameIdentifier).Value) && //日記の持ち主
                (leaf.time == latest) &&                                         //最新leaf
                (diary.retTime < DateTime.Now) &&                                //返却済み
                (leaf.exid == null)                                              //コメント者なし
                )
            {
                flag = true;
            }

            return(flag);
        }
Esempio n. 14
0
 internal void Subtract( Leaf subtrahend )
 {
     this.rangeLit.list = this.rangeLit.list.SUB( subtrahend.rangeLit.list );
 }
Esempio n. 15
0
        public IBinaryNode GetNearest(Builder builder, IBinaryNode current, SeedEvent seedEvent, double edgeLimit)
        {
            while (true)
            {
                var x = seedEvent.X;
                var y = seedEvent.Y;

                if ((int)y == (int)MaxY)
                {
                    var le   = new TreeItem(seedEvent.Vertex);
                    var evt  = new Leaf(le);
                    var next = Root;

                    while (next.GetNextLeaf() != null)
                    {
                        next = next.GetNextLeaf();
                    }

                    if (!(next is Leaf nextLeaf))
                    {
                        return(null);
                    }

                    var h1 = new PartialLine(nextLeaf.ListItem.Point);
                    var h2 = new PartialLine(le.Point);

                    h1.Twin = h2;
                    h2.Twin = h1;
                    PartialLines.Add(h1);
                    PartialLines.Add(h2);

                    if (nextLeaf.ListItem.Point.PartialLine == null)
                    {
                        nextLeaf.ListItem.Point.PartialLine = h1;
                    }
                    else
                    {
                        var n = nextLeaf.ListItem.Point.PartialLine;

                        while (n.Next != null)
                        {
                            n = n.Next;
                        }

                        n.Next = h1;
                    }

                    nextLeaf.ListItem.PartialLine = h1;
                    le.PartialLine = h1;

                    le.Point.PartialLine = h2;

                    var b0      = new Breakpoint(nextLeaf.ListItem, evt.ListItem);
                    var bpNode0 = new BreakpointNode(b0);
                    nextLeaf.BreakpointNode = bpNode0;

                    if (next == Root)
                    {
                        next.Parent   = bpNode0;
                        Root          = bpNode0;
                        bpNode0.Left  = next;
                        bpNode0.Right = evt;
                        evt.Parent    = bpNode0;
                    }
                    else
                    {
                        var parent = next.Parent;
                        parent.Right   = bpNode0;
                        bpNode0.Parent = parent;
                        bpNode0.Left   = next;
                        next.Parent    = bpNode0;
                        bpNode0.Right  = evt;
                        evt.Parent     = bpNode0;
                    }

                    b0.InitializeBreakpoint(y);
                    b0.X = (x + next.X) / 2;
                    b0.Y = y + edgeLimit;

                    var ce = new CircleEvent(b0.X, b0.Y);

                    h1.CircleEvent = ce;
                    ce.PartialLine = h1;

                    return(null);
                }

                current.CalculateInnerBreakpoint(y - 0.0001);

                if (Math.Abs(x - current.X) < EPSILON_DOUBLE)
                {
                    return(current);
                }

                var child = x > current.X ? current.Right : current.Left;
                if (child is null)
                {
                    return(current);
                }

                current = child;
            }
        }
Esempio n. 16
0
 void ResetLeaf(Leaf leaf)
 {
     RemoveLeafFromSelf(leaf);
     _root.SetLeaf(leaf);
 }
Esempio n. 17
0
		public Root(Branch branch, Leaf leaf)
		{
			this.branch = branch;
			this.leaf = leaf;
		}
Esempio n. 18
0
        public List <CircleEvent> AddSeedEvent(Leaf current, TreeItem listItem)
        {
            var circleEvents = new List <CircleEvent>();

            var currentVector2 = current.ListItem.Point;
            var newVector2     = listItem.Point;
            var h1             = new PartialLine(currentVector2);
            var h2             = new PartialLine(newVector2);

            h1.Twin = h2;
            h2.Twin = h1;
            PartialLines.Add(h1);
            PartialLines.Add(h2);

            if (currentVector2.PartialLine == null)
            {
                currentVector2.PartialLine = h1;
            }

            newVector2.PartialLine = h2;

            var oldHe = current.ListItem.PartialLine;

            current.ListItem.PartialLine = h1;
            listItem.PartialLine         = h1;

            var prev = current.GetPreviousLeaf();
            var next = current.GetNextLeaf();

            var newNode  = new Leaf(listItem);
            var copy     = current.ListItem.Copy();
            var copyNode = new Leaf(copy);

            var bp1 = new Breakpoint(current.ListItem, listItem);

            bp1.InitializeBreakpoint(listItem.Point.Y - 1);

            var bp2 = new Breakpoint(listItem, copy);

            bp2.InitializeBreakpoint(listItem.Point.Y - 1);

            var bp1Node = new BreakpointNode(bp1);
            var bp2Node = new BreakpointNode(bp2);

            current.BreakpointNode = bp1Node;
            newNode.BreakpointNode = bp2Node;

            if (current.Parent != null)
            {
                if (current == current.Parent.Left)
                {
                    current.Parent.Left = bp1Node;
                    bp1Node.Parent      = current.Parent;
                }
                else
                {
                    current.Parent.Right = bp1Node;
                    bp1Node.Parent       = current.Parent;
                }
            }
            else
            {
                SetRoot(bp1Node);
                Root.Parent = null;
            }

            bp1Node.Left   = current;
            current.Parent = bp1Node;

            bp1Node.Right  = bp2Node;
            bp2Node.Parent = bp1Node;

            bp2Node.Left   = newNode;
            newNode.Parent = bp2Node;

            bp2Node.Right   = copyNode;
            copyNode.Parent = bp2Node;

            if (oldHe != null)
            {
                copyNode.ListItem.PartialLine = oldHe;
                var pre = copyNode.ListItem.PartialLine;

                if (!pre.Face.Equals(currentVector2))
                {
                    pre = pre.Twin;
                }

                var onext = pre.Next;
                pre.Next    = h1;
                h1.Previous = pre;

                if (onext != null)
                {
                    onext.Previous = h1;
                    h1.Next        = onext;
                }
            }

            if (prev != null && prev is Leaf prevLeaf)
            {
                var circleEvent        = new CircleEvent(prevLeaf, current, newNode);
                var canCalculateCircle = circleEvent.CalculateCircle();

                prevLeaf.BreakpointNode.Breakpoint = new Breakpoint(prevLeaf.ListItem, current.ListItem);

                bp1Node.Breakpoint.InitializeBreakpoint(circleEvent.DistanceFromLine);
                prevLeaf.BreakpointNode.Breakpoint.InitializeBreakpoint(circleEvent.DistanceFromLine);

                if (canCalculateCircle && circleEvent.CheckConvergence())
                {
                    current.DisappearEvent = circleEvent;
                    circleEvents.Add(circleEvent);
                }
            }

            if (next != null && next is Leaf nextLeaf)
            {
                var circleEvent        = new CircleEvent(newNode, copyNode, nextLeaf);
                var canCalculateCircle = circleEvent.CalculateCircle();

                copyNode.BreakpointNode            = (BreakpointNode)copyNode.GetNext();
                copyNode.BreakpointNode.Breakpoint = new Breakpoint(copy, nextLeaf.ListItem);

                bp2Node.Breakpoint.InitializeBreakpoint(circleEvent.DistanceFromLine);
                copyNode.BreakpointNode.Breakpoint.InitializeBreakpoint(circleEvent.DistanceFromLine);

                if (canCalculateCircle && circleEvent.CheckConvergence())
                {
                    copyNode.DisappearEvent = circleEvent;
                    circleEvents.Add(circleEvent);
                }
            }
            else
            {
                copyNode.ListItem.PartialLine = h1;
            }

            return(circleEvents);
        }
Esempio n. 19
0
    public Map(string path)
    {
        Dictionary <string, object> map = JSON.Read(path);
        object result = null;

        map.TryGetValue("n", out result);
        name = (string)result;

        map.TryGetValue("p", out result);
        List <object> parameters = (List <object>)result;
        List <object> position   = (List <object>)parameters[0];
        short         depth      = (short)(int)parameters[1];

        dimensions = ((short)(int)position[0], (short)(int)position[1]);
        if (depth == 0)
        {
            root = new Leaf();
            return;
        }
        root = new Link(dimensions, dimensions / 2, depth);



        map.TryGetValue("i", out result);
        List <Image> images = new List <Image>();

        foreach (List <object> obj in ((List <object>)result))
        {
            images.Add(Image.FromJSON(obj));
        }
        this.images = images.ToArray();

        map.TryGetValue("s", out result);
        List <Shader> shaders = new List <Shader>();

        foreach (List <object> obj in ((List <object>)result))
        {
            shaders.Add(Shader.FromJSON(obj));
        }
        this.shaders = shaders.ToArray();

        map.TryGetValue("g", out result);
        List <Shape> shapes = new List <Shape>();

        foreach (List <object> obj in ((List <object>)result))
        {
            shapes.Add(Shape.FromJSON(obj));
        }
        this.shapes = shapes.ToArray();

        map.TryGetValue("o", out result);
        List <GameObject> objects = new List <GameObject>();

        foreach (List <object> obj in ((List <object>)result))
        {
            objects.Add(GameObject.FromJSON(obj));
        }
        FillTree(objects.ToArray());

        /*map.TryGetValue("e", out result);
         * List<KinematicObject> entities = new List<KinematicObject>();
         * foreach (object[] obj in ((object[])result))
         * {
         *  entities.Add(KinematicObject.FromJSON(obj));
         * }*/
    }
Esempio n. 20
0
 void ResetLeaf(Leaf leaf)
 {
     Debug.Log("<color=#800080>位置在" + _field.top + "," + _field.right + "," + _field.bottom + "," + _field.left + "的树梢节点移除位置在" + leaf.position + "半径是" + leaf.radius + "的叶子,重新存入树</color>");
     RemoveLeafFromSelf(leaf);
     _root.SetLeaf(leaf);
 }
Esempio n. 21
0
 public NodeRemoveLeafCommand(Node node, Leaf leaf)
 {
     mNode = node;
     mLeaf = leaf;
 }
Esempio n. 22
0
 public NodeAddLeafCommand(Node node, Leaf leaf)
 {
     mNode = node;
     mLeaf = leaf;
 }
Esempio n. 23
0
        protected override void Seed(Context context)
        {
            try
            {
                Location location = new Location();
                //Grades
                Grade grade1 = new Grade(1);
                Grade grade2 = new Grade(2);
                Grade grade3 = new Grade(3);
                Grade grade4 = new Grade(4);
                Grade grade5 = new Grade(5);
                Grade grade6 = new Grade(6);

                //Continenten
                Continent        africa     = new Continent("Afrika");
                Continent        antarctica = new Continent("Antarctica");
                Continent        asia       = new Continent("Azië");
                Continent        europe     = new Continent("Europa");
                Continent        latAm      = new Continent("Latijns Amerika");
                Continent        northAm    = new Continent("Noord Amerika");
                Continent        oceania    = new Continent("Oceanië");
                List <Continent> contList   = new List <Continent>()
                {
                    africa, antarctica, asia, europe, latAm, northAm, oceania
                };

                //Land
                Country belgium = new Country("België");
                Country canada  = new Country("Canada");

                //Locatie
                Location gent    = new Location("Gent", "6434", 0.0666134, 0.889536142, 15);
                Location toronto = new Location("Toronto", "71624", 1.389863861, 0.762127107, 173);

                double[]    percGent           = { 51, 42, 46, 50, 59, 65, 72, 74, 72, 72, 64, 59 };
                double[]    tempGent           = { 2.5, 3.0, 5.2, 8.4, 12.1, 15.1, 16.8, 16.6, 14.3, 10.3, 6.2, 3.2 };
                double[]    percToronto        = { 46, 46, 57, 64, 66, 69, 77, 84, 74, 63, 70, 66 };
                double[]    tempToronto        = { -6.6, -5.8, -0.7, 6.1, 12.5, 17.7, 20.8, 19.6, 15.3, 9.0, 3.3, -3.2 };
                Climatogram climatogramGent    = new Climatogram(setValues(percGent, tempGent), "1961 - 1990");
                Climatogram climatogramToronto = new Climatogram(setValues(percToronto, tempToronto), "1953 - 1991");

                //-------------------
                europe.Countries.Add(belgium);
                belgium.Locations.Add(gent);
                gent.Climatogram = climatogramGent;

                northAm.Countries.Add(canada);
                canada.Locations.Add(toronto);
                toronto.Climatogram = climatogramToronto;
                //-------------------

                //Bij elke graad meegeven welke continenten ze moeten behandelen
                foreach (Continent cont in contList)
                {
                    grade3.Continents.Add(cont);
                    grade4.Continents.Add(cont);
                    grade5.Continents.Add(cont);
                    grade6.Continents.Add(cont);
                }
                grade1.Continents.Add(europe);
                grade2.Continents.Add(europe);



                // determinatietabellen
                // eerste graad
                Node         g1rootNode         = new Node(new Tw(), 10, new Smaller());
                Node         g1yesNode          = new Node(new Tw(), 0, new Smaller());
                AbstractNode g1yes2Leaf         = new Leaf("Koud zonder dooiseizoen", "IJswoestijn", "/Content/images/ijswoestijn.jpg");
                AbstractNode g1yesNoLeaf        = new Leaf("Koud met dooiseizoen", "Toendra", "/Content/images/toendra.jpg");
                Node         g1noNode           = new Node(new TmBiggerOrEqualThan10(), 4, new Smaller());
                AbstractNode g1noYesLeaf        = new Leaf("Koudgematigd, strenge winter", "Taiga", "/Content/images/taiga.jpg");
                Node         g1no2Node          = new Node(new Tk(), 18, new Smaller());
                AbstractNode g1no2NoLeaf        = new Leaf("Warm, altijd droog", "Woestijn van de tropen", "/Content/images/woestijn.jpg");
                Node         g1no2YesNode       = new Node(new Nj(), 400, new Bigger());
                AbstractNode g1no2YesNoLeaf     = new Leaf("Gematigd, altijd droog", "Woestijn van de middelbreedten", "/Content/images/woestijn.jpg");
                Node         g1no2Yes2Node      = new Node(new Tk(), -3, new Smaller());
                AbstractNode g1no2YesLeaf       = new Leaf("Koelgematigd, strenge winter", "Taiga", "/Content/images/taiga.jpg");
                Node         g1no2Yes2NoNode    = new Node(new Tw(), 22, new Smaller());
                AbstractNode g1no2Yes2NoYesLeaf = new Leaf("Koelgematigd, zachte winter", "Loofbos", "/Content/images/loofwoud.jpg");
                AbstractNode g1no2Yes2NoNoLeaf  = new Leaf("Warmgematigd, natte winter", "Hardbladig van de subtropen", "/Content/images/hardbladig.jpg");

                g1no2Yes2NoNode.YesNode = g1no2Yes2NoYesLeaf;
                g1no2Yes2NoNode.NoNode  = g1no2Yes2NoNoLeaf;
                g1no2Yes2Node.YesNode   = g1no2YesLeaf;
                g1no2Yes2Node.NoNode    = g1no2Yes2NoNode;
                g1no2YesNode.NoNode     = g1no2YesNoLeaf;
                g1no2YesNode.YesNode    = g1no2Yes2Node;
                g1no2Node.NoNode        = g1no2NoLeaf;
                g1no2Node.YesNode       = g1no2YesNode;
                g1noNode.YesNode        = g1noYesLeaf;
                g1noNode.NoNode         = g1no2Node;
                g1yesNode.YesNode       = g1yes2Leaf;
                g1yesNode.NoNode        = g1noNode;
                g1yesNode.NoNode        = g1yesNoLeaf;
                g1rootNode.YesNode      = g1yesNode;
                g1rootNode.NoNode       = g1noNode;

                // alle andere  graden = grade2
                Node         g2rootNode              = new Node(new Tw(), 10, new SmallerOrEqual());
                Node         g2yesNode               = new Node(new Tw(), 0, new SmallerOrEqual());
                Leaf         g2yes2Leaf              = new Leaf("Koud zonder dooiseizoen", "IJswoestijn", "/Content/images/ijswoestijn.jpg");
                Leaf         g2yesNoLeaf             = new Leaf("Koud met dooiseizoen", "Toendra", "/Content/images/toendra.jpg");
                Node         g2noNode                = new Node(new Tj(), 0, new SmallerOrEqual());
                Leaf         g2noYesLeaf             = new Leaf("Koudgematigd, strenge winter", "Taiga", "/Content/images/taiga.jpg");
                Node         g2no2Node               = new Node(new Nj(), 200, new SmallerOrEqual());
                Node         g2no2YesNode            = new Node(new Tk(), 15, new SmallerOrEqual());
                AbstractNode g2no2Yes2Leaf           = new Leaf("Gematigd, altijd droog", "Woestijn van de middelbreedten", "/Content/images/woestijn.jpg");
                Leaf         g2no2YesNoLeaf          = new Leaf("Warm, altijd droog", "Woestijn van de tropen", "/Content/images/woestijn.jpg");
                Node         g2no3Node               = new Node(new Tk(), 18, new SmallerOrEqual());
                Node         g2no3YesNode            = new Node(new Nj(), 400, new SmallerOrEqual());
                AbstractNode g2no3Yes2Leaf           = new Leaf("Gematigd, droog klimaat", "Steppe", "/Content/images/steppe.jpg");
                Node         g2no3YesNoNode          = new Node(new Tk(), -10, new SmallerOrEqual());
                AbstractNode g2no3YesNoYesLeaf       = new Leaf("Koelgematigd, strenge winter", "Taiga", "/Content/images/taiga.jpg");
                Node         g2no3YesNo2Node         = new Node(new DryMonths(), 1, new SmallerOrEqual());
                Node         g2no3YesNo2YesNode      = new Node(new Tk(), -3, new SmallerOrEqual());
                AbstractNode g2no3YesNo2Yes2Leaf     = new Leaf("Koelgematigd, koude winter", "Gemengd Woud", "/Content/images/gemengd_woud.jpg");
                Node         g2no3YesNo2YesNoNode    = new Node(new Tw(), 22, new SmallerOrEqual());
                AbstractNode g2no3YesNo2YesNoYesLeaf = new Leaf("Koelgematigd, zachte winter", "Loofbos", "/Content/images/loofwoud.jpg");
                AbstractNode g2no3YesNo2YesNo2Leaf   = new Leaf("Warmgematigd, altijd nat", "Subtropisch Regenwoud", "/Content/images/regenwoud.jpg");
                Node         g2no3YesNo3Node         = new Node(new PrecipitationSummer(), new PrecipitationWinter(), new SmallerOrEqual());
                Node         g2no3YesNo3YesNode      = new Node(new Tw(), 22, new SmallerOrEqual());
                AbstractNode g2no3YesNo3Yes2Leaf     = new Leaf("Koelgematigd, natte winter", "Hardbladig van de middelbreedten", "/Content/images/hardbladig.jpg");
                AbstractNode g2no3YesNo3YesNoLeaf    = new Leaf("Warmgematigd, natte winter", "Hardbladig van de subtropen", "/Content/images/hardbladig.jpg");
                AbstractNode g2no3YesNo4Leaf         = new Leaf("Warmgematigd, natte zomer", "Subtropische Savanne", "/Content/images/subtropische_savanne.jpg");
                Node         g2no4Node               = new Node(new DryMonths(), 1, new SmallerOrEqual());
                AbstractNode g2no4YesLeaf            = new Leaf("Warm, nat seizoen", "Tropische Savanne", "/Content/images/savanne.jpg");
                AbstractNode g2no5Leaf               = new Leaf("Warm, altijd nat, nat seizoen", "Tropisch Regenwoud", "/Content/images/tropisch_regenwoud.jpg");

                g2no4Node.YesNode            = g2no4YesLeaf;
                g2no4Node.NoNode             = g2no5Leaf;
                g2no3YesNo3YesNode.YesNode   = g2no3YesNo3Yes2Leaf;
                g2no3YesNo3YesNode.NoNode    = g2no3YesNo3YesNoLeaf;
                g2no3YesNo3Node.YesNode      = g2no3YesNo3YesNode;
                g2no3YesNo3Node.NoNode       = g2no3YesNo4Leaf;
                g2no3YesNo2YesNoNode.YesNode = g2no3YesNo2YesNoYesLeaf;
                g2no3YesNo2YesNoNode.NoNode  = g2no3YesNo2YesNo2Leaf;
                g2no3YesNo2YesNode.YesNode   = g2no3YesNo2Yes2Leaf;
                g2no3YesNo2YesNode.NoNode    = g2no3YesNo2YesNoNode;
                g2no3YesNo2Node.YesNode      = g2no3YesNo2YesNode;
                g2no3YesNo2Node.NoNode       = g2no3YesNo3Node;
                g2no3YesNoNode.YesNode       = g2no3YesNoYesLeaf;
                g2no3YesNoNode.NoNode        = g2no3YesNo2Node;
                g2no3YesNode.YesNode         = g2no3Yes2Leaf;
                g2no3YesNode.NoNode          = g2no3YesNoNode;
                g2no3Node.YesNode            = g2no3YesNode;
                g2no3Node.NoNode             = g2no4Node;
                g2no2YesNode.YesNode         = g2no2Yes2Leaf;
                g2no2YesNode.NoNode          = g2no2YesNoLeaf;
                g2no2Node.YesNode            = g2no2YesNode;
                g2no2Node.NoNode             = g2no3Node;
                g2noNode.YesNode             = g2noYesLeaf;
                g2noNode.NoNode    = g2no2Node;
                g2yesNode.YesNode  = g2yes2Leaf;
                g2yesNode.NoNode   = g2yesNoLeaf;
                g2rootNode.YesNode = g2yesNode;
                g2rootNode.NoNode  = g2noNode;

                grade1.DeterminationTable = g1rootNode;
                grade2.DeterminationTable = g2rootNode;
                grade3.DeterminationTable = g2rootNode;
                grade4.DeterminationTable = g2rootNode;
                grade5.DeterminationTable = g2rootNode;
                grade6.DeterminationTable = g2rootNode;

                //SaveChanges : Add -> INSERT statement | wijzigingen -> UPDATE instructie | Remove -> DELETE instructie
                //--> CRUD methoden van Context -> Voegt de Grades toe samen met alle continenten en bijbehorende countries/locations voor die graad
                // Context doet aan ChangeTracking -> Houdt alle wijzigingen bij tot je SaveChanges aanroept
                // en zal dan voor alle wijzigingen INSERT,UPDATE of DELETE instructies creëren => Transactie

                context.Grades.Add(grade1);
                context.Grades.Add(grade2);
                context.Grades.Add(grade3);
                context.Grades.Add(grade4);
                context.Grades.Add(grade5);
                context.Grades.Add(grade6);

                context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                throw e;
            }
        }
Esempio n. 24
0
 public void AddLeaf(Leaf l)
 {
     Leafs.Add(l);
 }
Esempio n. 25
0
 public void OnFinish()
 {
     m_curLeaf = m_curLeaf.Leafs.First();
     m_curLeaf.DrawTree(m_builder, new List <string>(), true);
     //m_builder.Remove(0, 2);
 }
Esempio n. 26
0
    void Start()
    {
        List <Leaf> leafs = new List <Leaf>();

        Leaf l = new Leaf(0, 0, mapWidth, mapHeight, "");

        leafs.Add(l);

        bool canSplit = true;
        int  index    = 0;

        while (canSplit || index < leafs.Count)
        {
            canSplit = false;

            if (index < leafs.Count)
            {
                Leaf leaf = leafs[index];
                if (leaf.splited == false)
                {
                    if (leaf.width * leaf.height > maxLeafSize)
                    {
                        if (leaf.Split())
                        {
                            leafs.Add(leaf.leftChild);
                            leafs.Add(leaf.rightChild);
                            canSplit = true;
                        }
                    }
                }

                if (canSplit)
                {
                    index = 0;
                }
                else
                {
                    index++;
                }
            }
        }

        for (int k = 0; k < leafs.Count; k++)
        {
            Leaf leaf = leafs[k];

            if (leaf.splited == false)
            {
                GameObject go = new GameObject();

                for (int i = 0; i < leaf.height; i++)
                {
                    for (int j = 0; j < leaf.width; j++)
                    {
                        GameObject sq = Instantiate(square, new Vector3(leaf.x + j, leaf.y + i, 0), Quaternion.identity) as GameObject;
                        sq.transform.parent = go.transform;
                        sq.GetComponentInChildren <TextMesh>().text = leaf.index;
                        sq.GetComponent <SpriteRenderer>().color    = leaf.color;
                    }
                }
            }
        }
    }
 public int EvaluateLeaf(Leaf node, ADTreeContext context)
 {
     return(node.Duration);
 }
 // Use this for initialization
 void Awake()
 {
     motor = GetComponent<CharacterMotor>();
     controller = GetComponent<CharacterController>();
     leaf = GetComponent<Leaf>();
 }
Esempio n. 29
0
        private Node CreateABinaryTree(ref string formula, Node node)
        {
            if (node == null)
            {
                switch (formula[0])
                {
                case '~':
                    formula = formula.Remove(0, 1);
                    node    = new Negation(null);
                    break;

                case '>':
                    formula = formula.Remove(0, 1);
                    node    = new Implication(null, null);
                    break;

                case '=':
                    formula = formula.Remove(0, 1);
                    node    = new Biconditional(null, null);
                    break;

                case '&':
                    formula = formula.Remove(0, 1);
                    node    = new Conjunction(null, null);
                    break;

                case '|':
                    formula = formula.Remove(0, 1);
                    node    = new Disjunction(null, null);
                    break;

                case '%':
                    formula = formula.Remove(0, 1);
                    formula = formula.Insert(0, "&");
                    node    = new Negation(null);
                    break;

                case '(':
                    formula = formula.Remove(0, 1);
                    return(this.CreateABinaryTree(ref formula, node));

                case ',':
                    formula = formula.Remove(0, 1);
                    return(this.CreateABinaryTree(ref formula, node));

                case ')':
                    formula = formula.Remove(0, 1);
                    return(this.CreateABinaryTree(ref formula, node));

                default:
                    node = new Leaf(formula[0]);
                    if (!leaves.Exists(e => e == node.Value))
                    {
                        this.leaves.Add(node.Value);
                    }
                    formula = formula.Remove(0, 1);
                    break;
                }
                if (!(node is Leaf))
                {
                    node.leftChild = CreateABinaryTree(ref formula, node.leftChild);
                }

                if (!(node is Negation) && !(node is Leaf))
                {
                    node.rightChild = CreateABinaryTree(ref formula, node.rightChild);
                }

                return(node);
            }
            else
            {
                return(node);
            }
        }
Esempio n. 30
0
 public void OnEndContainer()
 {
     m_curLeaf = m_leafs.Pop();
 }
Esempio n. 31
0
            /// <summary>Balance tree and fixup pivot after removal.</summary>
            /// <remarks>
            /// On exit, an empty root is not pruned.
            /// </remarks>
            public void BalanceLeaf()
            {
                var leaf1 = (Leaf)TopNode;
                int ix1   = TopIndex;

                if (ix1 == 0)
                {
                    if (leaf1.KeyCount != 0)
                    {
                        SetPivot(leaf1.Key0);
                    }
                    else
                    {
                        if (leaf1.rightLeaf != null)
                        {
                            leaf1.rightLeaf.leftLeaf = leaf1.leftLeaf;
                            if (leaf1.leftLeaf != null)
                            {
                                leaf1.leftLeaf.rightLeaf = leaf1.rightLeaf;
                            }
                            else
                            {
                                tree.leftmostLeaf = leaf1.rightLeaf;
                            }
                            Demote();
                        }
                        else if (leaf1.leftLeaf != null)
                        {
                            leaf1.leftLeaf.rightLeaf = leaf1.rightLeaf;
                            tree.rightmostLeaf       = leaf1.leftLeaf;
                            Demote();
                        }

                        return;
                    }
                }

                if (tree.IsUnderflow(leaf1.KeyCount))
                {
                    Leaf leaf2 = leaf1.rightLeaf;
                    if (leaf2 != null)
                    {
                        if (leaf1.KeyCount + leaf2.KeyCount > tree.maxKeyCount)
                        {
                            // Balance leaves by shifting pairs from right leaf.
                            int shifts = (leaf1.KeyCount + leaf2.KeyCount + 1) / 2 - leaf1.KeyCount;
                            leaf1.MoveLeft(shifts);
                            TraverseRight();
                            SetPivot(leaf2.Key0);
                            TiltLeft(shifts);
                        }
                        else
                        {
                            leaf1.Coalesce();
                            leaf1.rightLeaf = leaf2.rightLeaf;
                            if (leaf2.rightLeaf == null)
                            {
                                tree.rightmostLeaf = leaf1;
                            }
                            else
                            {
                                leaf2.rightLeaf.leftLeaf = leaf1;
                            }
                            TraverseRight();
                            TiltLeft(leaf2.KeyCount);
                            Demote();
                        }
                    }
                }
            }
Esempio n. 32
0
        public List <CircleEvent> RemoveNode(CircleEvent ce, Leaf prev, Leaf remove, Leaf next)
        {
            var circleEvents = new List <CircleEvent>();

            var currentVector2 = prev.ListItem.Point;
            var newVector2     = next.ListItem.Point;
            var h1             = new PartialLine(currentVector2);
            var h2             = new PartialLine(newVector2);

            h1.Twin = h2;
            h2.Twin = h1;
            PartialLines.Add(h1);
            PartialLines.Add(h2);

            h1.CircleEvent = ce;
            var bp1 = new Breakpoint(prev.ListItem, next.ListItem);

            if (prev.BreakpointNode == remove.Parent)
            {
                prev.BreakpointNode = remove.BreakpointNode;
            }

            prev.BreakpointNode.Breakpoint = bp1;

            {
                var oldEdgeP = prev.ListItem.PartialLine;

                if (!oldEdgeP.Face.Equals(prev.ListItem.Point))
                {
                    oldEdgeP = oldEdgeP.Twin;
                }

                var n = oldEdgeP.Next;
                oldEdgeP.Next = h1;
                h1.Previous   = oldEdgeP;

                if (n != null)
                {
                    h1.Next    = n;
                    n.Previous = h1;
                }
            }

            {
                var oldEdgeN = next.ListItem.PartialLine;

                if (!oldEdgeN.Face.Equals(next.ListItem.Point))
                {
                    oldEdgeN = oldEdgeN.Twin;
                }

                var n = oldEdgeN.Next;

                oldEdgeN.Next = h2;
                h2.Previous   = oldEdgeN;

                if (n != null)
                {
                    h2.Next    = n;
                    n.Previous = h2;
                }
            }

            prev.ListItem.PartialLine = h1;

            if (remove.Parent.Parent == null)
            {
                Root = remove.Parent.Left == remove
                    ? remove.Parent.Right
                    : remove.Parent.Left;
                Root.Parent = null;
            }
            else
            {
                var grandparent = remove.Parent.Parent;
                var parent      = remove.Parent;

                if (remove == remove.Parent.Left)
                {
                    if (remove.Parent == grandparent.Left)
                    {
                        grandparent.Left    = parent.Right;
                        parent.Right.Parent = grandparent;
                    }
                    else
                    {
                        grandparent.Right   = parent.Right;
                        parent.Right.Parent = grandparent;
                    }
                }

                else
                {
                    if (remove.Parent == grandparent.Left)
                    {
                        grandparent.Left   = parent.Left;
                        parent.Left.Parent = grandparent;
                    }
                    else
                    {
                        grandparent.Right  = parent.Left;
                        parent.Left.Parent = grandparent;
                    }
                }

                remove.Parent = null;
            }

            var nextNextTree = next.GetNextLeaf();

            if (nextNextTree != null &&
                nextNextTree is Leaf nextNext)
            {
                var circleEvent        = new CircleEvent(prev, next, nextNext);
                var canCalculateCircle = circleEvent.CalculateCircle();

                next.BreakpointNode.Breakpoint = new Breakpoint(next.ListItem, nextNext.ListItem);

                bp1.InitializeBreakpoint(circleEvent.DistanceFromLine);

                next.BreakpointNode.Breakpoint.InitializeBreakpoint(circleEvent.DistanceFromLine);

                if (canCalculateCircle && circleEvent.CheckConvergence())
                {
                    next.DisappearEvent = circleEvent;

                    circleEvents.Add(circleEvent);
                }
            }

            var prevPrevTree = prev.GetPreviousLeaf();

            if (prevPrevTree != null &&
                prevPrevTree is Leaf prevPrev)
            {
                var circleEvent        = new CircleEvent(prevPrev, prev, next);
                var canCalculateCircle = circleEvent.CalculateCircle();

                prevPrev.BreakpointNode.Breakpoint = new Breakpoint(prevPrev.ListItem, prev.ListItem);
                bp1.InitializeBreakpoint(circleEvent.DistanceFromLine);

                prevPrev.BreakpointNode.Breakpoint.InitializeBreakpoint(circleEvent.DistanceFromLine);

                if (canCalculateCircle && circleEvent.CheckConvergence())
                {
                    prev.DisappearEvent = circleEvent;

                    circleEvents.Add(circleEvent);
                }
            }

            return(circleEvents);
        }
Esempio n. 33
0
    // METHODS

    public void readBSP()
    {
        try {
            byte[] theLump = new byte[0];
            byte[] vis     = new byte[0];
            BSPObject = new BSP(BSPFile.FullName);
            Console.WriteLine("Opening " + BSPFile.FullName);
            for (int i = 0; i < 18; i++)
            {
                try {
                    theLump = readLumpNum(i);
                    switch (i)
                    {
                    case 0:
                        BSPObject.Entities = Entity.createLump(theLump);
                        break;

                    case 1:
                        BSPObject.Planes = Plane.createLump(theLump);
                        break;

                    case 2:
                        BSPObject.Textures = Texture.createLump(theLump);
                        break;

                    case 3:
                        BSPObject.Materials = Texture.createLump(theLump);
                        break;

                    case 4:
                        BSPObject.Vertices = Vertex.createLump(theLump);
                        break;

                    case 5:
                        BSPObject.Normals = new Lump <LumpObject>(theLump.Length, 0);
                        break;

                    case 6:
                        BSPObject.Indices = new NumList(theLump, NumList.dataType.UINT);
                        break;

                    case 7:
                        vis = theLump;
                        break;

                    case 8:
                        BSPObject.Nodes = Node.createLump(theLump);
                        break;

                    case 9:
                        BSPObject.Faces = Face.createLump(theLump);
                        break;

                    case 10:
                        BSPObject.Lightmaps = new NumList(theLump, NumList.dataType.UBYTE);
                        break;

                    case 11:
                        BSPObject.Leaves = Leaf.createLump(theLump);
                        break;

                    case 12:
                        BSPObject.MarkSurfaces = new NumList(theLump, NumList.dataType.UINT);
                        break;

                    case 13:
                        BSPObject.MarkBrushes = new NumList(theLump, NumList.dataType.UINT);
                        break;

                    case 14:
                        BSPObject.Models = Model.createLump(theLump);
                        break;

                    case 15:
                        BSPObject.Brushes = Brush.createLump(theLump);
                        break;

                    case 16:
                        BSPObject.BrushSides = BrushSide.createLump(theLump);
                        break;

                    case 17:
                        BSPObject.TexInfo = TexInfo.createLump(theLump);
                        break;
                    }
                } catch {
                    dumpLump(theLump);
                }
            }
            try {
                int visLength = BSPObject.Leaves[2].PVS;
                if (visLength > 0 && vis.Length > 0)
                {
                    BSPObject.Vis = new Lump <LumpObject>(vis, visLength);
                }
            } catch (ArgumentOutOfRangeException) {; }
            if (BSPObject.Vis == null)
            {
                BSPObject.Vis = new Lump <LumpObject>(0, 0);
            }
            BSPObject.printBSPReport();
        }
        catch (System.IO.IOException) {
            Console.WriteLine("Unable to access BSP file! Is it open in another program?");
        }
        br.Close();
    }
Esempio n. 34
0
 //移除
 public bool RemoveLeaf(Leaf leaf)
 {
     return(_root.DoRemoveLeaf(leaf));
 }
Esempio n. 35
0
 public void DeleteLeaf()
 {
     leaf = null;
 }
Esempio n. 36
0
        //Leafへコメントする権限があるか
        //引数1:アクセスユーザ
        //引数2:DB
        //引数3:コメントするleaf
        //戻り値:true コメント可能、false 不可能
        public static async Task <bool> authCommentLeaf(ClaimsPrincipal user, ExchaDContext9 context, Leaf leaf)
        {
            bool flag = false;                                           //戻り値:コメント可不可フラグ

            Diary diary = await context.diaries.FindAsync(leaf.diaryId); //日記を取得

            if (diary == null)
            {
                return(false);                              //日記がないとき、不可能
            }
            //最新のleafの日時を取得する
            DateTime latest = await context.leaves
                              .Where(l => l.diaryId == leaf.diaryId)
                              .MaxAsync(l => l.time);

            //Leafへコメントする権限があるか、確認する
            //交換相手のとき、かつ、最新のLeaf、未コメントleafならば可能

            if (!user.Identity.IsAuthenticated)
            {
                //未ログインのとき、不可能
            }            //ログイン中のとき
            else if (
                (user.FindFirst(ClaimTypes.NameIdentifier).Value == diary.exid) &&              //交換相手
                (leaf.time == latest)                           //最新leaf
                //&& (leaf.exid == null)		//未コメント	//編集可能にする。タイムアップでのみ交換が終了する
                )
            {
                flag = true;
            }
            return(flag);
        }
    void InitializeMap(int level)
    {
        //Clear our lists.
        gridPositions.Clear ();
        wallPositions.Clear ();

        MasterRoot = null;
        boardHolder = new GameObject ("Board").transform;

        Leafs = CreateLeaves (level);

        MasterRoot.CreateRooms ();
    }
Esempio n. 38
0
 internal void Merge( Leaf addend )
 {
     foreach (CharRange rng in addend.rangeLit.list.Ranges)
         this.rangeLit.list.Add( rng );
 }
        public bool Split()
        {
            // begin splitting the leaf into two children
            if (leftChild != null || rightChild != null)
                return false; // we're already split! Abort!

            // determine direction of split
            // if the width is >25% larger than height, we split vertically
            // if the height is >25% larger than the width, we split horizontally
            // otherwise we split randomly
            bool splitH = System.Convert.ToBoolean(Random.Range (0, 1));
            int max;

            if (width > height && width / height >= 1.25)
                splitH = false;
            else if (height > width && height / width >= 1.25)
                splitH = true;

            if (splitH)
            {
                max = height - MinimumLeafSize;
            }
            else
            {
                max = width - MinimumLeafSize;
            }

            if (max <= MinimumLeafSize)
            {
                //Debug.Log(max + " was less than " + MinimumLeafSize);
                return false; // the area is too small to split any more...
            }
            else
            {
                int split = Random.Range (MinimumLeafSize, max); // determine where we're going to split

                // create our left and right children based on the direction of the split
                if (splitH)
                {
                    leftChild = new Leaf (x, y, width, split);
                    rightChild = new Leaf (x, y + split, width, height - split);
                }
                else
                {
                    leftChild = new Leaf (x, y, split, height);
                    rightChild = new Leaf (x + split, y, width - split, height);
                }
                return true; // split successful!
            }
        }
Esempio n. 40
0
            // CharClass : "[" ["^"] {code | code "-" code | FilteredClass}+ "]" ;
            internal Leaf CharClass()
            {
                // Assert chr == '['
                // Need to build a new string taking into account char escapes
                Leaf leaf = new Leaf( RegOp.charClass );
                bool invert = false;
                scan();                           // read past '['
                if (!esc && chr == '^') {
                    invert = true;
                    scan();                       // read past '^'
                }
                leaf.rangeLit = new RangeLiteral( invert );
                // Special case of '-' at start, taken as ordinary class member.
                // This is correct for LEX specification, but is undocumented
                // behavior for FLEX. GPLEX gives a friendly warning, just in
                // case this is actually a typographical error.
                if (!esc && chr == '-') {
                    Warn( 113, index - 1, 1, "-" );
                    leaf.rangeLit.list.Add( new CharRange( '-' ) );
                    scan();                       // read past -'
                }

                while (chr != NUL && (esc || chr != ']')) {
                    int startIx = index - 1; // save starting index for error reporting
                    int lhCodePoint = (esc ? EscapedChar() : CodePoint());
                    if (!esc && lhCodePoint == (int)'-')
                        Error( 82, startIx, index - startIx, null );
                    //
                    // There are three possible elements here:
                    //  * a singleton character
                    //  * a character range
                    //  * a filtered class like [:IsLetter:]
                    //
                    if (chr == '[' && !esc && peek() == ':') // character category
                    {
                        Leaf rslt = FilteredClass();
                        leaf.Merge( rslt );
                    }
                    else {
                        scan();
                        if (!esc && chr == '-')             // character range
                        {
                            scan();
                            if (!esc && chr == ']') {
                                // Special case of '-' at end, taken as ordinary class member.
                                // This is correct for LEX specification, but is undocumented
                                // behavior for FLEX. GPLEX gives a friendly warning, just in
                                // case this is actually a typographical error.
                                leaf.rangeLit.list.Add( new CharRange( lhCodePoint ) );
                                leaf.rangeLit.list.Add( new CharRange( '-' ) );
                                //Error(81, idx, index - idx - 1);
                                Warn( 114, startIx, index - startIx - 1, String.Format(
                                    CultureInfo.InvariantCulture,
                                    "'{0}','{1}'",
                                    CharacterUtilities.Map( lhCodePoint ),
                                    '-' ) );
                            }
                            else {
                                int rhCodePoint = (esc ? EscapedChar() : CodePoint());
                                if (rhCodePoint < lhCodePoint)
                                    Error( 54, startIx, index - startIx, null );
                                scan();
                                leaf.rangeLit.list.Add( new CharRange( lhCodePoint, rhCodePoint ) );
                            }
                        }
                        else                               // character singleton
                        {
                            leaf.rangeLit.list.Add( new CharRange( lhCodePoint ) );
                        }
                    }
                }
                checkAndScan( ']' );
                leaf.rangeLit.list.Canonicalize();
                return leaf;
            }
Esempio n. 41
0
        /// <summary>
        ///     Takes Frequency Value and Establishes Parent/Child relationship with Tree Nodes & Leafs
        /// </summary>
        /// <returns></returns>
        
        private bool BuildTree()
        {
        	Debug.Log ("Calling Build Tree");
            //Local Variables
            int iParentIndex = 0;

            List<Leaf> OptimizedTree = new List<Leaf>(HuffmanTree);
            List<Leaf> WorkingTree;
            Leaf NewParent;

            //Remove anything with a 0 Frequency Value
            OptimizedTree.RemoveAll(delegate(Leaf leaf) { return leaf.FrequencyValue == 0; });

            //Order with highest frequency at 'end', lowest at 'beginning'
            OptimizedTree.Sort(delegate(Leaf L1, Leaf L2) { return L1.FrequencyValue.CompareTo(L2.FrequencyValue); });

            WorkingTree = new List<Leaf>(OptimizedTree);
            while (WorkingTree.Count > 1)
            {
                //Sort by Frequency
                //Order with highest frequency at 'end', lowest at 'beginning'
                WorkingTree.Sort(delegate(Leaf L1, Leaf L2) { return L1.FrequencyValue.CompareTo(L2.FrequencyValue); });

                //Take 'First Two' and join them with a new node
                NewParent = new Leaf() { FrequencyValue = WorkingTree[0].FrequencyValue + WorkingTree[1].FrequencyValue, IsNode = true };

                HuffmanTree.Add(NewParent);

                //Assign Parent to Left Node
                iParentIndex = HuffmanTree.FindIndex(delegate(Leaf L1) { return L1.Equals(WorkingTree[0]); });
                HuffmanTree[iParentIndex].Left = true;
                HuffmanTree[iParentIndex].ParentID = NewParent.ID;

                //Assign Parent to Right Node
                iParentIndex = HuffmanTree.FindIndex(delegate(Leaf L1) { return L1.Equals(WorkingTree[1]); });
                HuffmanTree[iParentIndex].Right = true;
                HuffmanTree[iParentIndex].ParentID = NewParent.ID;
				
				OptimizedTree.Clear ();
				OptimizedTree.AddRange (HuffmanTree.ToArray ());
                //OptimizedTree = new List<Leaf>(HuffmanTree);

                //Remove anything with a 0 Frequency Value
                OptimizedTree.RemoveAll(delegate(Leaf leaf) { return leaf.FrequencyValue == 0; });

                //Order with highest frequency at 'end', lowest at 'beginning'
                OptimizedTree.Sort(delegate(Leaf L1, Leaf L2) { return L1.FrequencyValue.CompareTo(L2.FrequencyValue); });
				
				//Debug.Log ("While loop");
                //WorkingTree = new List<Leaf>(OptimizedTree);
				WorkingTree.Clear ();
				WorkingTree.AddRange (OptimizedTree.ToArray ());
				
                //Remove anything with a parent
                WorkingTree.RemoveAll(delegate(Leaf leaf) { return leaf.ParentID != new Guid(); });
            }

            return true;
        }
Esempio n. 42
0
 /**
  * does the work
  */
 private void findLeftLeaf()
 {
     leaf = null;
     if (sp == 0)
         return;
     Element ele = stack[--sp];
     while (ele is Node)
     {
         Node node = (Node)ele;
         float centerValue = centerValues[node.dim];
         float maxValue = centerValue + radius;
         float minValue = centerValue;
         if (! tHemisphere || node.dim != 0)
             minValue -= radius;
         if (minValue <= node.maxLeft && maxValue >= node.minLeft)
         {
             if (maxValue >= node.minRight && minValue <= node.maxRight)
                 stack[sp++] = node.eleRight;
             ele = node.eleLeft;
         }
         else if (maxValue >= node.minRight && minValue <= node.maxRight)
         {
             ele = node.eleRight;
         }
         else
         {
             if (sp == 0)
                 return;
             ele = stack[--sp];
         }
     }
     leaf = (Leaf)ele;
     leafIndex = 0;
 }
Esempio n. 43
0
        static void Main(string[] args)
        {
            //Question 1
            Context ctx = new Context(new ShipSafe(0));

            ctx.LevelUp();
            ctx.LevelUp();
            ctx.TakeDamage();
            ctx.LevelUp();
            ctx.LevelUp();
            ctx.LevelUp();
            ctx.TakeDamage();
            ctx.TakeDamage();
            //Question 2
            Component root      = new Composite(2);
            Component circle1   = new Leaf(1);
            Component rectangle = new Leaf(2);

            root.AddChild(circle1);
            root.AddChild(rectangle);

            Component container1 = new Composite(1);
            Component circle2    = new Leaf(3);
            Component circle3    = new Leaf(1);

            container1.AddChild(circle2);
            container1.AddChild(circle3);

            root.AddChild(container1);

            Component container2 = new Composite(1);
            Component t1         = new Leaf(5);
            Component t2         = new Leaf(1);
            Component t3         = new Leaf(1);

            container2.AddChild(t1);
            container2.AddChild(t2);
            container2.AddChild(t3);
            root.AddChild(container2);

            root.Draw("");

            Console.WriteLine(root.countLeaf());
            //Console.WriteLine(container1.countLeaf());
            //Console.WriteLine(container2.countLeaf());
            //Console.WriteLine(t1.countLeaf());

            Console.WriteLine(isZugi(root));
            //Question 3
            CarProxy car = new CarProxy();

            // Drive the car

            car.StartDriving();
            car.showLocation();

            //Question 5
            FatalLogger fatal = new FatalLogger();
            ErrorLogger error = new ErrorLogger();
            InfoLogger  info  = new InfoLogger();

            LogBase chainRoot = fatal;

            fatal.SetNext(error);
            error.SetNext(info);
            info.SetNext(null);

            chainRoot.Log("tell me why", 2);
            Console.WriteLine("==================");

            //Question 8
            GymAccessObject gymthings = new GymBase();

            gymthings.Run();

            //Question 10
            IWindow window = new BaseWindow();

            IWindow Tlatmeimad = new TlatMeimadWindow(window);
            IWindow super      = new FlashingWindow(Tlatmeimad);

            Console.WriteLine(super.GetDetails());

            IWindow myfavoriteWindow = new Colors(new TlatMeimadWindow(new FlashingWindow(new BaseWindow())));

            Console.WriteLine(myfavoriteWindow.GetDetails());
            //Question 12
            ComputerFactoryMethod cf = new ComputerFactoryMethod();

            Computer v1 = cf.GetComputer("Gaming");
        }
Esempio n. 44
0
        public void LoadFile()
        {
            string path = "NAZO.txt";

            string[] lines = File.ReadAllLines(path);
            int num = 1, x = 0, y = 0;
            bool first = true;
            foreach (string str in lines) {
                string[] cells = str.Split(new char[] { ',' });
                if (first) {
                    xSize = cells.Length;
                    ySize = lines.Length;
                    first = false;
                }
                foreach (string cell in cells) {
                    if (!string.IsNullOrEmpty(cell)) {
                        Leaf leaf = new Leaf(x, y);
                        if (cell == "S") {
                            leaf.Num = "S";
                            leaf.Range = 1;
                            leaf.Cross = false;
                            leafCount++;
                            start = leaf;
                        } else if (cell == "G") {
                            leaf.Num = "G";
                            leaf.Range = 0;
                            leaf.Cross = true;
                            leafCount++;
                            goal = leaf;
                        } else if (cell == "x") {
                            leaf.Num = "x";
                            leaf.Range = 0;
                            leaf.Cross = false;
                        } else {
                            leaf.Num = num.ToString();
                            leaf.Range = int.Parse(cell);
                            leaf.Cross = true;
                            num++;
                            leafCount++;
                        }
                        lotus.Add(leaf);
                        x++;
                    }
                }
                x = 0;
                y++;
            }
            //DebugPrint();
        }
Esempio n. 45
0
 public override int VisitLeaf(Leaf <int> leaf) => leaf.V;
Esempio n. 46
0
    public bool Split()
    {
        //check before spliting if the child are empty
        //Random.seed = (int)System.DateTime.Now.Ticks;
        if(leftChild !=null || rightChild !=null)
            return false;
        // Decide to slice horizontal or vertical
        bool splitH = CoinFlip();
        if (width > height && (float)width / (float)height >=1.25f)
            splitH =false;
        else if (height > width && (float)height / (float)width >=1.25f)
            splitH =true;

        // check if its possible to make a slice
        int max = (splitH ? height :width) - MIN_LEAF_SIZE;
        if (max <= MIN_LEAF_SIZE)
            return false;
        // get random number
        int split = Random.Range(MIN_LEAF_SIZE,max);

        // slice horizontal
        // add child leafs
        if(splitH)
        {
            leftChild = new Leaf(x,y,width,split);
            rightChild  =new Leaf(x,y+split,width, height -split);
        }
        //slice vertical
        // add child leafs
        else
        {
            leftChild = new Leaf(x,y,split,height);
            rightChild = new Leaf(x+split, y, width - split, height);

        }

            return true;
    }
Esempio n. 47
0
    // METHODS

    // Attempt to turn the Quake 2 BSP into a .MAP file
    public virtual Entities decompile()
    {
        DecompilerThread.OnMessage(this, "Decompiling...");
        // In the decompiler, it is not necessary to copy all entities to a new object, since
        // no writing is ever done back to the BSP file.
        mapFile = BSPObject.Entities;
        //int numAreaPortals=0;
        int numTotalItems = 0;
        int onePercent    = (int)((BSPObject.Brushes.Count + BSPObject.Entities.Count) / 100);

        if (onePercent < 1)
        {
            onePercent = 1;
        }
        bool containsAreaPortals = false;

        for (int i = 0; i < BSPObject.Entities.Count; i++)
        {
            // For each entity
            //DecompilerThread.OnMessage(this, "Entity " + i + ": " + mapFile[i]["classname"]);
            // Deal with area portals.
            if (mapFile[i]["classname"].Equals("func_areaportal", StringComparison.CurrentCultureIgnoreCase))
            {
                mapFile[i].Attributes.Remove("style");
                containsAreaPortals = true;
            }
            // getModelNumber() returns 0 for worldspawn, the *# for brush based entities, and -1 for everything else
            int currentModel = mapFile[i].ModelNumber;
            if (currentModel > -1)
            {
                // If this is still -1 then it's strictly a point-based entity. Move on to the next one.
                Leaf[] leaves      = BSPObject.getLeavesInModel(currentModel);
                int    numLeaves   = leaves.Length;
                bool[] brushesUsed = new bool[BSPObject.Brushes.Count]; // Keep a list of brushes already in the model, since sometimes the leaves lump references one brush several times
                numBrshs = 0;                                           // Reset the brush count for each entity
                for (int j = 0; j < numLeaves; j++)
                {
                    // For each leaf in the bunch
                    Leaf currentLeaf     = leaves[j];
                    int  firstBrushIndex = currentLeaf.FirstMarkBrush;
                    int  numBrushIndices = currentLeaf.NumMarkBrushes;
                    if (numBrushIndices > 0)
                    {
                        // A lot of leaves reference no brushes. If this is one, this iteration of the j loop is finished
                        for (int k = 0; k < numBrushIndices; k++)
                        {
                            // For each brush referenced
                            if (!brushesUsed[(int)BSPObject.MarkBrushes[firstBrushIndex + k]])
                            {
                                // If the current brush has NOT been used in this entity
                                //Console.Write("Brush " + numBrshs);
                                brushesUsed[(int)BSPObject.MarkBrushes[firstBrushIndex + k]] = true;
                                Brush brush = BSPObject.Brushes[(int)BSPObject.MarkBrushes[firstBrushIndex + k]];
                                if ((brush.Contents[1] & ((sbyte)1 << 7)) == 0)
                                {
                                    decompileBrush(brush, i);                                     // Decompile the brush
                                }
                                else
                                {
                                    containsAreaPortals = true;
                                }
                                numBrshs++;
                                numTotalItems++;
                                if (numTotalItems % onePercent == 0)
                                {
                                    parent.OnProgress(this, numTotalItems / (double)(BSPObject.Brushes.Count + BSPObject.Entities.Count));
                                }
                            }
                        }
                    }
                }
            }
            numTotalItems++;             // This entity
            if (numTotalItems % onePercent == 0)
            {
                parent.OnProgress(this, numTotalItems / (double)(BSPObject.Brushes.Count + BSPObject.Entities.Count));
            }
        }
        if (containsAreaPortals)
        {
            // If this map was found to have area portals
            int j = 0;
            for (int i = 0; i < BSPObject.Brushes.Count; i++)
            {
                // For each brush in this map
                if ((BSPObject.Brushes[i].Contents[1] & ((sbyte)1 << 7)) != 0)
                {
                    // If the brush is an area portal brush
                    for (j++; j < BSPObject.Entities.Count; j++)
                    {
                        // Find an areaportal entity
                        if (BSPObject.Entities[j]["classname"].Equals("func_areaportal", StringComparison.CurrentCultureIgnoreCase))
                        {
                            decompileBrush(BSPObject.Brushes[i], j); // Add the brush to that entity
                            break;                                   // And break out of the inner loop, but remember your place.
                        }
                    }
                    if (j == BSPObject.Entities.Count)
                    {
                        // If we're out of entities, stop this whole thing.
                        break;
                    }
                }
            }
        }
        if (!Settings.skipPlaneFlip)
        {
            DecompilerThread.OnMessage(this, "Num simple corrected brushes: " + numSimpleCorrects);
            DecompilerThread.OnMessage(this, "Num advanced corrected brushes: " + numAdvancedCorrects);
            DecompilerThread.OnMessage(this, "Num good brushes: " + numGoodBrushes);
        }
        parent.OnProgress(this, 1.0);
        return(mapFile);
    }
Esempio n. 48
0
 public void AddLeaf(Leaf leaf)
 {
     Leaves.Add(leaf);
 }
Esempio n. 49
0
 public StringBuilderWalker(StringBuilder builder)
 {
     m_curLeaf = new Leaf(string.Empty);
     m_builder = builder;
 }
    //Start of Class functions
    List<Leaf> CreateLeaves(int level)
    {
        List<Leaf> leaves = new List<Leaf>();

        Leaf root = new Leaf(0, 0, MapWidth, MapHeight);

        //Trying this to make more small rooms
        //Leaf.MinimumLeafSize = (level + 6);

        MasterRoot = root;

        leaves.Add(root);

        bool didSplit = true;

        while(didSplit)
        {
            didSplit = false;

            for(int i = 0; i < leaves.Count; i++)
            {
                if (leaves[i].leftChild == null && leaves[i].rightChild == null) // if this Leaf is not already split...
                {
                    // if this Leaf is too big, or 75% chance...
                    if (leaves[i].width > MaximumLeafSize || leaves[i].height > MaximumLeafSize || Random.Range (0,1) > 0.25)
                    {
                        if (leaves[i].Split()) // split the Leaf!
                        {
                            // if we did split, push the child leafs to the Vector so we can loop into them next
                            leaves.Add(leaves[i].leftChild);
                            leaves.Add(leaves[i].rightChild);
                            didSplit = true;
                        }
                    }
                }
            }
        }

        return leaves;
    }
Esempio n. 51
0
 public void RemoveLeaf(Leaf leaf)
 {
     Leaves.Remove(leaf);
 }
 public Leaf(int x, int y, int width, int height)
 {
     this.x = x;
     this.y = y;
     this.width = width;
     this.height = height;
     leftChild = null;
     rightChild = null;
 }
Esempio n. 53
0
        public byte[] Decode(byte[] bInput)
        {
            //Local Variables
            var  DecodeDictionary   = new List <Leaf>(255);
            Leaf DecodedLeaf        = null;
            long iInputBuffer       = 0;
            long iStreamLength      = 0;
            var  iInputBufferSize   = 0;
            var  iOutputBuffer      = 0;
            var  iDictionaryRecords = 0;
            var  iDictionaryEndByte = 0;
            var  iBytesWritten      = 0;

            //Populate Decode Dictionary with 256 Leafs
            for (var i = 0; i < 256; i++)
            {
                DecodeDictionary.Add(new Leaf());
            }

            //Retrieve Stream Length
            iStreamLength = BitConverter.ToInt64(bInput, 0);

            //Establish Output Buffer to write unencoded data to
            var bDecodedOutput = new byte[iStreamLength];

            //Retrieve Records in Dictionary
            iDictionaryRecords = bInput[8];

            //Calculate Ending Byte of Dictionary
            iDictionaryEndByte = (((iDictionaryRecords + 1) * 8) + 8);

            //Begin Decoding Dictionary (4 Bytes Per Entry)
            for (var i = 9; i <= iDictionaryEndByte; i += 8)
            {
                iInputBuffer = BitConverter.ToInt64(bInput, i);

                DecodedLeaf = new Leaf();

                //Get Byte Value
                DecodedLeaf.ByteValue = (byte)(iInputBuffer >> 56);
                if (DecodedLeaf.ByteValue != 0)
                {
                    iInputBuffer ^= (((Int64)DecodedLeaf.ByteValue) << 56);
                }

                //Get Bit Count
                DecodedLeaf.BitCount = (int)(iInputBuffer >> 48);
                iInputBuffer        ^= (((Int64)DecodedLeaf.BitCount) << 48);

                //Get Bit Value
                DecodedLeaf.BitValue = (int)(iInputBuffer);

                //Add Decoded Leaf to Dictionary
                DecodeDictionary[DecodedLeaf.ByteValue] = DecodedLeaf;
            }

            //Begin Looping through Input and Decoding
            iInputBuffer = 0;
            for (var i = (iDictionaryEndByte + 4); i < bInput.Length; i++)
            {
                //Increment the Buffer
                iInputBufferSize += 8;

                if (iInputBuffer != 0)
                {
                    iInputBuffer <<= 8;
                    iInputBuffer  ^= bInput[i];
                }
                else
                {
                    iInputBuffer = bInput[i];
                }

                //Loop through the Current Buffer until it's exhausted
                for (var j = (iInputBufferSize - 1); j >= 0; j--)
                {
                    iOutputBuffer = (int)(iInputBuffer >> j);

                    //Leading 0;
                    if (iOutputBuffer == 0)
                    {
                        continue;
                    }
                    var iBitCount = iInputBufferSize - j;
                    //Try and find a byte in the dictionary that matches what's currently in the buffer
                    for (var k = 0; k < 256; k++)
                    {
                        if (DecodeDictionary[k].BitValue == iOutputBuffer && DecodeDictionary[k].BitCount == iBitCount)
                        {
                            //Byte Found, Write it to the Output Buffer and XOR it from the current Input Buffer
                            bDecodedOutput[iBytesWritten] = DecodeDictionary[k].ByteValue;
                            iOutputBuffer  <<= j;
                            iInputBuffer    ^= iOutputBuffer;
                            iInputBufferSize = j;
                            iBytesWritten++;
                            break;
                        }
                    }
                }
            }
            return(bDecodedOutput);
        }
Esempio n. 54
0
        public byte[] Decode(byte[] bInput)
        {
            //Local Variables
            List<Leaf> DecodeDictionary = new List<Leaf>(255);
            Leaf DecodedLeaf = null;
            long iInputBuffer = 0;
            long iStreamLength = 0;
            int iInputBufferSize = 0;
            int iOutputBuffer = 0;
            int iDictionaryRecords = 0;
            int iDictionaryEndByte = 0;
            int iBytesWritten = 0;
            
            //Populate Decode Dictionary with 256 Leafs
            for (int i = 0; i < 256; i++)
            {
                DecodeDictionary.Add(new Leaf());
            }

            //Retrieve Stream Length
            iStreamLength = BitConverter.ToInt64(bInput, 0);
            
            //Establish Output Buffer to write unencoded data to
            byte[] bDecodedOutput = new byte[iStreamLength];

            //Retrieve Records in Dictionary
            iDictionaryRecords = bInput[8];

            //Calculate Ending Byte of Dictionary
            iDictionaryEndByte = (((iDictionaryRecords +1) * 8) + 8);

            //Begin Decoding Dictionary (4 Bytes Per Entry)
            for (int i = 9; i <= iDictionaryEndByte; i += 8)
            {
                iInputBuffer = BitConverter.ToInt64(bInput, i);

                DecodedLeaf = new Leaf();

                //Get Byte Value
                DecodedLeaf.ByteValue = (byte)(iInputBuffer >> 56);
                if(DecodedLeaf.ByteValue != 0) iInputBuffer ^= (((Int64)DecodedLeaf.ByteValue) << 56);

                //Get Bit Count
                DecodedLeaf.BitCount = (int)(iInputBuffer >> 48);
                iInputBuffer ^= (((Int64)DecodedLeaf.BitCount) << 48);

                //Get Bit Value
                DecodedLeaf.BitValue = (int)(iInputBuffer);

                //Add Decoded Leaf to Dictionary
                DecodeDictionary[DecodedLeaf.ByteValue] = DecodedLeaf;
            }

            //Begin Looping through Input and Decoding
            iInputBuffer = 0;
            for (int i = (iDictionaryEndByte +4); i < bInput.Length; i++)
            {
                //Increment the Buffer
                iInputBufferSize += 8;

                if (iInputBuffer != 0)
                {
                    iInputBuffer <<= 8;
                    iInputBuffer ^= bInput[i];
                }
                else
                {
                    iInputBuffer = bInput[i];
                }

                //Loop through the Current Buffer until it's exhausted
                for (int j = (iInputBufferSize - 1); j >= 0; j--)
                {
                    iOutputBuffer = (int)(iInputBuffer >> j);

                    //Leading 0;
                    if (iOutputBuffer == 0) continue;
                    int iBitCount = iInputBufferSize - j;
                    //Try and find a byte in the dictionary that matches what's currently in the buffer
                    for (int k = 0; k < 256; k++)
                    {
                        if (DecodeDictionary[k].BitValue == iOutputBuffer && DecodeDictionary[k].BitCount == iBitCount)
                        {
                            //Byte Found, Write it to the Output Buffer and XOR it from the current Input Buffer
                            bDecodedOutput[iBytesWritten] = DecodeDictionary[k].ByteValue;
                            iOutputBuffer <<= j;
                            iInputBuffer ^= iOutputBuffer;
                            iInputBufferSize = j;
                            iBytesWritten++;
                            break;
                        }
                    }
                }
            }
            return bDecodedOutput;
        }
Esempio n. 55
0
 public Leaf(string value = "", Leaf leftLeaf = null, Leaf rightLeaf = null)
 {
     Value     = value;
     LeftLeaf  = leftLeaf;
     RightLeaf = rightLeaf;
 }
 public LeafIterator( Leaf leaf )
 {
     this.leaf = leaf;
 }
Esempio n. 57
0
 public abstract T1 VisitLeaf(Leaf <T> leaf);
Esempio n. 58
0
        static void Main(string[] args)
        {
            #region 工厂方法
            double total = 0.0d;
            CashContext cc = new CashContext(new CashNormal());
            total = cc.GetResult(100.04);
            cc = new CashContext(new CashRebate("0.8"));
            total = cc.GetResult(100.04);
            Console.WriteLine(total);
            #endregion

            #region 装饰器方法
            Decorator.Component person = new Decorator.Component("xiaocai");

            Tshirt tshirt = new Tshirt();
            BigTrouser bt = new BigTrouser();

            bt.Decorator(person);
            tshirt.Decorator(bt);
            tshirt.show();

            Console.WriteLine("*****************************");
            #endregion

            #region 代理方法
            SchoolGirl sg = new SchoolGirl();
            sg.Name = "李娇骄";
            Proxy.Proxy daili = new Proxy.Proxy(sg);
            daili.GiveDolls();
            daili.GiveFlowers();
            #endregion

            #region 原型模式
            ConcretePrototype1 p1 = new ConcretePrototype1("123");
            ConcretePrototype1 c1 = (ConcretePrototype1)p1.Clone();
            Console.WriteLine("Cloned :"+c1.Id);

            Resume a = new Resume("Andy");
            a.setInfo("Man", "24");
            a.setWorkExperience("1998-2005","IBM ");
            Resume b = (Resume)a.Clone();
            b.setWorkExperience("2002-2005", "Dell");
            a.display();
            b.display();
            #endregion

            #region 模板模式
            Console.WriteLine("Student A testPaper:");
            TestPaperA testA = new TestPaperA();
            testA.Test1();
            testA.Test2();
            Console.WriteLine("Student B testPaper:");
            TestPaperB testB = new TestPaperB();
            testB.Test1();
            testB.Test2();
            #endregion

            #region 抽象工厂方法
            User user = new User();

            IFactory factory = new SqlServerFactory();
            IUser iu = factory.CreateUser();
            //IUser riu = (IUser)Assembly.Load("AbstractFactory").CreateInstance("SqlserverUser");
            //反射
            //Assembly.Load("程序集名称").CreateInstance("程序集名称.类名称");
            iu.Insert(user);
            iu.GetUser(1);
            #endregion

            #region Facade 外观模式
            Fund jijin = new Fund();
            jijin.BuyFund();
            jijin.sellFund();
            #endregion

            #region 建造者模式
            Director director = new Director();
            abstractBuilder builder1 = new Builder1();
            abstractBuilder builder2 = new BuilderB();
            director.Construct(builder1);
            Builder.Builder b1 = builder1.getBuilder();
            b1.show();

            director.Construct(builder2);
            Builder.Builder b2 = builder2.getBuilder();
            b2.show();
            #endregion
            #region 观察者模式
            Observer.ConcreteSubject s = new Observer.ConcreteSubject();
            s.Attach(new Observer.ConcreteObserver(s, "x"));
            s.Attach(new Observer.ConcreteObserver(s, "y"));
            s.SubjectState = "ABC";
            s.Notify();
            ///下面是使用委托
            ///委托就是一种引用方法的类型。一旦为委托分配了方法,委托将于该方法具有完全相同的行为。
            ///委托方法的使用可以像其他的方法一样具有参数和返回值。委托可以看作是对函数的抽象,是函数的”类“,委托的实例将代表一个具体的函数
            ///一个委托可以搭载多个方法,所有方法被依次唤起,委托搭载的方法不需要属于同一个类,只需要具有相同的原型和形式,也就是拥有相同的参数列表和返回类型。
            ///在使用带参数的委托时,只需要在声明事件的地方将参数传递给事件。在绑定时将调用的方法绑定给事件。
            Bosscs boss = new Bosscs();
            StockObserver tongshi1 = new StockObserver("tongshi1",boss);
            NBAObserver tongshiNBA = new NBAObserver("tongshiNBA", boss);
            boss.Update += new EventHandler1(tongshi1.CloseStockMarket);
            boss.Update += new EventHandler1(tongshiNBA.CloseStockMarket);
            boss.update2 += new EventHandler2(tongshiNBA.print);
            boss.SubjectState = " I am back ";
            boss.Notify();
            #endregion

            #region 状态模式
            State.Context c = new State.Context(new CreateStateA());
            c.Request();
            c.Request();
            c.Request();
            c.Request();

            #endregion

            #region 备忘录模式
            Originator o = new Originator();
            o.State = "On";
            o.Show();
            Caretaker care = new Caretaker();
            care.Memento = o.CreateMemento();
            o.State = "Off";
            o.Show();

            o.SetMemento(care.Memento);
            o.Show();

            GameRole gameRole = new GameRole();
            gameRole.GetInitState();
            gameRole.StateDisplay();

            RoleStateManager stateManager = new RoleStateManager();
            stateManager.Memento = gameRole.SaveState();

            gameRole.Fight();
            gameRole.StateDisplay();

            gameRole.RecoveryState(stateManager.Memento);
            gameRole.StateDisplay();
            #endregion

            #region 组合模式
            Composite.Composite root = new Composite.Component("root");
            root.Add(new Leaf("Leaf A"));
            root.Add(new Leaf("Leaf B"));

            Composite.Composite comp = new Composite.Component("comp X");
            comp.Add(new Leaf("Leaf XA"));
            comp.Add(new Leaf("Leaf XB"));
            root.Add(comp);

            Composite.Composite comp2 = new Composite.Component("Comp X2");
            comp2.Add(new Leaf("Leaf X2A"));
            comp2.Add(new Leaf("Leaf X2B"));
            comp.Add(comp2);

            root.Add(new Leaf("Leaf C"));
            Leaf leaf = new Leaf("Leaf D");

            root.Add(leaf);
            root.Display(1);
            root.Remove(leaf);
            root.Display(1);
            #endregion

            #region 迭代器模式
            ConCreteAggregate aggregate = new ConCreteAggregate();
            aggregate[0] = "大鸟";
            aggregate[1] = "小菜";
            aggregate[2]="行李";
            aggregate[3] = "老外";
            aggregate[4] = "小偷";
            Iterator.Iterator myIterator = new ConCreteIterator(aggregate);
            object item = myIterator.First();
            while (!myIterator.IsDone())
            {
                Console.WriteLine(myIterator.CurrentItem() + "请买车票");
                myIterator.Next();
            }
            #endregion

            #region 单例模式
             //所有类都有构造方法,不编码则默认生成空的构造方法,若有显示定义的构造方法,默认的构造方法就会失效。只要将构造方法改写为私有的,外部的程序就不能通过new 来初始化它。
            //通过一个共有的方法来返回类的实例。
            Singleton.Singleton s1 = Singleton.Singleton.GetInstance();
            Singleton.Singleton s2 = Singleton.Singleton.GetInstance();

            if (s1 == s2)
            {
                Console.WriteLine("两个对象是相同的实例。");
            }

            #endregion

            #region 命令模式
            Receiver r = new Receiver();
            Command.Command command = new Command.ConcreteCommand(r);
            Invoker invoker = new Invoker();
            invoker.SetCommand(command);
            invoker.ExecuteCommand();
            #endregion

            #region 职责链模式
            Handler h1 = new ConcreteHandler1();
            Handler h2 = new ConcreteHandler2();
            h1.SetSuccessor(h2);
            int[] requests = { 2, 3, 4, 5, 6, 12, 34, 11, 15 };
            foreach (int request in requests)
            {
                h1.HandlerRequest(request);
            }
            #endregion

            #region 中介者模式
            ConcreteMediator mediator = new ConcreteMediator();
            ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator);
            ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator);
            mediator.Colleague1 = colleague1;
            mediator.Colleague2 = colleague2;
            colleague1.Send("吃饭了吗?");
            colleague2.Send("还没有呢");
            #endregion

            #region 享元模式
            int extri = 22;
            FlyweightFactory f = new FlyweightFactory();
            Flyweight.Flyweight fx = f.GetFlyweight("X");
            fx.Operation(--extri);

            Flyweight.Flyweight fy = f.GetFlyweight("Y");
            fy.Operation(--extri);

            Flyweight.Flyweight fz = f.GetFlyweight("Z");
            fz.Operation(--extri);

            #endregion

            #region 解释器模式
            <<<<<<< HEAD
            Interpreter.Context context = new Interpreter.Context();
            IList<Interpreter.AbstractExpression> list = new List<Interpreter.AbstractExpression>();
            list.Add(new Interpreter.TerminalExpression());
            list.Add(new Interpreter.NormalExpression());
            foreach (Interpreter.AbstractExpression exp in list)
                exp.Interpret(context);
            =======
            Interpreter.Context context1 = new Interpreter.Context();
            IList<AbstractExpression> list = new List<AbstractExpression>();
            list.Add(new TerminalExpression());
            list.Add(new NonTerminalExpression());
            foreach (AbstractExpression exp in list)
            {
                exp.Interpreter(context1);
            }
            #endregion

            #region 访问者模式
            ObjectStructure os = new ObjectStructure();
            os.Add(new Man());
            os.Add(new Woman());
            Success v1 = new Success();
            os.Display(v1);
            Failing f1 = new Failing();
            os.Display(f1);

            Amativeness a1 = new Amativeness();
            os.Display(a1);
            >>>>>>> 77e342ef6e96917a8dc01e72e41626dcffd4ba13
            #endregion
            Console.Read();
        }
Esempio n. 59
0
  public static void Main( string[] args )
  {
    // Create a tree structure
    Composite root = new Composite( "root" );
    root.Add( new Leaf( "Leaf A" ));
    root.Add( new Leaf( "Leaf B" ));

    Composite comp = new Composite( "Composite X" );
    comp.Add( new Leaf( "Leaf XA" ) );
    comp.Add( new Leaf( "Leaf XB" ) );

    root.Add( comp );
    root.Add( new Leaf( "Leaf C" ));

    // Add and remove a leaf
    Leaf l = new Leaf( "Leaf D" );
    root.Add( l );
    root.Remove( l );

    // Recursively display nodes
    root.Display( 1 );

  }
Esempio n. 60
-2
 public void Start()
 {
     Leaf root = new Leaf(0,0,gridSize,gridSize);
     dungeon = new int[gridSize,gridSize];
     RoomLayout = new Room[7, 7];
     Debug.Log(dungeon.GetLength(0) +"_"+dungeon.GetLength(1) );
     leafList.Add(root);
     puzzleList = GameObject.FindObjectOfType<PuzzleList>();
     StartCoroutine(BuildLeafTree());
 }