【发布时间】:2015-10-24 23:37:27
【问题描述】:
因此,对于我目前的大学论文,我们打算创建一个 Sierpinksi 三角形并在其中递归地绘制新三角形。
我们得到的原始代码是这样的:
import sys, pygame
# a function that will draw a right-angled triangle of a given size anchored at a given location
def draw_triangle(screen, x, y, size):
pygame.draw.polygon(screen,white,[[x,y], [x+size,y], [x,y-size]])
#############################################################################################
# Define a function that will draw Sierpinski's Triangle at a given size anchored at a given location
# You need to update this function
# currently only one triangle is drawn
def sierpinski(screen, x, y, size):
draw_triangle(screen, x, y, size)
#############################################################################################
# Initialize the game engine
pygame.init()
# Define the colors we will use in RGB format
black = [ 0, 0, 0]
white = [255,255,255]
blue = [ 0, 0,255]
green = [ 0,255, 0]
red = [255, 0, 0]
# Set the height and width of the screen
size=[512, 512]
screen=pygame.display.set_mode(size)
# Loop until the user clicks the close button.
done=False
clock = pygame.time.Clock()
while done==False:
# This limits the while loop to a max of 10 times per second.
# Leave this out and we will use all CPU we can.
clock.tick(10)
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
# Clear the screen and set the screen background
screen.fill(black)
# Draw Sierpinski's triangle at a given size anchored at a given location
sierpinski(screen,0, 512, 512)
# Go ahead and update the screen with what we've drawn.
# This MUST happen after all the other drawing commands.
pygame.display.flip()
# Tidy up
pygame.quit ()
好的,我知道这只会创建一个三角形。这是我为使其“有点”工作所做的:
我创建了一个新的三角形函数来绘制一个倒三角形:
def draw_upside_down_triangle(screen, x, y, size, color):
pygame.draw.polygon(screen, color, [[x+size, y+size], [x+size, y], [x, y]])
然后我更新了旧的三角形函数以接受颜色变量:
def draw_triangle(screen, x, y, size, color):
pygame.draw.polygon(screen, color, [[x, y], [x+size, y], [x, y-size]])
之后我更新了递归绘制三角形的主函数:
def sierpinski(screen, x, y, size):
if size < 10:
return False
else:
draw_triangle(screen, x, y, size, white)
draw_upside_down_triangle(screen, x, y/2, size/2, black)
sierpinski(screen, x+size/2, y+size/2, size/2)
sierpinski(screen, x, y-size/2, size/2)
sierpinski(screen, x, y, size/2)
sierpinski(screen, x, y+size/2, size/2)
我关闭了这个功能
- 通过添加exit参数(当三角形get太小返回false)
- 如果不是太小,则用白色绘制第一个三角形
- 然后在相同的 x 位置绘制一个大小为一半但 y 位置为 黑色 的倒置三角形(这会产生 3 个三角形错觉)
- 毕竟我有 4 个递归调用,根据实验,我知道这些调用的顺序很重要,因为输出在更改时会发生根本变化。
目前输出如下:
我并不是要求任何人完成或更正我的代码,只是为了更好地理解或指出正确的方向。已经和这个战斗了几个小时了。
谢谢!
【问题讨论】:
-
让我想起了我早期的一个 pygame 脚本,其中我使用chaos game 技术绘制了一个谢尔宾斯基三角形。
标签: python recursion pygame fractals