Colors in Python Game Programming By albro

There are three main colors in light: Red, Green and Blue. If we first put the names of these three colors together, we will have the word RGB. Red, Blue and Yellow are the three main colors, but the monitor uses light, not color. To solve this problem, we use the RGB model. This model is for displaying colors on TV and monitor. Any other color can be created by combining different amounts of these three colors.
In pygame, we represent colors as tuples of three integers. The first value in the tuple is a numeric value for the color red. A value of 0 means no red color and a value of 255 means maximum red color. The second value corresponds to green and the third value to blue. We call these three numbers, which are used to represent a color, RGB values. If the three values are zero, black color is obtained. There is no color above black!
Each color is represented as a number between 0 (minimum) and 255 (maximum) that occupies 1 byte in memory. Therefore, an RGB color is represented as a 3-byte value. Since any combination of 0 to 255 can be used for each of the three primary colors, this means that Pygame can produce 16,777,216 different colors (ie 256 x 256 x 256 colors). However, if you use a number greater than 255 or a negative number, you will receive an error like this:

A tuple (0, 0, 0) with no red, green, or blue values represents the color black. Black color means the absence of other colors. The tuple (255, 255, 255) is for the maximum amount of red, green, and blue that produces white. White color is a perfect combination of red, green and blue. The tuple (255, 0, 0) is the maximum value of red, and the minimum value is green and blue, so the resulting color is red. Similarly, (0, 255, 0) is green and (0, 0, 255) is blue.
You can mix the amount of red, green and blue to make other colors. Here are the RGB values for some common colors:

The following image can be helpful in understanding the above concepts.

Change the color of the window
Changing the color of the window is perhaps the easiest thing to do with pyagme. We only add two new lines of code to the program in the previous part so that we can change the color of the window.
import pygame,sys
from pygame.locals import *
pygame.init()
# COLORS
RED=(255,0,0)
DISPLAYSURF=pygame.display.set_mode((400,300))
pygame.display.set_caption('Hello World!')
while True: # main game loop
for event in pygame.event.get():
if event.type==QUIT:
pygame.quit()
sys.exit()
DISPLAYSURF.fill(RED)
pygame.display.update()
In the program above, I've defined the red color with the value (255,0,0) and put it in the RED constant. Then I've used the fill method to show the color. This method draws the desired color on the window at the end of each iteration of the loop. Actually, this method, as its name suggests, fills the window with the defined color.

By executing the above code, we will have a red window as shown below.

Transparent colors
When you look at the window below, it has a red background. You can see things on the other side from behind this window. A red shade has been added to this glass.

In pygame, to have a transparent color like the image above, we need to add a fourth number between 0 and 255 to the triple RGB tuple. This fourth number is called the alpha value. The alpha value is a measure of how transparent a color is. If we draw a pixel with a new normal color, this new color completely replaces the color that was there before. But with transparent colors, i.e. colors that have an alpha value, a background color can be added to an already existing color. as below:

import pygame,sys
from pygame.locals import *
def draw_rect_alpha(surface, color, rect):
shape_surf = pygame.Surface(pygame.Rect(rect).size, pygame.SRCALPHA)
pygame.draw.rect(shape_surf, color, shape_surf.get_rect())
surface.blit(shape_surf, rect)
def draw_circle_alpha(surface, color, center, radius):
target_rect = pygame.Rect(center, (0, 0)).inflate((radius * 2, radius * 2))
shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA)
pygame.draw.circle(shape_surf, color, (radius, radius), radius)
surface.blit(shape_surf, target_rect)
def draw_polygon_alpha(surface, color, points):
lx, ly = zip(*points)
min_x, min_y, max_x, max_y = min(lx), min(ly), max(lx), max(ly)
target_rect = pygame.Rect(min_x, min_y, max_x - min_x, max_y - min_y)
shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA)
pygame.draw.polygon(shape_surf, color, [(x - min_x, y - min_y) for x, y in points])
surface.blit(shape_surf, target_rect)
pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
background = pygame.Surface(window.get_size())
ts, w, h, c1, c2 = 50, *window.get_size(), (160, 160, 160), (192, 192, 192)
tiles = [((x*ts, y*ts, ts, ts), c1 if (x+y) % 2 == 0 else c2) for x in range((w+ts-1)//ts) for y in range((h+ts-1)//ts)]
for rect, color in tiles:
pygame.draw.rect(background, color, rect)
run = True
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
window.blit(background, (0, 0))
draw_rect_alpha(window, (0, 0, 255, 127), (55, 90, 140, 140))
draw_circle_alpha(window, (255, 0, 0, 127), (150, 100), 80)
draw_polygon_alpha(window, (255, 255, 0, 127),
[(100, 10), (100 + 0.8660 * 90, 145), (100 - 0.8660 * 90, 145)])
pygame.display.flip()
pygame.quit()
exit()
In the image above, the color red has the value (255,0,0,127). By increasing the alpha value, I was able to make it a semi-transparent red color. I've done this for yellow and blue colors as well.
If the alpha value is 255, then the color we will have will be completely dark (that is, it is not transparent at all). The colors (0, 255, 0) and (0, 255, 0, 255) are exactly the same and show a degree of color darkness.
If we draw the above image with an alpha of 255, we will have an image as follows:

If the value of alpha is 0, it means that the color is completely transparent. If you draw any color with an alpha value of 0, no color will be displayed, because that color is completely transparent and invisible.
If we draw the above image with alpha 0 we will have:

Use transparent colors
pygame has three methods for using transparent colors:
- colorkeys
- surface's alphas
- per-pixel alphas
colorkey
This method makes the color completely transparent, or more precisely, it disappears. For example, in the image below, we have a black square with a red border. With colorkey, we can make the black part of the square not be shown and only have the red border.

BLACK = (0, 0, 0)
square.set_colorkey(BLACK) # Black colors will not be blit.
A surface (display object) can only have one colorkey. Setting another colorkey overwrites the previous colorkey. Colorkeys cannot have an alpha value, they can only hide and not display a color.
surface's alphas
This method makes the entire surface transparent with an alpha value. Using this method, we can have different values of alpha. We must note that this method affects the entire surface.
my_image.set_alpha(100) # 0 is fully transparent and 255 fully opaque.

per-pixel alphas
This method renders each pixel in the surface with a separate alpha value. This method gives you the most freedom and flexibility, but it is also the slowest method. In this method, each color argument must contain alpha.
size = width
height = (32, 32)
my_image = pygame.Surface(size, pygame.SRCALPHA) # Creates an empty per-pixel alpha Surface.
If the defined color has an alpha value, the surface will be transparent.
BLUE = (0, 0, 255, 255)
pygame.draw.rect(my_image, BLUE, my_image.get_rect(), 10)
Unlike the previous two methods, the default surface color is not black and will be transparent. That's why the black rectangle disappears.

The colorkey and surface alpha methods can be combined, but the alpha method for each pixel should be used alone.

import pygame,sys
from pygame.locals import *
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255, 50) # This color contains an extra integer. It's the alpha value.
PURPLE = (255, 0, 255)
screen = pygame.display.set_mode((200, 325))
screen.fill(WHITE) # Make the background white. Remember that the screen is a Surface!
clock = pygame.time.Clock()
size = (50, 50)
red_image = pygame.Surface(size)
green_image = pygame.Surface(size)
blue_image = pygame.Surface(size, pygame.SRCALPHA) # Contains a flag telling pygame that the Surface is per-pixel alpha
purple_image = pygame.Surface(size)
red_image.set_colorkey(BLACK)
green_image.set_alpha(50)
# For the 'blue_image' it's the alpha value of the color that's been drawn to each pixel that determines transparency.
purple_image.set_colorkey(BLACK)
purple_image.set_alpha(50)
pygame.draw.rect(red_image, RED, red_image.get_rect(), 10)
pygame.draw.rect(green_image, GREEN, green_image.get_rect(), 10)
pygame.draw.rect(blue_image, BLUE, blue_image.get_rect(), 10)
pygame.draw.rect(purple_image, PURPLE, purple_image.get_rect(), 10)
while True:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
screen.blit(red_image, (75, 25))
elif event.key == pygame.K_2:
screen.blit(green_image, (75, 100))
elif event.key == pygame.K_3:
screen.blit(blue_image, (75, 175))
elif event.key == pygame.K_4:
screen.blit(purple_image, (75, 250))
pygame.display.update()
After executing the above code, squares will be drawn by pressing keys 1, 2, 3 and 4.
pygame.Color objects
You need to know how to display a color because pygame's draw functions need a color to draw. The first way is a tuple of three or four numbers. Another way is to use a pygame.Color object. You can create color objects by calling the pygame.Color constructor and passing it three or four numbers. You can store the Color object in variables. Type the following codes in the Python shell or in the Python command line to better understand what is written:
>>> import pygame
>>> pygame.Color(255, 0, 0)
(255, 0, 0, 255)
>>> myColor = pygame.Color(255, 0, 0, 128)
>>> myColor == (255, 0, 0, 128)
True
>>>
Change the background color by pressing the keys
Write the following code in your code editor and run it. After running, if you press the R key, the background will be red and if you press the G key, the background will be green.
import pygame,sys
from pygame.locals import *
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
GRAY = (127, 127, 127)
WHITE = (255, 255, 255)
pygame.init()
screen = pygame.display.set_mode((640, 240))
running = True
background = GRAY
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
background = RED
elif event.key == pygame.K_g:
background = GREEN
screen.fill(background)
pygame.display.flip()
pygame.quit()
Change the name of the window and its color by pressing the keys
Write the following code in your code editor and run it. In this program, in addition to changing the background color, the name of the window is also changed. After running, if you press the R key, the background will be red, if you press the G key, the background will be green, if you press the B key, the background will be blue, and finally, if you press the K key, the background will be black and etc
import pygame,sys
from pygame.locals import *
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
CYAN = (0, 255, 255)
MAGENTA = (255, 0, 255)
GRAY = (127, 127, 127)
WHITE = (255, 255, 255)
key_dict = {K_k:BLACK, K_r:RED, K_g:GREEN, K_b:BLUE,
K_y:YELLOW, K_c:CYAN, K_m:MAGENTA, K_w:WHITE}
print(key_dict)
pygame.init()
screen = pygame.display.set_mode((640, 240))
running = True
background = GRAY
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
if event.type == KEYDOWN:
if event.key in key_dict:
background = key_dict[event.key]
caption = 'background color = ' + str(background)
pygame.display.set_caption(caption)
screen.fill(background)
pygame.display.update()
pygame.quit()









Comments