Java Turtle Graphics Animation Basic

时间:2016-03-18 02:00:12

标签: java turtle-graphics

这是一个通过在屏幕上移动乌龟来创建分形的程序。为什么我的程序中的乌龟不会移动?任何帮助将不胜感激!我很确定这是一个简单的修复,但我找不到它。

由于

  /**
  * This program is to create a fractal
  */

import java.awt.*;
class FractalEngine
{
  World world = new World(700,700); 
  Turtle turt = new Turtle(1,1,world);

public void drawFractal(String rule)
{
    turt.penUp();
    turt.moveTo(350,350);

    int lengthofRule = rule.length();

    int start = 0;
    int fin = 1;
    String tinyChar;

    for(int a = 0; a <= lengthofRule; a++)
    {
        if(start == 9)
            tinyChar = rule.substring(start);
        else 
            tinyChar = rule.substring(start,fin);

        if(tinyChar == "F")
            turt.forward(25);
        else if(tinyChar == "-")
            turt.turnLeft();
        else if(tinyChar == "+")
            turt.turnRight();
        else
            break;
        start++;
        fin++;

            System.out.println(tinyChar);
        }
    }
}
public class FractalEngineTester
{
public static void main(String[] args)
{
   FractalEngine fEng = new FractalEngine();



  String rule = "F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F";
  //String rule = "F-F+F+F-F";

   fEng.drawFractal(rule);
   //String rule = "F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F";
   //String rule = "F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F-F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F+F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F+F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F-F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F";
}
}

1 个答案:

答案 0 :(得分:0)

此代码的问题与海龟无关 - 它与字符和字符串有关。

这不起作用:

String tinyChar = rule.substring(start, fin);

if (tinyChar == "F")

您正在混合使用Stringchar逻辑。你要么做:

String tinyChar = rule.substring(start, fin);

if (tinyChar.equals("F"))  # use a method to do the String comparison

或者做:

char tinyChar = rule.charAt(start);

if (tinyChar == 'F')  // notice the change in quotes

下面是我对代码的修改,以解决此问题和其他问题。我正在使用一个不同的龟包,并简化了一些东西,所以如果没有一些修改,它将无法直接用于你:

import java.awt.*;

class FractalEngine
{
    Turtle turt = new Turtle();

    public void drawFractal(String rule)
    {
        int lengthofRule = rule.length();

        for (int position = 0; position < lengthofRule; position++)
        {
            char tinyChar = rule.charAt(position);

            if (tinyChar == 'F')
                turt.forward(25);
            else if (tinyChar == '-')
                turt.left(90);
            else if (tinyChar == '+')
                turt.right(90);
            else
                break;
        }
    }

    public static void main(String[] args)
    {
        FractalEngine fEng = new FractalEngine();

        String rule = "F-F+F+F-F-F-F+F+F-F+F-F+F+F-F+F-F+F+F-F-F-F+F+F-F";

        fEng.drawFractal(rule);
    }
}

<强>输出

enter image description here

当提出这样的问题时,请确保指出你的乌龟图形库来自哪里,因为有几个并且它们不完全相同。