Created
February 11, 2024 21:45
-
-
Save rkibria/387fd9b7a0b6bbc2be15afda0e4240a8 to your computer and use it in GitHub Desktop.
Fading effect in pygame using a blit from a surface based on a bytearray
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A fading effect created by manipulating a bytearray that underlies a Surface object | |
""" | |
import math, pygame | |
def main(): | |
pygame.init() | |
size = width, height = 320, 240 | |
screen = pygame.display.set_mode(size) | |
pygame.display.set_caption("Blit from bytearray") | |
clock = pygame.time.Clock() | |
bytes_image = bytearray(width * height * 4) | |
picture = pygame.image.frombuffer(bytes_image, size, 'RGBA') | |
frame = 0 | |
main_surface = pygame.display.get_surface() | |
rays = list() | |
num_rays = 200 | |
for i in range(num_rays): | |
# x, y, vx, vy | |
phi = 2 * math.pi / num_rays * i | |
rays.append([width/2, height/2, math.cos(phi), math.sin(phi)]) | |
def set_color(x, y, color): | |
i = (y * width + x) * 4 | |
bytes_image[i+0] = color.r | |
bytes_image[i+1] = color.g | |
bytes_image[i+2] = color.b | |
bytes_image[i+3] = 255 | |
# bg_surface = pygame.image.load('bg320x240.jpg') | |
def get_bg_color(x, y): | |
# return bg_surface.get_at((int(x), int(y))) | |
# simple gradient: | |
u = x / width | |
v = y / height | |
return pygame.Color(int(u * 255) % 255, | |
int(v * 255) % 255, | |
int((1 - u) * 255) % 255, | |
255) | |
while True: | |
clock.tick(60) | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT or event.type == pygame.KEYDOWN: | |
return | |
for ray in rays: | |
x,y,vx,vy = ray | |
x += vx | |
if x < 0 or x >= width: | |
x -= vx | |
vx *= -1 | |
y += vy | |
if y < 0 or y >= height: | |
y -= vy | |
vy *= -1 | |
set_color(int(x), int(y), get_bg_color(x, y)) | |
ray[0] = x | |
ray[1] = y | |
ray[2] = vx | |
ray[3] = vy | |
main_surface.blit(picture, (0, 0)) | |
pygame.display.flip() | |
frame += 1 | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://imgur.com/a/fUsVgRQ