削减程序中的代码并使其更整洁

Cutting the codes in the program and making it neater

我很难切割代码并将其放入循环中,以便使程序代码更整洁。

尽管我的代码按预期工作,但我认为有一种正确的创建方法,即添加一个 for 循环而不是编写所有这些代码,我知道有一种简单的方法可以做到这一点,我只是不知道如何正确地做。我知道我应该创建一个 for 循环。

正方形

from graphics import *

def main():
    win = GraphWin("Squares", 500, 500)
    
    
    rect = Rectangle(Point(0,500), Point(500,0))
    rect.setFill("Red")
    rect.draw(win)
    
    rect2 = Rectangle(Point(20,480), Point(480,20))
    rect2.setFill("white")
    rect2.draw(win)
    
    rect3 = Rectangle(Point(40,460), Point(460,40))
    rect3.setFill("red")
    rect3.draw(win)
    
    rect4 = Rectangle(Point(60,440), Point(440,60))
    rect4.setFill("white")
    rect4.draw(win)
    
    rect5 = Rectangle(Point(80,420), Point(420,80))
    rect5.setFill("red")
    rect5.draw(win)
    
    rect6 = Rectangle(Point(100,400), Point(400,100))
    rect6.setFill("white")
    rect6.draw(win)
    
    rect7 = Rectangle(Point(120,380), Point(380,120))
    rect7.setFill("red")
    rect7.draw(win)
    
    rect8 = Rectangle(Point(140,360), Point(360,140))
    rect8.setFill("white")
    rect8.draw(win)
    
    rect9 = Rectangle(Point(160,340), Point(340,160))
    rect9.setFill("red")
    rect9.draw(win)
    
    rect10 = Rectangle(Point(180,320), Point(320,180))
    rect10.setFill("white")
    rect10.draw(win)
    
    rect11 = Rectangle(Point(200,300), Point(300,200))
    rect11.setFill("red")
    rect11.draw(win)
    
    rect12 = Rectangle(Point(220,280), Point(280,220))
    rect12.setFill("white")
    rect12.draw(win)

结果显示正方形拼凑而成

尝试以下操作:

from graphics import *

def main():
    win = GraphWin("Squares", 500, 500)

    # create all rects
    rects = [Rectangle(Point(0 + 20*i,500 - 20*i), Point(500 - 20*i, 0 + 20*i)) for i in range(12)]

    # draw all rects
    for idx, rect in enumerate(rects):
        rect.fill("red" if idx % 2 == 0 else "white")
        rect.draw(win)

如果拼凑物只是一个背景并且您不打算修改它,您可以使用这个:

from graphics import *

def main():
    win = GraphWin("Squares", 500, 500)

    i = 1
    for x in range(0, 221, 20):
        rect = Rectangle(Point(x, 500 - x), Point(500 - x,x))
        rect.setFill("red" if i % 2 else "white")
        rect.draw(win)
        i += 1

由于使用矩形的轮廓作为 其他 颜色,只需绘制一半数量的矩形的替代方法:

SQUARE, WIDTH = 500, 20

def main():
    win = GraphWin("Squares", SQUARE, SQUARE)

    save_config = dict(DEFAULT_CONFIG)

    DEFAULT_CONFIG.update(dict(outline='red', fill='white', width=WIDTH))

    for xy in range(WIDTH//2, SQUARE//2, WIDTH*2):
        Rectangle(Point(xy, SQUARE - xy), Point(SQUARE - xy, xy)).draw(win)

    DEFAULT_CONFIG.update(save_config)

它已完全参数化,因此您可以通过调整 SQUAREWIDTH 参数使其适合不同大小的正方形或具有不同宽度的条纹。它不是使用当前设置的参数绘制 12 个交替颜色的矩形,而是绘制 6 个带有红色轮廓的白色矩形: