如何在 pygame.draw.lines 中为每一行使用不同的颜色 [英] How to use different colors for each line in pygame.draw.lines
问题描述
我最近开始学习 pygame
,这就是我的问题.无论如何,我可以为使用 pygame.draw.lines
绘制的每条线使用不同的颜色吗?这是我的代码.
导入pygamepygame.init()屏幕 = pygame.display.set_mode((640, 480), pygame.SCALED)screen.fill('白色')pygame.draw.lines(screen, 'red', True, [(10, 100), (20, 200), (30, 100)]) # 所有线条都是红色的为真:pygame.display.update()
我得到的输出
我想要的输出
我尝试了什么
pygame.draw.lines(screen, ['green', 'blue', 'orange'], True, [(10, 100), (20, 200), (30, 100)])
错误
ValueError: 无效的颜色参数
换句话说,我想在下面的代码中实现我想要的但使用 pygame.draw.lines
pygame.draw.line(screen, 'green', (10, 100), (20, 200))pygame.draw.line(screen, 'blue', (20, 200), (30, 100))pygame.draw.line(screen, 'orange', (30, 100), (10, 100))
我检查了 pygame.draw.lines
I recently started to learn pygame
and herein lies my question. Is there anyway I can use different colors for each line drawn using pygame.draw.lines
? This is my code.
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480), pygame.SCALED)
screen.fill('white')
pygame.draw.lines(screen, 'red', True, [(10, 100), (20, 200), (30, 100)]) # all lines are red
while True:
pygame.display.update()
Output I get
Output I want
What I tried
pygame.draw.lines(screen, ['green', 'blue', 'orange'], True, [(10, 100), (20, 200), (30, 100)])
Error
ValueError: invalid color argument
In other words, I want to achieve what I want in the following code but using pygame.draw.lines
pygame.draw.line(screen, 'green', (10, 100), (20, 200))
pygame.draw.line(screen, 'blue', (20, 200), (30, 100))
pygame.draw.line(screen, 'orange', (30, 100), (10, 100))
I checked the pygame.draw.lines
docs but I am not sure if the color
argument there takes a list as I have given. It only mentions "Color or int or tuple(int, int, int, [int]))
"
This example is for a triangle, but in my actual use-case I want to draw a decagon and I am not sure if using pygame.draw.line
10 times is the way to go if I want a different color for each line.
PS : Do let me know if any clarification is needed. Many Thanks.
You have to draw each line segment separately. Write a function that uses a list of points and colors to draw the line:
def draw_colorful_line(surf, colors, closed, points, width=1):
for i in range(len(points)-1):
pygame.draw.line(surf, colors[i], points[i], points[i+1], width)
if closed:
pygame.draw.line(surf, colors[-1], points[-1], points[0], width)
Use the function to draw the line:
colors = ['green', 'blue', 'red']
points = [(10, 100), (20, 200), (30, 100)]
draw_colorful_line(screen, colors, True, points)
这篇关于如何在 pygame.draw.lines 中为每一行使用不同的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!