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.
Related
Been using turtle library to make a billiard and cue ball trajectory. I have implemented the ball trajectory physics, so when it hits the walls (or limited distance specified) it reflects to the appropriate direction. But I faced a problem where the ball goes to a direction I didn't specify then according to the heading given it rotates a bit to that direction. I debugged the code and found no issues, and tried to find where the coordinates the cue ball is trying to initially go to, knowing that if the loop of ball movement changes, the initial value always is to go to that direction and breaks the point of having a heading.
import turtle
from math import *
t = turtle.Turtle()
width=200
# White ball - Moving ball
t.color("black")
t.shape("circle")
t.penup()
t.goto(90,-80)
# White ball - Permanent
ball=turtle.Turtle()
ball.speed(0)
ball.penup()
ball.goto(90,-80)
ball.color("black")
ball.shape("circle")
angleString="Enter the hit force's angle (0-360) in degrees: "
angle=int(input(angleString))
# Moving Ball
t.color("yellow")
# Ball movement mechanic
step=20
t.penup()
LIMIT_X=width-8
LIMIT_Y=(width/2)-8
t.setheading(angle)
t.pendown()
x=-LIMIT_X
y=LIMIT_Y
t.dx=step*cos(angle)
t.dy=step*sin(angle)
for x in range(50):
t.speed(1)
print(x,t.pos(), t.heading())
x+=t.dx
y+=t.dy
t.goto(x,y)
# Check vertical borders
if abs(x)>LIMIT_X:
t.dx=-t.dx
# Check horizontal borders
if abs(y)>LIMIT_Y:
t.dy=-t.dy
turtle.done()
showcasing an example of angle 120
I see two problems with your code. First, you have two different x variables in play at the same time:
x=-LIMIT_X
y=LIMIT_Y
t.dx=step*cos(angle)
t.dy=step*sin(angle)
for x in range(50):
t.speed(1)
print(x,t.pos(), t.heading())
x+=t.dx
y+=t.dy
t.goto(x,y)
I'm guessing the iteration x variable is only meant for the debugging print() statement, not to position the ball, and should be renamed.
Second, angle is in degrees but the trigonometric funtions from the math module assume radians, so these calculations make no sense:
t.dx=step*cos(angle)
t.dy=step*sin(angle)
Use the radians() function from math to convert the angle. (Turtle can work with either, but you need to tell it if you want to use radians instead of degrees.)
Additionally, this statement does nothing:
t.setheading(angle)
as you move your ball with goto(). The heading would only matter if you were moving your ball with forward().
My rework of your code fixing the above along with other changes:
from turtle import Screen, Turtle
from math import sin, cos, radians
WIDTH = 200
LIMIT_X = WIDTH - 8
LIMIT_Y = WIDTH/2 - 8
STEP = 20
ANGLE_STRING = "Enter the hit force's angle (0-360) in degrees: "
CURSOR_SIZE = 20
angle = int(input(ANGLE_STRING))
screen = Screen()
# Billard table (roughly)
table = Turtle()
table.hideturtle()
table.shape('square')
table.shapesize(WIDTH / CURSOR_SIZE + 1, WIDTH*2 / CURSOR_SIZE + 1)
table.color('green')
table.stamp()
# Black ball - Permanent
permanent = Turtle()
permanent.shape('circle')
permanent.color('black')
permanent.penup()
permanent.goto(90, -80)
# Yellow ball - Moving ball
moving = permanent.clone()
moving.color('yellow')
moving.pendown()
x = -LIMIT_X
y = LIMIT_Y
moving.dx = STEP * cos(radians(angle))
moving.dy = STEP * sin(radians(angle))
for z in range(50):
moving.speed('slowest')
print(z, moving.pos(), moving.heading())
x += moving.dx
y += moving.dy
moving.goto(x, y)
# Check vertical borders
if abs(x) > LIMIT_X:
moving.dx = -moving.dx
# Check horizontal borders
if abs(y) > LIMIT_Y:
moving.dy = -moving.dy
screen.mainloop()
I'm not saying it does what you want, it's simply less buggy. Perhaps basing your motion on setheading() and forward() instead of goto() might get you the result you desire. You'll have to rethink your wall reflection logic, of course.
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()
I have this code and I tried to do a flowchart but I have no clue how to make one.
All of my Flowchart I made, don't make any sense.
Could anyone of you guys please help me out???
import turtle
STARTING_X, STARTING_Y = 350, 200
turtle.penup()
turtle.width(2)
turtle.setheading(180)
turtle.sety(STARTING_Y)
for a in range(1, 8):
turtle.penup()
turtle.setx(STARTING_X)
for b in range(a):
turtle.pendown()
turtle.circle(25)
turtle.penup()
turtle.forward(60)
turtle.sety(turtle.ycor() - 60)
turtle.done()
The code:
# part 1
import turtle
STARTING_X, STARTING_Y = 350, 200
turtle.penup()
turtle.width(2)
turtle.setheading(180)
turtle.sety(STARTING_Y)
# part 2
for a in range(1, 8):
turtle.penup()
turtle.setx(STARTING_X)
for b in range(a): # part 3
turtle.pendown()
turtle.circle(25)
turtle.penup()
turtle.forward(60)
turtle.sety(turtle.ycor() - 60)
turtle.done()
Part 1:
Importing turtle
Making global variables for starting positions
turtle stuff (read docs)
Part 2:
for loop that runs 8 times
turtle pen up (not drawing)
start at predefined x position
for loop (see Part 3)
lower the y position with 60
Part 3:
runs a times
turtle pendown (drawing)
drawing a circle
turtle penup (not drawing)
go forward with 60 (in this case, lower the x position with 60 because of the direction in part 1)
**Summary**
This program draws 8 lines of circles, and each nth line contains n circles aligned to the right like this:
*
**
***
****
*****
******
*******
********
But circles instead of stars
First of all thank you very much for your help :)
But my question now is how to put that information into a flowchart like this.
I mean what's the Condition 1 / 2, what are the statements etc.
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 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()