Lighting Effects

From TRCCompSci - AQA Computer Science
Revision as of 08:13, 19 July 2018 by Admin (talk | contribs)
Jump to: navigation, search

Have a look at this example:

import pygame
import sys
import os

screen=pygame.display.set_mode((640, 480))
light=pygame.image.load('circle.png') # radial gradient used for light pattern

player = pygame.image.load(os.path.join("hero.png")).convert_alpha(); # load in player image, convert_alpha will keep transparent background

player = pygame.transform.scale(player, (32, 50)) # resize player
light=pygame.transform.scale(light, (800,800)) # resize gradient

night = True # boolean to set if it is night or day

while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT: 
            pygame.quit()
            sys.exit()
            break

        if e.type == pygame.MOUSEBUTTONDOWN:
            night = not night # toggle night between true and false

    pos = []
    pos = pygame.mouse.get_pos() # get mouse position

    screen.fill(pygame.color.Color('Red')) # just a background
    for x in range(0, 640, 20):
        pygame.draw.line(screen, pygame.color.Color('Green'), (x, 0), (x, 480), 3)  # just lines on the background

    if night: # if light effect needed
        filter = pygame.surface.Surface((640, 480)) # create surface same size as window
        filter.fill(pygame.color.Color('Black')) # Black will give dark unlit areas, Grey will give you a fog
        filter.blit(light,(pos[0]-400,pos[1]-400)) # blit light to the filter surface -400 is to center effect
        screen.blit(filter, (0, 0), special_flags=pygame.BLEND_RGBA_MIN) # blit filter surface but with a blend

    screen.blit(player,pos) # blit the player over the effect
    pygame.display.flip()

It uses a radial gradient (click file:Radial_Gradient.png for my gradient) to light around the player.