【问题标题】:Nested for loops not functioning嵌套的 for 循环不起作用
【发布时间】:2013-12-21 08:39:51
【问题描述】:

我有这个代码:

def makeBoard():
    squareX = 0
    squareY = 0
    squareType = "dark"
    darkSquare = imageLoader("darkBrownSquare.png")
    lightSquare = imageLoader("lightBrownSquare.png")
    for x in range(8):
        for y in range(8):
            if squareType == "dark":
                MAIN_SURF.blit(darkSquare, (squareX, squareY))
                squareType = "light"
            elif squareType == "light":
                MAIN_SURF.blit(lightSquare, (squareX, squareY))
                squareType = "dark"
            squareY += 64
        squareX += 64

它是用来绘制棋盘图案的,但我只得到了这个: 我认为这是因为 for 循环以及它们是嵌套的事实,但除此之外,我不知道。

【问题讨论】:

    标签: for-loop python-3.x pygame


    【解决方案1】:

    完成循环后你需要将 squareY 归零。

    那么之后

    squareX +=64
    

    只需添加

    squareY = 0
    

    此外,如果您使用 range 函数 step 参数并使用 x 和 y 而不是 squareX 和 squareY,您可以编写更易读的代码(这也将处理此错误)

    【讨论】:

      【解决方案2】:

      摆脱squareXsquareY 的东西,从一开始就创建正确的xy 值:

      for x in range(0, 64, 8):
          for y in range(0, 64, 8):
      

      或者将它们乘以8

      MAIN_SURF.blit(darkSquare, (8 * x, 8 * y))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-03
        • 1970-01-01
        • 2016-10-10
        • 1970-01-01
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多