太阳花
1 | # coding=utf-8 |
2 | import turtle |
3 | import time |
4 | |
5 | # 同时设置pencolor="red", fillcolor="yellow" |
6 | turtle.color("red", "yellow") |
7 | |
8 | # 开始填充 |
9 | turtle.begin_fill() |
10 | for _ in range(50): # 循环50次, 从0到49 |
11 | turtle.forward(200) # 前行200 |
12 | turtle.left(170) # 左转170° |
13 | # 结束填充 |
14 | turtle.end_fill() |
15 | |
16 | # 不会退出, 而是等待 |
17 | turtle.mainloop() |
五角星
# coding=utf-8
import turtle
import time turtle.pensize(5) # 线宽
turtle.pencolor("yellow") # 线的眼神
turtle.fillcolor("red") # 填充颜色 def draw_5AnglesShape():
turtle.begin_fill()
for _ in range(5):
turtle.forward(200)
turtle.right(144)
turtle.end_fill()
time.sleep(2) def draw_word(): # 写文字
turtle.penup()
turtle.goto(-150, -120)
turtle.color("violet")
turtle.write("五角星绘制完毕", font=('Arial', 40, 'normal')) if __name__ == "__main__":
draw_5AnglesShape()
draw_word()
turtle.mainloop()
彩色螺旋线
1 | # coding=utf-8 |
2 | import turtle |
3 | |
4 | from datetime import * |
5 | import time |
6 | |
7 | def doWork(): |
8 | turtle.pensize(2) |
9 | turtle.bgcolor("black") |
10 | colors = ["red","yellow","purple","blue"] |
11 | #turtle.tracer(False) |
12 | for x in range(400): |
13 | turtle.forward(2*x) |
14 | turtle.color(colors[x % 4]) |
15 | turtle.left(91) |
16 | #turtle.tracer(True) |
17 | # input() 可以有效解决闪退问题,或者下面的方法 |
18 | |
19 | if __name__ == "__main__": |
20 | doWork() |
21 | turtle.done(); |
22 |
方形蜘蛛网
# coding=utf-8
import turtle from datetime import *
import time def doWork(t):
for x in range(100):
t.forward(x)
t.left(90) if __name__ == "__main__":
t = turtle.Pen()
doWork(t)
turtle.done()
旋转的海龟
# coding=utf-8
import turtle from datetime import *
import time def doWork(t):
for x in range(100):
t.forward(x)
t.left(91) if __name__ == "__main__":
t = turtle.Pen()
doWork(t)
彩色的旋转的海龟
# coding=utf-8
import turtle from datetime import *
import time def doWork(t):
colors = ["red", "yellow", "blue", "green"]
for x in range(100):
t.pencolor(colors[x%4])
t.forward(x)
t.left(91) if __name__ == "__main__":
t = turtle.Pen()
doWork(t)
彩色的旋转的海龟2
# coding=utf-8
import turtle from datetime import *
import time def doWork(t):
turtle.bgcolor("black") # 修改背景颜色
sides = 6
colors = ["red", "yellow", "blue", "green"]
for x in range(100):
t.pencolor(colors[x%4])
t.forward(x * 3/sides + x)
t.left(360/sides + 1)
t.width(x*sides/200) if __name__ == "__main__":
t = turtle.Pen()
doWork(t)
蟒蛇绘制
1 | # coding=utf-8 |
2 | import turtle |
3 | from datetime import * |
4 | import time |
5 | |
6 | if __name__ == "__main__": |
7 | # 屏幕大小为(650,300) |
8 | turtle.setup(650,300) |
9 | turtle.penup() |
10 | turtle.fd(-250) |
11 | turtle.pendown() |
12 | turtle.pensize(10) |
13 | turtle.pencolor("yellow") |
14 | turtle.seth(-40) |
15 | for i in range(4): |
16 | turtle.circle(40,80) |
17 | turtle.circle(-40,80) |
18 | turtle.circle(40,80/2) |
19 | turtle.fd(40) |
20 | turtle.circle(16,180) |
21 | turtle.fd(40 * 2/3) |
22 | turtle.done() |
图形绘制
1 | # coding=utf-8 |
2 | import turtle |
3 | from datetime import * |
4 | import time |
5 | |
6 | if __name__ == "__main__": |
7 | turtle.pensize(3) |
8 | turtle.penup() |
9 | turtle.goto(-200,-50) |
10 | turtle.pendown() |
11 | turtle.begin_fill() |
12 | turtle.color("red") |
13 | turtle.circle(40, steps=3) |
14 | turtle.end_fill() |
15 | |
16 | |
17 | turtle.penup() |
18 | turtle.goto(-100,-50) |
19 | turtle.pendown() |
20 | turtle.begin_fill() |
21 | turtle.color("blue") |
22 | turtle.circle(40, steps=4) |
23 | turtle.end_fill() |
24 | |
25 | turtle.penup() |
26 | turtle.goto(0,-50) |
27 | turtle.pendown() |
28 | turtle.begin_fill() |
29 | turtle.color("green") |
30 | turtle.circle(40, steps=5) |
31 | turtle.end_fill() |
32 | |
33 | turtle.penup() |
34 | turtle.goto(100,-50) |
35 | turtle.pendown() |
36 | turtle.begin_fill() |
37 | turtle.color("yellow") |
38 | turtle.circle(40, steps=6) |
39 | turtle.end_fill() |
40 | |
41 | turtle.penup() |
42 | turtle.goto(200,-50) |
43 | turtle.pendown() |
44 | turtle.begin_fill() |
45 | turtle.color("purple") |
46 | turtle.circle(40) |
47 | turtle.end_fill() |
48 | |
49 | turtle.color("green") |
50 | turtle.penup() |
51 | turtle.goto(-100,50) |
52 | turtle.pendown() |
53 | turtle.write( u"彩色简单图形".encode("utf-8"), |
54 | font = ("Times", 18, "bold") ) |
55 | turtle.hideturtle() |
56 | |
57 | turtle.done() |
58 |
三角塔的绘制
#encoding: utf8 import turtle stepSize = 30 def draw1GreenTriangle(): """ 画有一个绿色的小小三角形 从图片上看, 整个图形就是由27个小三角形组成的 """ global stepSize turtle.color("black", "green") # 笔的颜色的黑色, 填充是绿色 turtle.begin_fill() # 开始填充 turtle.setheading(240) # 头向左下 turtle.forward(stepSize) # 移动指定个单位 turtle.left(120) # 逆时针旋转120度 turtle.forward(stepSize) # 移动10个单位 turtle.left(120) # 逆时针旋转120度 turtle.forward(stepSize) # 移动10个单位 turtle.end_fill() # 结束填充 def draw3GreenTriangle(): """ 就是画三个小三角形 原图片可以看做是9个这样的3个三角形组成的 """ draw1GreenTriangle(); turtle.left(120) # 逆时针旋转120度 turtle.forward(stepSize) # 移动指定单位 draw1GreenTriangle(); # 画第二个三角形 turtle.setheading(0) # 头向左 turtle.forward(stepSize) # 移动指定单位 draw1GreenTriangle(); # 画第三个三角形 turtle.forward(stepSize) # 移动指定个单位 def draw9GreenTriangle(): """ 就是画九个三角形 原图片可以看做是3个这样的9个三角形组成的 """ draw3GreenTriangle() # 画第一个三个小三角形 turtle.left(120) # 逆时针旋转120度 turtle.forward(stepSize*2) # 移动2个指定单位 draw3GreenTriangle() # 画第二个三个小三角形 turtle.setheading(0) # 头向左 turtle.forward(stepSize*2) # 移动2个指定单位 draw3GreenTriangle() # 画第三个三个小三角形 turtle.forward(stepSize*2) # 移动2个指定单位 def draw27GreenTriangle(): """ 画出最终图像, 就是27个小三角形, 其由三个draw9GreenTriangle()的结果组成 """ draw9GreenTriangle() turtle.left(120) # 逆时针旋转120度 turtle.forward(stepSize*4) # 移动4个指定单位 draw9GreenTriangle() turtle.setheading(0) # 头向左 turtle.forward(stepSize*4) # 移动4个指定单位 draw9GreenTriangle() if __name__ == "__main__": draw27GreenTriangle(); turtle.mainloop()
小猪佩奇
# coding:utf-8 import turtle as t def drawNose():
# 配置画笔属性
t.pensize(4)
t.hideturtle()
t.colormode(255)
t.color((255,155,192),"pink")
t.setup(840,500)
t.speed(10) # 绘制鼻圈
t.pu()
t.goto(-100,100)
t.pd()
t.seth(-30)
t.begin_fill()
a=0.4
for i in range(120):
if 0<=i<30 or 60<=i<90:
a=a+0.08
t.lt(3) #向左转3度
t.fd(a) #向前走a的步长
else:
a=a-0.08
t.lt(3)
t.fd(a)
t.end_fill() # 绘制鼻孔
t.pu()
t.seth(90)
t.fd(25)
t.seth(0)
t.fd(10)
t.pd()
t.pencolor(255,155,192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160,82,45)
t.end_fill() t.pu()
t.seth(0)
t.fd(20)
t.pd()
t.pencolor(255,155,192)
t.seth(10)
t.begin_fill()
t.circle(5)
t.color(160,82,45)
t.end_fill() def drawHead():
# 绘制吹风机头
t.color((255,155,192),"pink")
t.pu()
t.seth(90)
t.fd(41)
t.seth(0)
t.fd(0)
t.pd()
t.begin_fill()
t.seth(180)
t.circle(300,-30)
t.circle(100,-60)
t.circle(80,-100)
t.circle(150,-20)
t.circle(60,-95)
t.seth(161)
t.circle(-300,15)
t.pu()
t.goto(-100,100)
t.pd()
t.seth(-30)
a=0.4
for i in range(60):
if 0<=i<30 or 60<=i<90:
a=a+0.08
t.lt(3) #向左转3度
t.fd(a) #向前走a的步长
else:
a=a-0.08
t.lt(3)
t.fd(a)
t.end_fill() def drawEar():
# 绘制耳朵
t.color((255,155,192),"pink")
t.pu()
t.seth(90)
t.fd(-7)
t.seth(0)
t.fd(70)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50,50)
t.circle(-10,120)
t.circle(-50,54)
t.end_fill() t.pu()
t.seth(90)
t.fd(-12)
t.seth(0)
t.fd(30)
t.pd()
t.begin_fill()
t.seth(100)
t.circle(-50,50)
t.circle(-10,120)
t.circle(-50,56)
t.end_fill()def drawEye():# 绘制眼睛
t.color((255,155,192),"white")
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-95)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill() t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill() t.color((255,155,192),"white")
t.pu()
t.seth(90)
t.fd(-25)
t.seth(0)
t.fd(40)
t.pd()
t.begin_fill()
t.circle(15)
t.end_fill() t.color("black")
t.pu()
t.seth(90)
t.fd(12)
t.seth(0)
t.fd(-3)
t.pd()
t.begin_fill()
t.circle(3)
t.end_fill()def drawCheek():# 绘制腮
t.color((255,155,192))
t.pu()
t.seth(90)
t.fd(-95)
t.seth(0)
t.fd(65)
t.pd()
t.begin_fill()
t.circle(30)
t.end_fill()def drawMouth():# 绘制嘴
t.color(239,69,19)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(-100)
t.pd()
t.seth(-80)
t.circle(30,40)
t.circle(40,80)def drawFigure():# 绘制体型
t.color("red",(255,99,71))
t.pu()
t.seth(90)
t.fd(-20)
t.seth(0)
t.fd(-78)
t.pd()
t.begin_fill()
t.seth(-130)
t.circle(100,10)
t.circle(300,30)
t.seth(0)
t.fd(230)
t.seth(90)
t.circle(300,30)
t.circle(100,3)
t.color((255,155,192),(255,100,100))
t.seth(-135)
t.circle(-80,63)
t.circle(-150,24)
t.end_fill()def drawHand():# 绘制小手
t.color((255,155,192))
t.pu()
t.seth(90)
t.fd(-40)
t.seth(0)
t.fd(-27)
t.pd()
t.seth(-160)
t.circle(300,15)
t.pu()
t.seth(90)
t.fd(15)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-10)
t.circle(-20,90) t.pu()
t.seth(90)
t.fd(30)
t.seth(0)
t.fd(237)
t.pd()
t.seth(-20)
t.circle(-300,15)
t.pu()
t.seth(90)
t.fd(20)
t.seth(0)
t.fd(0)
t.pd()
t.seth(-170)
t.circle(20,90)def drawLeg():# 绘制腿脚
t.pensize(10)
t.color((240,128,128))
t.pu()
t.seth(90)
t.fd(-75)
t.seth(0)
t.fd(-180)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20) t.pensize(10)
t.color((240,128,128))
t.pu()
t.seth(90)
t.fd(40)
t.seth(0)
t.fd(90)
t.pd()
t.seth(-90)
t.fd(40)
t.seth(-180)
t.color("black")
t.pensize(15)
t.fd(20)def drawTail():# 绘制尾巴
t.pensize(4)
t.color((255,155,192))
t.pu()
t.seth(90)
t.fd(70)
t.seth(0)
t.fd(95)
t.pd()
t.seth(0)
t.circle(70,20)
t.circle(10,330)
t.circle(70,30)if __name__ =="__main__":
drawNose()
drawHead()
drawEar()
drawEye()
drawCheek()
drawMouth()
drawFigure()
drawHand()
drawLeg()
drawTail()
t.done()
玫瑰花
#encoding: utf8 from turtle import * import time # 设置屏幕尺寸为600*800 # 窗口位置为(1000,100) setup(600,800,1000, 100) speed(0) penup() seth(90) fd(340) seth(0) pendown() speed(5) begin_fill() fillcolor('red') circle(50,30) for i in range(10): fd(1) left(10) circle(40,40) for i in range(6): fd(1) left(3) circle(80,40) for i in range(20): fd(0.5) left(5) circle(80,45) for i in range(10): fd(2) left(1) circle(80,25) for i in range(20): fd(1) left(4) circle(50,50) time.sleep(0.1) circle(120,55) speed(0) seth(-90) fd(70) right(150) fd(20) left(140) circle(140,90) left(30) circle(160,100) left(130) fd(25) penup() right(150) circle(40,80) pendown() left(115) fd(60) penup() left(180) fd(60) pendown() end_fill() right(120) circle(-50,50) circle(-20,90) speed(1) fd(75) speed(0) circle(90,110) penup() left(162) fd(185) left(170) pendown() circle(200,10) circle(100,40) circle(-52,115) left(20) circle(100,20) circle(300,20) speed(1) fd(250) penup() speed(0) left(180) fd(250) circle(-300,7) right(80) circle(200,5) pendown() left(60) begin_fill() fillcolor('green') circle(-80,100) right(90) fd(10) left(20) circle(-63,127) end_fill() penup() left(50) fd(20) left(180) pendown() circle(200,25) penup() right(150) fd(180) right(40) pendown() begin_fill() fillcolor('green') circle(-100,80) right(150) fd(10) left(60) circle(-80,98) end_fill() penup() left(60) fd(13) left(180) pendown() speed(1) circle(-200,23) exitonclick()
绘制雪花
科赫曲线是de Rham曲线的特例
给定线段AB,科赫曲线可以由以下步骤生成
将线段分成三等份(AC,CD,DB)
以CD为底,向外(内外随意)画一个等边三角形DMC
将线段CD移去
分别对AC,CM,MD,DB重复1~3
太极阴阳
# coding:utf-8
from turtle import * def yin(radius, color1, color2):
width(3)
color("black", color1)
begin_fill()
circle(radius/2., 180)
circle(radius, 180)
left(180)
circle(-radius/2., 180)
end_fill()
left(90)
up()
forward(radius*0.35)
right(90)
down()
color(color1, color2)
begin_fill()
circle(radius*0.15)
end_fill()
left(90)
up()
backward(radius*0.35)
down()
left(90) def main():
reset()
yin(200, "black", "white")
yin(200, "white", "black")
ht()
return "Done!" if __name__ == '__main__':
main()
mainloop()
地球
# coding:utf-8 from turtle import Screen, Turtle, mainloop
from time import clock, sleep def mn_eck(p, ne,sz):
turtlelist = [p]
#create ne-1 additional turtles
for i in range(1,ne):
q = p.clone()
q.rt(360.0/ne)
turtlelist.append(q)
p = q
for i in range(ne):
c = abs(ne/2.0-i)/(ne*.7)
# let those ne turtles make a step
# in parallel:
for t in turtlelist:
t.rt(360./ne)
t.pencolor(1-c,0,c)
t.fd(sz) def main():
s = Screen()
s.bgcolor("black")
p=Turtle()
p.speed(0)
p.hideturtle()
p.pencolor("red")
p.pensize(3) s.tracer(36,0) at = clock()
mn_eck(p, 36, 19)
et = clock()
z1 = et-at sleep(1) at = clock()
while any([t.undobufferentries() for t in s.turtles()]):
for t in s.turtles():
t.undo()
et = clock()
return "runtime: %.3f sec" % (z1+et-at) if __name__ == '__main__':
msg = main()
print(msg)
mainloop()
两个画布
# coding:utf-8 from turtle import TurtleScreen, RawTurtle, TK def main():
root = TK.Tk()
cv1 = TK.Canvas(root, width=300, height=200, bg="#ddffff")
cv2 = TK.Canvas(root, width=300, height=200, bg="#ffeeee")
cv1.pack()
cv2.pack() s1 = TurtleScreen(cv1)
s1.bgcolor(0.85, 0.85, 1)
s2 = TurtleScreen(cv2)
s2.bgcolor(1, 0.85, 0.85) p = RawTurtle(s1)
q = RawTurtle(s2) p.color("red", (1, 0.85, 0.85))
p.width(3)
q.color("blue", (0.85, 0.85, 1))
q.width(3) for t in p,q:
t.shape("turtle")
t.lt(36) q.lt(180) for t in p, q:
t.begin_fill()
for i in range(5):
for t in p, q:
t.fd(50)
t.lt(72)
for t in p,q:
t.end_fill()
t.lt(54)
t.pu()
t.bk(50) return "EVENTLOOP" if __name__ == '__main__':
main()
TK.mainloop() # keep window open until user closes it
一棵树
# coding:utf-8 from turtle import Turtle, mainloop
from time import clock def tree(plist, l, a, f):
""" plist is list of pens
l is length of branch
a is half of the angle between 2 branches
f is factor by which branch is shortened
from level to level."""
if l > 3:
lst = []
for p in plist:
p.forward(l)
q = p.clone()
p.left(a)
q.right(a)
lst.append(p)
lst.append(q)
for x in tree(lst, l*f, a, f):
yield None def maketree():
p = Turtle()
p.setundobuffer(None)
p.hideturtle()
p.speed(0)
p.getscreen().tracer(30,0)
p.left(90)
p.penup()
p.forward(-210)
p.pendown()
t = tree([p], 200, 65, 0.6375)
for x in t:
pass
print(len(p.getscreen().turtles())) def main():
a=clock()
maketree()
b=clock()
return "done: %.2f sec." % (b-a) if __name__ == "__main__":
msg = main()
print(msg)
mainloop()
排序
# coding:utf-8
from turtle import *
import random class Block(Turtle): def __init__(self, size):
self.size = size
Turtle.__init__(self, shape="square", visible=False)
self.pu()
self.shapesize(size * 1.5, 1.5, 2) # square-->rectangle
self.fillcolor("black")
self.st() def glow(self):
self.fillcolor("red") def unglow(self):
self.fillcolor("black") def __repr__(self):
return "Block size: {0}".format(self.size) class Shelf(list): def __init__(self, y):
"create a shelf. y is y-position of first block"
self.y = y
self.x = -150 def push(self, d):
width, _, _ = d.shapesize()
# align blocks by the bottom edge
y_offset = width / 2 * 20
d.sety(self.y + y_offset)
d.setx(self.x + 34 * len(self))
self.append(d) def _close_gap_from_i(self, i):
for b in self[i:]:
xpos, _ = b.pos()
b.setx(xpos - 34) def _open_gap_from_i(self, i):
for b in self[i:]:
xpos, _ = b.pos()
b.setx(xpos + 34) def pop(self, key):
b = list.pop(self, key)
b.glow()
b.sety(200)
self._close_gap_from_i(key)
return b def insert(self, key, b):
self._open_gap_from_i(key)
list.insert(self, key, b)
b.setx(self.x + 34 * key)
width, _, _ = b.shapesize()
# align blocks by the bottom edge
y_offset = width / 2 * 20
b.sety(self.y + y_offset)
b.unglow() def isort(shelf):
length = len(shelf)
for i in range(1, length):
hole = i
while hole > 0 and shelf[i].size < shelf[hole - 1].size:
hole = hole - 1
shelf.insert(hole, shelf.pop(i))
return def ssort(shelf):
length = len(shelf)
for j in range(0, length - 1):
imin = j
for i in range(j + 1, length):
if shelf[i].size < shelf[imin].size:
imin = i
if imin != j:
shelf.insert(j, shelf.pop(imin))def partition(shelf, left, right, pivot_index):
pivot = shelf[pivot_index]
shelf.insert(right, shelf.pop(pivot_index))
store_index = left
for i in range(left, right):# range is non-inclusive of ending valueif shelf[i].size < pivot.size:
shelf.insert(store_index, shelf.pop(i))
store_index = store_index +1
shelf.insert(store_index, shelf.pop(right))# move pivot to correct positionreturn store_index def qsort(shelf, left, right):if left < right:
pivot_index = left
pivot_new_index = partition(shelf, left, right, pivot_index)
qsort(shelf, left, pivot_new_index -1)
qsort(shelf, pivot_new_index +1, right)def randomize():
disable_keys()
clear()
target = list(range(10))
random.shuffle(target)for i, t in enumerate(target):for j in range(i, len(s)):if s[j].size == t +1:
s.insert(i, s.pop(j))
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()def show_text(text, line=0):
line =20* line
goto(0,-250- line)
write(text, align="center", font=("Courier",16,"bold"))def start_ssort():
disable_keys()
clear()
show_text("Selection Sort")
ssort(s)
clear()
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()def start_isort():
disable_keys()
clear()
show_text("Insertion Sort")
isort(s)
clear()
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()def start_qsort():
disable_keys()
clear()
show_text("Quicksort")
qsort(s,0, len(s)-1)
clear()
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()def init_shelf():global s
s =Shelf(-200)
vals =(4,2,8,9,1,5,10,3,7,6)for i in vals:
s.push(Block(i))def disable_keys():
onkey(None,"s")
onkey(None,"i")
onkey(None,"q")
onkey(None,"r")def enable_keys():
onkey(start_isort,"i")
onkey(start_ssort,"s")
onkey(start_qsort,"q")
onkey(randomize,"r")
onkey(bye,"space")def main():
getscreen().clearscreen()
ht(); penup()
init_shelf()
show_text(instructions1)
show_text(instructions2, line=1)
enable_keys()
listen()return"EVENTLOOP" instructions1 ="press i for insertion sort, s for selection sort, q for quicksort"
instructions2 ="spacebar to quit, r to randomize"if __name__=="__main__":
msg = main()
mainloop()
圆舞曲
1 | # coding:utf-8 |
2 | |
3 | from turtle import * |
4 | |
5 | def stop(): |
6 | global running |
7 | running = False |
8 | |
9 | def main(): |
10 | global running |
11 | clearscreen() |
12 | bgcolor("gray10") |
13 | tracer(False) |
14 | shape("triangle") |
15 | f = 0.793402 |
16 | phi = 9.064678 |
17 | s = 5 |
18 | c = 1 |
19 | # create compound shape |
20 | sh = Shape("compound") |
21 | for i in range(10): |
22 | shapesize(s) |
23 | p =get_shapepoly() |
24 | s *= f |
25 | c *= f |
26 | tilt(-phi) |
27 | sh.addcomponent(p, (c, 0.25, 1-c), "black") |
28 | register_shape("multitri", sh) |
29 | # create dancers |
30 | shapesize(1) |
31 | shape("multitri") |
32 | pu() |
33 | setpos(0, -200) |
34 | dancers = [] |
35 | for i in range(180): |
36 | fd(7) |
37 | tilt(-4) |
38 | lt(2) |
39 | update() |
40 | if i % 12 == 0: |
41 | dancers.append(clone()) |
42 | home() |
43 | # dance |
44 | running = True |
45 | onkeypress(stop) |
46 | listen() |
47 | cs = 1 |
48 | while running: |
49 | ta = -4 |
50 | for dancer in dancers: |
51 | dancer.fd(7) |
52 | dancer.lt(2) |
53 | dancer.tilt(ta) |
54 | ta = -4 if ta > 0 else 2 |
55 | if cs < 180: |
56 | right(4) |
57 | shapesize(cs) |
58 | cs *= 1.005 |
59 | update() |
60 | return "DONE!" |
61 | |
62 | if __name__=='__main__': |
63 | print(main()) |
64 | mainloop() |
65 |
地球与行星
# coding:utf-8 from turtle import Shape, Turtle, mainloop, Vec2D as Vec G = 8 class GravSys(object):
def __init__(self):
self.planets = []
self.t = 0
self.dt = 0.01
def init(self):
for p in self.planets:
p.init()
def start(self):
for i in range(10000):
self.t += self.dt
for p in self.planets:
p.step() class Star(Turtle):
def __init__(self, m, x, v, gravSys, shape):
Turtle.__init__(self, shape=shape)
self.penup()
self.m = m
self.setpos(x)
self.v = v
gravSys.planets.append(self)
self.gravSys = gravSys
self.resizemode("user")
self.pendown()
def init(self):
dt = self.gravSys.dt
self.a = self.acc()
self.v = self.v + 0.5*dt*self.a
def acc(self):
a = Vec(0,0)
for planet in self.gravSys.planets:
if planet != self:
v = planet.pos()-self.pos()
a += (G*planet.m/abs(v)**3)*v
return a
def step(self):
dt = self.gravSys.dt
self.setpos(self.pos() + dt*self.v)
if self.gravSys.planets.index(self) != 0:
self.setheading(self.towards(self.gravSys.planets[0]))
self.a = self.acc()
self.v = self.v + dt*self.a ## create compound yellow/blue turtleshape for planets def main():
s = Turtle()
s.reset()
s.getscreen().tracer(0,0)
s.ht()
s.pu()
s.fd(6)
s.lt(90)
s.begin_poly()
s.circle(6, 180)
s.end_poly()
m1 = s.get_poly()
s.begin_poly()
s.circle(6,180)
s.end_poly()
m2 = s.get_poly() planetshape = Shape("compound")
planetshape.addcomponent(m1,"orange")
planetshape.addcomponent(m2,"blue")
s.getscreen().register_shape("planet", planetshape)
s.getscreen().tracer(1,0) ## setup gravitational system
gs = GravSys()
sun = Star(1000000, Vec(0,0),Vec(0,-2.5), gs,"circle")
sun.color("yellow")
sun.shapesize(1.8)
sun.pu()
earth =Star(12500,Vec(210,0),Vec(0,195), gs,"planet")
earth.pencolor("green")
earth.shapesize(0.8)
moon =Star(1,Vec(220,0),Vec(0,295), gs,"planet")
moon.pencolor("blue")
moon.shapesize(0.5)
gs.init()
gs.start()return"Done!"if __name__ =='__main__':
main()
mainloop()
细胞分裂
1 | # coding:utf-8 |
2 | |
3 | from turtle import * |
4 | from math import cos, pi |
5 | from time import clock, sleep |
6 | |
7 | f = (5**0.5-1)/2.0 # (sqrt(5)-1)/2 -- golden ratio |
8 | d = 2 * cos(3*pi/10) |
9 | |
10 | def kite(l): |
11 | fl = f * l |
12 | lt(36) |
13 | fd(l) |
14 | rt(108) |
15 | fd(fl) |
16 | rt(36) |
17 | fd(fl) |
18 | rt(108) |
19 | fd(l) |
20 | rt(144) |
21 | |
22 | def dart(l): |
23 | fl = f * l |
24 | lt(36) |
25 | fd(l) |
26 | rt(144) |
27 | fd(fl) |
28 | lt(36) |
29 | fd(fl) |
30 | rt(144) |
31 | fd(l) |
32 | rt(144) |
33 | |
34 | def inflatekite(l, n): |
35 | if n == 0: |
36 | px, py = pos() |
37 | h, x, y = int(heading()), round(px,3), round(py,3) |
38 | tiledict[(h,x,y)] = True |
39 | return |
40 | fl = f * l |
41 | lt(36) |
42 | inflatedart(fl, n-1) |
43 | fd(l) |
44 | rt(144) |
45 | inflatekite(fl, n-1) |
46 | lt(18) |
47 | fd(l*d) |
48 | rt(162) |
49 | inflatekite(fl, n-1) |
50 | lt(36) |
51 | fd(l) |
52 | rt(180) |
53 | inflatedart(fl, n-1) |
54 | lt(36) |
55 | |
56 | def inflatedart(l, n): |
57 | if n == 0: |
58 | px, py = pos() |
59 | h, x, y = int(heading()), round(px,3), round(py,3) |
60 | tiledict[(h,x,y)] = False |
61 | return |
62 | fl = f * l |
63 | inflatekite(fl, n-1) |
64 | lt(36) |
65 | fd(l) |
66 | rt(180) |
67 | inflatedart(fl, n-1) |
68 | lt(54) |
69 | fd(l*d) |
70 | rt(126) |
71 | inflatedart(fl, n-1) |
72 | fd(l) |
73 | rt(144) |
74 | |
75 | def draw(l, n, th=2): |
76 | clear() |
77 | l = l * f**n |
78 | shapesize(l/100.0, l/100.0, th) |
79 | for k in tiledict: |
80 | h, x, y = k |
81 | setpos(x, y) |
82 | setheading(h) |
83 | if tiledict[k]: |
84 | shape("kite") |
85 | color("black", (0, 0.75, 0)) |
86 | else: |
87 | shape("dart") |
88 | color("black", (0.75, 0, 0)) |
89 | stamp() |
90 | |
91 | def sun(l, n): |
92 | for i in range(5): |
93 | inflatekite(l, n) |
94 | lt(72) |
95 | |
96 | def star(l,n): |
97 | for i in range(5): |
98 | inflatedart(l, n) |
99 | lt(72) |
100 | |
101 | def makeshapes(): |
102 | tracer(0) |
103 | begin_poly() |
104 | kite(100) |
105 | end_poly() |
106 | register_shape("kite", get_poly()) |
107 | begin_poly() |
108 | dart(100) |
109 | end_poly() |
110 | register_shape("dart", get_poly()) |
111 | tracer(1) |
112 | |
113 | def start(): |
114 | reset() |
115 | ht() |
116 | pu() |
117 | makeshapes() |
118 | resizemode("user") |
119 | |
120 | def test(l=200, n=4, fun=sun, startpos=(0,0), th=2): |
121 | global tiledict |
122 | goto(startpos) |
123 | setheading(0) |
124 | tiledict = {} |
125 | a = clock() |
126 | tracer(0) |
127 | fun(l, n) |
128 | b = clock() |
129 | draw(l, n, th) |
130 | tracer(1) |
131 | c = clock() |
132 | print("Calculation: %7.4f s" % (b - a)) |
133 | print("Drawing: %7.4f s" % (c - b)) |
134 | print("Together: %7.4f s" % (c - a)) |
135 | nk = len([x for x in tiledict if tiledict[x]]) |
136 | nd = len([x for x in tiledict if not tiledict[x]]) |
137 | print("%d kites and %d darts = %d pieces." % (nk, nd, nk+nd)) |
138 | |
139 | def demo(fun=sun): |
140 | start() |
141 | for i in range(8): |
142 | a = clock() |
143 | test(300, i, fun) |
144 | b = clock() |
145 | t = b - a |
146 | if t < 2: |
147 | sleep(2 - t) |
148 | |
149 | def main(): |
150 | #title("Penrose-tiling with kites and darts.") |
151 | mode("logo") |
152 | bgcolor(0.3, 0.3, 0) |
153 | demo(sun) |
154 | sleep(2) |
155 | demo(star) |
156 | pencolor("black") |
157 | goto(0,-200) |
158 | pencolor(0.7,0.7,1) |
159 | write("Please wait...", |
160 | align="center", font=('Arial Black', 36, 'bold')) |
161 | test(600, 8, startpos=(70, 117)) |
162 | return "Done" |
163 | |
164 | if __name__ == "__main__": |
165 | msg = main() |
166 | mainloop() |
167 |
和平
1 | # coding:utf-8 |
2 | |
3 | from turtle import * |
4 | |
5 | def main(): |
6 | peacecolors = ("red3", "orange", "yellow", |
7 | "seagreen4", "orchid4", |
8 | "royalblue1", "dodgerblue4") |
9 | |
10 | reset() |
11 | Screen() |
12 | up() |
13 | goto(-320,-195) |
14 | width(70) |
15 | |
16 | for pcolor in peacecolors: |
17 | color(pcolor) |
18 | down() |
19 | forward(640) |
20 | up() |
21 | backward(640) |
22 | left(90) |
23 | forward(66) |
24 | right(90) |
25 | |
26 | width(25) |
27 | color("white") |
28 | goto(0,-170) |
29 | down() |
30 | |
31 | circle(170) |
32 | left(90) |
33 | forward(340) |
34 | up() |
35 | left(180) |
36 | forward(170) |
37 | right(45) |
38 | down() |
39 | forward(170) |
40 | up() |
41 | backward(170) |
42 | left(90) |
43 | down() |
44 | forward(170) |
45 | up() |
46 | |
47 | goto(0,300) # vanish if hideturtle() is not available ;-) |
48 | return "Done!" |
49 | |
50 | if __name__ == "__main__": |
51 | main() |
52 | mainloop() |
53 |
鼠标追随
1 | # coding:utf-8 |
2 | |
3 | from turtle import * |
4 | |
5 | def switchupdown(x=0, y=0): |
6 | if pen()["pendown"]: |
7 | end_fill() |
8 | up() |
9 | else: |
10 | down() |
11 | begin_fill() |
12 | |
13 | def changecolor(x=0, y=0): |
14 | global colors |
15 | colors = colors[1:]+colors[:1] |
16 | color(colors[0]) |
17 | |
18 | def main(): |
19 | global colors |
20 | shape("circle") |
21 | resizemode("user") |
22 | shapesize(.5) |
23 | width(3) |
24 | colors=["red", "green", "blue", "yellow"] |
25 | color(colors[0]) |
26 | switchupdown() |
27 | onscreenclick(goto,1) |
28 | onscreenclick(changecolor,2) |
29 | onscreenclick(switchupdown,3) |
30 | return "EVENTLOOP" |
31 | |
32 | if __name__ == "__main__": |
33 | msg = main() |
34 | print(msg) |
35 | mainloop() |
36 |
nim
1 | # coding:utf-8 |
2 | |
3 | import turtle |
4 | import random |
5 | import time |
6 | |
7 | SCREENWIDTH = 640 |
8 | SCREENHEIGHT = 480 |
9 | |
10 | MINSTICKS = 7 |
11 | MAXSTICKS = 31 |
12 | |
13 | HUNIT = SCREENHEIGHT // 12 |
14 | WUNIT = SCREENWIDTH // ((MAXSTICKS // 5) * 11 + (MAXSTICKS % 5) * 2) |
15 | |
16 | SCOLOR = (63, 63, 31) |
17 | HCOLOR = (255, 204, 204) |
18 | COLOR = (204, 204, 255) |
19 | |
20 | def randomrow(): |
21 | return random.randint(MINSTICKS, MAXSTICKS) |
22 | |
23 | def computerzug(state): |
24 | xored = state[0] ^ state[1] ^ state[2] |
25 | if xored == 0: |
26 | return randommove(state) |
27 | for z in range(3): |
28 | s = state[z] ^ xored |
29 | if s <= state[z]: |
30 | move = (z, s) |
31 | return move |
32 | |
33 | def randommove(state): |
34 | m = max(state) |
35 | while True: |
36 | z = random.randint(0,2) |
37 | if state[z] > (m > 1): |
38 | break |
39 | rand = random.randint(m > 1, state[z]-1) |
40 | return z, rand |
41 | |
42 | |
43 | class NimModel(object): |
44 | def __init__(self, game): |
45 | self.game = game |
46 | |
47 | def setup(self): |
48 | if self.game.state not in [Nim.CREATED, Nim.OVER]: |
49 | return |
50 | self.sticks = [randomrow(), randomrow(), randomrow()] |
51 | self.player = 0 |
52 | self.winner = None |
53 | self.game.view.setup() |
54 | self.game.state = Nim.RUNNING |
55 | |
56 | def move(self, row, col): |
57 | maxspalte = self.sticks[row] |
58 | self.sticks[row] = col |
59 | self.game.view.notify_move(row, col, maxspalte, self.player) |
60 | if self.game_over(): |
61 | self.game.state = Nim.OVER |
62 | self.winner = self.player |
63 | self.game.view.notify_over() |
64 | elif self.player == 0: |
65 | self.player = 1 |
66 | row, col = computerzug(self.sticks) |
67 | self.move(row, col) |
68 | self.player = 0 |
69 | |
70 | def game_over(self): |
71 | return self.sticks == [0, 0, 0] |
72 | |
73 | def notify_move(self, row, col): |
74 | if self.sticks[row] <= col: |
75 | return |
76 | self.move(row, col) |
77 | |
78 | |
79 | class Stick(turtle.Turtle): |
80 | def __init__(self, row, col, game): |
81 | turtle.Turtle.__init__(self, visible=False) |
82 | self.row = row |
83 | self.col = col |
84 | self.game = game |
85 | x, y = self.coords(row, col) |
86 | self.shape("square") |
87 | self.shapesize(HUNIT/10.0, WUNIT/20.0) |
88 | self.speed(0) |
89 | self.pu() |
90 | self.goto(x,y) |
91 | self.color("white") |
92 | self.showturtle() |
93 | |
94 | def coords(self, row, col): |
95 | packet, remainder = divmod(col, 5) |
96 | x = (3 + 11 * packet + 2 * remainder) * WUNIT |
97 | y = (2 + 3 * row) * HUNIT |
98 | return x - SCREENWIDTH // 2 + WUNIT // 2, SCREENHEIGHT // 2 - y - HUNIT // 2 |
99 | |
100 | def makemove(self, x, y): |
101 | if self.game.state != Nim.RUNNING: |
102 | return |
103 | self.game.controller.notify_move(self.row, self.col) |
104 | |
105 | |
106 | class NimView(object): |
107 | def __init__(self, game): |
108 | self.game = game |
109 | self.screen = game.screen |
110 | self.model = game.model |
111 | self.screen.colormode(255) |
112 | self.screen.tracer(False) |
113 | self.screen.bgcolor((240, 240, 255)) |
114 | self.writer = turtle.Turtle(visible=False) |
115 | self.writer.pu() |
116 | self.writer.speed(0) |
117 | self.sticks = {} |
118 | for row in range(3): |
119 | for col in range(MAXSTICKS): |
120 | self.sticks[(row, col)] = Stick(row, col, game) |
121 | self.display("... a moment please ...") |
122 | self.screen.tracer(True) |
123 | |
124 | def display(self, msg1, msg2=None): |
125 | self.screen.tracer(False) |
126 | self.writer.clear() |
127 | if msg2 is not None: |
128 | self.writer.goto(0, - SCREENHEIGHT // 2 + 48) |
129 | self.writer.pencolor("red") |
130 | self.writer.write(msg2, align="center", font=("Courier",18,"bold")) |
131 | self.writer.goto(0, - SCREENHEIGHT // 2 + 20) |
132 | self.writer.pencolor("black") |
133 | self.writer.write(msg1, align="center", font=("Courier",14,"bold")) |
134 | self.screen.tracer(True) |
135 | |
136 | def setup(self): |
137 | self.screen.tracer(False) |
138 | for row in range(3): |
139 | for col in range(self.model.sticks[row]): |
140 | self.sticks[(row, col)].color(SCOLOR) |
141 | for row in range(3): |
142 | for col in range(self.model.sticks[row], MAXSTICKS): |
143 | self.sticks[(row, col)].color("white") |
144 | self.display("Your turn! Click leftmost stick to remove.") |
145 | self.screen.tracer(True) |
146 | |
147 | def notify_move(self, row, col, maxspalte, player): |
148 | if player == 0: |
149 | farbe = HCOLOR |
150 | for s in range(col, maxspalte): |
151 | self.sticks[(row, s)].color(farbe) |
152 | else: |
153 | self.display(" ... thinking ... ") |
154 | time.sleep(0.5) |
155 | self.display(" ... thinking ... aaah ...") |
156 | farbe = COLOR |
157 | for s in range(maxspalte-1, col-1, -1): |
158 | time.sleep(0.2) |
159 | self.sticks[(row, s)].color(farbe) |
160 | self.display("Your turn! Click leftmost stick to remove.") |
161 | |
162 | def notify_over(self): |
163 | if self.game.model.winner == 0: |
164 | msg2 = "Congrats. You're the winner!!!" |
165 | else: |
166 | msg2 = "Sorry, the computer is the winner." |
167 | self.display("To play again press space bar. To leave press ESC.", msg2) |
168 | |
169 | def clear(self): |
170 | if self.game.state == Nim.OVER: |
171 | self.screen.clear() |
172 | |
173 | |
174 | class NimController(object): |
175 | |
176 | def __init__(self, game): |
177 | self.game = game |
178 | self.sticks = game.view.sticks |
179 | self.BUSY = False |
180 | for stick in self.sticks.values(): |
181 | stick.onclick(stick.makemove) |
182 | self.game.screen.onkey(self.game.model.setup, "space") |
183 | self.game.screen.onkey(self.game.view.clear, "Escape") |
184 | self.game.view.display("Press space bar to start game") |
185 | self.game.screen.listen() |
186 | |
187 | def notify_move(self, row, col): |
188 | if self.BUSY: |
189 | return |
190 | self.BUSY = True |
191 | self.game.model.notify_move(row, col) |
192 | self.BUSY = False |
193 | |
194 | |
195 | class Nim(object): |
196 | CREATED = 0 |
197 | RUNNING = 1 |
198 | OVER = 2 |
199 | def __init__(self, screen): |
200 | self.state = Nim.CREATED |
201 | self.screen = screen |
202 | self.model = NimModel(self) |
203 | self.view = NimView(self) |
204 | self.controller = NimController(self) |
205 | |
206 | |
207 | def main(): |
208 | mainscreen = turtle.Screen() |
209 | mainscreen.mode("standard") |
210 | mainscreen.setup(SCREENWIDTH, SCREENHEIGHT) |
211 | nim = Nim(mainscreen) |
212 | return "EVENTLOOP" |
213 | |
214 | if __name__ == "__main__": |
215 | main() |
216 | turtle.mainloop() |
217 |
python turtle 例子 海归绘图的更多相关文章
-
从Scratch到Python——python turtle 一种比pygame更加简洁的实现
从Scratch到Python--python turtle 一种比pygame更加简洁的实现 现在很多学校都开设了Scratch课程,学生可以利用Scratch创作丰富的作品,然而Scratch之后 ...
-
这42个Python小例子,太走心
告别枯燥,60秒学会一个Python小例子.奔着此出发点,我在过去1个月,将平时经常使用的代码段换为小例子,分享出来后受到大家的喜欢. 一.基本操作 1 链式比较 i = 3print(1 < ...
-
python+turtle 笔记
用Python+turtle绘制佩琪: from turtle import * def nose(x,y):#鼻子 penup()#提起笔 goto(x,y)#定位 pendown()#落笔,开始画 ...
-
让小乌龟可以唱歌——对Python turtle进行拓展
在Scratch中,小猫是可以唱歌的,而且Scratch的声音木块有着丰富的功能,在这方面Python turtle略有欠缺,今天我们就来完善一下. Python声音模块 Python处理声音的模块很 ...
-
Note of Python Turtle
Note of Python Turtle Turtle 库函数是 Python语言中一个流行的绘图函数库.Turtle 意思是海龟,在Python中显示为一个小箭头,通过它的移动而留 ...
-
Python turtle库详解
Python turtle库详解 Turtle库是Python语言中一个很流行的绘制图像的函数库,想象一个小乌龟,在一个横轴为x.纵轴为y的坐标系原点,(0,0)位置开始,它根据一组函数指令的控制,在 ...
-
Python turtle绘制阴阳太极图代码解析
本文详细分析如何使用Python turtle绘制阴阳太极图,先来分解这个图形,图片中有四种颜色,每条曲线上的箭头表示乌龟移动的方向,首先从中心画一个半圆(红线),以红线所示圆的直径作半径画一个校园, ...
-
[Spark][Python]groupByKey例子
Spark Python 索引页 [Spark][Python]sortByKey 例子 的继续: [Spark][Python]groupByKey例子 In [29]: mydata003.col ...
-
[Spark][Python]sortByKey 例子
[Spark][Python]sortByKey 例子: [training@localhost ~]$ hdfs dfs -cat test02.txt00002 sku01000001 sku93 ...
随机推荐
-
SQL Server 阻止了对组件 &#39;Ad Hoc Distributed Queries&#39; 的 STATEMENT&#39;OpenRowset/OpenDatasource&#39; 的访问
delphi ado 跨数据库访问 语句如下 ' and db = '帐套1' 报错内容是:SQL Server 阻止了对组件 'Ad Hoc Distributed Queries' 的 STATE ...
-
Bootstrap UI 编辑器
1. BootSwatchr BootSwatchr 是由 Drew Strickiand 独立开发和维护的,是唯一支持从右到左语言显示的 Bootstrap 自定义构建工具,这也是它的特色之一.Bo ...
-
sqlalchemy(一)基本操作
sqlalchemy(一)基本操作 sqlalchemy采用简单的Python语言,为高效和高性能的数据库访问设计,实现了完整的企业级持久模型. 安装 需要安装MySQLdb pip install ...
-
StackExchange.Redis 使用-配置
Configurationredis有很多不同的方法来配置连接字符串 , StackExchange.Redis 提供了一个丰富的配置模型,当调用Connect 或者 ConnectAsync 时需要 ...
-
参考:(Java Selenium)Element is not visible to clcik
1.The element is not visible to click. Use Actions or JavascriptExecutor for making it to click. By ...
-
远程桌面Default.rdp 中各个参数的含义
存储在 Default.rdp 文件中的设置 默认情况下,将在“我的文档”文件夹中创建 Default.rdp 文件.以下 RDP 设置存储在 Desktop.rdp 文件中: desktopwidt ...
-
php+jquery注册实例
写了一个简单的PHP+jQuery注册模块,需要填写的栏目包括用户名.邮箱.密码.重复密码和验证码,其中每个栏目需要具备的功能和要求如下图: 在做这个模块的时候,很大程度上借鉴了网易注册( http: ...
-
Product(大数相乘)
Description The problem is to multiply two integers X, Y. (0<=X,Y<10250) Input The input will ...
-
ReactiveX序列——RxSwift 浅析
ReactiveX序列——RxSwift Swift是苹果公司新推出的一门现代化的编程语言,并且将其开源出来了,Swift具有很多的优点,这也使得这门语言推出的短时间引起了很大反应的原因,在最近的 ...
-
Python作业之购物车
作业之购物车 购物车的要求如下: 输入总金额 选择购买的商品,金额足够时,把选择的商品添加到购物车,金额不足时,进行提示,商品将不会添加到购物车 随时可以退出程序,同时输出已购买的商品 具体代码如下: ...