タートルが特定の場所にドットを作成するたびに、カウンター変数が 1 ずつ増加する方法を探していますが、その変数はその正確な場所のドットにのみ応答するため、効果的にどのように記録されるかが記録されます。タートルが特定の場所に点を作ったことは何度もあります。何かのようなもの:
x=0
if (turtle.dot()):
x+1
ただし、明らかにこのシナリオでは、任意の位置のドットのカウントが増加します。前もって感謝します!ハ
タートルが特定の場所にドットを作成するたびに、カウンター変数が 1 ずつ増加する方法を探していますが、その変数はその正確な場所のドットにのみ応答するため、効果的にどのように記録されるかが記録されます。タートルが特定の場所に点を作ったことは何度もあります。何かのようなもの:
x=0
if (turtle.dot()):
x+1
ただし、明らかにこのシナリオでは、任意の位置のドットのカウントが増加します。前もって感謝します!ハ
a を使用しcollections.defaultdict
てドットを数え続け、独自のサブクラスを派生させて、メソッドが呼び出されたTurtle
場所を追跡することができます。dot{}
のキーは、呼び出されたdefaultdict
ときのタートルの x 座標と y 座標になります。dot()
ここに私が意味するものの例があります:
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