gpt4 book ai didi

Java Turtle 图形动画基础

转载 作者:太空宇宙 更新时间:2023-11-04 12:48:27 25 4
gpt4 key购买 nike

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

谢谢

  /**
* 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";
}
}

最佳答案

这段代码的问题与 turtle 无关——它完全与字符和字符串有关。

这不起作用:

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

下面是我对您的代码进行的修改,以解决这个问题和其他问题。我正在使用不同的 turtle 包,并且已经简化了一些事情,所以如果不进行一些修改,它不会直接为您工作:

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

当问这样的问题时,请务必指出您的 turtle 图形库来自哪里,因为有多个图形库,而且它们并不完全相同。

关于Java Turtle 图形动画基础,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36074841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com