java使用StdDraw创建一个Turtle实现 Turtle Graphics API中setPosition的功能
时间: 2023-06-08 18:08:34 浏览: 132
java turtle graphics
5星 · 资源好评率100%
可以使用以下代码实现:
```
import edu.princeton.cs.introcs.StdDraw;
public class Turtle {
private double x, y; // turtle position
private double angle; // turtle angle
// constructor
public Turtle(double x0, double y0, double a0) {
x = x0;
y = y0;
angle = a0;
}
// rotate the turtle's angle by delta degrees clockwise
public void turn(double delta) {
angle += delta;
}
// move the turtle forward a given distance
public void goForward(double distance) {
double oldx = x;
double oldy = y;
x += distance * Math.cos(Math.toRadians(angle));
y += distance * Math.sin(Math.toRadians(angle));
StdDraw.line(oldx, oldy, x, y);
}
// move the turtle backward a given distance
public void goBackward(double distance) {
goForward(-distance);
}
// set the turtle's position to (x, y)
public void setPosition(double x, double y) {
this.x = x;
this.y = y;
}
// set the turtle's angle to a
public void setAngle(double a) {
angle = a;
}
}
```
这个类中包含了最基本的海龟绘图 API:前进、后退、左转、右转、设置位置和方向。在 `setPosition` 方法中,只需要简单地将 `x` 和 `y` 的值设为相应的参数即可。
阅读全文