I am writing a program for the Python Turtle module and I would like it to choose a position X distance away. So basically, from the turtle's present position it needs to choose a point no further or less than X distance away and have the ability to draw a line to that position. Additionally, it should chose this position at random so it is different almost every time.I know I should use the Pythagorean theorem and perhaps the randint module, but I can't figure out how to implement either.
Any help greatly appreciated!
Cheers!
5813
Say in this case, you want x to be 50
import turtle
from random import randint
x = 50
turtle = turtle.Turtle()
degrees = randint(0, 360)
turtle.left(degrees)
turtle.forward(x)
turtle.getscreen()._root.mainloop()
Related
So I have an assignment that asked me to draw any regular polygon using Turtle and I created the code. It works but my mentor said to try again. I would like to know what I did wrong, Thank you!
The requirements for this assignment are:
The program should take in input from the user.
The program should have a function that:
takes in the number of sides as a parameter.
calculates the angle
uses the appropriate angle to draw the polygon
from turtle import Turtle
turtle = Turtle()
side = int(input("Enter the number of the sides: "))
def poly():
for i in range(side):
turtle.forward(100)
turtle.right(360 / side)
poly()
I think this might be better suited on math stackexchange.
A regular polygon has interior angles (n−2) × 180 / n. Theres a good blog post on that here.
You just need to change the angle by which you rotate every time:
from turtle import Turtle
turtle = Turtle()
num_sides = int(input("Enter the number of the sides: "))
def poly():
for i in range(num_sides):
turtle.forward(100)
# change this bit
turtle.right((num_sides - 2) * 180 / num_sides)
poly()
This is the function I used to draw a polygon using Turtle:
Draws an n-sided polygon of a given length. t is a turtle.
def polygon(t, n, length):
angle = 360.0 / n
polyline(t, n, length, angle)
I am trying to make a turtle analog clock, and to make the second, minute, an hour hands I am making a shape with turtle, and using .tilt() to tilt it 6 degrees every second.
The thing is, when I run .tilt() it rotates the ship from the middle, whereas I want to have it rotate from the bottom point (like an analog clock).
Is there a way to do that, or do I need to find another way to make this program?
Here is my code:
from turtle import *
import time
turtle = Turtle()
turtle.shape("square")
turtle.shapesize(6, .1)
tilt_amnt = 0
for x in range (60):
turtle.tilt(tilt_amnt)
tilt_amnt = tilt_amnt + 6
time.sleep(1)
I don't think there is a way to tilt the turtle in such a way where it turns from the bottom but you can rewrite the code to essentially do the same thing but using forward instead. Check this out.
from turtle import *
import time
turtle = Turtle()
turtle.pensize(2)
turtle.hideturtle()
turtle.speed(0)
tilt_amnt = 0
for x in range (60):
turtle.right(tilt_amnt)
turtle.forward(100)
turtle.backward(100)
tilt_amnt = tilt_amnt + 6
time.sleep(1)
turtle.clear()
Some thoughts: first, I wouldn't use tilt() (high overhead, forces an update), even if you do use turtles as hands, consider using right() or setheading(); second, I would use mode('logo') as this makes 0 degrees the top of the screen and makes headings clockwise (like, say a 'clock') instead of counterclockwise; third, if you want accuracy, don't use sleep() but rather extract the current time from the system and set your hands accordingly.
Large real world clocks do turn their hands from the middle, or more specifially, the center of gravity. This keeps the hands from slowing the mechanism on the way up, or rushing it on the way down. The trick is to make the hands look visually asymmetric but keep the weight symmetric. Here's a solution I came up with earlier that does something like this with turtles as the hands, turning from their centers.
Finally, here's a rewrite of the example #AlexJoslin provided to use realtime accuracy, potentially updating hand positions multiple times within a second:
from turtle import Screen, Turtle
from time import localtime as time
def tick():
second.setheading(6 * time().tm_sec)
second.clear()
second.forward(150)
second.backward(150)
screen.update()
screen.ontimer(tick)
screen = Screen()
screen.mode('logo')
screen.tracer(False)
second = Turtle()
second.hideturtle()
second.pensize(2)
tick()
screen.exitonclick()
I'm creating a game in python that you can move around and try to collect points by colliding with a coin. I want to add 2D physics to it to make it realistic. Is there any way to do that? Thanks
The nature of simulations is that they are different than reality. As we perform a simulation, we create a mathematical model of the behavior of objects. Let's consider simulation of gravity. We define a ball, then we displace the location of the ball as time flows. Newton modeled the falling of a ball by x=gt^2. Therefore we must define an acceleration for the ball towards the ground. Much more information about simulation is available in this video.
You can use this code in order to simulate gravity:
yvel=5*(time()-start_t)
where time() cames from from time import time
This is how to do it:
The explanation is inside the code.
#Importing all the modules
import turtle
from turtle import *
import math
#Creating the screen
screen=Screen()
#Creating the turtle
vector1=Turtle("classic")
vector1.speed(-1)
vector1.penup()
#Declaring all the needed variables
Vx=0
Vy=0
V=0
A=0
#Starting the while loop
while True:
#Updating the screen for better preformence
screen.update()
#Carculating the velocity
V=math.sqrt(Vx**2+Vy**2)
#Carculating the angle
if Vx!=0:
A=math.degrees(math.atan(Vy/Vx))
if Vy<0 and Vx<0 or Vy>0 and Vx<0:
A=A-180
elif Vy <0:
A=270
else:
A=90
#Moving the turtle
vector1.seth(A)
vector1.fd(V)
#Changing the values of the velocities
Vy-=0.5
if Vx>0:
Vx-=0.2
elif Vx<0:
Vx+=0.2
If there are any questions, please ask!
I'm trying to get the turtle shape to follow the direction of a line.
I have a simple parabola and I want the turtle shape to follow the direction of the line - when the graph goes up, the turtle faces up and when the graph comes down, the turtle faces down.
I am using goto() for the position of the turtle and x=x+1 for the x position on the graph:
t.goto(x,y)
t.right(??) - this?
t.left(??) - this?
t.setheading(??) or this?
What is the best method to achieve this? When I have tried using t.right() in a while loop (I am looping until x is complete), the turtle continues to spin in a circle as it moves, which is not what I want.
Still not getting this. I added the extra code that was suggested - here is the EDIT and the full code for what I am trying to achieve...
I am using the physics formula for trajectory (I used this so I know my values outputted are correct).
http://www.softschools.com/formulas/physics/trajectory_formula/162/
import math
import turtle
import time
w=turtle.Turtle()
i=0
angle=66.4
velocity=45.0
g=9.8
t=math.tan(math.radians(angle))
c=math.cos(math.radians(angle))
turtle.delay(9)
w.shape("turtle")
w.setheading(90)
while i < 150:
start = i * t
middle = g*(i**2)
bottom =(2*(velocity**2)*c**2)
total = start-middle/bottom
print(total)
w.setheading(turtle.towards(i,total))
w.goto(i,total)
i=i+1
turtle.exitonclick()
The orientation of the turtle can be determined from the derivative of your function at the current position.
If you have the function as a sympy function, you can ask Python to do the differentiation. Or you could just do it on your own. If your function is
y = x^2
, then the derivative is
dy = 2 * x
Given that derivative at the current position, its arc tangent gives you the turtle's heading:
t.setheading(math.atan(dy))
Make sure that the angle mode of the turtle is set to radians or convert them to degrees
t.setheading(math.degrees(math.atan(dy)))
I agree with #NicoSchertler that the arc tangent of the derivative is the way to go mathematically. But if it's just for good visuals, there's a simpler way. We can combine turtle's setheading() and towards() methods, constantly setting the turtle's heading towards the next position just before we go there:
from turtle import Screen, Turtle
turtle = Turtle(shape='turtle', visible=False)
turtle.penup()
turtle.goto(-20, -400)
turtle.pendown()
turtle.setheading(90)
turtle.showturtle()
for x in range(-20, 20):
y = -x ** 2
turtle.setheading(turtle.towards(x, y))
turtle.goto(x, y)
screen = Screen()
screen.exitonclick()
I'm working in turtle graphics to recreate this pattern:
This is probably a very basic question, but is there a simpler way for me to create that rotated square within a square shape? As it is, I just use one turtle to make a normal square, then slowly move a second turtle into position to draw the rotated part. Ex:
import turtle
alex = turtle.Turtle()
tess = turtle.Turtle()
for i in range(4):
alex.fd(50)
alex.lt(90)
tess.pu()
tess.fd(25)
tess.rt(90)
tess.fd(10)
tess.rt(225)
tess.pd()
for i in range(4):
tess.fd(50)
tess.lt(90)
Which to me is clunky at best, and doesn't work if I change the side-lengths (which I intend to do).
Thanks very much in advance!
This is a great time to start using functions! Using functions you can create a reusable chunk of code which can repeat a certain task - for example, drawing a square or a square-in-square shape.
Lets take your code and add a square function which draws a square of a certain size. To do this, we'll tell the function which turtle to use, as well as the size of the square:
def square(this_turtle, side_length):
for i in range(4):
this_turtle.fd(side_length)
this_turtle.lt(90)
Now let's use the new method in your code:
square(alex, 50)
tess.pu()
tess.fd(25)
tess.rt(90)
tess.fd(10)
tess.rt(225)
tess.pd()
square(tess, 50)
From here you can then think about how you could make a star function which makes a "square-in-square" shape of any given size. Good luck!
Here's a more detailed explaination on how you can use functions: http://openbookproject.net/thinkcs/python/english3e/functions.html (I suspect this is the tutorial you're already following!)
I'm going to suggest a contrary approach to yours and the other answers which are too focused on drawing squares which will take too much work to complete. Since this is a repeating pattern, I think stamping is the way to go, just like repeated patterns in real life. Specifically:
from turtle import Turtle, Screen
BASE_UNIT = 20
def tessellate(turtle, start, stop, step):
for x in range(start, stop + 1, step):
for y in range(start, stop + 1, step):
turtle.goto(x * BASE_UNIT, y * BASE_UNIT)
turtle.stamp()
turtle.left(45)
turtle.stamp()
alex = Turtle(shape="square")
alex.shapesize(8)
alex.color("red")
alex.penup()
tessellate(alex, -12, 12, 12)
tess = Turtle(shape="square")
tess.shapesize(4)
tess.color("gold")
tess.penup()
tessellate(tess, -6, 6, 12)
screen = Screen()
screen.exitonclick()
OUTPUT
Turtle stamps naturally rotate and scale which turtle drawings do not!
One thing you'll notice is that my pattern isn't quite the same. In the original the two red (or yellow) squares that make up a star are not the same size! They are slightly different to make the pattern work -- I leave it as an exercise for the OP to correct this.
Learn how to write a function; this is an excellent place to start. Write a function to draw a square of a given size, assuming that the turtle is presently at the starting point and facing the proper direction. Then put your square-drawing loop inside the function:
def draw_square(tortuga, size):
for i in range(4):
tortuga.fd(size)
tortuga.lt(90)
This will remove the drawing details from your main code.
The next thing you do is to write more general code to make Tess follow Alex to the proper spot -- or to make Alex move after finishing the first square, doing the second one himself.