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

Dex*_*ion 3 python pygame colors

如何在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))
Run Code Online (Sandbox Code Playgroud)

但这在颜色之间确实迈出了很大的一步,而且看上去笨拙。

slo*_*oth 5

关键是简单地计算出每个步骤每个通道(a,r,g和b)必须更改的数量。Pygame的Color类非常方便,因为它允许在每个通道上进行迭代,并且输入灵活,因此您可以在下面的示例中将例如更改'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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


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

...
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)
Run Code Online (Sandbox Code Playgroud)