How to create and manipulate Pygame Surfaces and Masks?

share link

by aryaman@openweaver.com dot icon Updated: Jul 21, 2023

technology logo
technology logo

Solution Kit Solution Kit  

The Pygame of "surface" refers to a rectangular area where you can draw or display graphics. It is a concept in Pygame, a popular Python library for creating 2D games and graphics. A surface in Pygame is a blank canvas on which you can draw various elements such as images, shapes, and text.  

 

Pygame provides a versatile framework for creating various types of games.  

  1. Arcade Games: Arcade games are fast-paced, action-packed games. It needs quick reflexes and hand-eye coordination. Examples include classic titles like Pac-Man, Space Invaders, and Asteroids.  
  2. Puzzle Games: Puzzle games focus on solving challenges or puzzles through logical thinking. Examples include Tetris, Sudoku, and Bejeweled. With surfaces in Pygame, you can create grids, tiles, and game boards to represent puzzles.  
  3. Strategy Games: Strategy games involve planning, resource management, and decision-making to achieve objectives. Examples are tower defense games and real-time strategy games like Age of Empires.  


Pygame stands as a versatile and accessible Python popularity of 2D game development. It's simple and active community support makes it an excellent choice for beginners. Pygame has been used to develop diverse game genres, from classic arcade-style games. 

Code

In this solution, we use the vector and math function of the pygame library

if ballrect.top < 0 and ball_vel.y < 0:
    ball_vel.y *= -1
elif ballrect.bottom > screen.get_height() and ball_vel.y > 0:
    ball_vel.y *= -1
if ballrect.left < 0 and ball_vel.x < 0:
    ball_vel.x *= -1
elif ballrect.right > screen.get_width() and ball_vel.x > 0:
    ball_vel.x *= -1

if ballrect.colliderect(redgoal_rect):

import pygame as pg
from pygame.math import Vector2


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color(30, 90, 0)

# You need surfaces with an alpha channel to
# create masks, therefore pass `pg.SRCALPHA`.
REDGOAL = pg.Surface((90, 150), pg.SRCALPHA)
REDGOAL.fill((255, 0, 0))
redgoal_rect = REDGOAL.get_rect(topleft=(100, 200))
redgoal_mask = pg.mask.from_surface(REDGOAL)

BALL = pg.Surface((30, 30), pg.SRCALPHA)
pg.draw.circle(BALL, [250, 250, 250], [15, 15], 15)
# Ball variables.
ball_pos = Vector2(275, 200)
ballrect = BALL.get_rect(center=ball_pos)
ball_vel = Vector2(0, 0)
ball_mask = pg.mask.from_surface(BALL)

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.KEYDOWN:
            if event.key == pg.K_a:
                ball_vel.x = -7
            elif event.key == pg.K_d:
                ball_vel.x = 8
            elif event.key == pg.K_w:
                ball_vel.y = -3
            elif event.key == pg.K_s:
                ball_vel.y = 5

    ball_vel *= .94  # Friction.
    ball_pos += ball_vel
    ballrect.center = ball_pos

    if ballrect.top < 0 and ball_vel.y < 0:
        ball_vel.y *= -1
    elif ballrect.bottom > screen.get_height() and ball_vel.y > 0:
        ball_vel.y *= -1
    if ballrect.left < 0 and ball_vel.x < 0:
        ball_vel.x *= -1
    elif ballrect.right > screen.get_width() and ball_vel.x > 0:
        ball_vel.x *= -1

    # Rect collision.
    # if ballrect.colliderect(redgoal_rect):
    #     print('goal!')

    # Calculate the offset between the objects.
    offset = redgoal_rect[0] - ballrect[0], redgoal_rect[1] - ballrect[1]
    # Pass the offset to the `overlap` method. If the masks collide,
    # overlap will return a single point, otherwise `None`.
    overlap = ball_mask.overlap(redgoal_mask, offset)

    if overlap:
        print('goal!')

    screen.fill(BG_COLOR)
    screen.blit(BALL, ballrect)
    screen.blit(REDGOAL, redgoal_rect)
    pg.display.flip()
    clock.tick(60)

pg.quit()


  1. Copy the code using the "Copy" button above, and paste it in a Python file in your IDE.
  2. Remove the first 10 lines of the above code
  3. Run the file to see the output.
  4. The ball moves with W(Up), A(Left), S(Down) and D(Right).


I hope you found this useful. I have added the link to dependent libraries, version information in the following sections.

Dependent Libraries


pygameby pygame

C doticonstar image 6066 doticonVersion:2.5.0.dev2doticon
no licences License: No License (null)

🐍🎮 pygame (the library) is a Free and Open Source python programming language library for making multimedia applications like games built on top of the excellent SDL library. C, Python, Native, OpenGL.

Support
    Quality
      Security
        License
          Reuse

            pygameby pygame

            C doticon star image 6066 doticonVersion:2.5.0.dev2doticonno licences License: No License

            🐍🎮 pygame (the library) is a Free and Open Source python programming language library for making multimedia applications like games built on top of the excellent SDL library. C, Python, Native, OpenGL.
            Support
              Quality
                Security
                  License
                    Reuse

                      Environment Tested 

                      I tested this solution in the following versions. Be mindful of changes when working with other versions. 

                      1. The solution is created in Python3.11. 
                      2. The solution is tested on pygame 2.3.0 version. 

                      Support

                      1. For any support on kandi solution kits, please use the chat
                      2. For further learning resources, visit the Open Weaver Community learning page.

                      FAQ:  

                      1. What are the different biting methods used in the pygame surface?  

                      In Pygame, blitting is copying pixels from one surface to another. It involves transferring the contents of one surface onto another surface. Pygame provides different blitting methods to control how pixels are copied. It is blended during this process.  

                       

                      2. What is the current transparency value of a Surface?  

                      You can retrieve the current transparency value of a surface using the get.alpha() method. This method returns an integer representing the current alpha value of the surface. The alpha value will range from 0 (transparent) to 255 (opaque).  

                       

                      3. What types of pixel formats exist for a Surface?  

                      A surface's pixel format determines how the colors of its pixels are represented. Pygame provides different pixel formats. You can use it when creating or manipulating surfaces. The choice of pixel format depends on the desired color depth. It depends on transparency requirements, memory usage, and compatibility with the graphics hardware. Different pixel formats have varying levels of color precision and memory requirements. It supports alpha blending.  

                       

                      4. Can I create an integer color value for my pygame display surface?  

                      It can create an integer color value. It represents a color for your display surface using the pygame.color class. The pygame.color class allows you to define colors using RGB, RGBA, HSL, or HSV formats. Once you have defined the color, you can convert it to an integer value using the pygame. Color object's __int__ () method.  

                       

                      5. What is the current transparent color key of the Surface object in my game engine?  

                      The transparent color key is a specific color. You can designate it as transparent and any pixels on the surface. The color will be rendered transparent when blitted onto another surface. The transparent color key technique supports a single color as transparent. It is not suitable for surfaces with complex or gradient transparency. 

                      See similar Kits and Libraries