首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我的循环还在运行?(Python Zelle Graphics)

为什么我的循环还在运行?(Python Zelle Graphics)
EN

Stack Overflow用户
提问于 2019-03-29 11:15:26
回答 1查看 127关注 0票数 2

我试图弄清楚为什么我的一个函数中的while循环即使在我的图形中的点相等之后仍然运行,这是当我设置它停止的时候。我有什么地方做错了吗?我试着换其他的东西来让它工作,但是没有成功。它是针对游戏的--当角色到达endbox时,循环需要中断,但在我显式编码之后,它并没有这样做。它在我的第二个函数中:

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2019-03-29 12:20:27

我认为这可能是由于浮点数的精确度造成的。我猜pete.getCenter()和endbox.getCenter()有点像float,float,你应该避免在float之间使用!=,比如1.0000001不等于1。

因此,即使角色到达端框,该位置仍将获得一点浮动偏移。

因此,当错误可以接受时,您可以将a != b更改为abs(a - b) > acceptable_error。示例代码如下:

代码语言:javascript
复制
# while peteloc != endbox.getCenter():
while abs(peteloc.getX() - endbox.getCenter().getX()) > 0.01 and abs(peteloc.getY() - endbox.getCenter().getY()) > 0.01:

希望这会对你有所帮助。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55409994

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档