Ejemplo n.º 1
0
 public HouseParser(List <string> phraseForSearch)
 {
     DebugBox.WriteLine("Начинаем парсинг данных.");
     phraseForSearch.ForEach(phrase =>
     {
         Zillow zillow = new Zillow();
         string link   = "https://www.zillow.com/homes/" + phrase.Replace(" ", "-") + "_rb/";
         zillow.URL    = link;
         results.Add(zillow);
     });
     CookieSet();
     results.ForEach(result =>
     {
         while (threadCount >= 200)
         {
             Thread.Sleep(500);
         }
         threadCount++;
         ParsInfo(result);
     });
     while (threadCount != 0)
     {
         Thread.Sleep(1000);
     }
     DebugBox.WriteLine("Парсинг завершён!");
 }
Ejemplo n.º 2
0
        public void OnDataReveiced(object sender, SerialDataReceivedEventArgs e)
        {
            using (ArduinoPort)
            {
                Thread.Sleep(1);

                SerialPort sp = (SerialPort)sender;
                returnMessage += (string)sp.ReadExisting();

                if (DebugBox.InvokeRequired)
                {
                    DebugBox.Invoke(new Action(() =>
                    {
                        DebugBox.AppendText("Message received.");
                        DebugBox.AppendText(Environment.NewLine);
                    }));
                }

                if (InfoBox.InvokeRequired)
                {
                    InfoBox.Invoke(new Action(() => {
                        InfoBox.AppendText(returnMessage);
                        InfoBox.AppendText(Environment.NewLine);
                    }));
                }
            }
        }
Ejemplo n.º 3
0
        private void AddRecipieButton_Click(object sender, EventArgs e)
        {
            //Check to see if input exists
            if (String.IsNullOrEmpty(RecipieNameInput.Text))
            {
                RecipieNameInput.Text = "Please input name!";
                return;
            }

            if (String.IsNullOrEmpty(IngredientsInput.Text))
            {
                IngredientsInput.Text = "Please input Ingredients!";
                return;
            }

            if (String.IsNullOrEmpty(StepInput.Text))
            {
                StepInput.Text = "Please input cooking steps!";
                return;
            }

            DebugBox.AppendText($"{RecipieNameInput.Text}, {IngredientsInput.Text}, {StepInput.Text}, {Convert.ToInt32(DaysInput.Value)}, {Convert.ToInt32(CookingTimeInput.Value)}");
            DebugBox.AppendText(Environment.NewLine);

            //If we've input, take that input and add it to the list!
            AddRecipie(RecipieNameInput.Text, IngredientsInput.Text, StepInput.Text, Convert.ToInt32(DaysInput.Value), Convert.ToInt32(CookingTimeInput.Value));
            RecipieNameInput.Text = null;
            IngredientsInput.Text = null;
            StepInput.Text        = null;
            UpdateRecipies();
        }
Ejemplo n.º 4
0
        private void ParsInfo(Zillow zillow)
        {
            Thread thread = new Thread(() =>
            {
                LinkParser linkParser;
                ReqParametres reqParametres;
                do
                {
                    //Парсим предварительную ссылку
                    reqParametres = new ReqParametres(zillow.URL);
                    reqParametres.SetUserAgent(Useragents.GetNewUseragent());
                    reqParametres.SetProxy();
                    linkParser   = new LinkParser(reqParametres.Request);
                    SavedCookies = linkParser.Cookies;
                } while (isCaptcha(linkParser.Data));
                string newLink = linkParser.Data.ParsFromTo("<link rel=\"canonical\" href=\"", "\"");
                //Проверяем на неверную ссылку
                if (newLink.Contains("https://www.zillow.com/homes/for_sale/"))
                {
                    zillow.Status = "No such adress";
                }
                else
                {
                    zillow.URL = newLink;

                    do
                    {
                        reqParametres = new ReqParametres(zillow.URL);
                        reqParametres.SetUserAgent(Useragents.GetNewUseragent());
                        reqParametres.SetProxy();
                        linkParser = new LinkParser(reqParametres.Request);
                    } while (isCaptcha(linkParser.Data));
                    zillow.Status = CheckOnStatus(linkParser.Data.ToLower()).Replace("<span tabindex=\"0\" role=\"button\"><span class=\"zsg-tooltip-launch_keyword\">", "")
                                    .Replace("<Span Tabindex=\"0\" Role=\"Button\"><Span Class=\"Zsg-Tooltip-Launch_Keyword\">", "");
                    if (zillow.Status.Equals("Undefined"))
                    {
                        DebugBox.WriteLine(linkParser.Data);
                    }
                    else
                    {
                        //Zestimate set
                        List <string> rawZestimate = linkParser.Data.ParsRegex("Zestimate<sup>®</sup></span></span>(.*?)\\$([0-9,./a-zA-Z]+)<", 2);
                        if (rawZestimate.Count != 0)
                        {
                            zillow.Zestimate = "$" + rawZestimate[0];
                        }
                        zillow.SoldPrice = CheckPrice(linkParser.Data);
                    }
                    SavedCookies = linkParser.Cookies;
                }
                threadCount--;
                progress++;
                DebugBox.WriteLine($"Обработано ссылок: {progress} из {results.Count}.");
                double val = 100.0f / results.Count * progress;
                WorkProgress.SetValue(val);
            });

            thread.IsBackground = true;
            thread.Start();
        }
Ejemplo n.º 5
0
        // Sets the default port
        public void SetComPort()
        {
            try
            {
                DebugBox.AppendText(COMBox.SelectedItem.ToString());
                DebugBox.AppendText(Environment.NewLine);
                ArduinoPort           = new SerialPort(COMBox.SelectedItem.ToString(), 9600, Parity.None, 8, StopBits.One);
                ArduinoPort.Handshake = Handshake.None;
                ArduinoPort.RtsEnable = true;
                message = "IDENTIFY";
                try
                {
                    ArduinoPort.Open();
                    Thread.Sleep(200);
                }
                catch (UnauthorizedAccessException ex)
                {
                    DebugBox.AppendText("Unauthorized Access Exception! Cannot open port " + COMBox.SelectedValue.ToString());
                    DebugBox.AppendText(Environment.NewLine);
                    DebugBox.AppendText(ex.ToString());
                }
                catch (Exception ex)
                {
                    DebugBox.AppendText("Unknown error: ");
                    DebugBox.AppendText(Environment.NewLine);
                    DebugBox.AppendText(ex.ToString());
                }
                Sender(ArduinoPort);

                returnMessage += ArduinoPort.ReadLine();
                if (returnMessage.Contains("CONNECTED"))
                {
                    InfoBox.AppendText(returnMessage);
                    returnMessage = "";
                    try
                    {
                        using (ArduinoPort)
                        {
                            ArduinoPort.DataReceived += new SerialDataReceivedEventHandler(OnDataReveiced);
                            DebugBox.AppendText("Created serial event handler");
                            DebugBox.AppendText(Environment.NewLine);
                        }
                    }
                    catch (Exception ex)
                    {
                        DebugBox.AppendText("Could not create serial event handler");
                        DebugBox.AppendText(Environment.NewLine);
                        DebugBox.AppendText(ex.ToString());
                        DebugBox.AppendText(Environment.NewLine);
                    }
                }
            }
            catch (Exception ex)
            {
                DebugBox.Text += "\nError: " + ex.ToString();
            }
        }
Ejemplo n.º 6
0
 private void Write_(String str)
 {
     DebugBox.Dispatcher.InvokeAsync(
         new Action(() => {
         DebugBox.AppendText(str);
         DebugBox.ScrollToEnd();
     })
         );
 }
Ejemplo n.º 7
0
    void Start()
    {
        gm      = GameMaster.instance;
        dbox    = gm.dbox;
        mainCam = Camera.main;

        PlaceTowerText  = PlaceTowerButton.gameObject.GetComponentInChildren <Text>();
        PlaceTowerImage = PlaceTowerButton.gameObject.GetComponent <Image>();
        PlaceWallText   = PlaceWallButton.gameObject.GetComponentInChildren <Text>();
        PlaceWallImage  = PlaceWallButton.gameObject.GetComponent <Image>();
        DemolishText    = DemolishButton.gameObject.GetComponentInChildren <Text>();
        DemolishImage   = DemolishButton.gameObject.GetComponent <Image>();
    }
Ejemplo n.º 8
0
        private void LoadConfig()
        {
            if (!settings.Initialize())
            {
                MessageBox.Show(settings.lastError, Resources.ERROR);
            }

            if (!settings.Open())
            {
                MessageBox.Show(settings.lastError, Resources.ERROR);
            }

            try
            {
                if (!settings.DebugEnabled)
                {
                    int w = this.Width;
                    DebugBox.Hide();
                    MaximumSize = new Size(w, tablePanel3.Bottom + 50);
                }

                this.SigVisible.Checked = settings.VisibleSignature;
            }
            catch (Exception) { }

            // UI
            comboLanguage.SelectedIndex = GetCulture(settings.Language);

            // Signature box content
            Contacttext.Text = settings.Contact;
            Reasontext.Text  = settings.Reason;
            Citytext.Text    = settings.City;
            Countytext.Text  = settings.County;
            Countrytext.Text = settings.Country;
            Indextext.Text   = settings.Index;

            // digidocpp.conf
            if (!conf.Initialize())
            {
                MessageBox.Show(conf.lastError, Resources.ERROR);
                return;
            }
            if (!conf.Open())
            {
                MessageBox.Show(conf.lastError, Resources.ERROR);
                return;
            }

            // DirectoryX509Store
            OpenCertStore(conf.CertStorePath);
        }
Ejemplo n.º 9
0
        // Reads the buffer if the event doesn't fire
        private void Read_Click(object sender, EventArgs e)
        {
            // Got error here. "Port is closed!"
            // ArduinoPort.Open();
            // This means the port closed before the arduino could respond!
            returnMessage += (string)ArduinoPort.ReadExisting();

            DebugBox.AppendText("Message received.");
            DebugBox.AppendText(Environment.NewLine);

            InfoBox.AppendText(returnMessage);
            InfoBox.AppendText(Environment.NewLine);
            // lineReader(message);
        }
Ejemplo n.º 10
0
        private void StartWork(string fileName)
        {
            DebugBox.WriteLine($"Получен файл {fileName}.");
            Thread thread = new Thread(() =>
            {
                string savedFileName    = fileName;
                ExcelReader excelReader = new ExcelReader(savedFileName);
                HouseParser houseParser = new HouseParser(excelReader.ResultValues);
                ExcelWriter excel       = new ExcelWriter(fileName, houseParser.results);
                DebugBox.WriteLine("Работа парсера успешно завершена!");
            });

            thread.IsBackground = true;
            thread.Start();
        }
Ejemplo n.º 11
0
 public static void Initialise(Start root)
 {
     if (Parent == null)
     {
         Parent = root;
     }
     if (WinForm == null)
     {
         WinForm = new DebugBox(root);
     }
     if (DebugOutputRichTextBox == null)
     {
         DebugOutputRichTextBox = WinForm.DebugOutputRichTextBox;
     }
 }
Ejemplo n.º 12
0
 private void UpdateTime()
 {
     while (true)
     {
         qt++;
         run++;
         this.Invoke((MethodInvoker) delegate {
             if (DebugBox.Lines.Length >= 2000)
             {
                 DebugBox.Clear();
             }
             UpdateTimeText();
         });
         Thread.Sleep(1000);
     }
 }
Ejemplo n.º 13
0
        private void SignIn_Click(object sender, EventArgs e)
        {
            DebugBox.Text = "";
            bool   isValid    = true;
            String user_input = User_Field.Text;
            String pass_input = Password_Field.Text;

            if (!FieldValidator.validateUser(user_input))
            {
                DebugBox.AppendText("\n*Username can only contain alphabet letters, 0-9, dot and underscore. No spaces allowed.\n");
                isValid = false;
            }

            if (!FieldValidator.validatePassword(pass_input))
            {
                DebugBox.AppendText("\n *Password can only contain alphabet letters, 0-9, and symbols ._/?!#$%^&*. No spaces allowed\n");
                isValid = false;
            }



            if (isValid)
            {
                var filter = Builders <BsonDocument> .Filter.Eq("username", user_input);

                BsonDocument userDocument;
                try
                {
                    userDocument = Connector.collection.Find(filter).First();
                    dynamic userData = JObject.Parse(userDocument.ToString());

                    string password = userData["password"].ToString();
                    if (Tools.Decrypt(password) == pass_input)
                    {
                        MessageBox.Show("Succesfully Logged in");
                    }
                    else
                    {
                        MessageBox.Show("Invalid password");
                    }
                }
                catch
                {
                    MessageBox.Show("Username not found");
                }
            }
        }
Ejemplo n.º 14
0
        public ExcelReader(string fileName)
        {
            ResultValues = new List <string>();
            DebugBox.WriteLine($"Приступаем к чтению {fileName}");
            Application ObjExcel = new Application();
            //Открываем книгу.
            Workbook ObjWorkBook = ObjExcel.Workbooks.Open(fileName, 0, false, 5, "", "", false, XlPlatform.xlWindows, "", true, false, 0, true, false, false);
            //Выбираем таблицу(лист).
            Worksheet ObjWorkSheet;

            ObjWorkSheet = (Worksheet)ObjWorkBook.Sheets[1];

            // Указываем номер столбца (таблицы Excel) из которого будут считываться данные.
            int numCol = 3;

            Range         usedColumn = ObjWorkSheet.UsedRange.Columns[numCol];
            Array         myvalues   = (Array)usedColumn.Cells.Value2;
            List <string> allValues  = new List <string>(myvalues.OfType <object>().Select(o => o.ToString()).ToArray());

            numCol     = 5;
            usedColumn = ObjWorkSheet.UsedRange.Columns[numCol];
            myvalues   = (Array)usedColumn.Cells.Value2;
            List <string> allAdditionalValues = new List <string>(myvalues.OfType <object>().Select(o => o.ToString()).ToArray());

            for (int i = 1; allValues.Count > i; i++)
            {
                if (allAdditionalValues.Count <= i)
                {
                    break;
                }
                ResultValues.Add(allValues[i] + " " + allAdditionalValues[i]);
            }
            DebugBox.WriteLine($"Чтение файла завершено, найдено {ResultValues.Count} строк.");

            // Выходим из программы Excel.
            ObjWorkBook.Close(true);
            ObjExcel.Quit();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(ObjWorkBook);
            ObjExcel     = null;
            ObjWorkBook  = null;
            ObjWorkSheet = null;
            System.GC.Collect();
        }
Ejemplo n.º 15
0
        // Send message to port
        public void Sender(SerialPort porto)
        {
            byte[] buffer = new byte[messageLength];
            int    n      = 0;

            message = message + '\n';
            try
            {
                DebugBox.AppendText("BreakState: " + ArduinoPort.BreakState + "\r\n");
                DebugBox.AppendText("Clear-to-Send line: " + ArduinoPort.CtsHolding + "\r\n");
                DebugBox.AppendText("CanRaiseEvent: " + CanRaiseEvents + "\r\n");
                foreach (char c in message)
                {
                    buffer[n] = Convert.ToByte(c);
                    n++;
                }
                porto.Write(buffer, 0, messageLength - 1);
                Thread.Sleep(500);
                if (ArduinoPort.BytesToWrite == 0)
                {
                    DebugBox.AppendText("Message sent");
                    DebugBox.AppendText(Environment.NewLine);
                }
                else
                {
                    DebugBox.AppendText("Message has not yet been sent\r\n");
                }
            }
            catch (Exception ex)
            {
                DebugBox.AppendText("Exception in conversion funktion:");
                DebugBox.AppendText(Environment.NewLine);
                DebugBox.AppendText(ex.ToString());
                DebugBox.AppendText(Environment.NewLine);
            }
        }
Ejemplo n.º 16
0
 // This sends message recorded in MessageBox.
 private void Send_Click(object sender, EventArgs e)
 {
     DebugBox.AppendText("Trying to send message:");
     DebugBox.AppendText(Environment.NewLine);
     message = MessageBox.Text;
     DebugBox.AppendText(message);
     DebugBox.AppendText(Environment.NewLine);
     ArduinoPort.Close();
     using (ArduinoPort)
     {
         try
         {
             ArduinoPort.Open();
         }
         catch (Exception ex)
         {
             DebugBox.AppendText("Error in Send event:");
             DebugBox.AppendText(Environment.NewLine);
             DebugBox.AppendText(ex.ToString());
             DebugBox.AppendText(Environment.NewLine);
         }
         Sender(ArduinoPort);
     }
 }
Ejemplo n.º 17
0
        public static void DrawDebug()
        {
            // Update view and projection with updated camera coordinates.
            DefaultEffect.View       = Game1.CurrentScene.CurrentCamera.View;
            DefaultEffect.Projection = Game1.CurrentScene.CurrentCamera.ProjectionMatrix;

            DefaultEffect.CurrentTechnique.Passes[0].Apply();

            for (int i = 0; i < DebugList.Count; i++)
            {
                DebugLine dl = DebugList[i];

                VertexPositionColor[] buffer = { new VertexPositionColor(dl.Start, dl.Color), new VertexPositionColor(dl.End, dl.Color) };

                Graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, buffer, 0, 1);
            }

            for (int i = 0; i < DebugHit.Count; i++)
            {
                DebugHit dh = DebugHit[i];
                VertexPositionColor[] buffer =
                {
                    new VertexPositionColor(dh.Point + new Vector3(0, 0, 1), dh.Color), new VertexPositionColor(dh.Point - new Vector3(0, 0, 1), dh.Color),
                    new VertexPositionColor(dh.Point + new Vector3(1, 0, 0), dh.Color), new VertexPositionColor(dh.Point - new Vector3(1, 0, 0), dh.Color),
                };
                Graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, buffer, 0, 2);
            }

            for (int i = 0; i < DebugBoxes.Count; i++)
            {
                DebugBox db = DebugBoxes[i];
                VertexPositionColor[] buffer =
                {
                    // TOP
                    new VertexPositionColor(db.Point + new Vector3(-0.5f, -0.5f, -0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(-0.5f, -0.5f,  0.5f), db.Color),

                    new VertexPositionColor(db.Point + new Vector3(-0.5f, -0.5f,  0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(0.5f,  -0.5f,  0.5f), db.Color),

                    new VertexPositionColor(db.Point + new Vector3(0.5f,  -0.5f,  0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(0.5f,  -0.5f, -0.5f), db.Color),

                    new VertexPositionColor(db.Point + new Vector3(0.5f,  -0.5f, -0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(-0.5f, -0.5f, -0.5f), db.Color),

                    // middle
                    new VertexPositionColor(db.Point + new Vector3(-0.5f, -0.5f, -0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(-0.5f,  0.5f, -0.5f), db.Color),

                    new VertexPositionColor(db.Point + new Vector3(-0.5f, -0.5f,  0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(-0.5f,  0.5f,  0.5f), db.Color),

                    new VertexPositionColor(db.Point + new Vector3(0.5f,  -0.5f,  0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(0.5f,   0.5f,  0.5f), db.Color),

                    new VertexPositionColor(db.Point + new Vector3(0.5f,  -0.5f, -0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(0.5f,   0.5f, -0.5f), db.Color),

                    // bottom
                    new VertexPositionColor(db.Point + new Vector3(-0.5f,  0.5f, -0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(-0.5f,  0.5f,  0.5f), db.Color),

                    new VertexPositionColor(db.Point + new Vector3(-0.5f,  0.5f,  0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(0.5f,   0.5f,  0.5f), db.Color),

                    new VertexPositionColor(db.Point + new Vector3(0.5f,   0.5f,  0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(0.5f,   0.5f, -0.5f), db.Color),

                    new VertexPositionColor(db.Point + new Vector3(0.5f,   0.5f, -0.5f), db.Color),
                    new VertexPositionColor(db.Point + new Vector3(-0.5f,  0.5f, -0.5f), db.Color),
                };
                Graphics.GraphicsDevice.DrawUserPrimitives(PrimitiveType.LineList, buffer, 0, buffer.Count() / 2);
            }
        }
Ejemplo n.º 18
0
 public static void AddDebugBox(DebugBox box)
 {
     DebugBoxes.Add(box);
 }
Ejemplo n.º 19
0
 private void debug(string txt)
 {
     DebugBox.AppendText(txt + System.Environment.NewLine);
 }
Ejemplo n.º 20
0
 private void debug(string txt)
 {
     DebugBox.AppendText(txt + System.Environment.NewLine);
     Application.DoEvents();
 }
Ejemplo n.º 21
0
        public void ListenServer()
        {
            //监听端口
            IPEndPoint     udpPoint    = new IPEndPoint(IPAddress.Any, hostport);
            UdpClient      udpClient   = new UdpClient(udpPoint);
            IPEndPoint     senderPoint = new IPEndPoint(IPAddress.Any, 0);
            GifRichTextBox transrtf    = new LinkerServer.GifRichTextBox();

            try
            {
                while (true)
                {
                    byte[] bytes   = udpClient.Receive(ref senderPoint);
                    string strIP   = "来自:" + senderPoint.Address.ToString() + ":" + senderPoint.Port.ToString();
                    string strInfo = Encoding.GetEncoding("gb2312").GetString(bytes, 0, bytes.Length);
                    transrtf.Rtf = strInfo; strInfo = transrtf.Text.ToString();

                    //请求外网地址:指令格式:GET:
                    if (strInfo.Contains("NAT"))
                    {
                        //返回外网地址
                        string sendMsg = "" + senderPoint.Address.ToString() + ":" + senderPoint.Port.ToString();
                        transrtf.Text = sendMsg;
                        sendMsg       = transrtf.Rtf;
                        byte[] sendData = Encoding.Default.GetBytes(sendMsg);

                        udpClient.Send(sendData, sendData.Length, senderPoint);

                        //更新日志
                        this.Invoke((MethodInvoker) delegate
                        {
                            DebugBox.AppendText(strIP + " 内容:请求NAT地址");
                            DebugBox.AppendText(Environment.NewLine);
                        });
                    }
                    //用户连接:指令格式:LOGIN:10001
                    else if (strInfo.Contains("LOGN:"))
                    {
                        //返回外网地址
                        string[] sArray  = Regex.Split(strInfo, ":", RegexOptions.IgnoreCase);
                        string   sendMsg = "NAT" + senderPoint.Address.ToString() + ":" + senderPoint.Port.ToString();
                        transrtf.Text = sendMsg;
                        sendMsg       = transrtf.Rtf;
                        byte[] sendData = Encoding.Default.GetBytes(sendMsg);
                        udpClient.Send(sendData, sendData.Length, senderPoint);

                        //添加用户到数据表
                        //如果已添加过就删除后再添加
                        if (userTable.Select("id='" + sArray[1] + "'").Length > 0)
                        {
                            foreach (DataRow row in userTable.Select("id='" + sArray[1] + "'"))
                            {
                                userTable.Rows.Remove(row);
                            }
                        }
                        userTable.Rows.Add(sArray[1], senderPoint.Address.ToString(), senderPoint.Port.ToString());

                        //更新日志
                        this.Invoke((MethodInvoker) delegate
                        {
                            DebugBox.AppendText(strIP + " 内容:" + sArray[1] + "已连接");
                            DebugBox.AppendText(Environment.NewLine);
                        });
                    }

                    //用户连接其他用户:指令格式:LINK:10001:10002
                    else if (strInfo.Contains("LINK:"))
                    {
                        //查询 请求用户A 与 目标用户B 的NAT地址
                        //MessageBox.Show(userTable.Select("id='" + sArray[2] + "'")[0]["id"].ToString());

                        string[]   sArray       = Regex.Split(strInfo, ":", RegexOptions.IgnoreCase);
                        DataRow[]  dtA          = userTable.Select("id='" + sArray[1] + "'");
                        IPEndPoint targetPointA = new IPEndPoint(IPAddress.Parse(dtA[0]["ip"].ToString()), Convert.ToInt32(dtA[0]["port"]));
                        IPEndPoint targetPointB = senderPoint;

                        //给 目标用户B 发送 请求用户A 的NAT地址
                        string sendMsg = "@L@I@N@K:" + targetPointA.Address.ToString() + ":" + targetPointA.Port.ToString();
                        transrtf.Text = sendMsg;
                        sendMsg       = transrtf.Rtf;
                        byte[] sendData = Encoding.Default.GetBytes(sendMsg);
                        udpClient.Send(sendData, sendData.Length, targetPointB);

                        //给 请求用户A 返回 目标用户B 的NAT地址
                        string sendMsg2 = "@L@I@N@K:" + targetPointB.Address.ToString() + ":" + targetPointB.Port.ToString();
                        transrtf.Text = sendMsg2;
                        sendMsg2      = transrtf.Rtf;
                        byte[] sendData2 = Encoding.Default.GetBytes(sendMsg2);
                        udpClient.Send(sendData2, sendData2.Length, targetPointA);

                        this.Invoke((MethodInvoker) delegate
                        {
                            DebugBox.AppendText(strIP + " 内容:" + sArray[1] + "与其他用户" + "已连接");
                            DebugBox.AppendText(Environment.NewLine);
                        });
                    }

                    else if (strInfo.Contains("LOUT:"))
                    {
                        //用户离线删除登记信息
                        string[] sArray = Regex.Split(strInfo, ":", RegexOptions.IgnoreCase);
                        foreach (DataRow row in userTable.Select("id='" + sArray[1] + "'"))
                        {
                            userTable.Rows.Remove(row);
                        }
                        //更新日志
                        this.Invoke((MethodInvoker) delegate
                        {
                            DebugBox.AppendText(strIP + " 内容:" + sArray[1] + "已断开");
                            DebugBox.AppendText(Environment.NewLine);
                        });
                    }


                    else if (strInfo.Contains("HOME"))
                    {
                        //欢迎与功能菜单
                        string sendMsg = "欢迎使用MSGServer" + "      在线[" + userTable.Rows.Count.ToString() + "]人";
                        transrtf.Text = sendMsg;
                        transrtf.AppendText(Environment.NewLine);
                        transrtf.AppendText("----------------------------------");
                        transrtf.AppendText(Environment.NewLine);
                        transrtf.AppendText("HOME 功能菜单        NAT  获取地址");
                        transrtf.AppendText(Environment.NewLine);
                        transrtf.AppendText("LIST 用户列表        TOTA 统计信息");
                        transrtf.AppendText(Environment.NewLine);
                        transrtf.AppendText("LINK:ID 连接用户     HELP 获取帮助");
                        transrtf.AppendText(Environment.NewLine);
                        transrtf.AppendText("CLEA 清除记录        PROE 设置参数");
                        sendMsg = transrtf.Rtf;
                        byte[] sendData = Encoding.Default.GetBytes(sendMsg);
                        udpClient.Send(sendData, sendData.Length, senderPoint);
                    }
                    else if (strInfo.Contains("LIST"))
                    {
                        string sendMsg = "MSGServer当前用户列表" + "  在线[" + userTable.Rows.Count.ToString() + "]人";
                        transrtf.Text = sendMsg;
                        transrtf.AppendText(Environment.NewLine);
                        transrtf.AppendText("-----------------------------------");
                        transrtf.AppendText(Environment.NewLine);
                        for (int i = 0; i < userTable.Rows.Count; i++)
                        {
                            string id   = userTable.Rows[i][0].ToString();
                            string ip   = userTable.Rows[i][1].ToString();
                            string port = userTable.Rows[i][2].ToString();
                            transrtf.AppendText("ID:" + id + "IP:" + ip + "PT:" + port);
                            transrtf.AppendText(Environment.NewLine);
                        }
                        sendMsg = transrtf.Rtf;
                        byte[] sendData = Encoding.Default.GetBytes(sendMsg);
                        udpClient.Send(sendData, sendData.Length, senderPoint);
                    }

                    else
                    {
                    }
                    Thread.Sleep(100);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Ejemplo n.º 22
0
        //Convert formats to correct ones

        public void DebugPrint(string text)
        {
            DebugBox.AppendText($"{text}");
            DebugBox.AppendText(Environment.NewLine);
            Console.WriteLine($"{text}");
        }
Ejemplo n.º 23
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = LibraryFolderDialog.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }

            ClearInterface();
            ImageList.Images.Clear();
            _indexList.Clear();
            _LImageList.Clear();
            PreviewListView.VirtualListSize = 0;
            PreviewListView.Items.Clear();

            DebugBox.Clear();

            folderName = LibraryFolderDialog.SelectedPath;

            LoadSettings form = new LoadSettings();

            form.ShowDialog();

            showFrontSide = form.GetFrontSide();

            string Prefix = "";

            if (form.GetManualPrefix())
            {
                Prefix = form.GetPrefix();
            }
            else
            {
                foreach (string file in Directory.EnumerateFiles(folderName, "*.lib"))
                {
                    Prefix = Path.GetFileNameWithoutExtension(file);
                    break;
                }
            }

            //DebugBox.Text += "Showfront: "+showFrontSide.ToString() + "\r\n";
            //DebugBox.Text += "Prefix: "+Prefix + "\r\n";
            Program.LoadFailed = false;

            MessageBox.Show("This can take a while.\n Press 'OK' to Start.");


            Stopwatch sw           = Stopwatch.StartNew();//Timing
            int       folderLength = Directory.GetFiles(folderName, "*.lib").Length;

            for (int i = 0; i < folderLength; i++)
            {
                string PathName = folderName + Path.DirectorySeparatorChar;
                string flName   = i.ToString(Prefix) + ".lib";
                string fullname = PathName + flName;

                if (File.Exists(fullname))
                {
                    //DebugBox.Text += fullname + "\r\n";

                    if (_library != null)
                    {
                        _library.Close();
                    }
                    _library = new MLibraryV2(fullname);
                    if (Program.LoadFailed)
                    {
                        break;
                    }

                    _NameList.Add(Path.GetFileName(fullname));

                    PreviewListView.VirtualListSize = ImageList.Images.Count + 1;
                }
            }
            sw.Stop();//Timing

            LibCountLabel.Text = ImageList.Images.Count.ToString();


            if (ImageList.Images.Count < 1)
            {
                MessageBox.Show("No images seem to be found.\nMake sure you choose the right prefix!");
            }
            else
            {
                MessageBox.Show("Folder processing finally finished.\nTime Taken: " + sw.Elapsed.TotalMilliseconds + "ms");
            }
        }
Ejemplo n.º 24
0
 private void DebugBox_Click(object sender, EventArgs e)
 {
     DebugBox.ScrollBars = RichTextBoxScrollBars.ForcedVertical;
     DebugBox.Show();
 }
Ejemplo n.º 25
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DialogResult result = LibraryFolderDialog.ShowDialog();

            if (result != DialogResult.OK)
            {
                return;
            }

            ClearInterface();
            ImageList.Images.Clear();
            _indexList.Clear();
            _LImageList.Clear();
            PreviewListView.VirtualListSize = 0;
            PreviewListView.Items.Clear();

            DebugBox.Clear();

            folderName = LibraryFolderDialog.SelectedPath;

            LoadSettings form = new LoadSettings();

            form.ShowDialog();

            showFrontSide = form.GetFrontSide();

            string Prefix = "";

            if (form.GetManualPrefix())
            {
                Prefix = form.GetPrefix();
            }
            else
            {
                foreach (string file in Directory.EnumerateFiles(folderName, "*.lib"))
                {
                    Prefix = Path.GetFileNameWithoutExtension(file);
                    break;
                }
            }

            //DebugBox.Text += "Showfront: "+showFrontSide.ToString() + "\r\n";
            //DebugBox.Text += "Prefix: "+Prefix + "\r\n";
            Program.LoadFailed = false;

            MessageBox.Show("这可能需要一段时间.\n 按“确定”开始.");


            Stopwatch sw           = Stopwatch.StartNew();//Timing
            int       folderLength = Directory.GetFiles(folderName, "*.lib").Length;

            for (int i = 0; i < folderLength; i++)
            {
                string PathName = folderName + Path.DirectorySeparatorChar;
                string flName   = i.ToString(Prefix) + ".lib";
                string fullname = PathName + flName;

                if (File.Exists(fullname))
                {
                    //DebugBox.Text += fullname + "\r\n";

                    if (_library != null)
                    {
                        _library.Close();
                    }
                    _library = new MLibrary(fullname);
                    if (Program.LoadFailed)
                    {
                        break;
                    }

                    _NameList.Add(Path.GetFileName(fullname));

                    PreviewListView.VirtualListSize = ImageList.Images.Count + 1;
                }
            }
            sw.Stop();//Timing

            LibCountLabel.Text = ImageList.Images.Count.ToString();


            if (ImageList.Images.Count < 1)
            {
                MessageBox.Show("似乎没有找到任何图像.\n确保选择了正确的前缀!");
            }
            else
            {
                MessageBox.Show("文件夹处理终于完成了.\n所用时: " + sw.Elapsed.TotalMilliseconds + "毫秒");
            }
        }
Ejemplo n.º 26
0
 private void skinButton3_Click(object sender, EventArgs e)
 {
     DebugBox.Clear();
 }
Ejemplo n.º 27
0
 private void DebugBox_TextChanged(object sender, EventArgs e)
 {
     DebugBox.ScrollToCaret();
 }
Ejemplo n.º 28
0
 private void DebugCheck_CheckedChanged(object sender, EventArgs e)
 {
     DebugBox.Visible ^= true;
     DebugBox.AppendText("Debug toggled");
     DebugBox.AppendText(Environment.NewLine);
 }
Ejemplo n.º 29
0
        public async void Play(object sender, EventArgs e)
        {
            ExecuteTimer.Stop();

            //Globals.FailSafe = 1; //Force failsafe

            //Check for failsafe
            if (Globals.PlayerTurn == 0 || Globals.FailSafe == 1 || Globals.PlayerTurn > PlayersAmount.Maximum || PlayersAmount.Value == 0 || Globals.NotEnoughCards == 1)
            {
                GamesAmount.Value = GamesAmount.Minimum;
                DebugBox.Text     = "";

                Status.Text = "Status: Simulation Ended  ---->  Error (either the card distribution is wrong or memory is corrupted) check debug box";

                DebugBox.AppendText("PlayerTurn ----> " + Globals.PlayerTurn + Environment.NewLine);
                if (Globals.FailSafe == 1)
                {
                    DebugBox.AppendText("FailSafe is set to 1 ---> Try using a set seed." + Environment.NewLine);
                }
                if (Globals.PlayerTurn > PlayersAmount.Maximum)
                {
                    DebugBox.AppendText("PlayerTurn > PlayersAmount.Maximum ----> Are you editing memory? Wrong value to edit" + Environment.NewLine);
                }
                if (PlayersAmount.Value == 0)
                {
                    DebugBox.AppendText("PlayersAmount.Value == 0 ----> Are you editing memory? Wrong value to edit" + Environment.NewLine);
                }
                if (Globals.NotEnoughCards == 1)
                {
                    DebugBox.AppendText("Globals.NotEnoughCards ---->  You need to add more cards" + Environment.NewLine);
                }

                DebugBox.AppendText(Environment.NewLine + "Open an issue on my GitHub and paste this output if you don't know how to solve this issue");
            }
            else
            {
                var watch = System.Diagnostics.Stopwatch.StartNew();

                Status.Text = "Status: Running simulation...";
                //var TempPlayerArray[] =



                //Alpha is the id of the game being simulated
                for (int alpha = 1; alpha <= GamesAmount.Value; alpha++)
                {
                    NewGame();
                    //Set game to on
                    Globals.isGameOn = true;

                    //Used to check if player can play or not
                    //var ALLOW_TURN_EDIT = 1;

                    //Display current game in Main
                    CurrentGameLabel.Text = "Current game: " + alpha + "/" + GamesAmount.Value;



                    //While game is on
                    //                           {{{{{{{{     NOTE: THIS IS BASICALLY THE BEGINNING OF THE AI     }}}}}}}}
                    while (Globals.isGameOn)
                    {
                        //Add a tiny-tiny delay
                        await PutTaskDelay(1);

                        //Reset personal flags
                        Globals.DoIHaveSameColors  = false;
                        Globals.DoIHaveSameNumbers = false;
                        Globals.DoIHaveSameID      = false;
                        Globals.DoIHaveWild        = false;

                        //Fix stepping, as it doesn't really work.
                        if (Stepping.Checked)
                        {
                            SpinWait.SpinUntil(() => Globals.DebugWait == false, 50); //This can be used to slow down the calculation
                            if (Globals.DebugWait == false)
                            {
                                Globals.DebugWait = true;
                                Globals.isGameOn  = false;
                            }
                        }


                        /*
                         *
                         * We should consider a setting up a risk score first, then choose what to play based on that
                         *
                         * But before that, check who's playing next.
                         *
                         *
                         */



                        //                                 {{{{{{{{     EVALUATION     }}}}}}}}



                        //                                 {{{{{{{{     WHO'S NEXT ?     }}}}}}}}
                        JObject rss  = JObject.Parse(Globals.JsonGame);
                        JObject game = rss["Game"] as JObject;

                        //Who's playing next?
                        // Json: Game --> Next_Player
                        Globals.PlayerTurn = (int)rss["Game"]["Next_Player"];

                        if (Globals.Clockwise == true)
                        {
                            if (Globals.PlayerTurn + 1 > PlayersAmount.Value)
                            {
                                game["Next_Player"] = 1;
                                Globals.PlayerTurn  = 1;
                            }
                            else
                            {
                                game["Next_Player"] = Globals.PlayerTurn + 1;
                                Globals.PlayerTurn  = Globals.PlayerTurn + 1;
                            }
                        }
                        else
                        {
                            if (Globals.PlayerTurn - 1 == 0)
                            {
                                game["Next_Player"] = PlayersAmount.Value;
                                Globals.PlayerTurn  = Convert.ToInt32(PlayersAmount.Value);
                            }
                            else
                            {
                                game["Next_Player"] = Globals.PlayerTurn - 1;
                                Globals.PlayerTurn  = Globals.PlayerTurn - 1;
                            }
                        }


                        //                                 {{{{{{{{     GET TOP CARD     }}}}}}}}
                        //Get top card

                        Scoreboard.Text = Globals.JsonGame; //debug

                        Globals.DoIHaveSameColors = false;
                        Globals.DoIHaveSameID     = false;

                        //Get identity of deck (current player turn)
                        JArray decks = (JArray)game["Player_Decks"][Globals.PlayerTurn.ToString()];

                        //Check if I have the same color
                        string color_to_check = (string)rss["Game"]["TopCard_Color"];
                        for (int i = 0; i < decks.Count; i++)
                        {
                            if (Globals.DoIHaveSameColors == false && color_to_check == decks[i].ToString().Split('_').Last())
                            {
                                //Set top card color
                                //Top should be: 0_Green
                                //Seed 0 -->  Deck: Contains 1_Green. so it's true (last is 9_blue)

                                Globals.DoIHaveSameColors = true;

                                //Scoreboard.Text = "Top: "+color_to_check+ ",   my: "+decks[i].ToString().Split('_').Last(); //debug
                            }
                        }


                        //Check if I have the same id
                        //It can be a number, trap, wild, ecc.. Same card ignoring color
                        string id_to_check = (string)rss["Game"]["TopCard_ID"];
                        for (int i = 0; i < decks.Count; i++)
                        {
                            if (Globals.DoIHaveSameID == false && id_to_check == decks[i].ToString().Split('_').First())
                            {
                                if (decks[i].ToString().Split('_').First() == "Wild")
                                {
                                    Globals.DoIHaveWild = true;
                                }
                                Globals.DoIHaveSameID = true;
                            }
                        }



                        /* Calculate end game
                         *
                         * -We can check if any player has no cards, that means someone has won
                         *      Better add this check after a placement/usage of card and then we set a flag or simply set "isGameOn" to true
                         *
                         */



                        //Atm I have no idea if the turn change works, as there's nothing that checks if a game must go on.
                        //Once code gets executed here, game just ends (thinking of including a score check for "isGameOn")

                        //Change turn

                        //End of game
                        if (Stepping.Checked == false)
                        {
                            Globals.isGameOn = false;
                        }
                    }
                }
                Status.Text = "Status: Simulation Ended";

                // the code that you want to measure comes here
                watch.Stop();
                var elapsedMs = watch.ElapsedMilliseconds;
                EmulationLabel.Text = "Emulation time taken: " + elapsedMs.ToString() + "ms";
            }

            //END OF SIMULATION
        }
Ejemplo n.º 30
0
 void Start()
 {
     gm   = GameMaster.instance;
     dbox = gm.dbox;
 }