我目前的大学论文要求我们创建一个Sierpinski三角形,并递归地在内部绘制新的三角形。
我们得到的原始代码是这样的:
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)
我开始编写这个函数:
- 添加退出参数(当三角形变得太小时返回 false)
- 如果三角形不太小,则用白色绘制第一个三角形
- 之后在相同的 x 位置但 y 坐标减半的地方,用黑色绘制一个倒置的一半大小的三角形(这创造了三角形错觉)
- 最后进行4次递归调用,经过实验,我知道这些调用的顺序很重要,因为改变它们会导致输出发生巨大变化。
目前的输出如下所示:
我并不是要求任何人完成或修正我的代码,只是想更好地理解或指出正确的方向。我已经苦战了几个小时。
谢谢!