我试图弄清楚为什么我的一个函数中的while
循环即使在我的图形中的点相等之后仍然运行,这是当我设置它停止的时候。我有什么地方做错了吗?我试着换其他的东西来让它工作,但是没有成功。它是针对游戏的--当角色到达endbox时,循环需要中断,但在我显式编码之后,它并没有这样做。它在我的第二个函数中:
from graphics import *
def field():
#creating the window
win = GraphWin('The Field',400,400)
win.setBackground('white')
#drawing the grid
boxlist = []
for i in range(0,400,40):
for j in range(0,400,40):
box = Rectangle(Point(i,j),Point(i+40,j+40))
box.setOutline('light gray')
box.draw(win)
boxlist.append(box)
#creating other boxes
startbox = Rectangle(Point(0,0),Point(40,40))
startbox.setFill('lime')
startbox.setOutline('light gray')
startbox.draw(win)
endbox = Rectangle(Point(360,360),Point(400,400))
endbox.setFill('red')
endbox.setOutline('light gray')
endbox.draw(win)
boxlist.append(startbox)
boxlist.append(endbox)
#creating Pete
pete = Rectangle(Point(2,2),Point(38,38))
pete.setFill('gold')
pete.draw(win)
return win,boxlist,pete
def move(win2,boxlist,pete,endbox):
peteloc = pete.getCenter()
#creating loop to move pete
while peteloc != endbox.getCenter():
click = win2.getMouse()
x = click.getX()
y = click.getY()
peteloc = pete.getCenter()
petex = peteloc.getX()
petey = peteloc.getY()
#moving pete
if x>=petex+20 and y<=petey+20 and y>=petey-20:
pete.move(40,0)
elif x<=petex-20 and y<=petey+20 and y>=petey-20:
pete.move(-40,0)
elif y>=petey+20 and x<=petex+20 and x>=petex-20:
pete.move(0,40)
elif y<=petey-20 and x<=petex+20 and x>=petex-20:
pete.move(0,-40)
peteloc = pete.getCenter()
# The main function
def main():
win2,boxlist,pete = field()
endbox = boxlist[len(boxlist)-1]
move(win2,boxlist,pete,endbox)
main()
发布于 2019-03-29 12:20:27
我认为这可能是由于浮点数的精确度造成的。我猜pete.getCenter()和endbox.getCenter()有点像float,float,你应该避免在float之间使用!=
,比如1.0000001不等于1。
因此,即使角色到达端框,该位置仍将获得一点浮动偏移。
因此,当错误可以接受时,您可以将a != b
更改为abs(a - b) > acceptable_error
。示例代码如下:
# while peteloc != endbox.getCenter():
while abs(peteloc.getX() - endbox.getCenter().getX()) > 0.01 and abs(peteloc.getY() - endbox.getCenter().getY()) > 0.01:
希望这会对你有所帮助。
https://stackoverflow.com/questions/55409994
复制相似问题