我正在寻找一种方式,以便每次在某个地方龟会产生一个点时,计数器变量将会增加一个,但只有该变量在该确切位置响应一个点,所以有效地记录了一只乌龟在特定位置制作点的次数。例如:确定一只海龟在某个地点点了多少次
x=0
if (turtle.dot()):
x+1
但很明显在这种情况下,计数将增加任何位置的点。提前致谢! C
我正在寻找一种方式,以便每次在某个地方龟会产生一个点时,计数器变量将会增加一个,但只有该变量在该确切位置响应一个点,所以有效地记录了一只乌龟在特定位置制作点的次数。例如:确定一只海龟在某个地点点了多少次
x=0
if (turtle.dot()):
x+1
但很明显在这种情况下,计数将增加任何位置的点。提前致谢! C
你可以使用一个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
没有,只是在寻找一种方式来监测的次数一只乌龟已经取得了一定的点一个点我正在写一个程序。 – Randoms
你知道现场的位置吗? – martineau
没有它应该是一般的任何地方,任何或所有需要的地方。 – Randoms