2013-09-29 31 views
-2

我正在寻找一种方式,以便每次在某个地方龟会产生一个点时,计数器变量将会增加一个,但只有该变量在该确切位置响应一个点,所以有效地记录了一只乌龟在特定位置制作点的次数。例如:确定一只海龟在某个地点点了多少次

x=0 
if (turtle.dot()): 
     x+1 

但很明显在这种情况下,计数将增加任何位置的点。提前致谢! C

+0

没有,只是在寻找一种方式来监测的次数一只乌龟已经取得了一定的点一个点我正在写一个程序。 – Randoms

+0

你知道现场的位置吗? – martineau

+0

没有它应该是一般的任何地方,任何或所有需要的地方。 – Randoms

回答

0

你可以使用一个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 
+0

这似乎是一个很好的解决方案,但是还有一种方法来表示当前位置的值。所以我可以像print(self.dots [self.position()])? – Randoms

+0

是的,你可以做这样的事情 - 参见我在我的答案更新中添加的'print_count()'方法。当你这样做时,你必须小心,不要在'dots'字典中添加一个条目,当你真正想要做的只是从它得到一个值,如果它已经存在。 – martineau

0

您能否使用返回笛卡尔坐标的turtle.pos()来检查乌龟的位置以及点的位置?

if ((turtle.pos() == (thisX, thisY)) and turtle.dot()): 
    x+1 
+0

然而,这将工作得很好,我需要将它用于任何可能的点。有没有办法对其进行修改以便可能? – Randoms

+0

如果它适用于其中一个,它应该在画布上使用任何笛卡尔“点”。只需将'thisX,thisY'设置为您要监控的坐标即可。 – AGHz