Hiding the turtle in python turtle drawing - python

I am trying to make it so that the turtle is hidden from the beginning of the program but even after putting t.hideturtle() right below where I declare the turtle as variable t the turtle still seems to show up in the middle of the drawing.
import turtle
from random import randint
s = turtle.getscreen()
t = turtle.Turtle()
t.hideturtle()
rx = randint(50,100)
ry = randint(50,100)
width, height = 32,32
s.screensize(width, height)
s.bgcolor("black")
t.goto(0,0)
t.speed(15)
num=10
while num<=1000:
r = randint(1,5)
if r == 1:
t.pencolor("white")
elif r == 2:
t.pencolor("#00FFFF")
elif r == 3:
t.pencolor("#89CFF0")
elif r == 4:
t.pencolor("#0000FF")
elif r == 5:
t.pencolor("#00FFFF")
t.right(25)
t.circle(num)
num=num+10
count=num//10
print("ran",count,"times")

This was a tricky one.
The key problem here is that your first statement creates one turtle and returns you its screen. That turtle remains visible. Your second statement creates a new turtle, which you hide. Change the order to:
t = turtle.Turtle()
s = t.getscreen()
and it all works as expected.

#TimRoberts writes:
The key problem here is that your first statement creates one turtle
and returns you its screen. That turtle remains visible. Your second
statement creates a new turtle, which you hide.
This is the problem with mixing turtle's object-oriented API and it's functional API. If we change the import to force just the object-oriented API, and block the functional one, we can do:
from turtle import Screen, Turtle
screen = Screen()
turtle = Turtle()
turtle.hideturtle()
or instead do:
from turtle import Screen, Turtle
turtle = Turtle()
turtle.hideturtle()
screen = Screen()
And it makes no difference. By mixing the functional API and the object-oriented API, you can easily unintentionally create the default turtle which isn't called for in this code.

I tried this line of code and it worked for me:
import turtle
turtle.hideturtle()

Related

Python turtle module

I'm currently new to python programming. Nowadays I'm building a snake game using the turtle module. I want to refresh the screen after every piece of snake object parts has moved. So I turned off the tracer and use the update function after the for loop.
But to do that I must import the time module and use the time.sleep() function.If I don't use it the python turtle module begins to not respond. I want to know what is the reason why I must use the time function and why I can't simply use sc.update directly without time function.
here is my code
from turtle import *
from snake import *
import time
sc = Screen()
sc.bgcolor('black')
sc.setup(width=600, height=600)
sc.tracer(0)
# diyego is our snake name
diyego = Snake(10)
run = 1
while run:
#here is the problem
sc.update()
time.sleep(1) #used time.sleep
for i in range(len(diyego.snake_object_list)-1, 0, -1):
infront_item_position = diyego.snake_object_list[i - 1].pos()
diyego.snake_object_list[i].goto(infront_item_position)
diyego.snake_head.forward(10)
sc.exitonclick()
#Snake module
from turtle import *
class Snake():
def __init__(self, number_of_parts):
"""Should pass the lenght of snake"""
self.snake_object_list = []
self.create_snake_parts(number_of_parts)
self.snake_head = self.snake_object_list[0]
def create_snake_parts(self, number_of_parts):
""" Get number of parts which snake shuld have and create snake it"""
x_cor = 0
for i in range(number_of_parts):
snake = Turtle()
snake.speed(0)
snake.shape("circle")
snake.color('white')
snake.penup()
snake.setx(x=x_cor)
self.snake_object_list.append(snake)
x_cor += -20
I just want to know why the turtle gets not respond when I remove the time.sleep()
What you describe is possible, but the problem isn't lack of use of the sleep() function but rather your use of (effectively) while True: which has no place in an event-driven world like turtle. Let's rework your code using ontimer() events and make the snake's basic movement a method of the snake itself:
from turtle import Screen, Turtle
CURSOR_SIZE = 20
class Snake():
def __init__(self, number_of_parts):
""" Should pass the length of snake """
self.snake_parts = []
self.create_snake_parts(number_of_parts)
self.snake_head = self.snake_parts[0]
def create_snake_parts(self, number_of_parts):
""" Get number of parts which snake should have and create snake """
x_coordinate = 0
for _ in range(number_of_parts):
part = Turtle()
part.shape('circle')
part.color('white')
part.penup()
part.setx(x_coordinate)
self.snake_parts.append(part)
x_coordinate -= CURSOR_SIZE
def move(self):
for i in range(len(self.snake_parts) - 1, 0, -1):
infront_item_position = self.snake_parts[i - 1].position()
self.snake_parts[i].setposition(infront_item_position)
self.snake_head.forward(CURSOR_SIZE)
def slither():
diyego.move()
screen.update()
screen.ontimer(slither, 100) # milliseconds
screen = Screen()
screen.bgcolor('black')
screen.setup(width=600, height=600)
screen.tracer(0)
diyego = Snake(10)
slither()
screen.exitonclick()

Turtle Text Flashing

When I attempt to put text over a turtle in the python turtle module, it flashes. Any solutions?
import turtle
s = turtle.Screen()
s.setup(width=500,height=600)
c = turtle.Turtle()
c.shapesize(stretch_len=5,stretch_wid=5)
c.goto(0,0)
c.shape("square")
pen = turtle.Turtle()
pen.hideturtle()
pen.goto(0,0)
pen.color("red")
while True:
pen.write("hello!")
s.update()
Although I don't see the flashing on my screen, my guess is your problem is related to this bad idiom:
while True:
# ...
s.update()
We need neither the while True: (which has no place in an event-driven environment like turtle) nor the call to update() (which is not needed given no previous call to tracer()). Let's rewrite this as turtle code:
from turtle import Screen, Turtle
screen = Screen()
screen.setup(width=500, height=600)
turtle = Turtle()
turtle.hideturtle()
turtle.shapesize(5)
turtle.shape('square')
turtle.stamp() # stamp a square so we can reuse turtle
pen = Turtle()
pen.hideturtle()
pen.color("red")
pen.write("Hello!", align='center', font=('Arial', 16, 'normal'))
screen.exitonclick()
Does that solve your problem?

Why my python kept crashing when it tried to run the turtle.tracer() method in turtle module?

I was coding a Snake Game using turtle module but when I add this line into my code the turtle screen and python crashed:
turtle.tracer(0)
can somebody help me so I can complete the game? Thanks a lot
my code:
from turtle import Turtle, Screen, colormode
screen = Screen()
screen.bgcolor("black")
screen.setup(width=600, height=600)
screen.title("My Snake Game")
screen.tracer(0)
x = 0
segments = []
for turtle in range(3):
turtle = Turtle("square")
turtle.color("white")
turtle.penup()
turtle.goto(0-x, 0)
x += 20
segments.append(turtle)
game_is_on = True
screen.update()
while game_is_on:
for segment in segments:
segment.forward(20)
screen.exitonclick()
I think we need to know more about what you mean by 'crashed'. If you mean everything froze, that's the code you wrote. Once you introduce tracer() you need to provide an update() for every change you want the user to see. But you don't have any update() calls in your loop so everything visually remains as it was before the loop. If you want to see the segments move, you need to do something like:
from turtle import Turtle, Screen
screen = Screen()
screen.bgcolor('black')
screen.setup(width=600, height=600)
screen.title("My Snake Game")
screen.tracer(0)
x = 0
segments = []
for turtle in range(3):
turtle = Turtle('square')
turtle.color('white')
turtle.penup()
turtle.setx(x)
x -= 20
segments.append(turtle)
screen.update()
game_is_on = True
while game_is_on:
for segment in segments:
segment.forward(20)
screen.update()
screen.exitonclick() # never reached
If you mean by 'crashed' that Python quit back to the operating system, then you need to describe the environment under which you're running this code.

Use onkey() to do multiple functions with Python turtle

I'm trying to write a basic turtle drawing game/program and I've been using onkey(function, "key") to have the user input keystrokes. Well I wanted the user to be able to change the width of the pen by either hitting the up key to increase the width by one, or the down key to decrease the width by one. I know I need some kind of loop, but I don't really know where to implement it.
Here's a simple example that will make the turtle walk in a continuous circle while you press up and down arrows to change the pen width:
from turtle import Turtle, Screen
def larger():
size = turtle.pensize()
if size < 10:
turtle.pensize(size + 1)
def smaller():
size = turtle.pensize()
if size > 1:
turtle.pensize(size - 1)
def move():
turtle.circle(150, extent=3)
screen.ontimer(move, 100)
turtle = Turtle()
screen = Screen()
screen.onkey(larger, "Up")
screen.onkey(smaller, "Down")
screen.listen()
move()
screen.mainloop()
Make sure you click on the window first to make it the key listener.
I think you can't, but you can call the function insde the function you bind to the key:
from turtle import *
def function1():
do_that = "do that"
print(do_that)
def function2():
do_this = "do this"
print(do_this)
function1()
onkey(function2, "space")
do this
do that
It worked for me ;)

Python - Keyboard Multiple Turtle Objects

I would like to create a program in which a Turtle object responds to key presses. I can do this, but I can't seem to understand how to move a second Turtle object, which is controlled by the computer, while the first one is moving. Any help would be appreciated.
Here is my code:
from turtle import *
from Tkinter import Tk
root = Tk()
root.withdraw()
turtle = Turtle()
def h1():turtle.forward(10)
def h2():turtle.left(45)
def h3():turtle.right(45)
def h4():turtle.back(10)
def h5(root=root):root.quit()
onkey(h1,"Up")
onkey(h2,"Left")
onkey(h3,"Right")
onkey(h4,"Down")
onkey(h5,"q")
listen()
root.mainloop()
Insert a second turtle before listen() that moves with keys w,a,s,d:
turtle2 = Turtle()
def h11():turtle2.forward(10)
def h21():turtle2.left(45)
def h31():turtle2.right(45)
def h41():turtle2.back(10)
onkey(h11,"w")
onkey(h21,"a")
onkey(h31,"d")
onkey(h41,"s")
I can't seem to understand how to move a second Turtle object, which
is controlled by the computer, while the first one is moving.
Below is some minimal code that does as you describe. Green turtle Pokey is computer controlled while red turtle Hokey is user controlled (click on the window first so your keystrokes are heard):
from turtle import Turtle, Screen
def move_pokey():
pokey.forward(10)
x, y = pokey.position()
if not (-width/2 < x < width/2 and -height/2 < y < height/2):
pokey.undo()
pokey.left(90)
screen.ontimer(move_pokey, 100)
hokey = Turtle(shape="turtle")
hokey.color("red")
hokey.penup()
pokey = Turtle(shape="turtle")
pokey.setheading(30)
pokey.color("green")
pokey.penup()
screen = Screen()
width = screen.window_width()
height = screen.window_height()
screen.onkey(lambda: hokey.forward(10), "Up")
screen.onkey(lambda: hokey.left(45), "Left")
screen.onkey(lambda: hokey.right(45), "Right")
screen.onkey(lambda: hokey.back(10), "Down")
screen.onkey(screen.bye, "q")
screen.listen()
screen.ontimer(move_pokey, 100)
screen.mainloop()
This is not finished code (shutdown of the timer event should be cleaner, Hokey's handlers should lock out additional events while running, etc.) but should give you a basic idea of how to go about it.

Categories