Python 确定海龟在某个位置上做了多少次圆点
我在寻找一种方法,每当海龟在某个地方做一个点时,一个反变量将上升一,但该变量只对该确切位置上的一个点做出响应,因此有一个有效的记录,记录海龟在特定位置做一个点的次数。比如:Python 确定海龟在某个位置上做了多少次圆点,python,if-statement,turtle-graphics,Python,If Statement,Turtle Graphics,我在寻找一种方法,每当海龟在某个地方做一个点时,一个反变量将上升一,但该变量只对该确切位置上的一个点做出响应,因此有一个有效的记录,记录海龟在特定位置做一个点的次数。比如: x=0 if (turtle.dot()): x+1 但显然在这种情况下,任何位置的点的计数都会增加。提前谢谢!C您是否可以使用返回笛卡尔坐标的turtle.pos(),来检查海龟的位置,从而检查圆点 if ((turtle.pos() == (thisX, thisY)) and turtle.dot(
x=0
if (turtle.dot()):
x+1
但显然在这种情况下,任何位置的点的计数都会增加。提前谢谢!C您是否可以使用返回笛卡尔坐标的
turtle.pos()
,来检查海龟的位置,从而检查圆点
if ((turtle.pos() == (thisX, thisY)) and turtle.dot()):
x+1
您可以使用
collections.defaultdict
来计算点,并派生自己的Turtle
子类来帮助跟踪调用dot{}
方法的位置。调用dot()
时,defaultdict
的键将是海龟的x和y坐标
下面是我的意思的一个例子:
from collections import defaultdict
from turtle import *
class MyTurtle(Turtle):
def __init__(self, *args, **kwds):
super(MyTurtle, self).__init__(*args, **kwds) # initialize base
self.dots = defaultdict(int)
def dot(self, *args, **kwds):
super(MyTurtle, self).dot(*args, **kwds)
self.dots[self.position()] += 1
def print_count(self):
""" print number of dots drawn, if any, at current position """
print self.dots.get(self.position(), 0) # avoid creating counts of zero
def main(turtle):
turtle.forward(100)
turtle.dot("blue")
turtle.left(90)
turtle.forward(50)
turtle.dot("green")
# go back to the start point
turtle.right(180) # turn completely around
turtle.forward(50)
turtle.dot("red") # put second one in same spot
turtle.right(90)
turtle.forward(100)
if __name__ == '__main__':
turtle1 = MyTurtle()
main(turtle1)
mainloop()
for posn, count in turtle1.dots.iteritems():
print('({x:5.2f}, {y:5.2f}): '
'{cnt:n}'.format(x=posn[0], y=posn[1], cnt=count))
输出:
(100.00,50.00):1
(100.00, 0.00): 2
不,只是想寻找一种方法来监控海龟在我正在编写的程序的某个点上做点的次数。你知道该点的位置吗?不,一般来说,它应该用于任何点,任何或每一个需要的点。这将非常有效,但是,我需要将其用于任何可能的点。有没有一种方法可以修改它,使之成为可能?如果它可以使用一个,那么它应该使用画布上的任何笛卡尔“点”。只需将“thisX,thisY”设置为要监视的坐标。这似乎是一个好的解决方案,但也有一种方法可以表示位置的当前值。所以我可以像print(self.dots[self.position()])?是的,你可以像这样做——请参阅我在更新答案时添加的print\u count()
方法。在这样做的时候,你必须小心不要在dots
字典中添加条目,因为你真正想做的是从它那里获取一个值,如果它已经存在的话。