2.1使用Turtle绘画--画一朵花
打开IDLE3,点击File-->New window,然后输入:
画花朵的第一部分
import turtle
window = turtle.Screen()
babbage = turtle.Turtle()
babbage.left(45)
babbage.forward(100)
babbage.right(90)
babbage.circle(10)
window.exitonclick()
然后点击Run-->Run Module 或者按F5键来运行程序。此时弹出一个对话框让你输入文件名称,这里我们输入:chapter2-example1.py
第二步:画第一片花瓣
import turtle
window = turtle.Screen()
babbage = turtle.Turtle()
babbage.left(45)
babbage.forward(100)
babbage.right(90)
babbage.circle(10)
#add code
babbage.left(15)
babbage.forward(50)
babbage.left(157)
babbage.forward(50)
window.exitonclick()
第三步:画剩余的所有花瓣
import turtle
window = turtle.Screen()
babbage = turtle.Turtle()
babbage.left(45)
babbage.forward(100)
babbage.right(90)
babbage.circle(10)
#update code
for i in range(1, 24):
babbage.left(15)
babbage.forward(50)
babbage.left(157)
babbage.forward(50)
window.exitonclick()
第四步:给花涂上颜色
import turtle
window = turtle.Screen()
babbage = turtle.Turtle()
babbage.color("green", "green")
babbage.left(45)
babbage.forward(100)
babbage.right(90)
babbage.color("yellow", "yellow")
babbage.begin_fill()
babbage.circle(10)
babbage.end_fill()
#update code
babbage.color("red", "red")
for i in range(1, 24):
babbage.left(15)
babbage.forward(50)
babbage.left(157)
babbage.forward(50)
window.exitonclick()
2.2一个Python游戏:猫和老鼠
import time
import turtle
box_size = 200
caught = False
score = 0
#functions that are called on keypresses
def up():
mouse.forward(10)
check_bound()
def left():
mouse.left(45)
def right():
mouse.right(45)
def back():
mouse.backward(10)
check_bound()
def quitTurtle():
window.byte()
#stop the mouse from leaving the square set by box size
def check_bound():
global box_size
if mouse.xcor() > box_size:
mouse.goto(box_size, mouse.ycor())
if mouse.xcor() < -box_size:
mouse.goto(-box_size, mouse.ycor)
if mouse.ycor() > box_size():
mouse.goto(mouse.xcor, box_size)
if mouse.xcor < -box_size:
mouse.goto(mouse.xcor, -box_size)
#set up screen
window = turtle.Screen()
mouse = turtle.Turtle()
cat = turtle.Turtle()
mouse.penup()
mouse.penup()
mouse.goto(100, 100)
#add key listeners
window.onkeypress(up, "Up")
window.onkeypress(back, "Back")
window.onkeypress(left, "Left")
window.onkeypress(right, "Right")
window.onkeypress(quitTurtle, "Escape")
difficulty = window.numinput("Difficulty", "Enter a difficulty from easy(1), for hard(5)",
minval = 1, maxval = 5)
window.listen()
#main loop
#note how it changes with difficulty
while not caught:
cat.setheading(cat.towards(mouse))
cat.forward(8 + difficulty)
if cat.distance(mouse) < 5:
caught = True
time.sleep(0.2 - (0.01 * difficulty))
window.textinput("GAME OVER", "Well done. You scored:" + str(score * difficulty))
window.byte()
2.3小结
1.Python程序由一系列命令组成并从上到下执行
2.可以通过循环和if语句控制程序的执行顺序
3.不必事必躬亲,通过倒入模块,使用模块中的的方法可以完成许多工作
4.函数可以帮助重用代码,也可以使程序变得易于理解和维护
5.变量可以存储信息以便后面使用