Пример #1
0
        private void LoadCustomer(WebBrowser webBrowser1)
        {
            try
            {
                HtmlWindowCollection coll = webBrowser1.Document.Window.Frames;
                foreach (HtmlWindow win in coll)
                {
                    HtmlElement ele = win.Document.GetElementById("tMemCardID");
                    if (ele != null)
                    {
                        TicketOrder ticketOrder = new TicketOrder();
                        if (ticketOrder.LoadTicketOrder(txtOrderId.Text.Trim()))
                        {
                            win.Document.GetElementById("tPNR").SetAttribute("value", ticketOrder.PNR);

                            System.Web.Caching.Cache cache = System.Web.HttpRuntime.Cache;
                            cache.Add("TicketOrderInfo", ticketOrder, null, DateTime.MaxValue, new TimeSpan(0, 5, 0), System.Web.Caching.CacheItemPriority.Normal, null);
                        }

                        ele.SetAttribute("value", ticketOrder.CardNum);
                        win.Document.GetElementById("tMemName").SetAttribute("value", ticketOrder.MemberName);

                        ele = win.Document.GetElementById("bMemInfo");
                        ele.InvokeMember("Click");
                        fillData = BLL.FillData.填写PNR;
                        break;
                    }
                }
            }
            catch { }
        }
    public FilledRegion Apply(FillData data)
    {
        //Keep track of the platforms as individual spawning regions.
        List <Region> playSpawns = new List <Region>();
        int           startingX;

        //Use a counter.
        for (int y = data.BeingFilled.Bottom - SpaceBetween; y >= data.BeingFilled.Top + SpaceBetween; y -= SpaceBetween)
        {
            startingX = data.BeingFilled.Left + Border;

            //Go through each block in the current line.
            int x;
            for (x = data.BeingFilled.Left + Border; x <= data.BeingFilled.Right - Border; ++x)
            {
                //With a certain chance, fill it.
                if (MathF.R.NextDouble() > PercentageHoles)
                {
                    data.SetMapAt(new Location(x, y), true);
                }
                //Otherwise, cut off the platform region here.
                else
                {
                    playSpawns.Add(new Region(new Location(startingX, y - 1), new Location(x - 1, y - 1)));
                    startingX = x + 1;
                }
            }

            playSpawns.Add(new Region(new Location(startingX, y - 1), new Location(x - 1, y - 1)));
        }

        return(new PlatformsRegion(data.BeingFilled, playSpawns));
    }
Пример #3
0
 private void Navigate(WebBrowser browser)
 {
     try
     {
         HtmlWindowCollection coll = browser.Document.Window.Frames;
         foreach (HtmlWindow win in coll)
         {
             HtmlElement ele = win.Document.GetElementById("LeftMenuTable");
             if (ele != null)
             {
                 HtmlElementCollection eleCollection = ele.All;
                 foreach (HtmlElement el in eleCollection)
                 {
                     if (el.InnerText == "订单导入")
                     {
                         el.GetElementsByTagName("a")[0].InvokeMember("Click");
                         process  = BLL.ProcessControl.填充数据;
                         fillData = BLL.FillData.填写会员卡号;
                         break;
                     }
                 }
             }
         }
     }
     catch { }
 }
Пример #4
0
        public ActionResult FillGap()
        {
            FillData fd = new FillData();

            fd.FillGapsInBD();
            return(View("ShowData"));
        }
Пример #5
0
        public ActionResult FillDataBase(FormCollection collection)
        {
            FillData fd = new FillData(Convert.ToBoolean(collection["startNewDB"]));

            fd.FillStaffBD();
            return(View("ShowData"));
        }
Пример #6
0
 /// <summary>
 /// Parses current drawing from JSON
 /// </summary>
 /// <param name="jsonDrawCommands">JSON draw commands</param>
 private void ParseCurrentDrawingFromJSON(JArray jsonDrawCommands)
 {
     foreach (JToken json_token in jsonDrawCommands)
     {
         if (json_token is JObject json_draw_command)
         {
             if (json_draw_command.ContainsKey("type") && json_draw_command.ContainsKey("data") && json_draw_command["data"] is JObject json_draw_command_data)
             {
                 switch (json_draw_command["type"].ToObject<string>())
                 {
                     case "line":
                         LineData line_data = json_draw_command_data.ToObject<LineData>();
                         if ((line_data != null) && line_data.IsValid)
                         {
                             currentDrawing.Add(new DrawCommand(EDrawCommandType.Line, line_data.FromX, line_data.FromY, line_data.ToX, line_data.ToY, (Color)line_data.Color, line_data.LineWidth));
                         }
                         else
                         {
                             throw new InvalidDataException("Line draw command data is invalid.");
                         }
                         break;
                     case "fill":
                         FillData fill_data = json_draw_command_data.ToObject<FillData>();
                         if ((fill_data != null) && fill_data.IsValid)
                         {
                             currentDrawing.Add(new DrawCommand(EDrawCommandType.Fill, fill_data.X, fill_data.Y, default, default, (Color)fill_data.Color, 0.0f));
                         }
                         else
                         {
                             throw new InvalidDataException("Fill draw command data is invalid.");
                         }
                         break;
                 }
             }
         }
Пример #7
0
        /// <summary>
        /// 打开选择地区窗体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChoice_Click(object sender, EventArgs e)
        {
            FillData fd = new FillData(GetValue);
            //FrmArea frm = new FrmArea((IGetAreas)this);
            FrmArea frm = new FrmArea(fd);

            //frm.MdiParent = this.MdiParent;
            frm.ShowDialog();
        }
Пример #8
0
    //Base generation (i.e. the rooms/junctions).

    public void InitializeBase()
    {
        //The size of the cell grid is found by combining each node
        //   (assumed to have the largest-possible room size) with each connecting tunnel.
        Location cells = new Location(((Settings.NumberOfNodes.X - 1) * Settings.TunnelLength.X) +
                                      (Settings.NumberOfNodes.X * MaxRoomSize.X) + 2,
                                      ((Settings.NumberOfNodes.Y - 1) * Settings.TunnelLength.Y) +
                                      (Settings.NumberOfNodes.Y * MaxRoomSize.Y) + 2);

        //Set up the graph/pather.
        Graph = new LimitedRectangularGrid(new RectangularGrid(Settings.TunnelLength.X + MaxRoomSize.X,
                                                               Settings.TunnelLength.Y + MaxRoomSize.Y,
                                                               false),
                                           false, false,
                                           new Interval(0, cells.X - 1, true, 0),
                                           new Interval(0, cells.Y - 1, true, 0));
        GraphPather = new PathFinder <PositionalNode>(Graph,
                                                      new PositionalNode(new float[2] {
            Single.NaN, Single.NaN
        }, 0),
                                                      (n, n2) => new PositionalEdge(n.Coordinate, n2.Coordinate, 0));

        //Set up the room map. Initial value is a fully-filled room.
        Map = new bool[cells.X, cells.Y];
        for (int i = 0; i < Map.GetLength(0); ++i)
        {
            for (int j = 0; j < Map.GetLength(1); ++j)
            {
                Map[i, j] = true;
            }
        }

        //Initialize the room nodes.
        NodeAreas  = new Dictionary <PositionalNode, Region>();
        NodeStates = new Dictionary <PositionalNode, NodeState>();
        foreach (PositionalNode n in Graph.AllNodes(new PositionalNode(new float[2] {
            1.0f, 1.0f
        })))
        {
            NodeStates.Add(n, NodeState.Untouched);
        }

        //Initialize other data.
        Regions       = new List <Region>();
        FilledRegions = new List <FilledRegion>();
        Holes         = new List <Location>();

        //Initialize counter to iterate through base room generation.
        DoneBaseGen           = false;
        listVersionBGIC       = NodeStates.Keys.ToList();
        baseGenIterateCounter = listVersionBGIC.GetEnumerator();
        baseGenIterateCounter.MoveNext();

        //Set up the fill data.
        FillData = new FillData(Map, new Region(-1, -1, -1, -1), Regions, Holes, GenSettings.WrapX, GenSettings.WrapY, true);
    }
Пример #9
0
        /// <summary>
        /// Equals Method
        /// </summary>
        /// <param name="fd"></param>
        /// <returns></returns>
        public bool Equals(FillData fd)
        {
            // If parameter is null return false:
            if ((object)fd == null)
            {
                return(false);
            }

            // Return true if the fields match:
            return((this.fillPatern == fd.fillPatern) && (this.icvBack == fd.icvBack) && (this.icvFore == fd.icvFore));
        }
Пример #10
0
        //异步执行开始函数
        protected override IAsyncResult BeginExecute(AsyncCodeActivityContext context, AsyncCallback callback, object state)
        {
            //根据EXCEL主控件标志获取其抽象化属性
            PropertyDescriptor property = context.DataContext.GetProperties()[ExcelCreate.GetExcelAppTag];
            //抽象化属性转换为可用ExcelApplication属性
            Excel::Application excelApp = property.GetValue(context.DataContext) as Excel::Application;

            try
            {
                //string sheetName = SheetName.Get(context);
                //string cellName_Begin = CellName_Begin.Get(context);
                //string cellName_End = CellName_End.Get(context);
                //int cellRow_Begin = CellRow_Begin.Get(context);
                //int cellColumn_Begin = CellColumn_Begin.Get(context);
                //int cellRow_End = CellRow_End.Get(context);
                //int cellColumn_End = CellColumn_End.Get(context);
                //Excel::_Worksheet sheet;
                //if (sheetName != null)
                //    sheet = excelApp.ActiveWorkbook.Sheets[sheetName];
                //else
                //    sheet = excelApp.ActiveSheet;

                //Excel::Range range1, range2;
                //range1 = cellName_Begin == null ? sheet.Cells[cellRow_Begin, cellColumn_Begin] : sheet.Range[cellName_Begin];
                //range2 = cellName_End == null ? sheet.Cells[cellRow_End, cellColumn_End] : sheet.Range[cellName_End];
                Excel::_Worksheet sheet;
                Excel::Range      range1, range2;
                RangeFunction.GetRange(excelApp, context, SheetName, CellName_Begin, CellName_End,
                                       CellRow_Begin, CellColumn_Begin, CellRow_End, CellColumn_End,
                                       out sheet, out range1, out range2);
                Excel::Range range3 = sheet.Range[range1, range2];
                range3.Value2 = FillData.Get(context);

                //释放资源
                System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                sheet = null;
                //资源回收
                GC.Collect();
            }
            catch (Exception e)
            {
                SharedObject.Instance.Output(SharedObject.enOutputType.Error, "EXCEL区域填充过程出错", e.Message);
                new CommonVariable().realaseProcessExit(excelApp);
            }

            m_Delegate = new runDelegate(Run);
            return(m_Delegate.BeginInvoke(callback, state));
        }
Пример #11
0
    public FilledRegion Apply(FillData data)
    {
        List <Region> spawnAreas = new List <Region>();

        //Get data.
        Generation.BeingFilled = data.BeingFilled;
        int numb   = Generation.NumbPlateaus;
        int width  = Generation.PlateauWidth;
        int space  = Generation.SpaceBetweenPlateaus;
        int border = Generation.Border;

        //Plateau location data.
        int height = (int)Math.Round((PlateauRelativeHeight * data.BeingFilled.Height), 0);

        if (height >= data.BeingFilled.Height)
        {
            height = data.BeingFilled.Height - 1;
        }
        int top = data.BeingFilled.Bottom - height;

        //Add the plateaus.
        Region r;

        for (int i = 0; i < numb; ++i)
        {
            r = new Region(data.BeingFilled.Left + border + (i * (space + width)), top, width - 1, data.BeingFilled.Bottom - top);
            data.FillRegion(true, r);
            spawnAreas.Add(new Region(new Location(r.Left, data.BeingFilled.Top),
                                      r.TopRight.Above));
        }

        //Make room for any holes that the plateaus covered.
        foreach (Location l in data.HolesAlongPerimeter())
        {
            //The hole is covered if it is just under the region and the space right above it is covered.
            if (data.BeingFilled.Touches(l.Above, true, true, false) &&
                data.GetMapAt(l.Above))
            {
                //Make a litle tunnel under the plateau.
                int[]  plateauSides = PlateauSides(l.X, numb, width, space, border, data.BeingFilled.Left, data.BeingFilled.Right);
                Region cleared      = new Region(plateauSides[0], data.BeingFilled.Bottom, width - 1, 0);
                data.FillRegion(false, cleared);
            }
        }

        return(new SteppedHallwayRegion(data.BeingFilled, spawnAreas));
    }
    public FilledRegion Apply(FillData data)
    {
        //Get the space between each shell. In most cases it should be 1.
        //In the case of a very large room, it could be 2.
        //Played around with a graphing calculator to get a good function that reflects this.
        int    minSpace = 1, maxSpace = 2;
        double coefficient        = Math.Sqrt(maxSpace - minSpace) / (data.BeingFilled.Area - MinArea);
        int    spaceBetweenShells = (int)Math.Round(Math.Pow(coefficient * (data.BeingFilled.Area - MinArea), 2.0) + 1.0, 0);

        //Make sure my function is valid.
        if (spaceBetweenShells < 1 || spaceBetweenShells > 2)
        {
            throw new InvalidOperationException("Oops!");
        }

        //Continuously fill in smaller and smaller shells centered around the region center.
        Region shell   = new Region(data.BeingFilled.TopLeft.Right.Below, data.BeingFilled.BottomRight.Left.Above, true);
        sbyte  holeDir = 1;

        //Smallest-allowable shell is 3x3, which means a region of width/height 2.
        while (shell.Area > 4)
        {
            //Fill in the perimeter.
            data.FillPerimeter(true, shell);

            //Clear the hole.
            if (holeDir < 0)
            {
                data.SetMapAt(shell.LeftMid, false);
            }
            else
            {
                data.SetMapAt(shell.RightMid, false);
            }

            //Flip the side the next hole will be on.
            holeDir *= -1;

            //Shrink the shell.
            for (int i = 0; i < spaceBetweenShells; ++i)
            {
                shell = new Region(shell.TopLeft.Right.Below, shell.BottomRight.Left.Above, false);
            }
        }

        return(new ConcentricSquaresRegion(data.BeingFilled, new Region(shell.TopLeft.Left.Above, shell.BottomRight.Right.Below)));
    }
Пример #13
0
    public FilledRegion Apply(FillData data)
    {
        bool horizontal = data.BeingFilled.Width > data.BeingFilled.Height;
        bool vertical   = data.BeingFilled.Height > data.BeingFilled.Width;

        //Put a thin line through the middle.
        if (horizontal)
        {
            data.FillRegion(true, new Region(data.BeingFilled.Left + 1, data.BeingFilled.CenterY, data.BeingFilled.Width - 2, 0, true));
        }
        else if (vertical)
        {
            data.FillRegion(true, new Region(data.BeingFilled.CenterX, data.BeingFilled.Top + 1, 0, data.BeingFilled.Height - 2, true));
        }

        return(new LineRegion(data.BeingFilled));
    }
Пример #14
0
    public void InitializeBase()
    {
        Regions        = new List <Region>();
        RegionsToSplit = new Stack <Region>();
        FilledRegions  = new List <FilledRegion>();
        Holes          = new List <Location>();

        Map = new bool[Size.X, Size.Y];
        for (int i = 0; i < Map.GetLength(0); ++i)
        {
            for (int j = 0; j < Map.GetLength(1); ++j)
            {
                if ((!Settings.WrapX && (i == 0 || i == Map.GetLength(0) - 1)) ||
                    (!Settings.WrapY && (j == 0 || j == Map.GetLength(1) - 1)))
                {
                    Map[i, j] = true;
                }
                else
                {
                    Map[i, j] = false;
                }
            }
        }

        if (!Settings.WrapX && !Settings.WrapY)
        {
            RegionsToSplit.Push(new Region(1, 1, Size.X - 3, Size.Y - 3));
        }
        else if (!Settings.WrapX)
        {
            RegionsToSplit.Push(new Region(1, 0, Size.X - 3, Size.Y - 1));
        }
        else if (!Settings.WrapY)
        {
            RegionsToSplit.Push(new Region(0, 1, Size.X - 1, Size.Y - 3));
        }
        else
        {
            RegionsToSplit.Push(new Region(0, 0, Size.X - 1, Size.Y - 1));
        }

        iterateFillPatternsRegionCount = 0;

        FillData = new FillData(Map, new Region(-1, -1, -1, -1), Regions, Holes, Settings.WrapX, Settings.WrapY, false);
    }
Пример #15
0
        /// <summary>
        /// Equals Method
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public override bool Equals(System.Object obj)
        {
            // If parameter is null return false.
            if (obj == null)
            {
                return(false);
            }

            // If parameter cannot be cast to FillDataList return false.
            FillData fd = obj as FillData;

            if ((System.Object)fd == null)
            {
                return(false);
            }

            // Return true if the fields match:
            return((this.fillPatern == fd.fillPatern) && (this.icvBack == fd.icvBack) && (this.icvFore == fd.icvFore));
        }
Пример #16
0
        private void LoadPNR(WebBrowser webBrowser1)
        {
            try
            {
                HtmlWindowCollection coll = webBrowser1.Document.Window.Frames;
                foreach (HtmlWindow win in coll)
                {
                    HtmlElement ele = win.Document.GetElementById("tPNR");
                    if (ele != null)
                    {
                        win.Document.GetElementById("bA").InvokeMember("Click");

                        process  = BLL.ProcessControl.提交;
                        fillData = BLL.FillData.初始化;

                        break;
                    }
                }
            }
            catch { }
        }
    public FilledRegion Apply(FillData data)
    {
        //Fill the square.
        data.FillRegion(true, new Region(data.BeingFilled.TopLeft.Right.Below, data.BeingFilled.BottomRight.Left.Above));

        //Create the lines.
        Region horz  = new Region(data.BeingFilled.LeftMid.Right, data.BeingFilled.Center.Left);
        Region horz2 = new Region(data.BeingFilled.Center.Right, data.BeingFilled.RightMid.Left);
        Region vert  = new Region(data.BeingFilled.TopMid.Below, data.BeingFilled.Center.Above);
        Region vert2 = new Region(data.BeingFilled.Center.Below, data.BeingFilled.BottomMid.Above);

        data.FillRegion(false, horz);
        data.FillRegion(false, horz2);
        data.FillRegion(false, vert);
        data.FillRegion(false, vert2);

        Region center = new Region(data.BeingFilled.Center, data.BeingFilled.Center);

        data.Holes.Add(center.Center);
        data.FillRegion(false, center);

        return(new CarvedPlusRegion(data.BeingFilled));
    }
Пример #18
0
    public FilledRegion Apply(FillData data)
    {
        float OuterCircle = data.BeingFilled.Width * 0.5f;

        if (OuterCircle <= InnerCircle)
        {
            throw new ArgumentOutOfRangeException("The outer radius has to be larger than the inner radius!");
        }

        Location center = data.BeingFilled.Center;

        //Make the circles.
        data.FillCircle(true, center, OuterCircle);
        data.FillCircle(false, center, InnerCircle);

        //Make the lines to get to the inner circle.
        data.FillLine(false, center, data.BeingFilled.BottomMid);
        data.FillLine(false, center, data.BeingFilled.TopMid);
        data.FillLine(false, center, data.BeingFilled.LeftMid);
        data.FillLine(false, center, data.BeingFilled.RightMid);

        //For spawn points, give the two points just to the left/right of the inner circle.
        return(new CircleRegion(data.BeingFilled, InnerCircle));
    }
    public FilledRegion Apply(FillData data)
    {
        //The spawning areas.
        List <Region> spawningAreas = new List <Region>();

        //Get/set some data.
        Region area = data.BeingFilled;

        PlateauGeneration.BeingFilled = data.BeingFilled;
        //If the corridor is going to be vertical, flip the width and height.
        if (area.Height > area.Width)
        {
            PlateauGeneration.BeingFilled = new Region(area.Y, area.X, area.Height, area.Width);
        }

        int numb        = PlateauGeneration.NumbPlateaus;
        int plateauSize = PlateauGeneration.PlateauWidth;

        int space  = PlateauGeneration.SpaceBetweenPlateaus;
        int border = PlateauGeneration.Border;

        //Plateau size data.
        //"maxSize" is the largest allowable hurdle height.
        int maxSize = PlateauGeneration.BeingFilled.Height - 1;

        if (area.Height > area.Width)
        {
            //Vertical.

            //Add the plateaus.
            int hurdleWidth, plateauExtent;
            for (int i = 0; i < numb; ++i)
            {
                //Get a width within the given random variation.
                hurdleWidth = (int)Math.Round((area.Width + 1) * (HurdleAverageSpaceScale + ((2 * HurdleHeightVariance * (float)GeneratorSettings.R.NextDouble()) - HurdleHeightVariance)), 0);
                //Keep it constrained.
                if (hurdleWidth > maxSize)
                {
                    hurdleWidth = maxSize;
                }
                if (hurdleWidth < 1)
                {
                    hurdleWidth = 1;
                }

                //Get the width of the plateau given the size of a hurdle.
                plateauExtent  = area.Width + 1 - hurdleWidth;
                plateauExtent /= 2;

                //Fill in the plateaus.
                data.FillRegion(true, new Region(area.Left, area.Top + border + (i * (space + plateauSize)), plateauExtent - 1, plateauSize - 1));
                if ((2 * plateauExtent) + hurdleWidth >= area.Width + 1)
                {
                    data.FillRegion(true, new Region(area.Right - plateauExtent + 1, area.Top + border + (i * (space + plateauSize)), plateauExtent - 1, plateauSize - 1));
                }
                else
                {
                    data.FillRegion(true, new Region(area.Right - plateauExtent, area.Top + border + (i * (space + plateauSize)), plateauExtent, plateauSize - 1));
                }
            }

            //Make room for any holes that the plateaus covered.
            foreach (Location l in data.HolesAlongPerimeter())
            {
                //The hole is covered if it is just left/right of the region and the space just right/left of it (respectively) is filled.
                if ((area.Touches(l.Left, true, true, false) && data.GetMapAt(l.Left)) ||
                    (area.Touches(l.Right, true, true, false) && data.GetMapAt(l.Right)))
                {
                    //Make a little tunnel under the plateau.
                    int[]  plateauSides = SteppedHallwayPattern.PlateauSides(l.Y, numb, plateauSize, space, border, area.Top, area.Bottom);
                    Region cleared;
                    if (l.X - 1 == area.Right)
                    {
                        cleared = new Region(data.BeingFilled.Right, plateauSides[0], 0, plateauSize - 1);
                    }
                    else
                    {
                        cleared = new Region(data.BeingFilled.Left, plateauSides[0], 0, plateauSize - 1);
                    }
                    data.FillRegion(false, cleared);
                }
            }
        }
        else
        {
            //Horizontal.

            //Add the plateaus.
            int hurdleHeight, plateauHeight;
            for (int i = 0; i < numb; ++i)
            {
                //Get a height within the given random variation.
                hurdleHeight = (int)Math.Round((area.Height + 1) * (HurdleAverageSpaceScale + ((2 * HurdleHeightVariance * (float)GeneratorSettings.R.NextDouble()) - HurdleHeightVariance)), 0);
                //Keep it constrained.
                if (hurdleHeight > maxSize)
                {
                    hurdleHeight = maxSize;
                }
                if (hurdleHeight < 1)
                {
                    hurdleHeight = 1;
                }

                //Get the height of the plateau given the size of a hurdle.
                plateauHeight  = area.Height + 1 - hurdleHeight;
                plateauHeight /= 2;

                //Fill in the plateaus.
                data.FillRegion(true, new Region(area.Left + border + (i * (space + plateauSize)), area.Top, plateauSize - 1, plateauHeight - 1));
                if ((2 * plateauHeight) + hurdleHeight >= area.Height + 1)
                {
                    data.FillRegion(true, new Region(area.Left + border + (i * (space + plateauSize)), area.Bottom - plateauHeight + 1, plateauSize - 1, plateauHeight - 1));
                    spawningAreas.Add(new Region(area.Left + border + (i * (space + plateauSize)), area.Top + plateauHeight, plateauSize - 1, data.BeingFilled.Height - plateauHeight - plateauHeight - 2));
                }
                else
                {
                    data.FillRegion(true, new Region(area.Left + border + (i * (space + plateauSize)), area.Bottom - plateauHeight, plateauSize - 1, plateauHeight));
                    spawningAreas.Add(new Region(area.Left + border + (i * (space + plateauSize)), area.Top + plateauHeight, plateauSize - 1, data.BeingFilled.Height - plateauHeight - plateauHeight - 1));
                }
            }
        }


        //Make room for any holes that the plateaus covered.
        foreach (Location l in data.HolesAlongPerimeter())
        {
            //Horizontal.
            if (area.Height < area.Width)
            {
                //The hole is covered if it is just below/above the region and the space above/below it (respectively) is filled.
                if ((area.Touches(l.Above, true, true, false) && data.GetMapAt(l.Above)) ||
                    (area.Touches(l.Below, true, true, false) && data.GetMapAt(l.Below)))
                {
                    //Make a little tunnel under the plateau.
                    int[] plateauSides = SteppedHallwayPattern.PlateauSides(l.X, numb, plateauSize, space, border, area.Left, area.Right);

                    Region cleared;
                    if (l.Y - 1 == area.Bottom)
                    {
                        cleared = new Region(plateauSides[0], data.BeingFilled.Bottom, plateauSize - 1, 0);
                    }
                    else
                    {
                        cleared = new Region(plateauSides[0], data.BeingFilled.Top, plateauSize - 1, 0);
                    }

                    data.FillRegion(false, cleared);
                }
            }

            //Vertical.
            else if ((area.Touches(l.Left, true, true, false) && data.GetMapAt(l.Left)) ||
                     (area.Touches(l.Right, true, true, false) && data.GetMapAt(l.Right)))
            {
                //Make a little tunnel under the plateau.
                int[] plateauSides = SteppedHallwayPattern.PlateauSides(l.Y, numb, plateauSize, space, border, area.Top, area.Bottom);

                Region cleared;
                if (l.X - 1 == area.Right)
                {
                    cleared = new Region(data.BeingFilled.Right, plateauSides[0], 0, plateauSize - 1);
                }
                else
                {
                    cleared = new Region(data.BeingFilled.Left, plateauSides[0], 0, plateauSize - 1);
                }

                data.FillRegion(false, cleared);
            }
        }

        //Return the new regions.
        return(new ThickHurdleRegion(data.BeingFilled, spawningAreas));
    }
Пример #20
0
    public void IterateFillPattern()
    {
        //Already done?
        if (iterateFillPatternsRegionCount >= Regions.Count)
        {
            return;
        }

        //Run an iteration.

        FilledRegion temp;
        Region       r = Regions[iterateFillPatternsRegionCount];

        iterateFillPatternsRegionCount++;

        //Pick a random applicable pattern (assuming one exists) and apply it.
        FillPattern p = Settings.MostSuitable(r);

        if (p != null)
        {
            //Clear the space, and apply the pattern.
            FillData.BeingFilled = r;
            FillData.FillRegion(false, r);
            temp = p.Apply(FillData);

            //If the filled region is blank, replace it with a BlankRegion.
            bool blank = true;
            for (int i = temp.Covering.Left; i <= temp.Covering.Right; ++i)
            {
                for (int j = temp.Covering.Top; j <= temp.Covering.Bottom; ++j)
                {
                    if (FillData.GetMapAt(new Location(i, j)))
                    {
                        blank = false;
                        break;
                    }
                }
                if (!blank)
                {
                    break;
                }
            }
            if (blank)
            {
                temp = new BlankRegion(temp.Covering);
            }

            //Now add it.
            FilledRegions.Add(temp);
            Region r2;

            //Make sure the spawn points are all valid.
            foreach (Spawns s in FilledRegions[FilledRegions.Count - 1].PotentialSpawns.Keys)
            {
                for (int i = 0; i < FilledRegions[FilledRegions.Count - 1].PotentialSpawns[s].Count; ++i)
                {
                    r2 = FilledRegions[FilledRegions.Count - 1].PotentialSpawns[s][i];

                    if (r2.Width < 0 || r2.Height < 0)
                    {
                        FilledRegions[FilledRegions.Count - 1].PotentialSpawns[s].RemoveAt(i--);
                    }
                }
            }
        }
        //If no regions fit, add a "NoRegion".
        else
        {
            FilledRegions.Add(new NoRegion(r));
        }
    }
Пример #21
0
    /// <summary>
    /// Gets all continuous top/bottom Lines from the given level using all the walls in the given row.
    /// The Lines are indexed by all wall bounds that make up part of that indexed Line.
    /// </summary>
    public static void GetHorizontalLines(FillData data, WallToLines associations, int row)
    {
        int      startingX, currentX;
        Interval temp;
        ColType  current;
        bool     bottomRow = (row == data.Map.GetLength(1) - 1);

        //Do the algorithm for both above and below the row.
        int currentRow;

        for (int dir = -1; dir < 2; dir += 2)
        {
            currentRow = row + dir;
            current    = (currentRow < row ? ColType.Bottom : ColType.Top);

            //There is one special case: the whole row is a valid line.
            bool rowFree = true;
            for (int i = 0; i < data.Map.GetLength(0); ++i)
            {
                if (data.GetMapAt(new Location(i, currentRow)) ||
                    !data.GetMapAt(new Location(i, row)))
                {
                    rowFree = false;
                    break;
                }
            }

            //If the whole row is one line, just use that.
            if (rowFree)
            {
                //If the level wraps around, use a large line.
                if (data.WrapX)
                {
                    associations.AddReferences(GetBounds(new Line(Orientation.Horizontal, new Interval(0, data.Map.GetLength(0) - 1, true, 2), row)),
                                               current,
                                               new Line(Orientation.Horizontal, new Interval(-data.Map.GetLength(0), 2.0f * data.Map.GetLength(0), true, 2), (row + currentRow) * 0.5f));
                }
                else
                {
                    associations.AddReferences(GetBounds(new Line(Orientation.Horizontal, new Interval(0, data.Map.GetLength(0) - 1, true, 2), row)),
                                               current,
                                               new Line(Orientation.Horizontal, new Interval(0, data.Map.GetLength(0) - 1, true, 2), row));
                }
            }

            //Otherwise, go through one wall at a time and build individual collections of Lines.
            else
            {
                //An edge is a whole Line if it spans an unbroken row of walls with no walls covering the edge.

                //Use a counter to run through the whole row in groups of unbroken rows.
                startingX = 0;
                currentX  = 0;
                temp      = null;
                while (startingX < data.Map.GetLength(0))
                {
                    //Get the next valid spot to start from.
                    while ((!data.GetMapAt(new Location(startingX, row)) ||
                            data.GetMapAt(new Location(startingX, currentRow))) &&
                           startingX < data.Map.GetLength(0))
                    {
                        currentX += 1;
                        startingX = currentX;
                    }
                    if (startingX >= data.Map.GetLength(0))
                    {
                        break;
                    }

                    //Keep the counter going as long as the next spot is valid (i.e.
                    //  there is a wall in this row but not above/underneath).
                    while (data.GetMapAt(new Location(currentX + 1, row)) &&
                           !data.GetMapAt(new Location(currentX + 1, currentRow)) &&
                           currentX < data.Map.GetLength(0))
                    {
                        currentX += 1;
                    }

                    //Now make the line.
                    temp = new Interval(startingX, currentX, true, 2);
                    associations.AddReferences(GetBounds(new Line(Orientation.Horizontal, temp, row)),
                                               current,
                                               new Line(Orientation.Horizontal, temp, (row + currentRow) * 0.5f));

                    //If this is near the left, wrap it around to the right.
                    if (data.WrapX && temp.Start < 2.0f)
                    {
                        associations.AddReferences(GetBounds(new Line(Orientation.Horizontal, temp + data.WorldSize.X, row)),
                                                   current,
                                                   new Line(Orientation.Horizontal, temp + data.WorldSize.X, (row + currentRow) * 0.5f));
                    }

                    //Move to the next spot in the row.
                    startingX = currentX + 1;
                    currentX  = startingX;
                }

                //If the level wraps around in the X, take the last Line and wrap it around.
                if (temp != null && data.WrapX)
                {
                    associations.AddReferences(GetBounds(new Line(Orientation.Horizontal, temp - data.WorldSize.X, row)),
                                               current,
                                               new Line(Orientation.Horizontal, temp - data.WorldSize.X, (row + currentRow) * 0.5f));
                }
            }
        }
    }
Пример #22
0
    /// <summary>
    /// Gets all continuous left/right Lines from the given level using all the walls in the given column.
    /// The Lines are indexed by all wall bounds that make up part of that indexed Line.
    /// </summary>
    public static void GetVerticalLines(FillData data, WallToLines associations, int col)
    {
        int      startingY, currentY;
        Interval temp;
        ColType  current;
        bool     rightCol = (col == data.Map.GetLength(0) - 1);

        //Do the algorithm for both the left and the right of the column.
        int currentCol;

        for (int dir = -1; dir < 2; dir += 2)
        {
            currentCol = col + dir;
            current    = (currentCol > col ? ColType.Right : ColType.Left);

            //Take care of the edge case where the whole row is a valid line.
            bool colFree = true;
            for (int j = 0; j < data.Map.GetLength(1); ++j)
            {
                if (data.GetMapAt(new Location(currentCol, j)) ||
                    !data.GetMapAt(new Location(col, j)))
                {
                    colFree = false;
                    break;
                }
            }

            //If the whole column is one line, just use that.
            if (colFree)
            {
                //If the level wraps around, use a large line.
                if (data.WrapY)
                {
                    associations.AddReferences(GetBounds(new Line(Orientation.Vertical, new Interval(0, data.Map.GetLength(1) - 1, true, 2), col)),
                                               current,
                                               new Line(Orientation.Vertical, new Interval(-data.Map.GetLength(1), 2.0f * data.Map.GetLength(1), true, 2), (col + currentCol) * 0.5f));
                }
                else
                {
                    associations.AddReferences(GetBounds(new Line(Orientation.Vertical, new Interval(0, data.Map.GetLength(1) - 1, true, 2), col)),
                                               current,
                                               new Line(Orientation.Vertical, new Interval(0, data.Map.GetLength(1) - 1, true, 2), col));
                }
            }

            //Otherwise, go through one wall at a time and build individual collections of Lines.
            else
            {
                //An edge is a whole Line if it spans an unbroken column of walls with no walls covering the edge.

                //Use a counter to run through the whole column in groups of unbroken walls.
                startingY = 0;
                currentY  = 0;
                temp      = null;
                while (startingY < data.Map.GetLength(1))
                {
                    //Get the next valid spot to start from.
                    while ((!data.GetMapAt(new Location(col, startingY)) ||
                            data.GetMapAt(new Location(currentCol, startingY))) &&
                           startingY < data.Map.GetLength(1))
                    {
                        currentY += 1;
                        startingY = currentY;
                    }
                    if (startingY >= data.Map.GetLength(1))
                    {
                        break;
                    }

                    //Keep the counter going as long as the next spot is valid (i.e.
                    //  there is a wall to the side but not in the way).
                    while (data.GetMapAt(new Location(col, currentY + 1)) &&
                           !data.GetMapAt(new Location(currentCol, currentY + 1)) &&
                           currentY < data.Map.GetLength(1))
                    {
                        currentY += 1;
                    }

                    //Now make the line.
                    temp = new Interval(startingY, currentY, true, 2);
                    associations.AddReferences(GetBounds(new Line(Orientation.Vertical, temp, col)),
                                               current,
                                               new Line(Orientation.Vertical, temp, (col + currentCol) * 0.5f));

                    //If this is near the top, wrap it around to the bottom.
                    if (data.WrapY && temp.Start < 2.0f)
                    {
                        associations.AddReferences(GetBounds(new Line(Orientation.Vertical, temp + data.WorldSize.Y, col)),
                                                   current,
                                                   new Line(Orientation.Vertical, temp + data.WorldSize.Y, (col + currentCol) * 0.5f));
                    }

                    //Move to the next spot in the column.
                    startingY = currentY + 1;
                    currentY  = startingY;
                }

                //If the level wraps around in the Y, take the last Line and wrap it around.
                if (temp != null && data.WrapY)
                {
                    associations.AddReferences(GetBounds(new Line(Orientation.Vertical, temp - data.WorldSize.Y, col)),
                                               current,
                                               new Line(Orientation.Vertical, temp - data.WorldSize.Y, (col + currentCol) * 0.5f));
                }
            }
        }
    }
Пример #23
0
        /// <summary>
        /// Constructs a lobby
        /// </summary>
        /// <param name="clientWebSocket">Client web socket</param>
        /// <param name="isConnectionSecure">Is connection secure</param>
        /// <param name="lobbyID">Lobby ID</param>
        /// <param name="minimalDrawingTime">Minimal drawing time in seconds</param>
        /// <param name="maximalDrawingTime">Maximal drawing time in seconds</param>
        /// <param name="minimalRoundCount">Minimal round count</param>
        /// <param name="maximalRoundCount">Maximal round count</param>
        /// <param name="minimalMaximalPlayerCount">Minimal of maximal player count</param>
        /// <param name="maximalMaximalPlayerCount">Maximal of maximal player count</param>
        /// <param name="minimalClientsPerIPLimit">Minimal clients per IP limit</param>
        /// <param name="maximalClientsPerIPLimit">Maximal clients per IP limit</param>
        /// <param name="maximalPlayerCount">Maximal player count</param>
        /// <param name="currentMaximalRoundCount">Current maximal round count</param>
        /// <param name="isLobbyPublic">Is lobby public</param>
        /// <param name="isVotekickingEnabled">Is votekicking enabled</param>
        /// <param name="customWordsChance">Custom words chance</param>
        /// <param name="allowedClientsPerIPCount">Allowed clients per IP count</param>
        /// <param name="drawingBoardBaseWidth">Drawing board base width</param>
        /// <param name="drawingBoardBaseHeight">Drawing board base height</param>
        /// <param name="minimalBrushSize">Minimal brush size</param>
        /// <param name="maximalBrushSize">Maximal brush size</param>
        /// <param name="suggestedBrushSizes">Suggested brush sizes</param>
        /// <param name="canvasColor">Canvas color</param>
        public Lobby
        (
            ClientWebSocket clientWebSocket,
            bool isConnectionSecure,
            string lobbyID,
            uint minimalDrawingTime,
            uint maximalDrawingTime,
            uint minimalRoundCount,
            uint maximalRoundCount,
            uint minimalMaximalPlayerCount,
            uint maximalMaximalPlayerCount,
            uint minimalClientsPerIPLimit,
            uint maximalClientsPerIPLimit,
            uint maximalPlayerCount,
            uint currentMaximalRoundCount,
            bool isLobbyPublic,
            bool isVotekickingEnabled,
            uint customWordsChance,
            uint allowedClientsPerIPCount,
            uint drawingBoardBaseWidth,
            uint drawingBoardBaseHeight,
            uint minimalBrushSize,
            uint maximalBrushSize,
            IEnumerable<uint> suggestedBrushSizes,
            IColor canvasColor
        )
        {
            Limits = new LobbyLimits
            (
                minimalDrawingTime,
                maximalDrawingTime,
                minimalRoundCount,
                maximalRoundCount,
                minimalMaximalPlayerCount,
                maximalMaximalPlayerCount,
                minimalClientsPerIPLimit,
                maximalClientsPerIPLimit,
                minimalBrushSize,
                maximalBrushSize
            );
            if (maximalPlayerCount < minimalMaximalPlayerCount)
            {
                throw new ArgumentException("Maximal player count can't be smaller than minimal of maximal player count.", nameof(maximalPlayerCount));
            }
            if (maximalPlayerCount > maximalMaximalPlayerCount)
            {
                throw new ArgumentException("Maximal player count can't be bigger than maximal of maximal player count.", nameof(maximalPlayerCount));
            }
            if (currentMaximalRoundCount < minimalRoundCount)
            {
                throw new ArgumentException("Current maximal round count can't be smaller than minimal round count.", nameof(currentMaximalRoundCount));
            }
            if (currentMaximalRoundCount > maximalRoundCount)
            {
                throw new ArgumentException("Current maximal round count can't be bigger than maximal round count.", nameof(currentMaximalRoundCount));
            }
            if (customWordsChance > 100U)
            {
                throw new ArgumentException("Custom words chance can't be bigger than 100.", nameof(customWordsChance));
            }
            if (allowedClientsPerIPCount < minimalClientsPerIPLimit)
            {
                throw new ArgumentException("Clients per IP limit can't be smaller than minimal clients per IP limit.", nameof(allowedClientsPerIPCount));
            }
            if (allowedClientsPerIPCount > maximalClientsPerIPLimit)
            {
                throw new ArgumentException("Clients per IP limit can't be bigger than maximal clients per IP limit.", nameof(allowedClientsPerIPCount));
            }
            if (drawingBoardBaseWidth < 1U)
            {
                throw new ArgumentException("Drawing board base width can't be smaller than one.", nameof(drawingBoardBaseWidth));
            }
            if (drawingBoardBaseHeight < 1U)
            {
                throw new ArgumentException("Drawing board base height can't be smaller than one.", nameof(drawingBoardBaseHeight));
            }
            this.clientWebSocket = clientWebSocket ?? throw new ArgumentNullException(nameof(clientWebSocket));
            IsConnectionSecure = isConnectionSecure;
            LobbyID = lobbyID ?? throw new ArgumentNullException(nameof(lobbyID));
            MaximalPlayerCount = maximalPlayerCount;
            CurrentMaximalRoundCount = currentMaximalRoundCount;
            IsLobbyPublic = isLobbyPublic;
            IsVotekickingEnabled = isVotekickingEnabled;
            CustomWordsChance = customWordsChance;
            AllowedClientsPerIPCount = allowedClientsPerIPCount;
            DrawingBoardBaseWidth = drawingBoardBaseWidth;
            DrawingBoardBaseHeight = drawingBoardBaseHeight;
            SuggestedBrushSizes = suggestedBrushSizes ?? throw new ArgumentNullException(nameof(suggestedBrushSizes));
            CanvasColor = canvasColor;
            AddMessageParser<ReadyReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    ReadyData ready = gameMessage.Data;
                    uint current_round = ready.CurrentRound;
                    uint current_maximal_round_count = ready.CurrentMaximalRoundCount;
                    long current_drawing_time = ready.CurrentDrawingTime;
                    if (current_maximal_round_count > Limits.MaximalRoundCount)
                    {
                        throw new InvalidDataException($"Current maximal round count can't be bigger than maximal round count, which is { Limits.MaximalRoundCount }.");
                    }
                    if (current_round > current_maximal_round_count)
                    {
                        throw new InvalidDataException($"Current round can't be bigger than current maximal round count, which is { current_maximal_round_count }.");
                    }
                    if (current_drawing_time > (Limits.MaximalDrawingTime * 1000L))
                    {
                        throw new InvalidDataException($"Current drawing time can't be bigger than the specified maximal maximal player count, which is { Limits.MaximalMaximalPlayerCount }.");
                    }
                    IsPlayerAllowedToDraw = ready.IsPlayerAllowedToDraw;
                    IsVotekickingEnabled = ready.IsVotekickingEnabled;
                    GameState = ready.GameState;
                    CurrentRound = current_round;
                    CurrentMaximalRoundCount = current_maximal_round_count;
                    CurrentDrawingTime = ready.CurrentDrawingTime;
                    if (ready.WordHints == null)
                    {
                        wordHints = Array.Empty<IWordHint>();
                    }
                    else
                    {
                        if (wordHints.Length != ready.WordHints.Count)
                        {
                            wordHints = new IWordHint[ready.WordHints.Count];
                        }
#if SCRIBBLERS_SHARP_NO_PARALLEL_LOOPS
                        for (int index = 0; index < wordHints.Length; index++)
#else
                        Parallel.For(0, wordHints.Length, (index) =>
#endif
                        {
                            WordHintData word_hint_data = ready.WordHints[index];
                            wordHints[index] = new WordHint(word_hint_data.Character, word_hint_data.Underline);
                        }
#if !SCRIBBLERS_SHARP_NO_PARALLEL_LOOPS
                        );
#endif
                    }
                    UpdateAllPlayers(ready.Players);
                    MyPlayer = players.ContainsKey(ready.PlayerID) ? players[ready.PlayerID] : null;
                    Owner = players.ContainsKey(ready.OwnerID) ? players[ready.OwnerID] : null;
                    currentDrawing.Clear();
                    JObject json_object = JObject.Parse(json);
                    if (json_object.ContainsKey("data"))
                    {
                        if (json_object["data"] is JObject json_data_object)
                        {
                            if (json_data_object.ContainsKey("currentDrawing"))
                            {
                                if (json_data_object["currentDrawing"] is JArray json_draw_commands)
                                {
                                    ParseCurrentDrawingFromJSON(json_draw_commands);
                                }
                            }
                        }
                    }
                    OnReadyGameMessageReceived?.Invoke();
                },
                MessageParseFailedEvent
            );
            AddMessageParser<NextTurnReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    NextTurnData next_turn = gameMessage.Data;
                    IsPlayerAllowedToDraw = false;
                    GameState = EGameState.Ongoing;
                    CurrentRound = next_turn.Round;
                    CurrentDrawingTime = next_turn.RoundEndTime;
                    UpdateAllPlayers(next_turn.Players);
                    PreviousWord = next_turn.PreviousWord ?? PreviousWord;
                    currentDrawing.Clear();
                    OnNextTurnGameMessageReceived?.Invoke();
                }, MessageParseFailedEvent
            );
            AddMessageParser<GameOverReceiveGameMessage>
            (
                (gameMessage, json) =>
                {
                    GameOverData game_over = gameMessage.Data;
                    IsPlayerAllowedToDraw = false;
                    GameState = EGameState.Ongoing;
                    CurrentRound = game_over.CurrentRound;
                    CurrentDrawingTime = game_over.CurrentDrawingTime;
                    UpdateAllPlayers(game_over.Players);
                    PreviousWord = game_over.PreviousWord ?? PreviousWord;
                    currentDrawing.Clear();
                    OnGameOverMessageReceived?.Invoke();
                }, MessageParseFailedEvent
            );
            AddMessageParser<NameChangeReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    NameChangeData name_change = gameMessage.Data;
                    if (players.ContainsKey(name_change.PlayerID) && players[name_change.PlayerID] is IInternalPlayer internal_player)
                    {
                        internal_player.UpdateNameInternally(name_change.PlayerName);
                        OnNameChangeGameMessageReceived?.Invoke(internal_player);
                    }
                },
                MessageParseFailedEvent
            );
            AddMessageParser<UpdatePlayersReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    UpdateAllPlayers(gameMessage.Data);
                    OnUpdatePlayersGameMessageReceived?.Invoke(players);
                },
                MessageParseFailedEvent
            );
            AddMessageParser<UpdateWordhintReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    GameState = EGameState.Ongoing;
                    WordHintData[] word_hints = gameMessage.Data;
                    if (wordHints.Length != word_hints.Length)
                    {
                        wordHints = new IWordHint[word_hints.Length];
                    }
#if SCRIBBLERS_SHARP_NO_PARALLEL_LOOPS
                    for (int index = 0; index < wordHints.Length; index++)
#else
                    Parallel.For(0, wordHints.Length, (index) =>
#endif
                    {
                        WordHintData word_hint_data = word_hints[index];
                        wordHints[index] = new WordHint(word_hint_data.Character, word_hint_data.Underline);
                    }
#if !SCRIBBLERS_SHARP_NO_PARALLEL_LOOPS
                    );
#endif
                    OnUpdateWordhintGameMessageReceived?.Invoke(wordHints);
                },
                MessageParseFailedEvent
            );
            AddMessageParser<MessageReceiveGameMessageData>((gameMessage, json) => OnMessageGameMessageReceived?.Invoke(players.ContainsKey(gameMessage.Data.AuthorID) ? players[gameMessage.Data.AuthorID] : null, gameMessage.Data.Content), MessageParseFailedEvent);
            AddMessageParser<NonGuessingPlayerMessageReceiveGameMessageData>((gameMessage, json) => OnNonGuessingPlayerMessageGameMessageReceived?.Invoke(players.ContainsKey(gameMessage.Data.AuthorID) ? players[gameMessage.Data.AuthorID] : null, gameMessage.Data.Content), MessageParseFailedEvent);
            AddMessageParser<SystemMessageReceiveGameMessageData>((gameMessage, json) => OnSystemMessageGameMessageReceived?.Invoke(gameMessage.Data), MessageParseFailedEvent);
            AddMessageParser<LineReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    LineData line = gameMessage.Data;
                    IColor color = (Color)line.Color;
                    GameState = EGameState.Ongoing;
                    currentDrawing.Add(new DrawCommand(EDrawCommandType.Line, line.FromX, line.FromY, line.ToX, line.ToY, color, line.LineWidth));
                    OnLineGameMessageReceived?.Invoke(line.FromX, line.FromY, line.ToX, line.ToY, color, line.LineWidth);
                },
                MessageParseFailedEvent
            );
            AddMessageParser<FillReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    FillData fill = gameMessage.Data;
                    IColor color = (Color)fill.Color;
                    currentDrawing.Add(new DrawCommand(EDrawCommandType.Fill, fill.X, fill.Y, fill.X, fill.Y, color, 0.0f));
                    OnFillGameMessageReceived(fill.X, fill.Y, color);
                },
                MessageParseFailedEvent
            );
            AddMessageParser<ClearDrawingBoardReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    currentDrawing.Clear();
                    OnClearDrawingBoardGameMessageReceived?.Invoke();
                },
                MessageParseFailedEvent
            );
            AddMessageParser<YourTurnReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    IsPlayerAllowedToDraw = true;
                    currentDrawing.Clear();
                    OnYourTurnGameMessageReceived?.Invoke((string[])gameMessage.Data.Clone());
                },
                MessageParseFailedEvent
            );
            AddMessageParser<CloseGuessReceiveGameMessageData>((gameMessage, json) => OnCloseGuessGameMessageReceived?.Invoke(gameMessage.Data), MessageParseFailedEvent);
            AddMessageParser<CorrectGuessReceiveGameMessageData>((gameMessage, json) => OnCorrectGuessGameMessageReceived?.Invoke(players.ContainsKey(gameMessage.Data) ? players[gameMessage.Data] : null), MessageParseFailedEvent);
            AddMessageParser<KickVoteReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    KickVoteData kick_vote = gameMessage.Data;
                    if (players.ContainsKey(kick_vote.PlayerID) && players[kick_vote.PlayerID] is IInternalPlayer internal_player)
                    {
                        internal_player.UpdateNameInternally(kick_vote.PlayerName);
                        OnKickVoteGameMessageReceived?.Invoke(internal_player, kick_vote.VoteCount, kick_vote.RequiredVoteCount);
                    }
                },
                MessageParseFailedEvent
            );
            AddMessageParser<DrawerKickedReceiveGameMessageData>((gameMessage, json) => OnDrawerKickedGameMessageReceived?.Invoke(), MessageParseFailedEvent);
            AddMessageParser<OwnerChangeReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    OwnerChangeData owner_change = gameMessage.Data;
                    if (players.ContainsKey(owner_change.PlayerID) && players[owner_change.PlayerID] is IInternalPlayer internal_player)
                    {
                        internal_player.UpdateNameInternally(owner_change.PlayerName);
                        OnOwnerChangeGameMessageReceived?.Invoke(internal_player);
                    }
                },
                MessageParseFailedEvent
            );
            AddMessageParser<DrawingReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    currentDrawing.Clear();
                    JObject json_object = JObject.Parse(json);
                    if (json_object.ContainsKey("data"))
                    {
                        if (json_object["data"] is JArray json_draw_commands)
                        {
                            ParseCurrentDrawingFromJSON(json_draw_commands);
                        }
                    }
                    OnDrawingGameMessageReceived?.Invoke(currentDrawing);
                },
                MessageParseFailedEvent
            );
            AddMessageParser<LobbySettingsChangedReceiveGameMessageData>
            (
                (gameMessage, json) =>
                {
                    LobbySettingsChangeData lobby_settings_change = gameMessage.Data;
                    uint maximal_player_count = lobby_settings_change.MaximalPlayerCount;
                    uint custom_words_chance = lobby_settings_change.CustomWordsChance;
                    if (maximal_player_count < Limits.MinimalMaximalPlayerCount)
                    {
                        throw new InvalidDataException($"Maximal player count can't be smaller than the specified minimal maximal player count, which is { Limits.MinimalMaximalPlayerCount }.");
                    }
                    if (maximal_player_count > Limits.MaximalMaximalPlayerCount)
                    {
                        throw new InvalidDataException($"Maximal player count can't be bigger than the specified maximal maximal player count, which is { Limits.MaximalMaximalPlayerCount }.");
                    }
                    if (custom_words_chance > 100U)
                    {
                        throw new InvalidDataException("Custom words chance can't be bigger than one hundred.");
                    }
                    MaximalPlayerCount = maximal_player_count;
                    IsLobbyPublic = lobby_settings_change.IsLobbyPublic;
                    IsVotekickingEnabled = lobby_settings_change.IsVotekickingEnabled;
                    CustomWordsChance = custom_words_chance;
                },
                MessageParseFailedEvent
            );
            webSocketSendThread = new Thread(async () =>
            {
                while ((this.clientWebSocket != null) && (this.clientWebSocket.State == WebSocketState.Open))
                {
                    while (sendGameMessageQueue.TryDequeue(out string send_game_message))
                    {
                        await clientWebSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(send_game_message)), WebSocketMessageType.Text, true, default);
                    }
                }
            });
            webSocketReceiveThread = new Thread(async () =>
            {
                using (MemoryStream memory_stream = new MemoryStream())
                {
                    using (StreamReader reader = new StreamReader(memory_stream))
                    {
                        while ((this.clientWebSocket != null) && (this.clientWebSocket.State == WebSocketState.Open))
                        {
                            try
                            {
                                WebSocketReceiveResult result = await this.clientWebSocket.ReceiveAsync(receiveBuffer, default);
                                if (result != null)
                                {
                                    memory_stream.Write(receiveBuffer.Array, 0, result.Count);
                                    if (result.EndOfMessage)
                                    {
                                        memory_stream.Seek(0L, SeekOrigin.Begin);
                                        receivedGameMessages.Enqueue(reader.ReadToEnd());
                                        memory_stream.Seek(0L, SeekOrigin.Begin);
                                        memory_stream.SetLength(0L);
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Console.Error.WriteLine(e);
                                this.clientWebSocket.Dispose();
                                this.clientWebSocket = null;
                            }
                        }
                    }
                }
            });
            webSocketSendThread.Start();
            webSocketReceiveThread.Start();
        }
 public FilledRegion Apply(FillData data)
 {
     return(new BlankRegion(data.BeingFilled));
 }
Пример #25
0
    private void FillTunnels()
    {
        //Go through all nodes and make tunnels,
        //  with special edge tunnels around the perimeter (if the level wraps around).
        Location lastNodePos = (Settings.TunnelLength + MaxRoomSize) * (Settings.NumberOfNodes - new Location(1, 1));
        Location topLeft, nextTopLeft;
        Region   beingCleared;

        foreach (PositionalNode n in NodeStates.Keys)//Graph.AllNodes(new PositionalNode(new float[2] { 1.0f, 1.0f }, 0)))
        {
            //Fill in the tunnel to the right and down from this cell.

            //Down.
            if (n.Coordinate[1] < lastNodePos.Y)
            {
                topLeft = new Location(VerticalTunnelX((int)n.Coordinate[0]), NodeAreas[n].Bottom);
                if (NodeStates[n] == NodeState.Room)
                {
                    topLeft = topLeft.Below;
                }
                nextTopLeft = NodeAreas[new PositionalNode(new float[2] {
                    n.Coordinate[0], n.Coordinate[1] + MaxRoomSize.Y + Settings.TunnelLength.Y
                }, 0)].TopLeft;

                beingCleared = new Region(topLeft, new Location(topLeft.X + Settings.TunnelThickness.Y - 1, nextTopLeft.Y - 1));
                FillData.FillRegion(false, beingCleared);
                Regions.Add(beingCleared);

                for (int x = beingCleared.Left; x <= beingCleared.Right; ++x)
                {
                    Holes.Add(new Location(x, beingCleared.Top));
                    Holes.Add(new Location(x, beingCleared.Bottom));
                }
            }
            //Right.
            if (n.Coordinate[0] < lastNodePos.X)
            {
                topLeft     = new Location(NodeAreas[n].Right, HorizontalTunnelY((int)n.Coordinate[1])).Right;
                nextTopLeft = NodeAreas[new PositionalNode(new float[2] {
                    n.Coordinate[0] + MaxRoomSize.X + Settings.TunnelLength.X, n.Coordinate[1]
                }, 0)].TopLeft;

                beingCleared = new Region(topLeft, new Location(nextTopLeft.X - 1, topLeft.Y + Settings.TunnelThickness.X - 1));
                FillData.FillRegion(false, beingCleared);
                Regions.Add(beingCleared);

                for (int y = beingCleared.Top; y <= beingCleared.Bottom; ++y)
                {
                    Holes.Add(new Location(beingCleared.Left, y));
                    Holes.Add(new Location(beingCleared.Right, y));
                }
            }

            //Border cases.

            //Left border.
            if (Settings.WrapAroundX && n.Coordinate[0] == 1.0f)
            {
                topLeft     = new Location(0, HorizontalTunnelY((int)n.Coordinate[1]));
                nextTopLeft = NodeAreas[n].TopLeft.Left;

                beingCleared = new Region(topLeft, new Location(nextTopLeft.X, topLeft.Y + Settings.TunnelThickness.X - 1));
                FillData.FillRegion(false, beingCleared);
                Regions.Add(beingCleared);

                for (int y = beingCleared.Top; y <= beingCleared.Bottom; ++y)
                {
                    Holes.Add(new Location(beingCleared.Right, y));
                }
            }
            //Top border.
            if (Settings.WrapAroundY && n.Coordinate[1] == 1.0f)
            {
                topLeft     = new Location(VerticalTunnelX((int)n.Coordinate[0]), 0);
                nextTopLeft = NodeAreas[n].TopLeft.Above;

                beingCleared = new Region(topLeft, new Location(topLeft.X + Settings.TunnelThickness.Y - 1, nextTopLeft.Y));
                FillData.FillRegion(false, beingCleared);
                Regions.Add(beingCleared);

                for (int x = beingCleared.Left; x <= beingCleared.Right; ++x)
                {
                    Holes.Add(new Location(x, beingCleared.Bottom));
                }
            }
            //Right border.
            if (Settings.WrapAroundX && n.Coordinate[0] == lastNodePos.X + 1)
            {
                topLeft = new Location(NodeAreas[n].Right, HorizontalTunnelY((int)n.Coordinate[1])).Right;

                beingCleared = new Region(topLeft, new Location(Map.GetLength(0) - 1, topLeft.Y + Settings.TunnelThickness.X - 1));
                FillData.FillRegion(false, beingCleared);
                Regions.Add(beingCleared);

                for (int y = beingCleared.Top; y <= beingCleared.Bottom; ++y)
                {
                    Holes.Add(new Location(beingCleared.Left, y));
                }
            }
            //Bottom border.
            if (Settings.WrapAroundY && n.Coordinate[1] == lastNodePos.Y + 1)
            {
                topLeft = new Location(VerticalTunnelX((int)n.Coordinate[0]), NodeAreas[n].Bottom).Below;

                beingCleared = new Region(topLeft, new Location(topLeft.X + Settings.TunnelThickness.Y - 1, Map.GetLength(1) - 1));
                FillData.FillRegion(false, beingCleared);
                Regions.Add(beingCleared);

                for (int x = beingCleared.Left; x <= beingCleared.Right; ++x)
                {
                    Holes.Add(new Location(x, beingCleared.Top));
                }
            }
        }
    }
Пример #26
0
        private void LoadCustomer(WebBrowser webBrowser1)
        {
            try
            {
                HtmlWindowCollection coll = webBrowser1.Document.Window.Frames;
                foreach (HtmlWindow win in coll)
                {
                    HtmlElement ele = win.Document.GetElementById("tMemCardID");
                    if (ele != null)
                    {
                        TicketOrder ticketOrder = new TicketOrder();
                        if (ticketOrder.LoadTicketOrder(order_Id))
                        {
                            win.Document.GetElementById("tPNR").SetAttribute("value", ticketOrder.PNR);

                            System.Web.Caching.Cache cache = System.Web.HttpRuntime.Cache;
                            cache.Add("TicketOrderInfo", ticketOrder, null, DateTime.MaxValue, new TimeSpan(0, 5, 0), System.Web.Caching.CacheItemPriority.Normal, null);
                        }

                        ele.SetAttribute("value", ticketOrder.CardNum);
                        win.Document.GetElementById("tMemName").SetAttribute("value", ticketOrder.MemberName);

                        ele = win.Document.GetElementById("bMemInfo");
                        ele.InvokeMember("Click");
                        fillData = BLL.FillData.��дPNR;
                        break;
                    }
                }
            }
            catch { }
        }
Пример #27
0
        private void LoadPNR(WebBrowser webBrowser1)
        {
            try
            {
                HtmlWindowCollection coll = webBrowser1.Document.Window.Frames;
                foreach (HtmlWindow win in coll)
                {
                    HtmlElement ele = win.Document.GetElementById("tPNR");
                    if (ele != null)
                    {
                        win.Document.GetElementById("bA").InvokeMember("Click");

                        process = BLL.ProcessControl.�ύ;
                        fillData = BLL.FillData.��ʼ��;

                        break;
                    }

                }
            }
            catch { }
        }
Пример #28
0
        private void Navigate(WebBrowser browser)
        {
            try
            {
                HtmlWindowCollection coll = browser.Document.Window.Frames;
                foreach (HtmlWindow win in coll)
                {
                    HtmlElement ele = win.Document.GetElementById("LeftMenuTable");
                    if (ele != null)
                    {
                        HtmlElementCollection eleCollection = ele.All;
                        foreach (HtmlElement el in eleCollection)
                        {
                            if (el.InnerText == "��������")
                            {
                                el.GetElementsByTagName("a")[0].InvokeMember("Click");
                                process = BLL.ProcessControl.�������;
                                fillData = BLL.FillData.��д��Ա����;
                                break;
                            }
                        }
                    }
                }

            }
            catch { }
        }
Пример #29
0
        public bool FillPage()
        {
            Hashtable columnHeader = new Hashtable();
            object    content;

            if (sheet.ReadNextRow())
            {
                while (sheet.ReadNextCell(false))
                {
                    content = sheet.GetContent();
                    columnHeader.Add(sheet.CurrentCell.ColumnIndex, content == null ? "" : content.ToString());
                }
            }
            FillData      data      = new FillData();
            List <IntPtr> controls  = GetFillControls();
            int           index     = 0;
            StringBuilder className = new StringBuilder(256);

            while (sheet.ReadNextRow())
            {
                int fillCount = 0;
                while (sheet.ReadNextCell(false))
                {
                    content = sheet.GetContent();
                    switch (columnHeader[sheet.CurrentCell.ColumnIndex] as string)
                    {
                    case "用符号识别(选择(是、否、不适用))":
                        data.SymbolIdentity = content == null ? "不适用" : string.IsNullOrEmpty(content.ToString()) ? "不适用" : content.ToString();
                        break;

                    case "位置":
                        data.Position = content == null ? null : content.ToString();
                        break;
                    }
                }
                for (; index < controls.Count && fillCount < 2; index++)
                {
                    NativeApi.GetClassName(controls[index], className, 255);
                    if (className.ToString().StartsWith(CCCFillManager.ComboBoxClassName))
                    {
                        ApiSetter.SetComboBoxSelected(hwnd, controls[index], data.SymbolIdentity);
                        fillCount++;
                    }
                    else if (className.ToString().StartsWith(CCCFillManager.EditClassName))
                    {
                        ApiSetter.SetText(controls[index], data.Position);
                        fillCount++;
                    }
                    else if (saveButton != IntPtr.Zero && className.ToString().StartsWith(CCCFillManager.ButtonClassName))
                    {
                        className.Clear();
                        NativeApi.GetWindowText(controls[index], className, 255);
                        if (className.ToString() == "保存")
                        {
                            saveButton = controls[index];
                        }
                    }
                }
            }
            if (saveButton == IntPtr.Zero)
            {
                for (; index < controls.Count; index++)
                {
                    className.Clear();
                    NativeApi.GetWindowText(controls[index], className, 255);
                    if (className.ToString() == "保存")
                    {
                        saveButton = controls[index];
                    }
                }
            }
            this.Main.ClickSaveButton(saveButton);
            return(true);
        }
Пример #30
0
        private void DescargarCategoriasClick(object sender, EventArgs e)
        {
            FillData servicio = new FillData();

            servicio.FillCategory();
        }
Пример #31
0
    public void IterateBase()
    {
        if (DoneBaseGen)
        {
            return;
        }

        count += 1;

        PositionalNode current = baseGenIterateCounter.Current;

        //Make either a room or a tunnel junction at the given spot.
        if (GeneratorSettings.R.NextDouble() < Settings.PercentRooms)
        {
            //Room.

            Location size = new Location(Settings.RoomDimensions.X + (int)Settings.RoomXVariance.Random(),
                                         Settings.RoomDimensions.Y + (int)Settings.RoomYVariance.Random());
            size = new Location(System.Math.Max(size.X, Settings.TunnelThickness.X),
                                System.Math.Max(size.Y, Settings.TunnelThickness.Y));
            Region room = new Region((int)current.Coordinate[0],
                                     (int)current.Coordinate[1],
                                     size.X - 1, size.Y - 1);
            if (!room.SubRegionOf(new Region(0, 0, Map.GetLength(0), Map.GetLength(1))))
            {
                DoneBaseGen = !baseGenIterateCounter.MoveNext();
                NodeStates.Remove(current);
                return;
            }

            //Move the room to the center.
            Location offset = new Location((int)Math.Round((MaxRoomSize.X - room.Width - 1) / 2.0f, 0), (int)Math.Round((MaxRoomSize.Y - room.Height - 1) / 2.0f, 0));
            room = new Region(room.TopLeft + offset, room.BottomRight + offset);

            //Clear the room area.
            Regions.Add(room);
            FillData.FillRegion(false, room);
            //Add the room data.
            NodeStates[current] = NodeState.Room;
            NodeAreas.Add(current, room);
        }
        else
        {
            //Tunnel junction.

            Location size  = MaxRoomSize;
            Region   space = new Region((int)current.Coordinate[0],
                                        (int)current.Coordinate[1],
                                        size.X - 1, size.Y - 1);

            space = new Region(space.Left + Settings.JunctionOffset.X,
                               space.Top + Settings.JunctionOffset.Y,
                               Settings.TunnelThickness.Y - 1,
                               Settings.TunnelThickness.X - 1);
            if (!space.SubRegionOf(new Region(0, 0, Map.GetLength(0), Map.GetLength(1))))
            {
                DoneBaseGen = !baseGenIterateCounter.MoveNext();
                NodeStates.Remove(current);
                return;
            }

            Regions.Add(space);
            FillData.FillRegion(false, space);

            //Add the room data.
            NodeStates[current] = NodeState.TunnelJunction;
            NodeAreas.Add(current, space);
        }

        //Prepare for the next iteration.
        DoneBaseGen = !baseGenIterateCounter.MoveNext();
    }
    public FilledRegion Apply(FillData data)
    {
        //Keep track of the spawn areas above the steps, indexed by y coordinate.
        Dictionary <int, Region> platformSpaces = new Dictionary <int, Region>();

        //Get step data.
        int  stepWidth  = (int)Math.Round(StepSizeScale * (data.BeingFilled.Width + 1), 0);
        int  spaceWidth = data.BeingFilled.Width + 1 - stepWidth - stepWidth;
        bool left       = true;

        Location line1, line2;

        for (int y = data.BeingFilled.Bottom - 1; y > data.BeingFilled.Top; y -= Space)
        {
            //Fill the line.
            if (left)
            {
                line1 = new Location(data.BeingFilled.Left, y);
                line2 = new Location(data.BeingFilled.Left + stepWidth - 1, y);

                data.FillLine(true, line1, line2);
                platformSpaces.Add(y, new Region(line1, line2, true));
            }
            else
            {
                line1 = new Location(data.BeingFilled.Left + stepWidth + spaceWidth, y);
                line2 = new Location(data.BeingFilled.Right, y);

                data.FillLine(true, line1, line2);
                platformSpaces.Add(y, new Region(line1, line2, true));
            }

            //Change sides.
            left = !left;
        }

        //Free any holes.
        foreach (Location l in data.HolesAlongPerimeter())
        {
            //If the hole is on the left side and there's a platform in the way:
            if (data.BeingFilled.Touches(l.Right, true, true, false) &&
                data.GetMapAt(l.Right))
            {
                //Remove the left edge of the platform.

                data.SetMapAt(l.Right, false);

                Region r = platformSpaces[l.Y];
                ++r.X;
                --r.Width;
                platformSpaces[l.Y] = r;
            }
            //Otherwise, if the hole is on the right side and there's a platform in the way:
            else if (data.BeingFilled.Touches(l.Left, true, true, false) &&
                     data.GetMapAt(l.Left))
            {
                //Remove the right edge of the platform.

                data.SetMapAt(l.Left, false);

                Region r = platformSpaces[l.Y];
                --r.Width;
                platformSpaces[l.Y] = r;
            }
        }

        return(new AlternatingStepsRegion(data.BeingFilled, platformSpaces.Values));
    }
Пример #33
0
 public FrmArea(FillData fd)
 {
     InitializeComponent();//一定要记得调用初始化窗体控件的方法
     //MessageBox.Show("4567sdfgh67");
     this.fd = fd;
 }