Question

I am looking for a way so that every time a turtle makes a dot in a certain place, a counter variable will go up by one, but that variable only responds to a dot in that exact location, so there is effectively a record of how many times a turtle has made a dot in a specific location. Something like:

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

but obviously in this scenario, the count will increase for a dot of any position. Thanks in advance! C

Était-ce utile?

La solution

You could use acollections.defaultdictto keep count the dots and derive your own Turtle subclass to help keep track of where thedot{}method is called. The key for thedefaultdictwill be the x and y coordinates of the turtle when dot() was called.

Here an example of what I mean:

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))

Output:

(100.00, 50.00): 1
(100.00,  0.00): 2

Autres conseils

Could you use turtle.pos(), which returns Cartesian coordinates, to check the position of the turtle and consequently the dot?

if ((turtle.pos() == (thisX, thisY)) and turtle.dot()): 
    x+1
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top