首页 > 解决方案 > While循环从richtextbox读取不同的行

问题描述

我正在尝试制作一个简单的海龟程序,您可以在其中输入多行代码以在PictureBox. 代码在那里用于图形,但我正在努力处理循环并让它读取字符串的下一行。我知道这将是一件非常简单的事情,但我已经尝试了几个小时无济于事。我已经添加了代码的第一部分,因为我确定这就是问题所在。我想我把它弄得太复杂了。

它是从富文本框中读取的,我试图逐行读取它,但每次都拆分这些行。因此,如果输入这样的内容:

square 50

drawto 100,100

moveto 200,200

square 100

到目前为止,当单击按钮时,它运行第一行,但我希望它遍历每一行并执行每个操作。我知道我的命名约定不是最好的


private void buttonRun_Click(object sender, EventArgs e) //what happens when run is clicked - main part of code
{
    Console.WriteLine("RUN PROGRAM");
    int lineno = 0;
    string Commandc1 = ProgramCommandWindow.Text.Trim().ToLower();
    StringReader strReader = new StringReader(Commandc1);
    string[] textlines = Commandc1.Split(new[] { Environment.NewLine }, StringSplitOptions.None);


    while (true)
    {
        textlines[lineno] = strReader.ReadLine(); //reads line of text
        while (textlines[lineno] != null)
        {
            //Commandc1 = strReader.ReadLine();
            string[] Commandc = textlines[lineno].Split(' ', ',');
            while (Commandc[0].Equals("moveto") == true)
            {
                if (!Int32.TryParse(Commandc[+1], out positionx)) ; //translate string to int
                if (!Int32.TryParse(Commandc[+2], out positiony)) ;

                Picturebox.xPos = positionx;
                Picturebox.yPos = positiony;
                //Commandc1 = strReader.ReadLine();
                Refresh();//refresh display
                lineno++;

            }
            while (Commandc[0].Equals("drawto") == true) //what happens if draw line command is used
            {

                if (!Int32.TryParse(Commandc[+1], out positionx)) ; //translate string to int
                if (!Int32.TryParse(Commandc[+2], out positiony)) ;

                Picturebox.toX = positionx;
                Picturebox.toY = positiony;
                MyOutputWindow.DrawLine(Picturebox.toX, Picturebox.toY);
                Console.WriteLine("COMMAND - DRAW LINE");
                //Commandc1 = strReader.ReadLine();
                Refresh();//refresh display

                lineno++;
            }
            while (Commandc[0].Equals("square") == true) //what happens if draw square command is used
            {

                if (!Int32.TryParse(Commandc[+1], out positionshape)) ; //translate string to int 

                Picturebox.sizes = positionshape;
                MyOutputWindow.DrawSquare(Picturebox.sizes);
                Console.WriteLine("COMMAND - DRAW SQUARE");
                //Commandc1 = strReader.ReadLine();
                Refresh();//refresh display

                lineno++;

            }



            break;
        }
        //else while (Commandc1 == "end")
        //{
        //   break;
        //}

        Refresh();//refresh display
        break;
    }
}

标签: c#turtle-graphics

解决方案


推荐阅读