gpt4 book ai didi

python - 如何在pygame中从一种颜色淡入另一种颜色?

转载 作者:太空宇宙 更新时间:2023-11-03 12:26:20 25 4
gpt4 key购买 nike

我如何在 pygame 中从一种颜色淡入另一种颜色?我想慢慢地改变圆圈的颜色,从绿色到蓝色到紫色到粉红色到红色到橙色到黄色再到绿色。我该怎么做?目前,我正在使用

def colour():
switcher = {
0: 0x2FD596,
1: 0x2FC3D5,
2: 0x2F6BD5,
3: 0x432FD5,
4: 0x702FD5,
5: 0xBC2FD5,
6: 0xD52F91,
7: 0xD52F43,
8: 0xD57F2F,
9: 0xD5D52F,
10: 0x64D52F,
11: 0x2FD557,
}
return switcher.get(round((datetime.datetime.now() - starting_time).total_seconds()%11))

但这在颜色之间有很大的差距,看起来很笨重。

最佳答案

关键是简单地计算每一步您必须改变每个 channel (a、r、g 和 b)的程度。 Pygame 的 Color 类非常方便,因为它允许在每个 channel 上进行迭代,而且它的输入很灵活,所以你可以改变,例如'blue' 到下面示例中的 0x2FD596,它仍然会运行。

这是一个简单的运行示例:

import pygame
import itertools

pygame.init()

screen = pygame.display.set_mode((800, 600))

colors = itertools.cycle(['green', 'blue', 'purple', 'pink', 'red', 'orange'])

clock = pygame.time.Clock()

base_color = next(colors)
next_color = next(colors)
current_color = base_color

FPS = 60
change_every_x_seconds = 3.
number_of_steps = change_every_x_seconds * FPS
step = 1

font = pygame.font.SysFont('Arial', 50)

running = True
while running:

for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

text = font.render('fading {a} to {b}'.format(a=base_color, b=next_color), True, pygame.color.Color('black'))

step += 1
if step < number_of_steps:
# (y-x)/number_of_steps calculates the amount of change per step required to
# fade one channel of the old color to the new color
# We multiply it with the current step counter
current_color = [x + (((y-x)/number_of_steps)*step) for x, y in zip(pygame.color.Color(base_color), pygame.color.Color(next_color))]
else:
step = 1
base_color = next_color
next_color = next(colors)

screen.fill(pygame.color.Color('white'))
pygame.draw.circle(screen, current_color, screen.get_rect().center, 100)
screen.blit(text, (230, 100))
pygame.display.update()
clock.tick(FPS)

enter image description here


如果您不想依赖帧率而是使用基于时间的方法,您可以将代码更改为:

...
change_every_x_milliseconds = 3000.
step = 0

running = True
while running:

...

if step < change_every_x_milliseconds:
current_color = [x + (((y-x)/change_every_x_milliseconds)*step) for x, y in zip(pygame.color.Color(base_color), pygame.color.Color(next_color))]
else:
...
...

pygame.display.update()
step += clock.tick(60)

关于python - 如何在pygame中从一种颜色淡入另一种颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51973441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com