如题,最好能用递推式,我用if函数没做下去,请问能有大佬帮忙看看吗
1条回答 默认 最新
爱吃芒果的猴子 2023-05-25 15:09关注import turtle import random # 设置画布大小 turtle.setup(800, 600) # 随机生成矩形个数 num_rectangles = random.randint(5, 10) # 定义矩形宽度和高度的范围 min_width = 20 max_width = 100 min_height = 20 max_height = 100 # 定义已经绘制的矩形的位置和大小 rectangles = [] # 定义绘制矩形的函数 def draw_rectangle(x, y, width, height): turtle.penup() turtle.goto(x, y) turtle.pendown() turtle.setheading(0) turtle.forward(width) turtle.right(90) turtle.forward(height) turtle.right(90) turtle.forward(width) turtle.right(90) turtle.forward(height) # 循环绘制矩形 for i in range(num_rectangles): # 随机生成矩形的宽度和高度 width = random.randint(min_width, max_width) height = random.randint(min_height, max_height) # 随机生成矩形的位置,直到不与已经绘制的矩形重叠 while True: x = random.randint(-350, 350) y = random.randint(-250, 250) overlap = False for rect in rectangles: if x < rect[0] + rect[2] and x + width > rect[0] and y < rect[1] + rect[3] and y + height > rect[1]: overlap = True break if not overlap: break # 绘制矩形 draw_rectangle(x, y, width, height) # 将已经绘制的矩形的位置和大小添加到列表中 rectangles.append((x, y, width, height)) # 隐藏画笔 turtle.hideturtle() # 显示绘制结果 turtle.done()解决 无用评论 打赏 举报