I am writing this code to print polygons. If the number is two or less, it is supposed to print nothing according to my professor but I cant figure this out. Can somebody tell me what I need to write in my function for 2 or less side numbers to not print anything?
import turtle
import math
turtle.shape("turtle")
turtle.speed(3)
from turtle import *
pensize (5)
pencolor ("purple")
def polygon(num_side, length):
for i in range(num_side):
turtle.forward(length)
turtle.left(360/num_side)
print(polygon(2, 100)) #nothing?
turtle.penup()
turtle.goto(50, 0)
turtle.pendown()
print(polygon(3,100)) #triangle
turtle.penup()
turtle.goto(50, 0)
turtle.pendown()
print(polygon(4, 100)) #square
turtle.penup()
turtle.goto(50, 0)
turtle.pendown()
print(polygon(5, 100)) #pentagon
turtle.penup()
turtle.goto(50, 0)
turtle.pendown()
print(polygon(6, 100)) #hexagon
turtle.penup()
turtle.goto(50, 0)
turtle.pendown()
print(polygon(7, 100)) #heptagon
You need to exit if the number of sides is less than three and only output if n is more than 2. Thus, the if will take care of this.
import turtle
import math
turtle.shape("turtle")
turtle.speed(3)
turtle.pensize (5)
turtle.pencolor ("purple")
def polygon(num_side, length):
if num_side > 2:
for i in range(num_side):
turtle.forward(length)
turtle.left(360/num_side)
turtle.pendown()
for n in range(10):
polygon(n, 100)
Related
i'm very new to programming and in here i'm supposed to create a pyramid shape of bricks where the edge of the pyramid is filled with one color and the inside of it is filled with random colors, but i can't seem to figure it out how to move the bricks to create a new row, column and the random colors specified only to inside bricks of the pyramid. Does anyone have a suggestion? Thanks in advance. This is my code and it's still working for one brick only:
import turtle
import math
import random
bottom_brick = 10
top_brick = 1
brick_length = 35
brick_width = 25
from turtle import *
from turtle import Screen
screen = Screen()
screen.bgcolor('white')
turtle.speed('fastest')
penup ()
goto(0, -100)
pendown()
fillcolor('#BC4A3C')
begin_fill()
#bottom_brick and top_brick are inputs from the user
#to indicate how many bricks are used for the bottom layer and the top layer
# brick_length and brick_width are also input from user
for i in range (0, bottom_brick):
turtle.setposition(0.5 * (i % 2), i)
for j in range(i, bottom_brick):
forward(brick_length)
left(90)
forward(brick_width)
left(90)
forward(brick_length)
left(90)
forward(brick_width)
left(90)
end_fill()
done()
This will get you most of the way there with regards to making sure your bricks are laid out correctly:
import turtle
bottom_brick = 10
top_brick = 1
brick_length = 35
brick_width = 25
turtle.Screen().bgcolor('white')
turtle.speed('fastest')
turtle.penup()
turtle.goto(0, -100)
turtle.pendown()
#bottom_brick and top_brick are inputs from the user
#to indicate how many bricks are used for the bottom layer and the top layer
# brick_length and brick_width are also input from user
for i in range(bottom_brick - top_brick + 2):
for j in range(bottom_brick - i + 1):
turtle.setposition((j + i / 2) * brick_length, i * brick_width)
turtle.fillcolor('#BC4A3C')
turtle.begin_fill()
turtle.forward(brick_length)
turtle.left(90)
turtle.forward(brick_width)
turtle.left(90)
turtle.forward(brick_length)
turtle.left(90)
turtle.forward(brick_width)
turtle.left(90)
turtle.end_fill()
turtle.done()
Note that the fill color needs to be set inside the loop, and that's the spot where you'll want to randomize the color so that each brick is different. You'll also need to be mindful of when the pen is up and when it's down in order to avoid extra lines showing up.
This seems like an opportunity for better living through stamping instead of drawing:
from turtle import Screen, Turtle
from random import random
top_brick = 1
bottom_brick = 10
brick_length = 35
brick_width = 25
CURSOR_SIZE = 20
screen = Screen()
turtle = Turtle()
turtle.hideturtle()
turtle.shape('square')
turtle.shapesize(brick_width / CURSOR_SIZE, brick_length / CURSOR_SIZE)
turtle.penup()
turtle.sety((bottom_brick - top_brick + 1) * brick_width / -2)
for row in range(bottom_brick, top_brick - 1, -1):
turtle.goto(-brick_length * (row / 2), turtle.ycor() + brick_width)
for column in range(row):
if top_brick < row < bottom_brick and 0 < column < row - 1:
turtle.fillcolor(random(), random(), random())
else:
turtle.fillcolor('#BC4A3C')
turtle.stamp()
turtle.forward(brick_length)
screen.exitonclick()
Plus an example of how you might handle the brick coloring issue.
I'm trying to use turtle in order to draw a rectangle, and then 32 equal cells inside it. But I somehow can't get it right, I don't know why.
Here is the code I've written:
import turtle, tkinter, datetime, time
turtle.setx(-400)
turtle.sety(200)
turtle.pendown()
turtle.pencolor('#00807c')
for i in range (0,4):
x = 800
if i%2 == 0:
turtle.fd(x)
else:
turtle.fd(x/2)
turtle.right(90)
def cells(position):
for i in range (0,4):
x = 100
turtle.fd(x)
turtle.right(90)
if turtle.pos() == position:
turtle.fd(x)
position = turtle.pos()
for j in range(0, 8):
cells(turtle.pos())
turtle.done()
The result is weird, it only draws three or four cells and then the program ends.
I'd be grateful if somebody could possibly help me with this problem. Thanks.
I've rewritten your code and I don't understand why you're using a function. I've used 3 loops:
loop 3(4):
loop 2(8):
loop 1(4):
The first loop repeats himself 4 times and draws the sides of 1 square
The second loop runs the first loop 8 times, so it draws 8 squares next to each other
The third loop runs the second loop 4 times, so it draws 4 lines of 8 squares.
And that makes a field of 32 cells.
My code:
import turtle, tkinter, datetime, time
turtle.penup()
turtle.hideturtle()
turtle.setx(-400)
turtle.sety(200)
turtle.pendown()
turtle.pencolor('#00807c')
turtle.speed(0)
turtle.pendown()
for i in range (4):
x = 800
if i%2 == 0:
turtle.fd(x)
else:
turtle.fd(x/2)
turtle.right(90)
for w in range (4):
for i in range (8):
for i in range (4):
x = 100
turtle.fd(x)
turtle.right(90)
turtle.forward(x)
turtle.penup()
turtle.goto(-400,turtle.ycor()-100)
turtle.pendown()
turtle.done()
PS: I've also changed a few things like:
I hid the turtle
I changed the speed (to maximum)
I added a turtle.penup()-command before I moved the turtle in the beginning, so you don't see a black line.
Kind regards
spyrolix
You can create two functions, to simplify the logic: One to draw a square, and one to position the turtle at the place to draw a square. Then, using a little bit of index arithmetic in two nested loops (one for rows, and one for columns), use the indices values, and the side length of a square to draw at the correct location:
Maybe like this:
import turtle, tkinter
def draw_square(side):
"""draws a square of side=side starting at the current turtle location
"""
turtle.pendown()
turtle.setheading(0)
for _ in range(4):
turtle.forward(side)
turtle.left(90)
turtle.penup()
def draw_grid(rows, cols):
"""positions the turtle at the correct location,
in order to draw a grid of squares
"""
for jdx in range(rows):
for idx in range(cols):
turtle.penup()
turtle.goto(startx + side*idx, starty + side*jdx)
draw_square(side)
turtle.pencolor('#00807c')
side = 20
startx, starty = 0, 0 # this can be changed,
# other locations used are relative to this starting point
turtle.penup()
turtle.goto(startx, starty)
rows, cols = 4, 8 # this can be changed
draw_grid(rows, cols)
turtle.goto(startx, starty) # return to the starting point
turtle.done()
This is a situation where I would switch from drawing to stamping to simplify the code and speed it up:
from turtle import Screen, Turtle
WIDTH, HEIGHT = 800, 400
SQUARE = 100
CURSOR_SIZE = 20
def cells(t):
x, y = t.position()
for dy in range(HEIGHT // SQUARE):
turtle.goto(x, y + dy * SQUARE)
for dx in range(WIDTH // SQUARE):
turtle.stamp()
turtle.forward(SQUARE)
screen = Screen()
turtle = Turtle()
turtle.hideturtle()
turtle.shape('square')
turtle.shapesize(HEIGHT / CURSOR_SIZE, WIDTH / CURSOR_SIZE)
turtle.color('#00807c', 'white')
turtle.speed('fastest')
turtle.penup()
turtle.stamp() # draw outer perimeter
turtle.shapesize(SQUARE / CURSOR_SIZE)
turtle.goto(SQUARE/2 - WIDTH/2, SQUARE/2 - HEIGHT/2)
cells(turtle) # draw inner squares
screen.exitonclick()
I'd also remove magic numbers from the body of the code and declare them at the start to make them easier to adjust.
This my program using turtle to draw the circle target:
import turtle
def origin_circle(turtle, radius):
turtle.penup()
turtle.goto(0, -radius)
turtle.pendown()
turtle.circle(radius)
for radius in range(100, 200, 10):
origin_circle(turtle, radius)
The code makes a moving curve, but I want the circle to be drawn at once.
The circle() method draws a circle, but the dot() method stamps one out. However, the dot() method doesn't have a separate line and fill concept and tends to overwrite itself, so we have to handle it carefully:
import turtle
def origin_circle(turtle, radius):
turtle.dot(radius + 2, 'black')
turtle.dot(radius, 'white')
for radius in range(200, 0, -40):
origin_circle(turtle, radius)
turtle.hideturtle()
turtle.mainloop()
Alternatively, we could stamp out circular cursors ourselves:
import turtle
def origin_circle(turtle, radius):
turtle.shapesize(radius)
turtle.stamp()
turtle.shape('circle')
turtle.color('black', 'white')
for radius in range(10, 0, -2):
origin_circle(turtle, radius)
turtle.hideturtle()
turtle.mainloop()
But this doesn't produce as pleasing a result:
Of course, we can always cheat and use turtle.speed('fastest'), or better yet, turn tracing off altogether:
import turtle
def origin_circle(turtle, radius):
turtle.penup()
turtle.sety(-radius)
turtle.pendown()
turtle.circle(radius, steps=90)
turtle.tracer(False)
for radius in range(20, 120, 20):
origin_circle(turtle, radius)
turtle.hideturtle()
turtle.tracer(True)
turtle.mainloop()
But the result still won't look as nice as the turtle.dot() approach, even if you bump up the steps parameter of turtle.circle():
for the first code how to add an arrow on the top of each curve, one
at down of each curve?
This is easier done modifying my third example as we can more easily draw semicircles and stamp the cursor. I'm using a custom cursor for arrow alignment across circles purposes:
import turtle
def origin_circle(turtle, radius):
turtle.penup()
turtle.sety(-radius)
turtle.pendown()
turtle.stamp()
turtle.circle(radius, extent=180, steps=45)
turtle.stamp()
turtle.circle(radius, extent=180, steps=45)
turtle.addshape("pointer", ((0, 0), (5, -4), (0, 4), (-5, -4)))
turtle.shape("pointer")
turtle.tracer(False)
for idx, radius in enumerate(range(20, 120, 20), start=0):
origin_circle(turtle, radius)
turtle.hideturtle()
turtle.tracer(True)
turtle.mainloop()
import turtle
ab=turtle.Turtle()
ab.speed(0)
import turtle
def zielscheibe(ringe=10):
if ringe<1 or ringe>1000:
ab.write('Bitte eine Zahl zwischen 1 und 1000 eingeben')
return
ab.pu()
ab.goto(300,0)
ab.seth(90)
x=300/ringe
for n in range(ringe):
ab.pd()
if n ==ringe-1:
ab.color('black')
elif n %2==0:
ab.color('red')
else:
ab.color('white')
ab.begin_fill()
ab.circle(300-x*n)
ab.end_fill()
ab.pu()
ab.left(90)
ab.fd(x)
ab.right(90)
zielscheibe(10)
turtle.mainloop()
I need to make my python code draw my stars in different sizes at random. I've tried every method I know but unable to figure it out...still trying to completely understand loops.
import turtle
import random
for n in range(60):
turtle.penup()
turtle.goto(random.randint(-400, 400), random.randint(-400, 400))
turtle.pendown()
red_amount = random.randint( 0, 100) / 100.0
blue_amount = random.randint(0 , 100) / 100.0
green_amount = random.randint( 0, 100) / 100.0
turtle.pencolor((red_amount, green_amount, blue_amount))
turtle.pensize(random.randint(1, 10))
for i in range(6):
turtle.begin_fill()
turtle.forward(50)
turtle.right(144)
turtle.end_fill()
All it does currently is draw stars at the same size.
You've added code to randomize the color, starting position and pen width but there's none to change the size of the stars. The size is controlled by this statement:
turtle.forward(50)
but you don't want to simply replace the 50 with another call to the random module as your stars will come out irregular. You need to compute a random size before the loop and then use that size in the forward() call in the loop:
import turtle
import random
for n in range(60):
turtle.penup()
turtle.goto(random.randint(-400, 400), random.randint(-400, 400))
turtle.pendown()
red_amount = random.random()
blue_amount = random.random()
green_amount = random.random()
turtle.color(red_amount, green_amount, blue_amount)
turtle.pensize(random.randint(1, 10))
size = random.randint(25, 100)
turtle.begin_fill()
for i in range(5):
turtle.forward(size)
turtle.right(144)
turtle.end_fill()
turtle.done()
I've also made a few style changes to your code while I was at it.
--im a beginner ..so im not sure how to make sure that the snowflakes don't overlap. Thanks!
import turtle
turtle.right(90)
turtle.penup()
turtle.goto(-700,300)
turtle.pendown()
def snowflakebranch(n):
turtle.forward(n*4)
for i in range(3):
turtle.backward(n)
turtle.right(45)
turtle.forward(n)
turtle.backward(n)
turtle.left(90)
turtle.forward(n)
turtle.backward(n)
turtle.right(45)
def snowflake(n):
for i in range(8):
snowflakebranch(n)
turtle.backward(n)
turtle.right(45)
import random
turtle.colormode(255)
turtle.tracer(0)
for i in range(35):
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
turtle.color(r, g, b)
x = random.randint(-500, 500)
y = random.randint(-500, 500)
d = random.randint(6, 16)
snowflake(d)
turtle.penup()
turtle.goto(x, y)
#turtle.forward(250)
turtle.pendown()
turtle.update()
One approach would be to calculate a bounding rectangle (or circle) for each snowflake. Save these as a list or a set. Whenever you plan to make a new snowflake, first check if its bounding rectangle (or circle) overlaps with the bounds of any previous snowflakes. If it does, don't draw it. If it doesn't, draw it and save its bounds too. An incomplete outline of this approach:
import turtle
import random
def snowflakebranch(n):
turtle.forward(n * 4)
for _ in range(3):
turtle.backward(n)
turtle.right(45)
turtle.forward(n)
turtle.backward(n)
turtle.left(90)
turtle.forward(n)
turtle.backward(n)
turtle.right(45)
def snowflake(n):
for _ in range(8):
snowflakebranch(n)
turtle.backward(n)
turtle.right(45)
def overlapping(bounds_list, bounds):
for previous in bounds_list:
if overlap(previous, bounds):
return True
return False
def overlap(b1, b2):
# return True or False if these two rectanges or circles overlap
pass
turtle.penup()
turtle.colormode(255)
turtle.tracer(0)
previous_bounds = []
i = 0
while i < 35:
x = random.randint(-500, 500)
y = random.randint(-500, 500)
turtle.goto(x, y)
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
turtle.color(r, g, b)
turtle.pendown()
d = random.randint(6, 16)
# work out the bounding rectangle or circle based on 'd', 'x' & 'y'
# e.g. (x, y, width & height) or (x, y, radius)
bounds = ( ... )
if not overlapping(previous_bounds, bounds):
snowflake(d)
turtle.update()
previous_bounds.append(bounds)
i += 1
turtle.penup()
turtle.done()
An image of non-overlapping snowflakes using the above logic with the bounding circles also displayed:
I actually like the look of your overlapping snowflakes. Even if you want overlap, the above logic will allow you to control how much overlap.