I'm making a recursive drawing of a tree using repl.it py turtle. This is my code
import turtle
import random
def about(x): return x * random.uniform(0.95,1.05)
# recursively draw a tree
def tree(t,a,s):
if s<2: return
t.left(a)
t.fd(s)
tree(t.clone(),about(30), s * about(.7))
tree(t,about(-30), s * about(.7))
t = turtle.getpen()
t.ht(); t.speed(0); t.tracer(0)
tree(t,90,40)
t.update()
Also here. But it only draws part of the tree. If I change it to
t.tracer(150)
then it works! Also tracer(10) works, but tracer(200) does not work. Is there a limit to how high tracer can go?
First, let's discuss your drawing code. Your tree consists of about 500 lines drawn by 500 different turtles! This seems excessive, so let's rewrite your code to use a single turtle that undoes it's movements rather clone itself:
from turtle import Screen, Turtle
from random import uniform
def about(x):
return x * uniform(0.95, 1.05)
# recursively draw a tree
def tree(t, a, s):
if s < 2:
return
t.forward(s)
t.left(a)
tree(t, about(30), s * about(0.7))
t.right(2 * a)
tree(t, about(-30), s * about(0.7))
t.left(a)
t.backward(s)
screen = Screen()
screen.tracer(0)
turtle = Turtle()
turtle.hideturtle()
turtle.setheading(90)
tree(turtle, 15, 50)
screen.tracer(1)
screen.mainloop()
As far as tracer() is concerned, I wasn't able to reproduce your results but the image never completed either. The argument to tracer() specifies that you only want to update the image on every nth graphic operation. This is very specialized and I only recommend values of 0 and 1. First, it's difficult to calculate what every nth update should be, based on the algorithm, and what makes sense visually to the user. Second, in standard Python turtle, there are some operations that cause an update regardless of tracer() setting which throws off this calculation, unless you know when these extra update occur.
In your case, for speed purposes, set tracer(0) when the intense drawing begins, and set tracer(1) when you're done drawing. Then everything should work fine.
Related
I thought using Screen.tracer(0) disabled animation in Python Turtle Graphics. However in the following program, if you comment out screen.update(), there is still some animation happening - the turtle trail gets drawn although the turtle doesn't "move" (or get updated). What is happening here please? Is there way to make updating the screen completely manual?
import turtle
def move():
my_turtle.forward(1)
my_turtle.right(1)
screen.update() # Comment out this line to see issue.
screen.ontimer(move, 10)
screen = turtle.Screen()
my_turtle = turtle.Turtle()
my_turtle.shape("turtle")
screen.tracer(0)
move()
turtle.done()
No, screen.tracer(0) doesn't stop all animation. Some turtle commands like end_fill() invoke screen.update() directly, some like dot() invoke it due to other methods that they in turn invoke. You only advise the system when you call update(), not control it completely.
Put your update() calls where you believe you need them, and don't assume certain methods force an update, otherwise future updates of turtle might break your code. (I.e. someone might actually fix turtle.)
For potentially helpful details, see my tracer() rules of thumb and information about the first argument's numeric value
In turtle.py, forward() calls _go() which sets an endpoint, then calls _goto()
_goto() creates a newline if line segments get above 42
if len(self.currentLine) > 42: # 42! answer to the ultimate question
# of life, the universe and everything
self._newLine()
The value appears to be arbitrary; you could set it to something higher, but then there are pauses where nothing appears to be happening.
def _newLine(self, usePos=True):
"""Closes current line item and starts a new one.
Remark: if current line became too long, animation
performance (via _drawline) slowed down considerably.
"""
I have found this code on this website, and I have a few questions about it. I have already made a Sierpinski triangle on Python using my rudimentary knowledge and it is way too long and very bad.
I've done it using functions and some variables, but I have some questions with this code I have found. First of all, what is the "T" constantly brought up, the length and depth, and where is this all given a value. Where is the length and depth specified, and what does it do to the code?
Please note I am a beginner.
Here is the code:
import turtle
def draw_sierpinski(length,depth):
if depth==0:
for i in range(0,3):
t.fd(length)
t.left(120)
else:
draw_sierpinski(length/2,depth-1)
t.fd(length/2)
draw_sierpinski(length/2,depth-1)
t.bk(length/2)
t.left(60)
t.fd(length/2)
t.right(60)
draw_sierpinski(length/2,depth-1)
t.left(60)
t.bk(length/2)
t.right(60)
window = turtle.Screen()
t = turtle.Turtle()
draw_sierpinski(100,2)
window.exitonclick()
t = turtle.Turtle()
t is an instance of the class Turtle located in the module turtle that is previously imported
import turtle
As the instance t is in the global scope the python interpreter is able to find it, even within the function draw_sierpinski(length,depth)
I have no idea where you obtained the code however here are the docs for the turtle module.
To find out what the code does try it by yourself. Just pip install turtle and run the code
From the turtle docs
Turtle graphics is a popular way for introducing programming to kids.
It was part of the original Logo programming language developed by
Wally Feurzig and Seymour Papert in 1966. Imagine a robotic turtle
starting at (0, 0) in the x-y plane. After an import turtle, give it
the command turtle.forward(15), and it moves (on-screen!) 15 pixels in
the direction it is facing, drawing a line as it moves. Give it the
command turtle.right(25), and it rotates in-place 25 degrees
clockwise.
I dont know how to change the size of a turtle hitbox in python turtle graphics
I haven't tried anything yet because I'm new, and know very little about this. I've tried googling it, though, but nothing popped up.
from turtle import *
import turtle
from random import randint
import time
screen = turtle.Screen()
screen.setup(1920, 1080)
player = turtle.Turtle()
I want to add a button that you have to click to start right here
The game starts right here :
wn = turtle.Screen()
last_pressed = 'up'
def setup(col, x, y, w, s, shape):
player.penup()
player.up()
player.goto(x,y)
player.width(w)
player.turtlesize(s)
player.color(col)
player.lt(90)
player.down()
wn.onkey(up, "s")
wn.onkey(left, "d")
wn.onkey(right, "a")
wn.onkey(back, "w")
wn.onkey(quitTurtles, "Escape")
wn.listen()
wn.mainloop()
This may not be exactly what you are looking for, but this might work in your situation.
Detecting collision in Python turtle game
This is a thread on collision detection between objects and with some tweaking of numbers you could increase the hitbox of the turtle using the abs() function
I dont know how to change the size of a turtle hitbox in python turtle graphics
What do you mean by "hitbox"? I'm not sure what you mean by that (and neither does Google, apparently).
Do you mean that you want a rectangular button to click on? If that's the case, you could use the tkinter module together with the turtle module to create a button to click. (But be aware that it's not always easy to get the tkinter and turtle modules to work together to do what you want.)
If you want a button to click on, but don't need a Tkinter button, you could just try creating a new turtle in the shape of a rectangle that intercepts mouse clicks with onclick(). You can see an example of this if you run:
python3 -m turtledemo
and select Examples >> colormixer from the main menubar.
Or, if by "hitbox" you mean how to detect when one turtle has intercepted another turtle (as in, one has come close enough to the other to be considered a "hit"), I suggest querying each turtle's location, then using the Pythagorean Theorem to calculate the distance from each other. If this distance is within a predetermined threshold, consider the hitbox as being "hit."
You can see an example of this by typing:
python3 -m turtle
(Pay attention to the yellow turtle as he tries to catch up to the other turtle.)
I apologize if this answer isn't quite what you're looking for, but I'm just not sure what you mean by "hitbox." Maybe you could clarify?
I just saw this question today (2 years too late i know), and was having a similar problem / question.
What I ended up doing was running 3 distance checks (as i had increased my object size by 3) which differed along the x-axis (width). So it would check the distance between the ball(turtle) and the paddle (any 3 points and if it was shorter than X it would trigger the collision mechanic.
so it was something like :
check the ball class' ball object, and see how far away it is from the paddle,
and if its either in the center, or 30 pixels to the left or right of the center then hit.
if
ball.ball.distance(pad.paddle(), pad.paddle.ycor()) < 30 or
ball.ball.distance(pad.paddle.xcor() - 30, pad.paddle.ycor()) < 30 or
ball.ball.distance(pad.paddle.xcor() + 30, pad.paddle.ycor()) < 30
I am creating a game in python using turtle but I am unable to control the speed of the turtle in the loop as the speed of the turtle is 0. It is supposed to run like flash but it is running at normal speed
import turtle
c=turtle.Screen()
a=turtle.Turtle()
a.speed(0)
b=True
def ch( a , d):
global b
b = False
while b:
a.fd(1)
c.onclick(ch)
c.mainloop()
speed(0) can only speed up the animations a bit.
Try using c.tracer(0, 0)
This fully disables all animations, and should result it a bit more of a speed up. Although, to refresh the screen you'll need to call c.update()
First, your code is structured incorrectly. You don't need to call onclick() in a loop, it simply sets a handler function so only needs to be called once. Also, mainloop() should be running the events, not called after the events are over.
I don't believe you're going get any more speed out of this code unless you increase the forward distance. Simply increading to fd(3) will make a noticeable differece. My rework of your code:
from turtle import Turtle, Screen
def click_handler(x, y):
global flag
flag = False
def turtle_forward():
if flag:
turtle.forward(3)
screen.ontimer(turtle_forward, 0)
flag = True
screen = Screen()
screen.onclick(click_handler)
turtle = Turtle()
turtle.speed('fastest')
turtle_forward()
screen.mainloop()
Is there a way in pygame for sprites, when dragged, to snap to an invisible (or visible) grid? Kinda like drag 'n drop? If so, how? I've been trying to do some sprite overlap, but it's too tedious to make an if-statement for each of the grid-lines. So how can I make a snap-to-grid drag-n-drop sprite? This is for a chess program. I'll appreciate your help.
Make an array of corners of the chess board using for loops.
corners = []
for x in range(edgeRight, edgeLeft, interval):
for y in range(edgeTop, edgeBottom, interval):
corners.append((x,y))
Then, make an event listener. When the piece is being dragged around, insert this code into whatever while statement you have:
px, py = Piece.Rect.topleft //using tuples to assign multiple vars
for cx, cy in corners:
if math.hypot(cx-px, cy-py) < distToSnap:
Piece.setPos((cx,cy))
break
I have no idea what your actual code is, but this should give you an idea. Again, pygame has no snap-to-grid functionality.
So this can be done quite simply by using the round function in python.
sprite.rect.x = ((round(sprite.rect.x/gridSquareSize))*gridSquareSize)
sprite.rect.y = ((round(sprite.rect.y/gridSquareSize))*gridSquareSize)
This manipulates the round function, by rounding your sprite's coordinates to the nearest grid square.