星空背景

  1. from turtle import *
  2. import random
  3. screen = Screen()
  4. screen.setup(1200, 800)
  5. screen.bgcolor('black')
  6. speed(0)
  7. penup()
  8. hideturtle()
  9. for _ in range(100):
  10. x = random.random()
  11. print('the x:', x)
  12. x = x * 1200 - 1200/2
  13. y = random.random() * 800 - 800/2
  14. r = random.random()
  15. g = random.random()
  16. b = random.random()
  17. d = random.randint(0, 3)
  18. goto(x, y)
  19. color(r, g, b)
  20. dot(d)
  21. done()

image.png

八大行星

image.png

课外练习

到处乱窜的小乌龟

  1. #!/usr/local/bin/env python3
  2. # encoding: utf-8
  3. '''
  4. create a window and a turtle
  5. while the turtle is still in the window:
  6. generate a random number from 0 to 1
  7. if the number == 0:
  8. turn left
  9. else:
  10. turn right
  11. move the turtle forward 50
  12. '''
  13. import random
  14. import turtle
  15. def isInScreen(w, t):
  16. boundleft = - w.window_width() / 2
  17. boundright = w.window_width() / 2
  18. boundtop = w.window_height() / 2
  19. boundbottom = -w.window_height() / 2
  20. turtleX = t.xcor()
  21. turtleY = t.ycor()
  22. inscreen = True
  23. if turtleX > boundright or turtleX < boundleft:
  24. inscreen = False
  25. if turtleY > boundtop or turtleY < boundbottom:
  26. inscreen = False
  27. return inscreen
  28. wn = turtle.Screen()
  29. t = turtle.Turtle()
  30. t.shape('turtle')
  31. while isInScreen(wn, t):
  32. step = random.randrange(0, 2)
  33. if step == 0:
  34. t.left(90)
  35. else:
  36. t.right(90)
  37. t.forward(50)
  38. wn.exitonclick()

image.png