Select the desired demo.
Note that the content is editable.
Simple demo
When you click on Run, Brython translates the Python code into
Javascript, which is then being executed in a single thread. The end result of
turtle module computations is the creation of an aminated scene that
uses SVG. This scene is then added to the DOM so that it can be seen.
The first time you do this, Brython has to do extra work to translate the
turtle module from Python into Javascript; subsequent runs will be faster.
As soon as a scene has been created, the Run button will be disabled
and two new buttons will be enabled: one to clear everything so that the program
could be modified and executed again, and the second which can be used to show
the scene that was created as many times as desired, without requiring additional
computation.
When you select another demonstration, everything will be cleared automatically
without having to click on the Clear button.
from browser import document
import turtle
turtle.set_defaults(
turtle_canvas_wrapper = document['turtle-div']
)
t = turtle.Turtle()
t.width(5)
for c in ['red', '#00ff00', '#fa0', 'rgb(0,0,200)']:
t.color(c)
t.forward(100)
t.left(90)
# dot() and write() do not require the pen to be down
t.penup()
t.goto(-30, -100)
t.dot(40, 'rgba(255, 0, 0, 0.5')
t.goto(30, -100)
t.dot(40, 'rgba(0, 255, 0, 0.5')
t.goto(0, -70)
t.dot(40, 'rgba(0, 0, 255, 0.5')
t.goto(0, 125)
t.color('purple')
t.write("I love Brython!", font=("Arial", 20, "normal"))
turtle.done()
Another simple demo
In this demo, we change the default canvas size.
This demo was originally created as a test for the correct turtle orientation,
and for demonstrating instant (fastest) drawing.
from browser import document
import turtle
turtle.set_defaults(
canvwidth = 600, # default is 500
canvheight = 400, # default is 500
turtle_canvas_wrapper = document['turtle-div']
)
t = turtle.Turtle("turtle")
t.width(3)
for c in ['red', 'blue', 'orange', 'green', 'purple', 'brown']:
t.color(c, "white")
t.forward(100)
t.left(60)
### bottom half drawn "instantly"
t.speed(0)
for c in ['red', 'blue', 'orange', 'green', 'purple', 'brown']:
t.color(c)
t.forward(100)
t.right(60)
turtle.done()
Yet another simple demo
This demo shows the available turtles, how to use stamp(),
and how to change the background color.
from browser import document
import turtle
turtle.set_defaults(
canvheight = 400,
turtle_canvas_wrapper = document["turtle-div"]
)
def draw_square(t):
t.begin_fill()
for i in range(4):
t.forward(40)
t.left(90)
t.end_fill()
for name,c,y in [(None, "black", 150), # same as "classic"
("classic", "blue", 100),
("arrow", "orange", 50),
("circle", "red", -50),
("square", "purple",-100),
("triangle", "brown", -150),
("turtle", ("green", "white"), 0)]:
if name is not None:
t = turtle.Turtle(name)
else:
t = turtle.Turtle()
screen = t.getscreen()
screen.bgcolor("rgb(255, 255, 200)")
t.penup()
if len(c) == 2:
t.color(c[0], c[1])
else:
t.color(c)
t.goto(-100, y)
t.pendown()
draw_square(t)
t.penup()
t.forward(100)
t.stamp()
t.forward(100)
screen.bgcolor("white")
turtle.done()
Other than setting some defaults, and calling done()
at the end, this demo has been copied from code linked in
a post on reddit, as a test to show that everything required had been
properly implemented in this version of the turtle module.
If the turtle module has already been imported at least once,
depending on your browser, it can take between 10 and 20 seconds to
create this scene.
Once it has been created, you can view it being drawn as often as you want
by clicking on Replay scene.
# Example from reddit post
from browser import document
from turtle import Turtle, done, set_defaults
from random import randint
# added for diagnostic
import time
start_time = time.time()
set_defaults(
canvwidth = 650,
canvheight = 650,
turtle_canvas_wrapper = document["turtle-div"]
)
grass = Turtle()
grass.color("#007b0c")
sky = Turtle()
sky.color("#e5e5ff")
sky.pensize(100)
sky.speed(0)
tuft = Turtle()
cut = Turtle()
cut.speed(0)
lake = Turtle()
mountain = Turtle()
mountain.pensize()
mountain.color("#a9a9a9")
mountain.speed(0)
trees = Turtle()
trees.pensize(5)
trees.color("#654321")
cloud = Turtle()
turtles = [grass, sky, mountain, trees, cloud, lake, tuft, cut]
def penup():
for i in turtles:
i.penup()
def pendown():
for i in turtles:
i.pendown()
def speed():
for i in turtles:
i.speed(0)
i.hideturtle()
hexnum = ["1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"]
penup()
sky.goto(-200, -200)
pendown()
skycol = ["add8e6",
"b5d8e5",
"bdd8e4",
"c5d8e3",
"cdd8e3",
"d6d8e2",
"ded8e1",
"e6d8e1",
"eed8e0",
"f6d8df",
"ffd9df"
]
def drawsky():
print("Drawing sky")
for i in skycol:
temp = '#' + i
sky.color(temp)
sky.forward(500)
sky.left(90)
sky.forward(20)
sky.left(90)
sky.color(temp)
sky.forward(500)
sky.right(90)
sky.forward(20)
sky.right(90)
def drawmountains():
penup()
mountain.goto(-300,-100)
pendown()
mountain.begin_fill()
print("\n")
print("Drawing mountains 1")
for i in range(10):
templen = randint(20,200)
tempang = randint(45,80)
mountain.left(tempang)
mountain.forward(templen)
mountain.right(2 * tempang)
mountain.forward(templen)
mountain.setheading(0)
mountain.goto(300, -400)
mountain.goto(-300, -400)
mountain.end_fill()
mountain.color("#d3d3d3")
penup()
mountain.goto(-300, -150)
pendown()
mountain.begin_fill()
print("Drawing mountains 2")
for i in range(10):
templen = randint(20, 200)
tempang = randint(20, 30)
mountain.left(tempang)
mountain.forward(templen)
mountain.right(2 * tempang)
mountain.forward(templen)
mountain.setheading(0)
mountain.goto(300, -400)
mountain.goto(-300, -400)
mountain.end_fill()
mountain.color("#6d8383")
penup()
mountain.goto(-300, -165)
pendown()
mountain.begin_fill()
print("Drawing mountains 3")
for i in range(10):
templen = randint(20,200)
tempang = randint(10,20)
mountain.left(tempang)
mountain.forward(templen)
mountain.right(2 * tempang)
mountain.forward(templen)
mountain.setheading(0)
mountain.goto(300, -400)
mountain.goto(-300, -400)
mountain.end_fill()
browns = ["#7a5230", "#614126", "#49311c", "#302013", "#181009"]
greens = ["#004000", "#003300", "#002600", "#001900", "#004c00"]
def drawgrass(amount,locx,locy):
tuft.color("#004000")
def tuftdraw(size):
if randint(0, 1) == 1:
size = -size
tuft.color(greens[randint(0, 4)])
penup()
tuft.goto(locx + size,locy + size)
pendown()
tuft.goto(locx + 5 + size, locy + 10 + size)
tuft.goto(locx + size, locy + size)
tuft.goto(locx - 5 + size, locy + 10 + size)
tuft.goto(locx - 1 + size, locy - 1 + size)
tuft.goto(locx + 3 + size, locy + 6 + size)
tuft.goto(locx + 1 + size, locy - 1 + size)
tuft.goto(locx - 2 + size, locy + 5 + size)
for i in range(amount):
for i in range(randint(1, 4)):
tuftdraw(i * 3)
def drawtrees():
def grassdraw():
penup()
grass.goto(randint(-160, -150),randint(-240, -190))
pendown()
grass.begin_fill()
for i in range(200):
grass.color(greens[randint(0, 4)])
grass.goto(randint(-300, -50), randint(-200, -150))
grass.end_fill()
def greentree():
temppos = trees.pos()
trees.color(greens[randint(0, 4)])
trees.pensize(1)
trees.setheading(90)
trees.begin_fill()
trees.forward(40)
trees.right(160)
trees.forward(50)
trees.end_fill()
trees.setheading(90)
trees.goto(temppos)
trees.begin_fill()
trees.forward(40)
trees.left(160)
trees.forward(50)
trees.end_fill()
trees.goto(temppos)
trees.setheading(90) #part 2
trees.begin_fill()
trees.forward(50)
trees.right(160)
trees.forward(50)
trees.end_fill()
trees.setheading(90)
trees.goto(temppos)
trees.begin_fill()
trees.forward(50)
trees.left(160)
trees.forward(50)
trees.end_fill()
trees.goto(temppos)
trees.setheading(90) #part 3
trees.begin_fill()
trees.forward(60)
trees.right(160)
trees.forward(50)
trees.end_fill()
trees.setheading(90)
trees.goto(temppos)
trees.begin_fill()
trees.forward(60)
trees.left(160)
trees.forward(50)
trees.end_fill()
grassdraw()
print("\n")
trees.speed(0)
def treees(treeheight):
trees.color(browns[randint(0, 4)])
trees.pensize(randint(2, 4))
penup()
trees.goto(treeheight) #goes to random location and draws random length
pendown()
trees.setheading(90)
trees.forward(randint(20, 30))
greentree()
trees.left(270) #turns back to the normal direction
for i in range(10):
print("Drawing tree", i + 1, "/20")
temph = randint(-270, -80),randint(-180, -170)
treees(temph)
for i in range(10):
print("Drawing tree", i + 11, "/20")
temph = randint(-270, -80),randint(-200, -190)
treees(temph)
def clouddraw():
print("\n")
cloud.color("white")
def randloc():
location = randint(-250, 250),randint(0, 270)
return location
def brushstroke(randloc, leng):
penup()
cloud.goto(randloc)
pendown()
cloud.pensize(randint(3, 5))
cloud.forward(leng)
def singlecloud():
temp = randloc()
temp2 = temp[1]
temp3 = temp[0]
leng = 30
for i in range(20):
temp4 = (temp3, temp2)
brushstroke(temp4, leng)
temp2 += 1
temp3 += randint(-10, 10)
leng += randint(-40, 40)
for i in range(4):
print("Drawing cloud:", i + 1)
singlecloud()
def lakedraw():
print("\nDrawing lake")
blues = ["00004c",
"000066",
"000099",
"0000b2",
"0000cc",
"0000e5",
"0000ff"
]
penup()
lake.goto(randint(-50, 50), randint(-170, -150))
temp = Turtle()
temp.penup()
temp.hideturtle()
temp.goto(lake.pos())
pendown()
lake.begin_fill()
lake.pensize(5)
for i in range(50):
lake.color("#" + blues[randint(0, 6)])
lake.forward(5)
lake.right(randint(0, 5) / 10)
if randint(0, 2) == 2:
drawgrass(5, lake.pos()[0], lake.pos()[1])
while lake.heading() > 185:
lake.color("#" + blues[randint(0, 6)])
lake.forward(2)
lake.right(randint(-2, 8))
for i in range(50):
lake.color("#" + blues[randint(0, 6)])
lake.forward(5)
lake.left(randint(0, 2) / 10)
for i in range(100):
lake.color("#" + blues[randint(0, 6)])
lake.forward(5)
lake.right(randint(0, 8) / 10)
lake.color("#" + blues[1])
lake.goto(temp.pos())
lake.end_fill()
def lilypads(amount):
lily = Turtle()
lily.hideturtle()
lily.speed(0)
for i in range(amount):
lily.color(greens[randint(0, 4)])
lily.penup()
lily.goto(randint(0, 200), randint(-300, -175))
lily.pendown()
for i in range(2, 7):
lily.forward(2)
lily.pensize(i)
for i in range(0, 7):
lily.forward(2)
lily.pensize(7 - i)
def cutdraw():
print("\nCutting out")
cut.penup()
cut.color("black")
cut.pensize(40)
cut.goto(-250, 250)
cut.pendown()
cut.goto(250, 250)
cut.goto(250, -250)
cut.goto(-250, -250)
cut.goto(-250, 250)
penup()
cut.speed(9)
cut.color("white")
cut.pensize(200)
cut.goto(-345, 345)
cut.pendown()
cut.goto(345, 345)
cut.goto(345, -345)
cut.goto(-345, -345)
cut.goto(-345, 345)
speed() #sets all speeds to fastest
drawsky()
clouddraw()
drawmountains()
lakedraw()
lilypads(25)
drawtrees()
cutdraw() #cuts off the edges
done()
print("Elapsed time: %s seconds" % (time.time() - start_time))
OOP version: comparison with CPython
All of the implemented methods listed below are called at least once
in the demonstration program.
Due to the way that a scene is constructed, anything dealing with
removing items drawn on the screen does not
make sense in this implementation of the turtle module.
In general, when a "public" non-implemented method is called, a warning
is written on stderr.
from browser import document
import turtle
from math import pi
turtle.set_defaults(
turtle_canvas_wrapper = document["turtle-div"]
)
t = turtle.Turtle("turtle")
t.speed(1)
t.forward(50)
print("Should be (50, 0):", t.position())
print("Should be 50: ", t.xcor())
print("Should be 0: ", t.ycor())
t.left(90)
t.color("blue")
t.speed(2)
t.fd(50)
print("Should be (50, 50):", t.pos())
print("Should be 225: ", t.towards(0, 0))
print("Should be 90: ", t.heading())
print("Should be approximately 71:", t.distance(0, 0))
# Draw the same square in three different angle modes
t.width(4)
print("Drawing using degrees - the default")
print("Heading should be 90: ", t.heading())
for i in range(4):
t.forward(100)
t.left(90)
print("Drawing using radians")
t.radians()
print("Heading should be pi/2: ", t.heading())
for i in range(4):
t.forward(100)
t.left(pi/2)
print("Drawing using gradients")
t.degrees(400)
print("Heading should be 100: ", t.heading())
for i in range(4):
t.forward(100)
t.left(100)
t.degrees()
t.width(1)
t.lt(90)
t.color("orange")
t.backward(50)
t.right(90)
t.color("green")
t.back(50)
t.rt(90)
t.color("red")
t.bk(50)
t.stamp()
t.speed(4)
t.color("black", "white")
t.goto(-100, 100)
t.stamp()
t.color("blue", "yellow")
t.setposition(0, 100)
t.stamp()
t.color("green", "white")
t.setpos(100, 100)
t.stamp()
t.speed(10)
t.color("orange")
t.sety(-100)
t.setx(-100)
t.stamp()
t.color("cyan")
t.home()
t.stamp()
t.color("green")
t.width(4)
t.setheading(180)
t.forward(150)
t.seth(90)
t.fd(20)
t.dot(30, "rgba(255, 0, 0, 0.2)")
t.color("red")
t.speed(0)
t.forward(30)
t.left(90)
t.circle(30)
turtle.done()
OOP version: comparison with CPython
Note: anything dealing with removing items drawn on the screen does not
make sense in this implementation of the turtle module.
shape()
resizemode(): not implemented
shapesize() | turtlesize(): not implemented
shearfactor(): not implemented
settiltangle(): not implemented
tiltangle(): not implemented
tilt(): not implemented
shapetransform(): not implemented
get_shapepoly()
Using events
This version of the turtle module creates an animated scene
which can be played back as is multiple times.
This scene cannot be interacted with.
onclick(): not implemented
onrelease(): not implemented
ondrag(): not implemented
Special Turtle methods
begin_poly(): not implemented
end_poly(): not implemented
get_poly(): not implemented
clone()
getturtle() | getpen()
getscreen()
setundobuffer(): not implemented
undobufferentries(): not implemented
This turtle implementation does not support colormode:
all colours must be given as strings. However, more
color modes are supported since color may be given by name
['red'], by hexadecimal notation ['#abcdef', or '#345'], in rgb notation
['rgb(255, 255, 255)'], rgba notation ['rgba(255, 255, 255, 0.5)'],
hsl notation ['hsl(36, 73%, 37%)'], or any other notation supported by
a browser.
textinput(): not implemented
numinput(): not implemented
Methods specific to Screen
bye()
exitonclick()
setup()
title()
Classes available
Of all the classes listed in the CPython documentation,
only Screen and Turtle
are guaranteed to be available.
from browser import document
import turtle
turtle.set_defaults(
turtle_canvas_wrapper = document["turtle-div"]
)
screen = turtle.Screen()
print("Uncomment one of the demo choices at the bottom.")
def test(x, y):
t = turtle.Turtle("turtle")
others = []
t.penup()
t.goto(x, y)
font = ("Arial", 12, "normal")
for _ in range(4):
t.dot(2, "green")
t.pen("black")
t.write(t.position(), font=font, align="center",
color="black")
t.fd(200)
t.left(90)
others.append(t.clone())
t.goto(x + 100, y + 100)
t.color("green", "white")
for o in others:
o.color("red")
o.speed(1)
o.left(320)
for tt in screen.turtles():
tt.ht()
screen.bgcolor("rgb(240, 255, 240)")
def demo_default():
test(0, 0)
def demo_logo():
screen.mode("logo")
test(0, 0)
def demo_world():
screen.mode("world")
test(250, 250)
def demo_custom():
screen.setworldcoordinates(0, 500, 500, 0)
# notice how the coordinates are inverted
test(250, 250)
#demo_default()
#demo_logo()
#demo_world()
#demo_custom()
turtle.done()
Procedural version: comparison with CPython
This demo shows the procedural version of the turtle module.
We did not provide an html container, so a default one is created
which is not styled; to show it, we changed the background color in
the code.
All implemented methods from the
CPython version mentioned in the other demos should also be available as functions.
We do not list them all nor test them all here, but chose a few for a demo.
If you find a missing function, please file an issue.