How to understand the operation of this Python Sierpinski code? - python

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.

Related

Fractal design for svg file

I'm very new to coding and I am attempting to create a box svg file with a fractal spiral design on one of the box wings. I'm having a difficult time with this and I'm hoping someone can offer some guidance as to where I'm going wrong.
Here is part of my code:
import turtle
def spiral(x, y):
spiral1 = turtle.setpos({},{})
return spiral1.format(x,y)
t = turtle.Turtle()
t.pensize(1)
t.pencolor('orange')
t.speed(0)
for i in range (10):
t.circle(10 + i, 45)
spiral_1 = spiral(int(box_x)*96, int(box_height)*96)
this is giving me an error:unsupported operand type(s) for * 'dict' and 'float'
Essentially what I want to do is write this spiral onto my actual svg file which has specific coordinates I've already defined (i.e box_height)). I'm not quite sure where to go from here. I'd really appreciate your help.
Edit: perhaps I need to figure out how to generate the pattern with svg code rather than turtle
I'm hoping someone can offer some guidance as to where I'm going wrong
I'm having a hard time figuring out where you went right:
spiral1 = turtle.setpos({},{})
This doesn't appear to be Python argument syntax and setpos() always returns None so there's no point in saving the result into spiral1.
return spiral1.format(x,y)
None doesn't have a format() method. Also, the return at this point in the code causes it to ignore the next six lines of code. Effectively, not drawing at all.
spiral_1 = spiral(int(box_x)*96, int(box_height)*96)
spiral() doesn't return anything useful, so no point saving the result. Let's rework your code so that it actually draws a spiral:
from turtle import Screen, Turtle
box_x, box_y = 96, 96
def spiral(x, y):
turtle.penup()
turtle.setposition(x, y)
turtle.pendown()
for i in range(100):
turtle.circle(10 + i, 45)
screen = Screen()
turtle = Turtle()
turtle.pencolor('orange')
turtle.speed('fastest')
spiral(box_x, box_y)
screen.exitonclick()
I don't see why this question is tagged [fractals]. Nor do I see why it's tagged [xml] and [svg] as it's a simple Python syntax and turtle graphics question. And you really shouldn't be getting started with Python 2.7 as it is no longer supported.

Why is Repl.it python turtle.tracer(n) limited to 150?

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.

Changing turtle cursor shape using Python

Is there a simple way to change the turtle cursor to an open hand and back to normal cursor?
I have searched and did not find a thing.
I'm using Python turtle on Windows.
Any answer is appreciated!
There are few preset shapes for turtle such as, arrow, circle, etc. You can find them here https://docs.python.org/3.3/library/turtle.html?highlight=turtle#turtle.shape, or you could use the turtle.register_shape(image_name) function. Hope this helps!
Is there a simple way to change the cursor to an open hand and back to
normal cursor?
Yes, you first want the register_shape() method of the screen, passing it your GIF file name. Then you pass the same file name to the shape() method of turtle. (Newer implementations of turtle and tkinter accept more file types but traditionally this needs to be a GIF.)
Demonstrating with a guinea pig GIF found on iconsplace.com, the following code switches from the turtle cursor that comes with the Python library to a guinea pig cursor from that site when you click on the window:
from turtle import Screen, Turtle
IMAGE = "guinea-pig-icon-24.gif"
def change(x, y):
turtle.shape(IMAGE)
screen = Screen()
screen.register_shape(IMAGE)
turtle = Turtle('turtle')
screen.onclick(change)
screen.mainloop()
Switching back again is simple as calling the shape() method again.

t=turtle.Pen() says turtle doesn't have the attribute Pen

After importing turtle, I keep trying to put t=turtle.Pen() but it says turtle doesn't have the attribute Pen.
I have tried
turtle=turtle.Pen()
t=turtle.Turtle()
myturtle=turtle.Pen()
my turtle =turtle.Turtle()
but every time it says turtle does not have attribute whatever I put as my attribute. Does anyone know why this is happening? I have python version 3.5.0
Here is a brief turtle example:
https://gist.github.com/wolfospealain/af3410a9e71eb2ff7be5625174c4f4c5
#!/usr/bin/python3.5
import turtle
turtle.shape("turtle")
turtle.left(45)
turtle.forward(50)
turtle.right(65)
turtle.circle(150,350)
turtle.home()
big=("Arial", 36, "normal")
turtle.penup()
turtle.goto(-40,150)
turtle.write("Hello World!", font=big)
turtle.home()
turtle.back(20)
turtle.exitonclick()
Notice how you must first import turtle to make the turtle library available to your program.
Notice, too, that all the method names are lower case (for example, turtle.penup()).
I think you probably meant turtle.penup(), which allows you to "move" without drawing.
You can find complete turtle documentation here: https://docs.python.org/3.3/library/turtle.html
Here is a short tutorial you might find helpful: https://www.tutorialspoint.com/turtle-programming-in-python

How do I change the Hitbox size of a turtle in python turtle graphics?

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

Categories