This is the bycicle i am trying to make but i cant.
I am really sorry if it gets downgrades and i am really new to python turtle.
I am currently trying to animate. I am done with the animation but i am struglling with making the handle of the bycicle.
After writing the code it dosent make any change.
So if possible. Anyone can make the handle and explain how he did it?
Thank you..
import time
def moving_wheel(turtle):
turtle.fillcolor('orange')
turtle.begin_fill()
turtle.circle(20)
turtle.end_fill()
def moving_handle(turtle):
pos = turtle.pos()
turtle.left(90)
turtle.forward(70)
turtle.left(120)
turtle.forward(110)
turtle.penup()
turtle.goto(pos)
turtle.right(210)
turtle.pendown()
if __name__ == "__main__":
screen = turtle.Screen()
screen.setup(600, 600)
screen.bgcolor('green')
screen.tracer(0)
t1 = turtle.Turtle()
t2 = turtle.Turtle()
t3 = turtle.Turtle()
# set a turtle object color
t1.color('red')
t2.color('red')
t3.color('red')
# set turtle object speed
t1.speed(0)
t2.speed(0)
t3.speed(0)
t1.width(2)
t2.width(2)
t3.width(1.5)
t1.hideturtle()
t2.hideturtle()
t3.hideturtle()
# turtle object in air
t1.penup()
t2.penup()
t3.penup()
# set initial position
t1.goto(-250, 0)
t2.goto(-150,0)
t3.goto(-150,20)
t3.pendown()
# move turtle object to surface
t1.pendown()
t2.pendown()
# infinite loop
while True:
# clear turtle work
t1.clear()
t2.clear()
t3.clear()
# call function to draw ball
moving_wheel(t1)
moving_wheel(t2)
moving_handle(t3)
# update screen
screen.update()
# forward motion by turtle object
t1.forward(0.1)
t2.forward(0.1)
t3.forward(0.1)
There is no error in your code. You have to only sit and add more forward, left/right, penup/pendown, etc. - and this need to test different value and see which gives expected result.
I would split problem into smaller figures with more regular angles and size.
Bottom part looks like 3 triangles and it would be simpler to use regular triangles with angles 60.
Maybe you should even create function triangle(size) for this.
This is what I tried to draw these triangles.
def moving_handle(turtle):
pos = turtle.pos()
# --- first triangle without last side ---
# rotate to start position
turtle.left(120)
for _ in range(2):
turtle.forward(50)
turtle.left(120)
# move without drawing last side
turtle.penup()
turtle.forward(50)
turtle.left(120)
turtle.pendown()
# rotate back to old position
turtle.left(-120)
# --- second triangle
# move to new position without drawing
turtle.penup()
turtle.left(180)
turtle.forward(50)
turtle.left(-180)
turtle.pendown()
# draw trangle
# rotate to start position
turtle.left(120)
for _ in range(3):
turtle.forward(50)
turtle.left(120)
# rotate back to old position
turtle.left(-120)
# --- second triangle
# draw trangle
# rotate to start position
turtle.left(60)
for _ in range(3):
turtle.forward(50)
turtle.left(120)
# rotate back to old position
turtle.left(-60)
# move to the beginning
turtle.penup()
turtle.goto(pos)
turtle.pendown()
Related
I am making a tic tac toe game and when the user presses 'o' a circle is printed but the circle is always on the left of the turtle. i would like the turtle to be in the center of a box and draw the circle around itself.
You have to move turtle on your own - using left,right,forward, penup, pendowm.
Example
import turtle
radius = 100
# move
turtle.penup()
turtle.right(90)
turtle.forward(radius)
turtle.left(90)
turtle.pendown()
# circle
turtle.circle(radius)
# move back
turtle.penup()
turtle.right(-90)
turtle.forward(radius)
turtle.left(-90)
turtle.pendown()
Result:
There are a couple of ways to draw a circle centered around a Python turtle without moving the turtle. The first is the dot() method. It takes a diameter, rather than a radius, and optionally allows you to specify the color at the same time:
import turtle
RADIUS = 100
turtle.dot(RADIUS * 2)
turtle.dot(RADIUS * 1.6, turtle.bgcolor()) # "unfill" the circle
turtle.done()
Another way to do it is via stamping, that is, make the turtle cursor itself a circle, size it, and then call stamp():
import turtle
RADIUS = 100
CURSOR_RADIUS = 10
turtle.hideturtle()
turtle.shape('circle')
turtle.fillcolor(turtle.bgcolor())
turtle.shapesize(RADIUS / CURSOR_RADIUS, outline=RADIUS/5)
turtle.stamp()
turtle.done()
Both of the above have the side effect of overwritting anything that the circle surrounds, which doesn't seem like a problem for tic-tac-toe. To avoid this, you can, of course, temporarily shift the turtle's position, as #furas suggests:
import turtle
RADIUS = 100
turtle.width(RADIUS/5)
turtle.penup()
turtle.sety(turtle.ycor() - RADIUS)
turtle.pendown()
turtle.circle(RADIUS)
turtle.penup()
turtle.sety(turtle.ycor() + RADIUS)
turtle.pendown()
turtle.done()
Hi I'm just learning coding so I have a question about the Turtle function.
In my assignment I am trying to use the turtle to move into a spiral not circular but in a square. Basically I am trying to spin the turtle using a while and for loop. Is that not the right move?
I have no coding that works so giving an example might not work. Sorry...
Example
I am not sure what shape do you want to end up with but this following code will paint you a square
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
turtle.forward(50)
turtle.left(90)
as you can see I used 2 function here:
the forward function which moves the line forward in the arrow direction
the left function which spins the arrow left in the specified degree(90 for a square angel)
was that helpful? I'm here for more questions (:
#if you want to make square spiral in python then u must use this
import turtle
t = turtle.Turtle()
side = 200
for i in range(100):
t.forward(side)
t.right(90) #Exterior angle of a square is 90 degree
side = side - 2
Turtle docs say when end_poly() is reached:
Stop recording the vertices of a polygon. Current turtle position is
last vertex of polygon. This will be connected with the first vertex.
With my example, the final line is not drawn from the last vertex back to the first vertex. It acts the same in 2.7 and 3.7 Python.
from turtle import *
print("position 0:",position())
width(5)
pencolor("red")
fillcolor("blue")
begin_fill()
begin_poly()
fd(100)
print("position 1:",position())
left(90)
fd(100)
print("position 2:",position())
end_poly()
end_fill()
p = get_poly()
print("poly p:",p)
register_shape("myShape",p)
shapes_ = getshapes()
print("shapes_:", shapes_)
Output:
position 0: (0.00,0.00)
position 1: (100.00,0.00)
position 2: (100.00,100.00)
poly p: ((0.00,0.00), (100.00,0.00), (100.00,100.00))
shapes_: ['arrow', 'blank', 'circle', 'classic', 'myShape', 'square', 'triangle', 'turtle']
Image of polygon
I believe this is an error in the documentation, but an understandable one.
First, you clearly can draw what you want by closing the figure yourself:
from turtle import Turtle, Screen
screen = Screen()
turtle = Turtle(visible=False)
turtle.width(5)
turtle.color("red", "blue")
position = turtle.position()
turtle.begin_fill()
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.goto(position)
turtle.end_fill()
screen.exitonclick()
So what's the deal with polygons? Well, unless you implement the code yourself, there's nothing turtle can do, by default, with polygons, except use them as turtle cursors. In which case it's passing them onto tkinter which is responsible for the closing the polygon:
from turtle import Turtle, Screen
screen = Screen()
turtle = Turtle(visible=False)
turtle.penup()
turtle.begin_poly()
turtle.forward(100)
turtle.left(90)
turtle.forward(100)
turtle.end_poly()
screen.register_shape("myShape", turtle.get_poly())
turtle.shape("myShape") # when the polygon gets closed
turtle.shapesize(outline=5)
turtle.color("red", "blue")
turtle.stamp()
screen.exitonclick()
(I'm guessing it's in tkinter's canvas.coords() where the polygon gets closed.) Note that your width(5) means nothing in this case, nor does *_fill() as a cursor's outline width is set using shapesize() and a cursor is naturally filled. It doesn't need a color specified at polygon creation time, you can wait until the new cursor is deployed.
I believe this statement in the end_poly() documentation:
last vertex of polygon. This will be connected with the first vertex.
Should really reside in the polygon section of turtle's register_shape() documentation. But you can understand the error as turtle only thinks the role of *_poly() is for creating new cursors. Whereas polygons should be a first class, flexible datatype in turtle.
I'm trying to draw a checkerboard.
I drew the board, but now I have to define a function (a loop) that fills in every other square with black. I've been trying to write a loop to do this for a while, can someone help?
Here's my code:
import turtle
def drawGrid():
turtle.penup()
turtle.goto(-300, 250)
turtle.pendown()
turtle.forward(300)
turtle.right(90)
turtle.forward(300)
turtle.right(90)
turtle.forward(300)
turtle.right(90)
turtle.forward(300)
def drawColumns():
for i in range(4):
turtle.right(90)
turtle.forward(37.5)
turtle.right(90)
turtle.forward(300)
turtle.left(90)
turtle.forward(37.5)
turtle.left(90)
turtle.forward(300)
def drawRows():
turtle.left(180)
rows = 0
while rows <= 3:
rows += 1
turtle.forward(37.5)
turtle.right(90)
turtle.forward(300)
turtle.left(90)
turtle.forward(37.5)
turtle.left(90)
turtle.forward(300)
turtle.right(90)
def main():
drawGrid()
drawColumns()
drawRows()
if __name__ == "__main__":
main()
Turtles fill method works on shapes, i.e. a completely bounded area. So rather than drawing a grid you need to think in terms of drawing a series of squares.
So lets start by defining a simple function to draw a filled in square. It takes a turtle object and a size which is the length of the side.
import turtle
def draw_filled_square(this_turtle, size):
"""Draw a square by drawing a line and turning through 90 degrees 4 times"""
this_turtle.pendown()
this_turtle.fill(True)
for _ in range(4):
this_turtle.forward(size)
this_turtle.right(90)
this_turtle.fill(False)
this_turtle.penup()
we can call it like this:
window = turtle.Screen()
myturtle = turtle.Turtle()
square_size = 90
myturtle.goto(-300, 200)
draw__filled_square(myturtle, square_size)
Which draws a single square. Note that it puts it back at the starting place, so we need to move it before drawing the next square.
Now, in practice, as long as we draw the outline of the box we only need to draw filled squares, unfilled squares can be represented negative space. But for the purposes of explanation I'm going to also draw them.
Defining a function for an unfilled square is easy -- just duplicate the existing function but set this_turtle.fill(False) at the beginning instead.
Anytime something needs to count in a repeating sequence (1, 2, 3, 4, 1, 2, 3, 4, ...) it calls for use of modulo (remainder). Modulo means remainder so if x modulo y is 0 it means x is exactly divisible by y. This translates into code as if x % y == 0:
Here's a simple drum machine to demonstrate:
def drum_loop(x):
# go bang on the fourth beat
if x % 4 == 0:
print("bang!")
else:
print("tish")
# prints tish, tish, tish, bang! tish, tish, tish, bang!
for i in range(1,9):
drum_loop(i)
Alternating is just like counting 0, 1 , 0, 1 repeatedly.
So we can draw a row like this:
for i in range(8):
if i % 2 == 0:
draw_filled_square(myturtle, square_size)
else:
draw_unfilled_square(myturtle, square_size)
# move to start of next square
myturtle.forward(square_size)
Now just repeating this isn't going to do the trick, but it should be clear you can use modulo 2 again to make the rows alternate properly.
Do this by defining a row function that will alternate between starting with a black and starting with a white square, then calling this from within another loop. (Don't forget to go back to the beginning and move down every time you start a row).
Here's another example where drawing creates more work for the poor turtle than simply stamping. Rather than thinking about drawing and filling boxes, think about the board itself as a filled square onto which other filled squares are stamped:
from turtle import Turtle, Screen
NUMBER_SQUARES = 8
SQUARE_SIZE = 40
BOARD_SIZE = SQUARE_SIZE * NUMBER_SQUARES
BORDER_FRACTION = 1.025 # add a slight edge to board
STAMP_SIZE = 20 # size of turtle square image
turtle = Turtle(shape='square', visible=False)
turtle.shapesize(BOARD_SIZE / STAMP_SIZE * BORDER_FRACTION)
turtle.color('black')
turtle.stamp()
turtle.shapesize(SQUARE_SIZE / STAMP_SIZE)
turtle.color('white')
turtle.penup()
for y in range(-NUMBER_SQUARES//2, NUMBER_SQUARES//2):
parity = y % 2 == 0
for x in range(-NUMBER_SQUARES//2, NUMBER_SQUARES//2):
if parity:
turtle.goto(x * SQUARE_SIZE + SQUARE_SIZE//2, y * SQUARE_SIZE + SQUARE_SIZE//2)
turtle.stamp()
parity = not parity
Screen().exitonclick()
This solution can print a board in any two colors (e.g. black and red), it doesn't assume a white background. Just another example of better living through stamping.
import turtle
turtle.pensize(2)
turtle.penup()
turtle.goto(-160,-160)
turtle.pendown()
turtle.color("black")
for i in range(4):
turtle.forward(320)
turtle.left(90)
for y in range(-160,160,80):
for x in range(-160,160,80):
turtle.begin_fill()
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
for k in range(4):
turtle.forward(40)
turtle.left(90)
turtle.end_fill()
for y in range(-120,160,80):
for x in range(-120,160,80):
turtle.begin_fill()
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
for k in range(4):
turtle.forward(40)
turtle.left(90)
turtle.end_fill()
turtle.done()
Let's have a look at the zig-zag approach (the explanation of the code is commented inside):
import turtle
def drawGrid(rows, cols, size):
turtle.sety(turtle.ycor() + size * rows) # Draw the initial line
f = size * 2
turtle.begin_fill()
for j in range(cols): # Make the columns
if j % 2:
turtle.backward(f) # Make room for the zig-zag up and zig-zag down
for i in range(rows * 2): # rows * 2 because there will be both zig-zag down and a zig-zag up for each row
turtle.forward(size)
turtle.right(90)
if i % 2:
turtle.left, turtle.right = turtle.right, turtle.left # Switch the zig-zag direction
turtle.left(180)
turtle.end_fill()
turtle.sety(turtle.ycor() - size * rows) # Draw the final line
turtle.penup()
turtle.goto(-300, -50) # Set the bottom-left position of the grid
turtle.pendown()
turtle.speed("fastest") # Because I have no patience
drawGrid(8, 8, 40)
Output:
Note that the number of rows and columns must be even for this to work.
I need to draw a square given a center point using the turtle module.
def drawCentSq(t,center,side):
xPt=center[0]
yPt=center[1]
xPt-=int(side/side)
yPt+=int(side/side)
t.up()
t.goto(xPt,yPt)
t.down()
for i in range(4):
t.forward(side)
t.right(90)
def main():
import turtle
mad=turtle.Turtle()
wn=mad.getscreen()
print(drawCentSq(mad,(0,0),50))
main()
I'm having a hard time making my turtle go to the right starting point.
You need:
xPt-=int(side/2.0)
yPt+=int(side/2.0)
As it was you were just += and -= 1.
I need to draw a square given a center point using the turtle module.
As #seth notes, you can do this by fixing the center calculation in your code:
from turtle import Turtle, Screen
def drawCentSq(turtle, center, side):
""" A square is a series of perpendicular sides """
xPt, yPt = center
xPt -= side / 2
yPt += side / 2
turtle.up()
turtle.goto(xPt, yPt)
turtle.down()
for _ in range(4):
turtle.forward(side)
turtle.right(90)
yertle = Turtle()
drawCentSq(yertle, (0, 0), 50)
screen = Screen()
screen.exitonclick()
But let's step back and consider how else we can draw a square at a given point of a given size. Here's a completely different solution:
def drawCentSq(turtle, center, side):
""" A square is a circle drawn at a rough approximation """
xPt, yPt = center
xPt -= side / 2
yPt -= side / 2
turtle.up()
turtle.goto(xPt, yPt)
turtle.right(45)
turtle.down()
turtle.circle(2**0.5 * side / 2, steps=4)
turtle.left(45) # return cursor to original orientation
And here's yet another:
STAMP_UNIT = 20
def drawCentSq(turtle, center, side):
""" A square can be stamped directly from a square cursor """
mock = turtle.clone() # clone turtle to avoid cleaning up changes
mock.hideturtle()
mock.shape("square")
mock.fillcolor("white")
mock.shapesize(side / STAMP_UNIT)
mock.up()
mock.goto(center)
return mock.stamp()
Note that this solution returns a stamp ID that you can pass to yertle's clearstamp() method to remove the square from the screen if/when you wish.