用Python画一个七巧板拼出来的船
时间: 2023-11-16 17:15:36 浏览: 182
C++面向对象-课程设计题目(2018版).docx
以下是使用Python turtle库绘制七巧板拼出来的船的示例代码:
```python
import turtle
# 定义七巧板的7个木块,每个木块用一个列表表示,其中每个元素表示一个块的位置
blocks = [
[(0, 0), (0, 1), (0, 2), (0, 3), (0, 4)],
[(0, 0), (0, 1), (0, 2), (0, 3), (1, 3)],
[(0, 0), (0, 1), (0, 2), (1, 2), (1, 3)],
[(0, 0), (0, 1), (1, 1), (1, 2), (2, 2)],
[(0, 0), (1, 0), (1, 1), (1, 2), (2, 2)],
[(0, 0), (0, 1), (1, 1), (1, 2), (2, 1)],
[(0, 0), (0, 1), (1, 1), (2, 1), (2, 2)]
]
# 定义每个木块的颜色
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple', 'brown']
# 定义船的颜色
ship_color = 'black'
# 创建画布和画笔
canvas = turtle.Screen()
pen = turtle.Turtle()
# 定义函数,用于绘制一个木块
def draw_block(block, color):
pen.penup()
pen.goto(block[0][1] * 30, -block[0][0] * 30)
pen.pendown()
pen.color(color)
pen.begin_fill()
for pos in block[1:]:
pen.goto(pos[1] * 30, -pos[0] * 30)
pen.goto(block[0][1] * 30, -block[0][0] * 30)
pen.end_fill()
# 绘制船的底部
pen.penup()
pen.goto(-60, -120)
pen.pendown()
pen.color(ship_color)
pen.begin_fill()
pen.goto(60, -120)
pen.goto(60, -90)
pen.goto(-60, -90)
pen.goto(-60, -120)
pen.end_fill()
# 绘制船的帆
pen.penup()
pen.goto(-60, 0)
pen.pendown()
pen.color(ship_color)
pen.begin_fill()
pen.goto(-60, 30)
pen.goto(0, 60)
pen.goto(60, 30)
pen.goto(60, 0)
pen.goto(-60, 0)
pen.end_fill()
# 绘制每个木块
for i in range(7):
draw_block(blocks[i], colors[i])
# 隐藏画笔
pen.hideturtle()
# 显示画布
canvas.mainloop()
```
运行以上代码后,将会在窗口中显示一个七巧板拼出的船。其中,船的颜色为黑色,每个木块使用不同的颜色。
阅读全文