gpt4 book ai didi

python - randint() 只生成高值并且没有绘制足够的对象

转载 作者:行者123 更新时间:2023-12-01 03:03:05 25 4
gpt4 key购买 nike

对于这个项目,我需要在随机点绘制 400 个不同的正方形,并且彼此之间至少相距 5 个像素。目前,框大多绘制在窗口底部,并且在程序卡住之前只绘制了大约一半。我咨询了我的教授,他们被难住了。

#Importing things I need
import random
from graphics import *

def enterValue(used_spots, y_spots, corner1, corner2):
#enters the value where our square starts into the array, if it's a
#valid value.
used_spots.append(corner1)
y_spots.append(corner2)

def checkPlace(used_spots,y_spots,corner1,corner2):
#checks the placement of every square to see if our new one is valid.
# the total size of a square is 20px edge + 5 px Border + 3 px width.
# So we need to check based on that number.
slot=0
check=0
for slot in range(0,len(used_spots)):
#if the distance between the squares is more than 28 pixels, return
# true. Else, stop checking and return false
if abs(corner1-used_spots[slot])<28 and abs(corner2-y_spots[slot]<28):
check=0
break
else:
check=1
return check

def randomCorners():
#gets us a random variable for x and y of a box's corner
corner1=random.randint(3,1800-28)
corner2=random.randint(3,900-28)
return corner1, corner2

def drawBox(corner1,corner2,EDGE,WIDTH,colors,win):
#Draws the box
point1=Point(corner1,corner2)
point2=Point(corner1+EDGE,corner2+EDGE)
square=Rectangle(point1,point2)
square.setWidth(WIDTH)
square.setFill(random.choice(colors))
square.draw(win)

def main():
#delcaring variables
corner1=0
corner2=0
used_spots=[]
y_spots=[]
WIDTH=3
EDGE=20
colors=["red","orange","yellow","blue","pink","green"]
win=GraphWin("MAINWINDOW",1800,900)
win.setBackground("white")

#Draws a random box at a random spot, then makes a spot for a new potential box
#and tests it
corner1,corner2=randomCorners()
drawBox(corner1,corner2,EDGE,WIDTH,colors,win)
enterValue(used_spots,y_spots,corner1,corner2)
corner1,corner2=randomCorners()

while len(used_spots) < 400:
#If we can draw a box there, draw it and add coords to the lists,
#then generates a new set of coordinates.
if checkPlace(used_spots,y_spots,corner1,corner2)==1:
drawBox(corner1,corner2,EDGE,WIDTH,colors,win)
enterValue(used_spots,y_spots,corner1,corner2)

#otherwise, make a new coordinate and try again.
corner1,corner2=randomCorners()

main()

最佳答案

问题出在您的 checkPlace 函数中:

if abs(corner1-used_spots[slot])<28 and abs(corner2-y_spots[slot]<28):

应该是

if abs(corner1-used_spots[slot])<28 and abs(corner2-y_spots[slot])<28:

(注意最后一个括号的位置)。

您的代码将小于比较的结果传递给 abs 函数,而不是在比较中使用 abs 函数的结果。

因此,只要 corner2 小于 y_spots[slot] + 28,条件就会评估为 true(因为 abs 不是直到比较之后调用),这意味着较低的值(屏幕顶部)将触发它,并且如果它们也满足其他条件则被拒绝。最终,used_spotsy_spots 中会有足够的条目,至少有一个条目始终会触发 if 中的两个条件,并且程序会锁定、卡住在无限循环中尝试找到有效的坐标。

关于python - randint() 只生成高值并且没有绘制足够的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43646904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com