How to get the right output for this turtle function? - python

I have a logic error for this function. I need to write a function called spikes() that draw
lines radiating from a common starting point. It takes three parameters, which are
numLines for number of lines to draw, lengthIncr for the length of the first line and
increase in length of the successive lines, and angle that goes clockwise and it is the angle between successive lines. I use the latest version of Python (3.4.2). Also, the function spides must repeatedly call the function drawLine(). I think the error is the call function for drawLine in the function spikes, but I don't know how to fix it. The output I get is a very long curve line that goes downward forever. The real output I should get is spikes. Here is the code:
#Question 14 Part a-
import turtle
s = turtle.Screen()
t = turtle.Turtle()
def drawLine(t, length):
t.pendown()
t.forward(length)
t.penup()
length = 50
drawLine(t, length)
#Question 14 Part b-
def spikes(numLines, lengthIncr, angle):
for i in range(numLines):
drawLine(t, lengthIncr * i)
t.right(angle)
print(spikes(36, 25, 5))
#Output I should get: '''

I'm not an expert on turtle, but is this what you're looking for?
import turtle
s = turtle.Screen()
t = turtle.Turtle()
def drawLine(t, length):
t.pendown()
t.forward(length)
t.penup()
def there_and_back(t, length):
drawLine(t, length)
t.penup()
t.right(180)
t.forward(length)
t.right(180)
t.pendown()
length = 50
#Question 14 Part b-
def spikes(numLines, lengthIncr, angle):
for i in range(numLines):
length = lengthIncr * i
there_and_back(t, length)
t.right(angle)
print(spikes(36, 25, 5))

Related

Trying to make two turtles move randomly in a square and saying when they're close to each other

So my assignement is to:
make a blue rectangle
write a function that makes the turle move in a random direction within an interval of 90 degrees and move forward in a random interval of 0-25
create a blue square
Move the turle to a random point in the square
Code so the turtle moves back inside the square if it leaves it
Create an additonal turle (both should have different colors)
Use the same statement to move both turtles (with the move_random function) 500 times
if the turtles are closer than 50 units - print a string that counts the number of times they are 50 units close.
This is what it should look like:
enter image description here
I've added some comments to explain my thought process
Any and all help is appreciated
The code:
EDIT: fixed the indentations, now i get the error message on the last line that the name "meet" is not defined. Also if i run the code without the last line which is supposed to print the amount of close encounters, nothing happens, no errors, but no turtles either.
import turtle
import random
#makes the jump function
def jump(t, x, y):
t.penup()
t.goto(x, y)
t.pendown()
#creares a turtle at a defined place
def make_turtle(x, y):
t = turtle.Turtle()
jump(t, x, y) # Use of the function defined above
return t
#function to create a rectangle and fill it with a color
def rectangle(x, y, width, height, color):
t = make_turtle(x, y)
t.speed(0)
t.hideturtle()
t.fillcolor(color)
t.begin_fill()
for dist in [width, height, width, height]:
t.forward(dist)
t.left(90)
t.end_fill()
#function to move turtle in a random heading (90 degree interval) between 0--25 units forward
#While also making it turn around if it is outside of the square
def move_random(t):
if abs(t.pos()[0]) >= 250 or abs(t.pos()[1]) >= 250:
target = (0, 0)
d = (0,0)
t.setheading(d)
else:
ini = t.heading()
new = rd.randint(ini - 45, ini + 45)
t.setheading(new)
t.forward(rd.randint(0, 25))
#creates the square and both turtles
t = make_turtle(0 , 0)
t.color("green")
t2 = make_turtle(0 , 0)
t2.color("black")
rectangle(-250, -250, 500, 500, "lightblue")
jump(t, rd.randint(-250, 250), rd.randint(-250, 250))
jump(t2, rd.randint(-250, 250), rd.randint(-250, 250)) #jumps the turles randomly in the square
meet = 0
for i in range(1, 501): #makes the turtles move randomly as specified above
move_random(t)
move_random(t2)
if t.distance(t2) < 50:
t.write("close")
meet += 1
print(str(meet), "close encounter") #prints the amount of times they are close to each other
if abs(t.pos()[0]) >= 250 or abs(t.pos()[1]) >= 250:
target = (0, 0)
d = (0,0)
t.setheading(d)
else:
See that function before the "else:"? You missed a tab there.

Turtle module in Python:

Here is the question : Write a non-fruitful function called barChart, that takes the numeric list of data as a parameter, and draws the bar chart. Write a full program calling this function. The current version of the drawBar function unfortuately draws the top of the bar through the bottom of the label. A nice elaboration is to make the label appear completely above the top line. To keep the spacing consistent you might pass an extra parameter to drawBar for the distance to move up. For the barChart function make that parameter be some small fraction of maxheight+border. The fill action makes this modification particularly tricky: You will want to move past the top of the bar and write b efore or after drawing and filling the bar..
What should I change?
Here is my code :
import turtle
def drawBar(t, height):
""" Get turtle t to draw one bar, of height. """
t.begin_fill() # start filling this shape
t.left(90)
t.forward(height)
t.write(str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height)
t.left(90)
t.end_fill() # stop filling this shape
You can pass the maximum value of the number list then draw the text and bar separately.
Try this code:
import turtle
def drawBar(t, height, mx):
# draw text
t.penup()
t.left(90)
t.forward(mx*10+10)
t.write(str(height).center(12))
t.right(180)
t.forward(mx*10+10)
t.left(90)
t.pendown()
""" Get turtle t to draw one bar, of height. """
t.fillcolor(.1, 1-1*height/mx/2, .1) # darker is higher value
t.begin_fill() # start filling this shape
t.left(90)
t.forward(height*10)
#t.write(" " + str(height))
t.right(90)
t.forward(40)
t.right(90)
t.forward(height*10)
t.left(90)
t.end_fill()
# bottom line
t.right(180)
t.forward(40)
t.right(180)
t.forward(40)
t = turtle.Turtle()
nums = [3,1,4,1,5,9,2]
t.speed(0) # fastest
for n in nums:
drawBar(t, n, max(nums))
t.hideturtle()
input('Enter to exit')
Output

Turning simple polygons about a point in Python Turtle

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()

Python recursive turtle fractal

I am trying to write a recursive turtle program that will draw a fractal tree recreating the shape below:
Turtle Fractal
This should be done with depth = 3, so three different levels of squares. My issue is that with the code I have already, the turtle on screen still doesn't move. Here is my code so far, any help is appreciated:
import turtle
def main():
turtle.speed(0)
turtle.screensize(1000,1000)
turtle.exitonclick()
turt = turtle.Turtle()
squares(turt, length, depth)
def squares(t,length, depth):
length = 200
depth = 3
amt = 1
if depth == 0:
return
elif depth == 3:
t.penup()
t.goto(-1000,-1000)
t.forward(length)
t.left(90)
t.forward(length)
t.left(90)
t.forward(length)
t.left(90)
t.forward(length)
squares(t, length/2, depth - 1)
elif depth == 2:
This incomplete elif will keep the code from even running:
elif depth == 2:
You define main(), but fail to call it:
def main():
You need to add an explicit call to main() at the end:
main()
Should you actually call main(), this premature exitionclick() will turn control over to tkinter before you ever invoke squares():
turtle.exitonclick()
turt = turtle.Turtle()
squares(turt, length, depthc)
the exitonclick() should be the last statement of main(), or happen after main outside the function. Your recursion will never happen as you overwrite two of your arguments:
def squares(t,length, depth):
length = 200
depth = 3
so length and depth will never change despite this test:
if depth == 0:
return
Fixing all of these won't get you a program that draws the fractal you desire, but fixing them is likely a necessary first step.
To make the code draw a fractal, you need to interlace the call to squares() with each forward motion of the turtle. Not do it just at the end:
t.forward(length)
t.left(90)
t.forward(length)
t.left(90)
t.forward(length)
t.left(90)
t.forward(length)
squares(t, length/2, depth - 1)
But something more like:
for _ in range(4):
t.forward(length / 4)
if depth > 1:
t.right(90)
squares(t, length / 2, depth - 1)
t.left(90)
t.forward(3 * length / 4)
...
An absolute value like this is to be avoided in a recursive fractal:
t.goto(-1000,-1000)
And of course, keep your pendown() calls properly matched to your penup() calls.

How Can I Fill These Squares in Turtle - Python

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()

Categories

Resources