4

I have two turtles in my program. An animation happened where they collide together, but I would like one turtle to be on top of the other like this:

Visual Image

So, my question is - how can I make this happen - is there a simple line of code such as: turtle.front(), if not what is it?

cdlane
  • 40,441
  • 5
  • 32
  • 81
A Display Name
  • 367
  • 1
  • 9
  • 18

2 Answers2

3

I discuss this briefly in my response to Make one turtle object always above another where the rule of thumb for this simple situation is:

last to arrive is on top

Since Python turtle doesn't optimize away zero motion, a simple approach is to move the turtle you want on top by a zero amount:

import turtle

def tofront(t):
    t.forward(0)

gold = turtle.Turtle("square")
gold.turtlesize(5)
gold.color("gold")
gold.setx(-10)

blue = turtle.Turtle("square")
blue.turtlesize(5)
blue.color("blue")
blue.setx(10)

turtle.onscreenclick(lambda x, y: tofront(gold))

turtle.done()

The blue turtle overlaps the gold one. Click anywhere and the situation will be reversed.

Although @Bally's solution works, my issue with it is that it creates a new turtle everytime you adjust the layering. And these turtles don't go away. Watch turtle.turtles() grow. Even my solution leaves footprints in the turtle undo buffer but I have to believe it consumes less resources.

Community
  • 1
  • 1
cdlane
  • 40,441
  • 5
  • 32
  • 81
1

Just add this to turtle.py file

def tofront(self, tobring):
    newfront = tobring.clone()
    tobring.ht()
    return newfront

works correct, so method - sould return you new clone of turtle, on the top of all other turtles. parameter tobring - it's your current turtle (the one you want to bring to front)

you can use this def in your program or put it into turtle.py file if so, don't forget to add it to list of commands, - _tg_turtle_functions

_tg_turtle_functions = ['back', 'backward', 'begin_fill', 'begin_poly', 'bk',
    'circle', 'clear', 'clearstamp', 'clearstamps', 'clone', 'tofront', 'color',

I did it after clone command

Hope this will help you

Bally
  • 11
  • 2
  • 2
    This solution creates a new turtle every time the layering is adjusted and these turtles hang around (see `turtle.turtles()`) I've provided a simpler alternate answer to this question that doesn't involve creating new turtles. – cdlane Apr 08 '17 at 02:29