Python Zelle 图形和 While 循环

我正在尝试创建不重叠的矩形抽认卡并将它们放置在 Zelle Graphics 中的随机位置。xMin 和 yMin 是矩形左上角的坐标,xMax 和 yMax 是矩形右下角的坐标。我尝试生成随机 (xCenter,yCenter) 坐标来创建一个新矩形,并检查新矩形是否与任何现有矩形重叠。如果重叠,则生成新的随机点,直到不再重叠为止。


我得到了检查重叠的功能,但后来我在 while 循环中遇到了问题。我是 Python 的初学者,因此非常感谢您的帮助!


from graphics import *

from random import randrange *


def checkLocation(xMin,xMax,yMin,yMax,xMinList,xMaxList,yMinList,yMaxList):

    for x in range (xMin,xMax):

        for y in range (yMin,yMax):

            for i in range(len(xMinList)):

                if xMinList[i] < x < xMaxList[i] and yMinList[i] < y < yMaxList[i]:

                    return False 

    #if the new rectangle isn't overlapping, append its 4 corner into the list for future comparison:                

    xMinList.append(xMin)

    xMaxList.append(xMax)

    yMinList.append(yMin)

    yMaxList.append(yMax)


    return xMinList,xMaxList,yMinList,yMaxList




def main():

    win = GraphWin("Flash Card", 800,800)

    xCenter, yCenter = randrange (200,600), randrange (200,600) #display the words from the text in randomly generated locations                   

    xMin = xCenter - 50

    xMax = xCenter + 50


    yMin = yCenter - 50

    yMax = yCenter + 50


    xMinList = [300,500,200,100,600] #I hard coded these 4 lists for the purpose of testing

    xMaxList = [350,580,220,140,650]


    yMinList = [100,500,300,600,400]

    yMaxList = [160,540,325,680,450]


    #while checkLocation is False (location overlapping), check again until it's True (not overlapping)

    while not checkLocation(xMin,xMax,yMin,yMax,xMinList,xMaxList,yMinList,yMaxList):

        checkLocation(xMin,xMax,yMin,yMax,xMinList,xMaxList,yMinList,yMaxList)

    xMinList, xMaxList,yMinList,yMaxList =  checkLocation(xMin,xMax,yMin,yMax,xMinList,xMaxList,yMinList,yMaxList)



    rect = Rectangle (Point(xMin,yMin),Point(xMax,yMax))

    rect.draw(win)

主要的()


白衣非少年
浏览 138回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python