java创建一个Turtle实现 Turtle Graphics API 的功能
时间: 2023-06-08 21:09:16 浏览: 76
java turtle graphics
5星 · 资源好评率100%
Java可以通过创建一个Turtle类实现Turtle Graphics API的功能。下面是一个简单的实现示例:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.util.ArrayList;
public class Turtle {
private Point position;
private double angle;
private boolean penDown;
private Color penColor;
private ArrayList<Point> path;
public Turtle() {
position = new Point(0, 0);
angle = 0;
penDown = true;
penColor = Color.BLACK;
path = new ArrayList<>();
}
public void draw(Graphics g) {
g.setColor(penColor);
for (int i = 0; i < path.size() - 1; i++) {
Point p1 = path.get(i);
Point p2 = path.get(i + 1);
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
}
public void penDown(boolean down) {
penDown = down;
}
public void setPenColor(Color color) {
penColor = color;
}
public void forward(double distance) {
double newX = position.x + distance * Math.cos(Math.toRadians(angle));
double newY = position.y + distance * Math.sin(Math.toRadians(angle));
Point newPoint = new Point((int) newX, (int) newY);
if (penDown) {
path.add(position);
path.add(newPoint);
}
position = newPoint;
}
public void turn(double degrees) {
angle += degrees;
}
public void setPosition(int x, int y) {
position = new Point(x, y);
}
}
```
该类包含了笔的位置、方向、颜色等属性,以及前进、旋转、设置位置等方法,可以实现良好的绘图效果。
阅读全文