慕尼黑5688855
关键是将所有东西参数化为合适大小的立方体,然后将填充代码变成可以调用来填充这些立方体的子程序。下面是沿着这些行重新编写的代码,可以将任何奇数 3 或更大的数作为输入处理:from graphics import *UNIT = 100def patchWork(win, size): blocks = size // 2 def hatch_box(x, y): for n in range(0, UNIT, UNIT//5): line = Line(Point(n + x * UNIT, y * UNIT), Point((x + 1) * UNIT, UNIT - n + y * UNIT)) line.draw(win) for n in range(UNIT, 0, -UNIT//5): line = Line(Point(n + x * UNIT, (y + 1) * UNIT), Point(x * UNIT, UNIT - n + y * UNIT)) line.draw(win) for n in range(UNIT, 0, -UNIT//5): line = Line(Point((x + 1) * UNIT, n + y * UNIT), Point(n + x * UNIT, (y + 1) * UNIT)) line.setFill('red') line.draw(win) for n in range(0, UNIT, UNIT//5): line = Line(Point(x * UNIT, UNIT - n + y * UNIT), Point(UNIT - n + x * UNIT, y * UNIT)) line.setFill('red') line.draw(win) for y in range(blocks): for x in range(blocks): hatch_box(x, y) for y in range(blocks + 1, 2 * blocks + 1): for x in range(blocks + 1, 2 * blocks + 1): hatch_box(x, y) def draw_circles(x, y): for o in range(0, UNIT, UNIT // 10): for c in range(0, UNIT, UNIT // 10): circle = Circle(Point(c + UNIT // 20 + x * UNIT, o + UNIT // 20 + y * UNIT), UNIT // 20) circle.setFill('blue') circle.draw(win) for y in range(blocks): for x in range(blocks + 1, 2 * blocks + 1): draw_circles(x, y) draw_circles(y, x) def draw_cube(x, y): cube = Rectangle(Point(x * UNIT, y * UNIT), Point((x + 1) * UNIT, (y + 1) * UNIT)) cube.setFill('yellow') cube.draw(win) x = blocks for y in range(0, 2 * blocks + 1): draw_cube(x, y) draw_cube(y, x)def layout(size): win = GraphWin('Patchwork', size * UNIT, size * UNIT) for i in range(0, size * UNIT, UNIT): Line(Point(i, 0), Point(i, size * UNIT)).draw(win) Line(Point(0, i), Point(size * UNIT, i)).draw(win) return windef main(): patchWorkSize = int(input("What patchwork size would you like? ")) if patchWorkSize % 2 == 1 and patchWorkSize > 2: win = layout(patchWorkSize) patchWork(win, patchWorkSize) win.getMouse() # pause for click in window win.close() else: print('Only odd sizes 3 or greater are available')main()你应该能够UNIT在合理范围内改变。