Пример #1
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();
        }
Пример #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);
                    }));
                }
            }
        }
Пример #3
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();
            }
        }
Пример #4
0
 private void Write_(String str)
 {
     DebugBox.Dispatcher.InvokeAsync(
         new Action(() => {
         DebugBox.AppendText(str);
         DebugBox.ScrollToEnd();
     })
         );
 }
Пример #5
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);
        }
Пример #6
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");
                }
            }
        }
Пример #7
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);
            }
        }
Пример #8
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);
     }
 }
Пример #9
0
 private void debug(string txt)
 {
     DebugBox.AppendText(txt + System.Environment.NewLine);
 }
Пример #10
0
 private void debug(string txt)
 {
     DebugBox.AppendText(txt + System.Environment.NewLine);
     Application.DoEvents();
 }
Пример #11
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
        }
Пример #12
0
 private void DebugCheck_CheckedChanged(object sender, EventArgs e)
 {
     DebugBox.Visible ^= true;
     DebugBox.AppendText("Debug toggled");
     DebugBox.AppendText(Environment.NewLine);
 }
Пример #13
0
        //Convert formats to correct ones

        public void DebugPrint(string text)
        {
            DebugBox.AppendText($"{text}");
            DebugBox.AppendText(Environment.NewLine);
            Console.WriteLine($"{text}");
        }
Пример #14
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());
            }
        }