如何修改Pygame星形绘制代码添加内部条纹图案?
给Pygame星形添加内部条纹的实现方案
下面提供两种实用的实现方式,你可以根据需求选择:
方案1:中心辐射状条纹
这种方式从星形中心向各个顶点绘制线条,形成放射状条纹效果,代码改动极小:
import pygame # Window size WINDOW_WIDTH = 400 WINDOW_HEIGHT = 400 DARK_BLUE = ( 3, 5, 54) STARRY = ( 230, 255, 80 ) ### initialisation pygame.init() window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) ) pygame.display.set_caption("Star with Radial Stripes") # Define a star centre_coord = ( WINDOW_WIDTH//2, WINDOW_HEIGHT//2 ) star_points = [ (165, 151), (200, 20), (235, 151), (371, 144), (257, 219), (306, 346), (200, 260), (94, 346), (143, 219), (29, 144) ] # Main Loop clock = pygame.time.Clock() done = False while not done: # Handle user-input for event in pygame.event.get(): if ( event.type == pygame.QUIT ): done = True # Re-draw the window window.fill( DARK_BLUE ) # background fill pygame.draw.polygon( window, STARRY, star_points ) # Draw the star base # 添加中心辐射条纹 stripe_color = DARK_BLUE stripe_thickness = 3 for point in star_points: pygame.draw.line(window, stripe_color, centre_coord, point, stripe_thickness) pygame.display.flip() # Update the display # Clamp FPS clock.tick_busy_loop(60) pygame.quit()
方案2:平行填充条纹(横向/纵向)
如果需要平行条纹效果,可以利用Pygame的**剪切区域(clip)**功能,限制条纹仅在星形内部绘制,灵活性更高:
import pygame # Window size WINDOW_WIDTH = 400 WINDOW_HEIGHT = 400 DARK_BLUE = ( 3, 5, 54) STARRY = ( 230, 255, 80 ) ### initialisation pygame.init() window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) ) pygame.display.set_caption("Star with Parallel Stripes") # Define a star centre_coord = ( WINDOW_WIDTH//2, WINDOW_HEIGHT//2 ) star_points = [ (165, 151), (200, 20), (235, 151), (371, 144), (257, 219), (306, 346), (200, 260), (94, 346), (143, 219), (29, 144) ] # Main Loop clock = pygame.time.Clock() done = False while not done: # Handle user-input for event in pygame.event.get(): if ( event.type == pygame.QUIT ): done = True # Re-draw the window window.fill( DARK_BLUE ) # background fill # 创建带alpha的表面,用于绘制带条纹的星形 star_surface = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT), pygame.SRCALPHA) # 先绘制星形底色 pygame.draw.polygon(star_surface, STARRY, star_points) # 设置剪切区域,后续绘制仅在星形内部生效 star_surface.set_clip(star_points) # 绘制横向条纹(改成x轴循环可实现纵向条纹) stripe_color = DARK_BLUE stripe_height = 8 stripe_spacing = stripe_height # 间距等于条纹高度,形成交替效果 for y in range(0, WINDOW_HEIGHT, stripe_height + stripe_spacing): pygame.draw.rect(star_surface, stripe_color, (0, y, WINDOW_WIDTH, stripe_height)) # 将带条纹的星形贴到窗口 window.blit(star_surface, (0, 0)) pygame.display.flip() # Update the display # Clamp FPS clock.tick_busy_loop(60) pygame.quit()
补充说明
- 方案1适合快速实现放射状效果,调整
stripe_thickness可改变线条粗细; - 方案2可通过修改
stripe_height、stripe_spacing或循环轴方向,得到不同密度、方向的平行条纹; - 若需要斜向条纹,可将绘制矩形改为绘制斜线,循环调整线条的起始/结束坐标即可。
内容的提问来源于stack exchange,提问作者3141592654
相关产品推荐
相关产品推荐

