方形用编程代码怎么绘制

时间:2025-01-23 21:59:51 游戏攻略

使用Python的turtle库

```python

import turtle

def draw_square():

创建绘图窗口

window = turtle.Screen()

window.title("Draw a Square")

window.bgcolor("white")

创建画笔

pen = turtle.Turtle()

pen.color("black")

pen.pensize(3)

绘制正方形的四条边

for _ in range(4):

pen.forward(100) 移动画笔向前

pen.right(90) 调整画笔角度

关闭绘图窗口

window.mainloop()

运行绘制正方形的函数

draw_square()

```

使用Python的matplotlib库

```python

import matplotlib.pyplot as plt

def draw_square():

fig, ax = plt.subplots()

ax.set_xlim(0, 1)

ax.set_ylim(0, 1)

ax.add_patch(plt.Rectangle((0, 0), 1, 1, edgecolor='black'))

plt.axis('off')

plt.show()

运行绘制正方形的函数

draw_square()

```

使用Java的Swing库

```java

import javax.swing.*;

import java.awt.*;

public class SquareDrawer {

public static void main(String[] args) {

SwingUtilities.invokeLater(() -> {

JFrame frame = new JFrame("Perfect Square Drawer");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(400, 400);

frame.add(new SquarePanel());

frame.setVisible(true);

});

}

public static class SquarePanel extends JPanel {

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

int width = getWidth();

int height = getHeight();

int squareSize = Math.min(width, height);

int x = (width - squareSize) / 2;

int y = (height - squareSize) / 2;

g.drawRect(x, y, squareSize, squareSize);

}

}

}

```

使用JavaScript在页面上输出正方形

```html

Draw Square