ThePythonGameBook

learn Python. Create Games

User Tools

Site Tools


en:pygame:step004

Step 004 - Colorkey and Alpha Values

screenshot screenshot screenshot screenshot
004_colorkey.py 004_alphademo.py 004_alphademo_pretty.py 004_per-pixel-alphademo.py

In this page you will find 4 code examples: 004_colorkey.py , 004_alphademo.py , 004_alphademo_pretty.py and 004_per-pixel-alphademo.py. All examples demonstrate how to work with transparency and pygame surfaces.

004_colorkey.py is simple to understand. Compare it with 003_static_blit.py on the previous page and look at the blue circle. Do you notice a difference ? Right, the ugly black corners around the blue circle are gone. This is thanks to pygame's set_colorkey command. By defining a specific color on a pygame surface as colorkey, you make this color (in our example, the black color) transparent.

There are 2 kind of image files: Those with in-build transparency , and those without. Only graphic files of the file type .png and .gif can have transparency1). Other file tpyes like the popular .jpg format can not have transparency. If you want transparency for such images you must add them manually with pygame. 004_alphademo.py shows you how to do that. Look at the slowly blinking colormonster (3rd from the left the second row). You can see the amount of alpha-value (the white text below the picture) necessary to make a picture fully visible or fully transparent.

You can also press the keys <key>Ins</key>, <key>Dec</key>, <key>Home</key>, <key>End</key>,<key>PageUp</key>, <key>PageDown</key>, <key>Num+</key>, <key>Num–</key> to manually change the rgb and alpha values in the topright images. Press the keys to see what happens.

For even more effects, you can change the Blit mode by pressing <key>ENTER</key>. This affects the mixing of rgb values from the image and those specified by the keys.

004_per-pixel-alphademo.py shows you an interesting effect by changing the alpha-value of individual pixels. Move the mouse around and use the scroll wheel.

Code Discussion 004_colorkey.py

Colorkey

There is only one important line in this example. To get rid of the ugly black corners of the blue ball surface we declare the color black (0.0.0) as transparent.

#make black the transparent color (red,green,blue)
ball.set_colorkey((0,0,0))        

To make the blitting of a pygame surface faster, it is a good idea to use .convert() on the surface once all drawing on the surface is done. Note that if the surface contains transparent colors, you need to use convert.alpha() instead of .convert().

Blitting on the Screen

The same ballsurface is blitted on the screen (not on the background!) twice in this example: once (the left ball) before the mainloop start and once inside the mainloop. Inside the mainloop a pattern of colourful lines is drawn each frame. The lines will draw on top of the left surface, but the right surface is drawn on top of the lines.

Note that the “corners” of the ball surfaces are not simply white but transparent. The colourful lines are good visible “below” the corners of the right ball surface.

Note that in this code example, inside the mainloop all commands draw directly on the screen surface.

Documentation

Code Discussion 004_alphademo.py

004_alphademo.py shall show you the possibilities of alpha-values (transparency) and image files.

Don't worry if you do not understand all of 004_alphademo.py yet - i don't understand all of it, neither. The important thing is to know how to use it. Some techniques like loading surfaces from files and using text will be explained in other pages. Also note that there are 2 ways of handling keyboard input in 004_alphademo.py.

  • pressed_keys : to indicate of a specific key is pressed at this moment.
  • key_pressed : to check if a specific key was (once) pressed and released.

Both methods will be discussed in more detail in →step011.

Blend Modes

From the different blit-modes, BLEND_RGBA_MULT (mode number 8) seems to be the most meaningful one. Using this blit mode, you can make an image all blue, red or green by setting the per-pixel-alpha values for the corresponding colour. At the same time, you can set an alpha value for the whole image. This works both for images without transparency such as .jpg images but also for images with in-build transparency such as .gif or .png images.

def get_alpha_surface( surf, alpha=128, red=128, green=128, blue=128, mode=pygame.BLEND_RGBA_MULT):
    """    
    Allocate a new surface with user-defined values (0-255)
    for red, green, blue and alpha.
 
    Thanks to Claudio Canepa <ccanepacc@gmail.com>.
    """
 
    tmp = pygame.Surface( surf.get_size(), pygame.SRCALPHA, 32)
    tmp.fill( (red,green,blue,alpha) )
    tmp.blit(surf, (0,0), surf.get_rect(), mode)
    return tmp

For an example of how to use this function, see this code snippet:

tmp = get_alpha_surface(pngMonster3, a, r, g, b, mode) 
screen.blit(tmp, (600,10))

The different modes are integer values and can be found in the pygame documentation or by using python's
interactive interpreter:

>>>import pygame
>>>help(pygame.constants)

Alpha Value for the Whole Surface

If you have a pygame surface without in-build transparency (let's say loaded from an .jpg image) you can set an alpha-value (transparency) for the whole surface with a simple set_alpha() command as shown in this code snippet from 004_alphademo.py:

jpgMonster2.set_alpha(alpha) # alpha (0-255) for whole surface
screen.blit(jpgMonster2, (400,300))  # blit on screen

Documentation

Ideas

<note tip>replace colormonster.jpg with a picture of your own head. rename the picture or the relevant code line inside 005_alphademo.py. Can you make your face all blue or all purple just by pressing keys ?</note>

<note tip>set_aplpha() allows you to create fading effects for game intros, in-game cinematic or game-over screens. Use a paint programm like Gimp, create a stunning game title (or game over message) and save it in the .jpg format. Now try to let pygame fade in or fade out of this picture (ideally while playing music, see →step010)</note>

Source Code on Github

file in folder download comment
004_colorkey.py pygame Download the whole Archive with all files from Github:
https://github.com/horstjens/ThePythonGameBook/archives/master
This program runs stand-alone and does not need other files
004_alphademo.py pygame this program needs other files (see below) to run
004_alphademo_pretty.py pygame yipyip's version of alphademo. This program needs other files (see below) to run
800px-La_naissance_de_Venus.jpg
pygame/data source: wikipedia
colormonster.jpg
pygame/data a .jpg graphic an not have in-build transparency. (notice the white background)
colormonster.png
pygame/data a .png (as well as .gif) graphic can have in-build transparency. Notice the transparent background
ente.jpg
ente.jpg
pygame/data a picture of a duck2)

If you see no colourful source code below, click on “reload” on your browser. Or follow the links to github.

004_colorkey.py

004_alphademo.py

This program need other graphic files to be located in a subfolder called data. See the file table above for details. To get the program working correctly, you best download and unpack the whole file archive (link in the file table above).

View/Edit/Download the file directly in Github: https://github.com/horstjens/ThePythonGameBook/blob/master/pygame/004_alphademo.py

004_alphademo_pretty.py

This program need other graphic files to be located in a subfolder called data. See the file table above for details. To get the program working correctly, you best download and unpack the whole file archive (link in the file table above).

<note tip>This version is for python 2.x only ! For python 3.x, see the next code example below</note>

View/Edit/Download the file directly in Github: https://github.com/horstjens/ThePythonGameBook/blob/master/pygame/004_alphademo_pretty.py

004_alphademo_pretty_python3x.py

This program need other graphic files to be located in a subfolder called data. See the file table above for details. To get the program working correctly, you best download and unpack the whole file archive (link in the file table above).

<note tip>This verison works with python3.x only. For python 2x version, see the oode example above</note>

View/Edit/Download the file directly in Github: https://github.com/horstjens/ThePythonGameBook/blob/master/pygame/004_alphademo_pretty_python3x.py

004_per-pixel-alphademo.py

This program needs one other graphic file -ente.jpg- to be located in a subfolder called data. See the file table above for details. To get the program working correctly, you best download and unpack the whole file archive (link in the file table above).

Note: For Python 3.x, change the two instances of the xrange() function (which was deprecated in Python 3) to range().

https://github.com/horstjens/ThePythonGameBook/blob/master/pygame/004_per-pixel-alphademo.py



Comment this Page

~~DISQUS~~

1)
that does not mean that such files always have a transparent color!
2)
a duck is called “Ente” in German
/var/www/horst/thepythongamebook.com/data/pages/en/pygame/step004.txt · Last modified: 2014/01/09 11:07 (external edit)