我试图弄清楚为什么我的一个函数中的while
循环仍然在运行,即使在图形中的点相等之后,也就是我将其设置为停止的时候。我做错什么了吗?我试着换其他东西让它工作,但运气不好。
这是为了一个游戏——当角色到达结束框时,循环需要中断,但在我显式地将其编码为之后,它就不会这样做了。这是我的第二个功能:
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()
Zelle graphics
Point
对象似乎永远不会以相等的方式进行比较:我们必须提取坐标并进行自己的比较。尽管@recnac提供了一个可行的解决方案(+1),但我将建议一个更通用的解决方案。我们将创建一个对从
_BBox
继承的任何对象都有效的distance()
方法,该方法包括Rectangle
、Oval
、Circle
和Line
:我们现在可以测量物体之间的距离,水平,垂直和对角线。因为你的盒子一次移动20个像素,我们可以假设如果它们彼此有1个像素,它们在同一个位置。重写代码以使用
distance()
方法和其他调整:我想可能是浮子的精度造成的。我想是吧皮特·盖特中心()和endbox.getCenter文件()类似于[float,float],应该避免在float之间使用
!=
,例如1.0000001不等于1。你知道吗因此,即使角色到达结束框,位置仍然会有一点浮动偏差。你知道吗
因此,当错误可以接受时,可以将
a != b
更改为abs(a - b) > acceptable_error
。示例代码如下:希望对你有帮助。你知道吗
相关问题 更多 >
编程相关推荐