[by sunyuemng ymsjj@sina.com 转载请保留]
这是上半年对分形有兴趣的写的,用到了pygame作为显示接口,
你把pygame的接口函数集看看就很清楚了,然后就是充分利用
了python的数据类型的优势,对对象很陌生的朋友也很容易搞清
下面的程序,有兴趣的朋友可以看看。
请安装合适版本的python和pygame。
#filename fractal.py
import pygame
from pygame.locals import *
fg=220,220,220
bg=0,0,0
#如何指定向量:
#将图形右转90度,使level=1的唯一的线段和线段(0,0)^(1,0)重合,
#然后取父线起点、终点,母线起点,起点指向终点的向量
#∧形填充线父体
f_a=[(.5j,1),
(-.5j,1)]
f_b=[(0,.5),
(.5+.5j,.5-.5j)]
#填充线母体
m_a=[(.5+.25j,.5),
(.5-.25j,.5),
(.25-.5j,.5j),
(.25+.5j,-.5j)]
#龙曲线
m_b=[(.5-.5j,.5+.5j),
(.5-.5j,-.5+.5j)]
#koch
m_c=[(0,.333),
(.333,.167-.289j),
(.5-.289j,.167+.289j),
(.667,.333)]
#sierpinski变种
m_d=[(.25-.433j,-.25+.433j),
(.25-.433j,.5),(1,-.25-.433j)]
#四种树
m_e=[(1,.4-.4j),
(1,.4+.4j)]
m_f=[(.5,.5),
(.3,.38+.25j),
(.3,.38-.25j)]
m_g=[(0,.4),(.4,.3),
(.7,.3),(.4,.25-.17j),
(.7,.25+.17j)]
m_h=[(0,.5),
(.5,.5),
(1,.21-.2j),
(1.21-.2j,.41-.12j),
(1.62-.32j,.38+.06j),
(1,.37+.2j),
(1.37+.2j,.36),
(1.73+.2j,.27-.16j)]
p_a=(80+230j,200+0j)
p_b=(50+300j,300+0j)
p_c=(200+330j,-110j)
name=[filling line 1,
dragon curve,
koch,
sierpinski-like,
filling line 2,
tree 1,
tree 2,
tree 3,
tree 4]
father=[f_a,0,0,0,f_b,0,0,0,0] #父体表
mother=[m_a,m_b,m_c,m_d,m_a,m_e,m_f,m_g,m_h] #母体表
limit=[5,11,5,8,6,8,6,4,4] #最大跌代次数
holdon=[0,0,0,0,0,1,1,1,1] #是否保留上一级图形
place=[0,p_a,p_b,p_b,0,p_c,0,0,p_c] #输出与屏幕的向量差
def fractal(base,vector,level):
if level:
for b,v in mother:
b=b*vector+base
v=v*vector
fractal(b,v,level-1)
elif not father:
pygame.draw.line(screen,fg,(base.real,
base.imag),
(base.real+vector.real,
base.imag+vector.imag))
else:
for s,e in father:
s=s*vector+base
e=e*vector+base
pygame.draw.line(screen,fg,(s.real,s.imag),
(e.real,e.imag))
pygame.init()
pygame.display.set_caption(分形图形 0.2α sunyueming)
screen=pygame.display.set_mode((400,400))
screen.fill(bg)
font=pygame.font.font(none, 16)
fn=0
lv=0
fn=1
lv=1
done=0
while not done:
for e in pygame.event.get():
if e.type == quit or (e.type == keyup and e.key == k_escape):
done=1
if e.type == keyup and e.key == k_down:
if fn<>len(mother)-1:
fn=fn+1
else:
fn=0
lv=0
screen.fill(bg)
if e.type == keyup and e.key == k_space:
if lv lv=lv+1
if not holdon[fn]:
screen.fill(bg)
if fn<>fn or lv<>lv:
mother=mother[fn]
father=father[fn]
if not place[fn]:
pb,pv=200+320j,-240j
else:
pb,pv=place[fn]
text=practal – +name[fn]+ level=+str(lv+1)+
ren=font.render(text, 0, fg, bg)
screen.blit(ren, (10, 10))
fn=fn
lv=lv
fractal(pb,pv,lv)
pygame.display.update()
