The Wayback Machine - https://web.archive.org/web/20240816175857/https://www.geeksforgeeks.org/pygame-surface/
Open In App

Pygame – Surface

Last Updated : 29 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

When using Pygame, surfaces are generally used to represent the appearance of the object and its position on the screen. All the objects, text, images that we create in Pygame are created using surfaces.

Creating a surface

Creating surfaces in pygame is quite easy. We just have to pass the height and the width with a tuple to pygame.Surface() method. We can use various methods to format our surface as we want. For example, we can use pygame.draw() to draw shapes, we can use surface.fill() method to fill on the surface. Now, the implementation of these functions. Let’s discuss syntax and parameters.

Syntax: pygame.surface()

It takes 4 arguments a tuple of width and height, flags, depth, mask.

pygame.draw():

It is used to draw an object, shape.

Syntax: Surface.rect(surface, color, rect)

The code for drawing a rectangle using the pygame.draw.rect() method is below:

Python




# Importing the library
import pygame
import time
   
# Initializing Pygame
pygame.init()
   
# Creating the surface
sample_surface = pygame.display.set_mode((400,300))
   
# Choosing red color for the rectangle
color = (255,255,0)
   
# Drawing Rectangle
pygame.draw.rect(sample_surface, color,
                 pygame.Rect(30, 30, 60, 60))
 
# The pygame.display.flip() method is used
# to update content on the display screen
pygame.display.flip()


Output:

surface_name.fill():

pygame.Surface.fill: It is used for filling color in the surface.

Syntax:pygame.Surface.fill(color, rect=None, special_flags=0)

The code for filling color in the surface using the surface_name.fill() method is:

Python




# Importing the library
import pygame
   
# Initializing Pygame
pygame.init()
   
# Creating the surface
sample_surface = pygame.display.set_mode((400,300))
   
# Choosing yellow color to fill
color = (255,255,0)
 
# filling color to the surface
sample_surface.fill(color)
 
# updating the display
pygame.display.flip()


Output:

Loading image on the surface

Although we can draw shapes and fill out colors on the surface, we still need to have a picture on the surface. We can make such a surface easily with pygame.image.load() method. This method takes the image path relative or absolute as an input.

Syntax: pygame.image.load(img) 

Code:

Python




# Importing the library
import pygame
 
 
# Initializing Pygame
pygame.init()
 
# creating the display surface
display_surface = pygame.display.set_mode((500, 500 ))
 
# Creating the image surface
image = pygame.image.load('gfg_logo.png')
 
# putting our image surface on display
# surface
display_surface.blit(image,(100,100))
 
# updating the display
pygame.display.flip()


Output:

Adding Blitting

For a surface to be displayed it needs to blitted on the screen. Blitting can be thought of as copying the pixels of one surface to another. We can blit by using the surface.blit() method which takes a surface that needs to be blit as the first argument and the tuple of coordinates as a second coordinate.

Syntax: pygame.Surface.blit(source, dest, area=None, special_flags=0)

Python




# Importing the library
import pygame
 
# Initializing Pygame
pygame.init()
 
# creating the display surface
display_surface = pygame.display.set_mode((500, 500 ))
 
# Creating the first image surface
image1 = pygame.image.load('gfg_logo.png')
 
# Creating the second image surface
image2 = pygame.image.load('gfg_logo.png')
 
# putting our first image surface on
# display surface
display_surface.blit(image1,(0,0))
 
# putting our second image surface on
# display surface
display_surface.blit(image1,(300,300))
 
# updating the display
pygame.display.flip()


Output:

Now that we have already discussed some surface functions like .blit(), .fill(), etc. Let us discuss some more important functions of pygame screens.

  • pygame.Surface.convert: It makes a copy of the surface with pixel format changed. The new pixel format can be determined from an existing surface or depth, flags, and masks arguments can be used.

Syntax: pygame.Surface.convert(Surface=None)
 

Code:

Python




# Importing the library
import pygame
   
# Initializing Pygame
pygame.init()
   
# Creating the surface
sample_surface = pygame.display.set_mode((400,300))
 
# changing the pixel format of an image
pygame.Surface.convert(sample_surface)
 
# updating the display
pygame.display.flip()


Output:

  • pygame.Surface.convert_alpha: It creates a new copy of the surface with the desired pixel format. The new surface will be in a format suited for quick blitting to the given format with per-pixel alpha. If no surface is given, the new surface will be optimized for blitting to the current display.

Syntax: pygame.Surface.convert_alpha(Surface) 

Code:

Python




# Importing the library
import pygame
   
# Initializing Pygame
pygame.init()
   
# Creating the surface
sample_surface = pygame.display.set_mode((400,300))
 
# changing the pixel format
# of an image including per pixel alphas
pygame.Surface.convert_alpha(sample_surface)
 
# updating the display
pygame.display.flip()


Output:

  • pygame.Surface.copy: It creates a new copy of the surface. The duplicate surface will have the same pixel formats, color palettes, transparency settings, and class as the original.

Syntax: pygame.Surface.copy()

Code:

Python




# Importing the library
import pygame
   
# Initializing Pygame
pygame.init()
   
# Creating the surface
sample_surface = pygame.display.set_mode((400,300))
 
# creating a copy of sample_surface
# and naming it as copied_surface
copied_surface=pygame.Surface.copy(sample_surface)
 
# updating the display
pygame.display.flip()


Output:

  • pygame.Surface.set_colorkey: Set the current color key for the surface. When blitting this surface onto a destination, any pixels that have the same color as the colorkey will be transparent.

Syntax: set_colorkey(Color, flags=0)  

Code: 

Python




# Importing the library
import pygame
 
# Initializing Pygame
pygame.init()
 
# creating the display surface
display_surface = pygame.display.set_mode((500, 500 ))
 
# Creating the image surface
image = pygame.image.load('gfg_logo.png')
 
# putting our image surface on display surface
# making the white colored part
# of the surface as transparent
pygame.Surface.set_colorkey (image, [255,255,255])
 
display_surface.blit(image,(100,100))
 
# updating the display
pygame.display.flip()


 
 Output:

 

The output of the above code will be geeksforgeeks logo on a black surface with white-colored pixel changed to transparent.
 

  • pygame.Surface.get_colorkey: It returns the current color key value for the Surface. If the color key is not set, then None is returned.

Syntax: get_colorkey()

Code: 

Python




# Importing the library
import pygame
 
# Initializing Pygame
pygame.init()
 
# creating the display surface
display_surface = pygame.display.set_mode((500, 500))
 
# Creating the image surface
image = pygame.image.load('gfg_logo.png')
 
# putting our image surface on display surface
# making the white colored part of the surface
# as transparent
pygame.Surface.set_colorkey(image, [255, 255, 255])
 
# printing the colorkey value for the surface
print(pygame.Surface.get_colorkey(image))
 
display_surface.blit(image, (100, 100))
 
# updating the display
pygame.display.flip()


Output:

The output of the above code will be a window showing various surfaces as seen in the get_colorkey example as well as the colorkey value will also be printed.

  • pygame.Surface.set_alpha: The alpha value set for the full surface image.  Pass 0 for invisible and 255 for fully opaque.

Syntax: set_alpha(value, flags=0) or set_alpha(None)

Code:

Python




# Importing the library
import pygame
 
# Initializing Pygame
pygame.init()
 
# creating the display surface
display_surface = pygame.display.set_mode((500, 500 ))
 
# Creating the image surface
image = pygame.image.load('gfg_logo.png')
 
# putting our image surface on display surface
# making the alpha value of surface as 100
pygame.Surface.set_alpha(image, 100)
 
display_surface.blit(image,(100,100))
 
# updating the display
pygame.display.flip()


Output:

 

The output of the above code will be, geeksforgeeks logo, which will be slightly transparent as we have changed its alpha value to 100.

  • pygame.Surface.get_alpha: It returns the current alpha value for the surface.

Syntax: get_alpha()

 Code:

Python




# Importing the library
import pygame
 
# Initializing Pygame
pygame.init()
 
# creating the display surface
display_surface = pygame.display.set_mode((500, 500 ))
 
# Creating the image surface
image = pygame.image.load('gfg_logo.png')
 
# putting our image surface on display surface
# making alpha value of image surface to 100
pygame.Surface.set_alpha(image, 100)
 
# printing the alpha value of the surface
print(pygame.Surface.get_alpha(image))
 
display_surface.blit(image,(100,100))
 
# updating the display
pygame.display.flip()


Output: 

The output of the above code will be a window showing various surfaces as seen in the set_alpha example as well as the alpha value will also be printed.



Previous Article
Next Article

Similar Reads

Adding Collisions Using pygame.Rect.colliderect in Pygame
Prerequisite: Drawing shapes in Pygame, Introduction to pygame In this article, we are going to use pygame.Rect.colliderect for adding collision in a shape using Pygame in Python. We can easily add collisions in Pygame shapes using the colliderect( ). For this, we are going to draw two rectangles then we will check if the rectangles are colliding o
3 min read
Pygame - surface.blit() function
surface.blit() function draws a source Surface onto this Surface. The draw can be positioned with the dest argument. The dest argument can either be a pair of coordinates representing the position of the upper left corner of the blit or a Rect, where the upper left corner of the rectangle will be used as the position for the blit. The size of the d
2 min read
How to create a text input box with Pygame?
In this article, we will discuss how to create a text input box using PyGame. Installation Before initializing pygame library we need to install it. This library can be installed into the system by using pip tool that is provided by Python for its library installation. Pygame can be installed by writing these lines into the terminal. We can install
3 min read
How to add moving platforms in PyGame
Prerequisite: Drawing in Pygame In this article, we will learn how we can add moving platforms to our game using PyGame in Python. Creating a Platform We can easily create any type of platform in pygame using the draw( ) method. For this, we will create react with specific width and height using the draw.rect() function. Syntax: pygame.draw.rect(su
5 min read
How to get keyboard input in PyGame ?
While using pygame module of Python, we sometimes need to use the keyboard input for various operations such as moving a character in a certain direction. To achieve this, we have to see all the events happening. Pygame keeps track of events that occur, which we can see with the events.get() function. In this article, we are going to discuss how we
3 min read
Python | Display images with PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop using this toolkit. Command to install pygame : pip in
2 min read
Python | Display text to PyGame window
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop using this toolkit.. Command to install pygame on wind
6 min read
Python | Drawing different shapes on PyGame window
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. Command to install pygame : pip instal
3 min read
Introduction to pygame
Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI, and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so. Installing pygame: Pygame requires Python;
5 min read
PyGame Set Mouse Cursor from Bitmap
In this article, we are going to see how to set the mouse cursor from bitmap using the PyGame module in Python. What is PyGame?It is a cross-platform set of Python modules designed for writing video games.It includes computer graphics and sound libraries designed to be used with the Python programming language.It can handle time, video, music, font
5 min read
How to create an empty PyGame window?
Pygame window is a simple window like any other window, in which we display our game screen. It is the first task we do so that we can display our output onto something. Our main goal here is to create a window and keep it running unless the user wants to quit. To perform these tasks first we need to install pygame package and import some pre-defin
2 min read
Python | Making an object jump in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. So, in this article, we will learn how
3 min read
Python | Playing audio file in Pygame
Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so. Note: For more information, refer to Introdu
2 min read
Python - Moving an object in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this tutorial, we are going to lear
3 min read
Slide Puzzle using PyGame - Python
Slide Puzzle game is a 2-dimensional game i.e the pieces can only be removed inside the grid and reconfigured by sliding them into an empty spot. The slide puzzle game developed here is a 3X3 grid game i.e 9 cells will be there from 1 to 8(9 is not here since a blank cell is needed for sliding the neighboring cells). In this article, we are going t
15 min read
Python - Drawing design using arrow keys in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this article we will see how we can
3 min read
Bubble sort visualizer using PyGame
In this article we will see how we can visualize the bubble sort algorithm using PyGame i.e when the pygame application get started we can see the unsorted bars with different heights and when we click space bar key it started getting arranging in bubble sort manner i.e after every iteration maximum value element should come at last. Bubble Sort is
3 min read
Save/load game Function in Pygame
Pygame is a free-to-use and open-source set of Python Modules. And as the name suggests, it can be used to build games, and to save game data or the last position of the player you need to store the position of the player in a file so when a user resumes the game its game resumes when he left. In this case, the text file with JSON format stores the
4 min read
Pygame - Random Movement of Object
Prerequisite: How to draw rectangle in Pygame? In this article, we will learn how we can add random movements in objects using PyGame in Python. Random movement in a single object To add random movement in our object we are going to use randint method of the random module. Syntax: random.randint(a, b) Parameters: a and b : Two integers Returns: Ret
6 min read
How to initialize all the imported modules in PyGame?
PyGame is Python library designed for game development. PyGame is built on the top of SDL library so it provides full functionality to develop game in Python. Pygame has many modules to perform it's operation, before these modules can be used, they must be initialized. All the modules can be initialized individually or one at a time. This post desc
2 min read
Install Pygame in Linux
In this article, we will discuss how to install PyGame in the Linux system. We are using Ubuntu 20 LTS you can use any other one. To successfully install PyGame in your Linux system, follow the below procedure: First Check you are using python's latest version or not. Because the PyGame is only supported python 3.7.7 or higher version so make sure
2 min read
Collision Detection in PyGame
Prerequisite: Introduction to pygame Collision detection is a very often concept and used in almost games such as ping pong games, space invaders, etc. The simple and straight forward concept is to match up the coordinates of the two objects and set a condition for the happening of collision. In this article, we will be detecting a collision betwee
7 min read
Adding Boundary to an Object in Pygame
Boundaries to any game are very important. In snake games, space invaders, ping pong game, etc. the boundary condition is very important. The ball bounces at the boundaries of the screen in ping pong games. So, the idea behind this boundaries is to change the position of the ball or object in reverse direction as soon as it hits the wall. Let us se
5 min read
Interesting Facts about PYGAME
Pygame is a set of python module which is used in designing video games. In Pygame, there are computer graphics and sound libraries in order to develop high quality and user interactive games. Pygame was developed by Pete Shinners. Till 2000, it was a community project, later on it was released under open source free software General Public License
2 min read
Binary Search Visualization using Pygame in Python
An algorithm like Binary Search can be understood easily by visualizing. In this article, a program that visualizes the Binary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sorting algorithm, and fill the pygame window with ba
4 min read
Ternary Search Visualization using Pygame in Python
An algorithm like Ternary Search can be understood easily by visualizing. In this article, a program that visualizes the Ternary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sorting algorithm, and fill the pygame window with
5 min read
Snowfall display using Pygame in Python
Not everybody must have witnessed Snowfall personally but wait a minute, What if you can see the snowfall right on your screen by just a few lines of creativity and Programming. Before starting the topic, it is highly recommended revising the basics of Pygame. Steps for snowfall creation 1. Importing modules First, we need to import the Pygame modu
3 min read
How to change screen background color in Pygame?
Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Functions Used: pygame.init(): This function is used to initialize all the pygame modules.pygame.display.set_mode(): This function i
1 min read
How to draw rectangle in Pygame?
Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Functions Used: pygame.display.set_mode(): This function is used to initialize a surface for display. This function takes the size o
2 min read
Difference between Pygame VS Arcade Library in Python
Game programming is very rewarding nowadays and it can also be used in advertising or as a teaching tool. Game development encompasses mathematics, logic, physics, AI, and much more and it can be amazingly fun. In Python, up until now, Pygame library was employed for the same, but there is a new module: Arcade Library. Here we will discuss how they
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg