java创建一个实现 turtle 图形 API 的类。编写将乌龟移动到指定位置、画笔颜色、画笔粗细、的函数
时间: 2023-06-09 15:05:53 浏览: 50
好的,可以的。以下是 Java 创建一个实现 Turtle 图形 API 的类的代码示例:
```java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Turtle extends JFrame {
// 画板
private DrawPanel drawPanel;
// 乌龟的位置和方向
private Point position;
private double direction;
// 画笔颜色和粗细
private Color penColor;
private int penWidth;
/**
* 构造函数
*/
public Turtle(int width, int height, Color penColor, int penWidth) {
setSize(width, height);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
drawPanel = new DrawPanel();
add(drawPanel);
this.penColor = penColor;
this.penWidth = penWidth;
direction = 0;
position = new Point(width / 2, height / 2);
}
/**
* 将乌龟移动到指定位置
*/
public void moveTo(int x, int y) {
position.x = x;
position.y = y;
}
/**
* 设置画笔颜色
*/
public void setPenColor(Color color) {
this.penColor = color;
}
/**
* 设置画笔粗细
*/
public void setPenWidth(int width) {
this.penWidth = width;
}
/**
* 向前移动指定距离
*/
public void forward(int distance) {
Point newPosition = new Point(
position.x + (int) Math.round(distance * Math.cos(Math.toRadians(direction))),
position.y - (int) Math.round(distance * Math.sin(Math.toRadians(direction)))
);
if (drawPanel.isDrawing()) {
drawPanel.drawLine(position, newPosition, penColor, penWidth);
}
position = newPosition;
}
/**
* 向左旋转指定角度
*/
public void left(double angle) {
direction += angle;
}
/**
* 向右旋转指定角度
*/
public void right(double angle) {
direction -= angle;
}
private class DrawPanel extends JPanel {
private boolean isDrawing;
public DrawPanel() {
isDrawing = true;
}
public boolean isDrawing() {
return isDrawing;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
}
public void drawLine(Point start, Point end, Color color, int width) {
Graphics g = getGraphics();
g.setColor(color);
g.fillRect(end.x, end.y, width, width);
g.drawLine(start.x, start.y, end.x, end.y);
}
}
}
```
调用示例:
```java
Turtle turtle = new Turtle(800, 600, Color.BLACK, 1);
turtle.setVisible(true);
turtle.moveTo(400, 300);
turtle.forward(100);
turtle.left(90);
turtle.setPenColor(Color.RED);
turtle.setPenWidth(5);
turtle.forward(50);
```