Pygame接口应用·递归分形

王朝c#·作者佚名  2006-12-17
窄屏简体版  字體: |||超大  

[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()

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航