|
发表于 2025-4-23 08:08:15
|
显示全部楼层
以下是修正后的代码,修正了坐标转换、递归逻辑和语法错误,现在可以分步绘制谢尔宾斯基三角形:
- import pygame
- import math
- import sys
- # 初始化设置
- pygame.init()
- WIDTH, HEIGHT = 1000, 800
- screen = pygame.display.set_mode((WIDTH, HEIGHT))
- pygame.display.set_caption("谢尔宾斯基三角形")
- clock = pygame.time.Clock()
- # 颜色定义
- COLORS = {
- "bg": (25, 25, 35),
- "line": (180, 210, 255),
- "highlight": (100, 200, 255)
- }
- # 动画系统参数
- class AnimState:
- def __init__(self):
- self.drawing_stack = [] # 修正:初始化空列表
- self.speed = 1
- self.is_paused = False
- self.step_counter = 0
- # 坐标系转换(修正坐标转换逻辑)
- def adjust_coords(x, y):
- return (x + WIDTH//2, HEIGHT//2 - y)
- # 递归绘制生成器(修正递归逻辑)
- def recursive_draw_gen(parent_points, depth):
- if depth < 0: return
-
- # 绘制正三角形
- yield ("draw", parent_points)
-
- # 计算三个中点
- a, b, c = parent_points
- mid_ab = ((a[0]+b[0])/2, (a[1]+b[1])/2)
- mid_bc = ((b[0]+c[0])/2, (b[1]+c[1])/2)
- mid_ca = ((c[0]+a[0])/2, (c[1]+a[1])/2)
-
- # 生成三个子三角形任务
- yield from recursive_draw_gen([a, mid_ab, mid_ca], depth-1)
- yield from recursive_draw_gen([b, mid_ab, mid_bc], depth-1)
- yield from recursive_draw_gen([c, mid_ca, mid_bc], depth-1)
- def main():
- state = AnimState()
- size = 400 # 缩小尺寸以适应屏幕
-
- # 初始正三角形顶点(修正坐标计算)
- initial_points = [
- (0, size * math.sqrt(3)/3), # 顶部顶点
- (-size/2, -size * math.sqrt(3)/6), # 左下
- (size/2, -size * math.sqrt(3)/6) # 右下
- ]
-
- state.drawing_stack = list(recursive_draw_gen(initial_points, depth=5))
-
- while True:
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- pygame.quit()
- sys.exit()
-
- screen.fill(COLORS["bg"]) # 修正:使用具体颜色键
-
- # 绘制逻辑
- if not state.is_paused and state.drawing_stack:
- steps = int(math.pow(2, state.speed - 1))
- for _ in range(min(steps, len(state.drawing_stack))):
- action, points = state.drawing_stack.pop(0)
-
- if action == "draw":
- # 转换所有顶点坐标
- adjusted = [adjust_coords(x, y) for x, y in points]
- pygame.draw.polygon(screen, COLORS["line"], adjusted, 1)
-
- state.step_counter += 1
-
- pygame.display.flip()
- clock.tick(60)
- if __name__ == "__main__":
- main()
复制代码
修改亮点说明:
1. 坐标转换:修正后的 adjust_coords 函数现在能正确将数学坐标转换为屏幕坐标
2. 递归逻辑:现在正确计算中点并生成三个子三角形
3. 初始三角形:使用等边三角形公式计算顶点坐标
4. 绘制逻辑:使用列表推导式转换所有顶点坐标
5. 颜色使用:修正了颜色字典的键值引用
运行效果:程序会从最大的正三角形开始,逐步绘制出越来越小的子三角形,最终形成经典的谢尔宾斯基分形图案。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|