星空背景
from turtle import *
import random
screen = Screen()
screen.setup(1200, 800)
screen.bgcolor('black')
speed(0)
penup()
hideturtle()
for _ in range(100):
x = random.random()
print('the x:', x)
x = x * 1200 - 1200/2
y = random.random() * 800 - 800/2
r = random.random()
g = random.random()
b = random.random()
d = random.randint(0, 3)
goto(x, y)
color(r, g, b)
dot(d)
done()
八大行星
课外练习
到处乱窜的小乌龟
#!/usr/local/bin/env python3
# encoding: utf-8
'''
create a window and a turtle
while the turtle is still in the window:
generate a random number from 0 to 1
if the number == 0:
turn left
else:
turn right
move the turtle forward 50
'''
import random
import turtle
def isInScreen(w, t):
boundleft = - w.window_width() / 2
boundright = w.window_width() / 2
boundtop = w.window_height() / 2
boundbottom = -w.window_height() / 2
turtleX = t.xcor()
turtleY = t.ycor()
inscreen = True
if turtleX > boundright or turtleX < boundleft:
inscreen = False
if turtleY > boundtop or turtleY < boundbottom:
inscreen = False
return inscreen
wn = turtle.Screen()
t = turtle.Turtle()
t.shape('turtle')
while isInScreen(wn, t):
step = random.randrange(0, 2)
if step == 0:
t.left(90)
else:
t.right(90)
t.forward(50)
wn.exitonclick()