I'm trying to get this code to request an input: number of points on a star, then use the turtle module to draw each respective star. Each one is meant to be in a distinct location and have a distinct line and fill color. This code won't draw second and third stars, though it'll draw the first one fine. Also, the fill function only fills the "arms" of the star, not the body. I'm attaching some code and a screenshot of when I tried it with the three inputs: 5, 7, and 9.
from turtle import *
def start():
"""This function initializes the window and the turtle.
Do not modify this function.
"""
setup(564, 564)
width(7)
side_length = 60 # Also the radius of a circle enclosed by the star.
penup()
goto(0, -side_length) # Start at the bottom of the star.
pendown()
def main():
points = int(input('How many points would you like on your star? '))
A = 360 / points
B = 2 * A
x = 0
side_length = 60
while x < points:
color('blue', 'red')
begin_fill()
left(A)
forward(side_length)
right(B)
forward(side_length)
x += 1
end_fill()
penup()
goto(2*side_length, 2*side_length)
pendown()
points = int(input('How many points would you like on your star? '))
while x < points:
color('green', 'yellow')
begin_fill()
left(A)
forward(side_length)
right(B)
forward(side_length)
x += 1
end_fill()
penup()
goto(-2*side_length, 2*side_length)
pendown()
points = int(input('How many points would you like on your star? '))
while x < points:
color('orange', 'purple')
begin_fill()
left(A)
forward(side_length)
right(B)
forward(side_length)
x += 1
end_fill()
# Do not change anything after this line.
if __name__ == '__main__':
start()
main()
done()
Related
so I'm working on a program where i want the output to have 4 triangles with the lengths 20,40,60,80 placed vertically where the top of each triangle should be exactly halfway along the baseline of the triangle above.
I have managed to get the first two triangles correct but cannot get the top two to align the way I want. I know I am going wrong somewhere but i cannot seem to see it
from turtle import *
NUMBER_OF_SHAPES = 4
for shape in range(1, NUMBER_OF_SHAPES + 1):
#Draw a Triangle
for sides in range(3):
forward(20 * shape)
left(120)
#Move forward to start position of next triangle
penup()
left(120)
forward(20 * shape)
right(120)
pendown()
from turtle import *
import time
NUMBER_OF_SHAPES = 4
for shape in range(1, NUMBER_OF_SHAPES + 1):
#Draw a Triangle
for sides in range(5): #redraw some edges to place the cursor on the top
forward(20 * shape)
left(120)
#Move forward to start position of next triangle
penup()
right(60)
forward(10 * (shape+1)) # half of the size of the next triangle
right(180)
time.sleep(0.5)
pendown()
Think outside the triangle:
from turtle import *
for length in range(20, 100, 20):
penup()
sety(length + ycor())
pendown()
circle(-2*length/3, steps=3)
hideturtle()
exitonclick()
Here were using turtle's circle() method to achieve two goals, first to draw a triangle, steps=3, and second to draw centered triangles starting from their top point by using a negative radius. Beyond that we simply need to adjust the vertical position.
As far as your code, I believe the problem is simpler than you're trying to make it. Things get easier if we start by moving forward half the length of the triangle, and then build from there:
from turtle import *
NUMBER_OF_SHAPES = 4
for shape in range(1, NUMBER_OF_SHAPES + 1):
forward(10 * shape)
for _ in range(4):
left(120)
forward(20 * shape)
right(120)
exitonclick()
This, in combination with reversing the order of the steps in the loop, and increasing iterations to 4, leaves us centered for the next triangle.
I need help turning polygon shapes (triangle and square) in Python turtle to match a picture.
Below I am trying to copy the image.
I specifically need help on what to add to my code given the triangle and square to have them repeat outwards like the picture. Because as of now the triangles and squares look like this (pentagon code is correct and works) All help is appreciated. Thank you.
import turtle
def polygon(turtle, side, length):
turtle.color("Blue")
for i in range(4):
turtle.backward(length)
turtle.left(side)
def polygon1(turtle, side1, length):
turtle.color("Green")
for i in range(3):
turtle.left(side1)
turtle.forward(length)
def polygon2(turtle, side2, length):
turtle.color("Red")
for i in range(5):
turtle.forward(length)
turtle.left(side2)
def main():
my_turtle = turtle.Turtle()
wn = turtle.Screen()
Bill = turtle.Turtle()
length = 100
side = 90
side1 = 120
side2 = 72
Bill.pensize(5)
Bill.speed(0)
#Pentagons
Bill.pu()
Bill.right(180)
y = -45
for i in range(5):
Bill.pu()
Bill.goto(60, y)
Bill.pd()
polygon2(Bill, side2, length)
y -= 20
#Triangle
Bill.pu()
Bill.left(240)
x = 45
for j in range(5):
Bill.pu()
Bill.goto(10, x)
Bill.pd()
polygon1(Bill, side1, length)
x += 20
#Square
Bill.pu()
Bill.left(240)
b = 6
for b in range(5):
Bill.pu()
Bill.goto(148, b)
Bill.pd()
polygon(Bill, side, length)
b -= 20
wn.exitonclick()
if __name__ == '__main__':
main()
pentagon code is correct and works
I don't believe the pentagon code is correct nor that you're approaching this in the correct way. The inner three shapes should form an equilateral triangle -- yours don't as you're eyeballing instead of calculating. Instead of trying to get the turtle to be in the right spot, why not have the turtle move forward in the direction of the sides of this central triangle, drawing polygons as it goes.
That is, embrace the drawing as a whole rather than trying to divide and conquer.
We'd need to make sure the polygon drawing code restores the turtle's state when it's done, so it can simply move forward to the next polygon. We'll need to make explicit which numbers are arbitrary, and which are calculable. Although the original diagram appears to use at least three turtles to achieve it's result, we'll do it with one as you attempted:
from turtle import Turtle, Screen
SHAPES = [(5, "Red"), (3, "Green"), (4, "Blue")]
LENGTH = 100
DELTA = 20
REPLICATIONS = 5
THICKNESS = 5
HEIGHT = (3 ** 0.5 / 2) * LENGTH # assumes 3 shapes, should fix!
DIVISIONS = 360 / len(SHAPES)
def polygon(turtle, sides, color):
turtle.color(color)
turtle.left(90)
turtle.forward(LENGTH / 2)
for _ in range(sides):
turtle.right(360 / sides)
turtle.forward(LENGTH)
turtle.backward(LENGTH / 2) # restore turtle to original state
turtle.right(90)
wn = Screen()
bill = Turtle()
bill.speed('fastest')
bill.pensize(THICKNESS)
bill.penup()
for offset, (sides, color) in enumerate(SHAPES):
bill.setheading(-DIVISIONS * offset - 90)
bill.forward(HEIGHT / 3) # assumes 3 shapes, should fix!
for _ in range(REPLICATIONS):
bill.pendown()
polygon(bill, sides, color)
bill.penup()
bill.forward(DELTA)
bill.home()
wn.exitonclick()
Answered
I need to create a function named "caterpillar()", this function is used to join my draw_circle() function, and draw_line() functions together to create a caterpullar. I'm stuck on trying to create the three circles needed for the caterpillars body using draw_circle within a while loop. This is all my code so far:
from turtle import *
import turtle
def moveto(x,y):
penup()
goto(x,y)
pendown()
def draw_circle(xpos,ypos,radius,colour):
moveto(xpos,ypos)
circle(radius)
turtle.fillcolor(colour)
def draw_line(x1, y1, x2, y2):
penup()
goto(x1,y1)
pendown()
goto(x2,y2)
def draw_square(x,y,length,colour):
moveto(x,y)
forward(length)
right(90)
forward(length)
right(90)
forward(length)
right(90)
forward(length)
turtle.fillcolor(colour)
def caterpillar():
draw_line(0,30,-20,-15) # feelers
draw_line(0,30,20,-15) # feelers
draw_line(60,30,40,-15) # feelers
draw_line(60,30,80,-15) # feelers
draw_line(120,30,100,-15) # feelers
draw_line(120,30,140,-15) # feelers
for _ in range(3) : # 3 body circles
xpos = 0
ypos = 0
radius = 30
turtle.begin_fill()
draw_circle(0,0,30,"green")
turtle.end_fill()
xpos = xpos + (radius*2)
caterpillar()
I am stuck on the last part under "for _ in range(3)" - I need to loop three circles using the draw_circle function at these specific coords:
Caterpillar
I've been stuck on this for hours, any help would be much appreciated!
Edit:
Also forgot to mention, that i keep getting the error "File "C:\Users\Rekesh\Desktop\caterpillar\1.py", line 48, in caterpillar
xpos = xpos +(radius*2)
UnboundLocalError: local variable 'xpos' referenced before assignment
When I use xpos = xpos, i'm not sure if this is needed.
I need my turtle to stop after 4 circles but he won't do it! Can anyone help? I wouldn't ask unless I was really stuck and I have been researching for a while.
from turtle import *
import time
### Positioning
xpos= -250
ypos= -250
radius= 40
speed(10)
###Program main function
while radius == 40:
pu()
goto (xpos, ypos)
pd()
begin_fill()
color("red")
circle(radius)
end_fill()
xpos = xpos + (radius*2)
while radius == 40 - you never change radius, so it will never stop. Instead, loop over an iterable like range():
for _ in range(5):
Remember, you don't have to use the loop variable within the loop. It's okay to use it as nothing other than a counter.
The following code would draw your N times, where you would replace N with the number of circles you want it to draw:
from turtle import *
import time
### Positioning
xpos= -250
ypos= -250
radius= 40
speed(10)
currentIterateCount = N
###Program main function
while currentIterateCount != 0:
pu()
goto (xpos, ypos)
pd()
begin_fill()
color("red")
circle(radius)
end_fill()
xpos = xpos + (radius*2)
currentIterateCount--;
The reason that it drew more circles than you wanted is because you were checking against a variable that never changed.
By this I mean you were seeing if radius changed, but never changing it.
I am trying to fill the color in these squares:
Right now the turtle only fills the corners of theses squares, not the entire square.
Here is my code:
import turtle
import time
import random
print ("This program draws shapes based on the number you enter in a uniform pattern.")
num_str = input("Enter the side number of the shape you want to draw: ")
if num_str.isdigit():
squares = int(num_str)
angle = 180 - 180*(squares-2)/squares
turtle.up
x = 0
y = 0
turtle.setpos(x,y)
numshapes = 8
for x in range(numshapes):
turtle.color(random.random(),random.random(), random.random())
x += 5
y += 5
turtle.forward(x)
turtle.left(y)
for i in range(squares):
turtle.begin_fill()
turtle.down()
turtle.forward(40)
turtle.left(angle)
turtle.forward(40)
print (turtle.pos())
turtle.up()
turtle.end_fill()
time.sleep(11)
turtle.bye()
I've tried moving around turtle.begin_fill() and end_fill() in numerous locations with no luckā¦ Using Python 3.2.3, thanks.
I haven't really used turtle, but it looks like this may be what you want to do. Correct me if I've assumed the wrong functionality for these calls:
turtle.begin_fill() # Begin the fill process.
turtle.down() # "Pen" down?
for i in range(squares): # For each edge of the shape
turtle.forward(40) # Move forward 40 units
turtle.left(angle) # Turn ready for the next edge
turtle.up() # Pen up
turtle.end_fill() # End fill.
You're drawing a series of triangles, using begin_fill() and end_fill() for each one. What you can probably do is move your calls to begin_fill() and end_fill() outside the inner loop, so you draw a full square and then ask for it to be filled.
Use fill
t.begin_fill()
t.color("red")
for x in range(4):
t.fd(100)
t.rt(90)
t.end_fill()
Along with moving begin_fill() and end_fill() outside the loop, as several folks have mentioned, you've other issues with your code. For example, this is a no-op:
turtle.up
I.e. it doesn't do anything. (Missing parentheses.) This test:
if num_str.isdigit():
Doesn't do much for you as there is no else clause to handle the error. (I.e. when it isn't a number, the next statement simply uses the string as a number and fails.) This calculation seems a bit too complicated:
angle = 180 - 180*(squares-2)/squares
And finally there should be a cleaner way to exit the program. Let's address all these issues:
from turtle import Screen, Turtle
from random import random
NUMBER_SHAPES = 8
print("This program draws shapes based on the number you enter in a uniform pattern.")
num_str = ""
while not num_str.isdigit():
num_str = input("Enter the side number of the shape you want to draw: ")
sides = int(num_str)
angle = 360 / sides
delta_distance = 0
delta_angle = 0
screen = Screen()
turtle = Turtle()
for x in range(NUMBER_SHAPES):
turtle.color(random(), random(), random())
turtle.penup()
delta_distance += 5
turtle.forward(delta_distance)
delta_angle += 5
turtle.left(delta_angle)
turtle.pendown()
turtle.begin_fill()
for _ in range(sides):
turtle.forward(40)
turtle.left(angle)
turtle.forward(40)
turtle.end_fill()
screen.exitonclick()