In this article, we will see how we can make a simple app with Pygame.
Pygame is a library for python that helps us to build multimedia applications (Apps) and games. This library works as a wrapper for Simple DirectMedia Layer (SDL).
Approach
- Create the app class
- Add text class.
- Add Screen class
- Set Different windows.
What are Classes?
A class is a template-like entity for creating objects. These class objects consist of varied behavior associated with them. In Pygame, we have different types of classes available they are App class, Text Class, and Scene Class. These in general have their own behavior and properties and can be used for varied purposes.
App class
App class is the basis for a game template or any application that we are building. This class can also be called the base or the formation of an application or game. It allows various functionality like resizable, fullscreen, and no frame mode in Pygame thus it becomes the necessary class while declaring or building any app or game via Pygame in python.
Steps needed to form a base App class:
- Importing the Pygame module.
- Now, we initialize the App class.
- Declare the main class and run the app class.
Python3
import pygame as py
from pygame. locals import *
class App_Class:
def __init__( self ):
py.init()
App_Class.screen = py.display.set_mode(
( 540 , 340 ))
App_Class.running = True
def play( self ):
while App_Class.running:
for event in py.event.get():
if event. type = = QUIT:
App_Class.running = False
py.quit()
if __name__ = = '__main__' :
App_Class().play()
|
Output:
App Class in pygame
Text class
While building our application sometimes we want to display some messages for that, we required Text class. It is the template in which we can build different types of text formats in our window. This class mainly instantiates text objects of our window. So we can say if we want to play with our text then go for Text class.
Steps needed to form a Text class:
- Import the Pygame module and all the libraries from the Pygame.
- Now declare the text class and its functions like font_set, rendering, and previously used app class (As app class is the base class for all the other multimedia classes).
- Finally, declare the main class for calling the run function of the app class that will run the test class feature in it.
Python3
import pygame as py
from pygame. locals import *
class Text:
def __init__( self , text, pos, * * options):
self .text = text
self .fontname = None
self .pos = pos
self .fontcolor = Color( 'Green' )
self .font = py.font.Font( self .fontname, 50 )
self .placing = self .font.render( self .text, True ,
self .fontcolor)
self .rect = self .placing.get_rect()
self .rect.bottomleft = self .pos
def building( self ):
app.screen.blit( self .placing, self .rect)
class app:
def __init__( self ):
py.init()
app.screen = py.display.set_mode(( 540 , 340 ))
app.t = Text( 'Text Class in pygame' , pos = ( 100 , 150 ))
app.running = True
def run( self ):
while app.running:
for event in py.event.get():
if event. type = = QUIT:
app.running = False
app.screen.fill(Color( 'blue' ))
app.t.building()
py.display.update()
py.quit()
if __name__ = = '__main__' :
app().run()
|
Output:
Scene Class
In games we have different screens, they might be the Intro scene, Game over the scene, or Level scene. In all these, we see different backgrounds or scenes. This all can be done with the help of the Scene class.
Steps needed to form a Scene class:
- The first step is to declare the scene class. By doing this, we actually create a container in which we can store all the necessary features required for our game.
- Now we have to append multiple scenes to the applications scene list a container.
- After appending, we will add the scene id and the color for the multiple scenes. We will add a scene id so that we can easily call each scene according to the scene id.
- Now it will flip each node and finally display the screen.
- Representation of the scene is followed by their unique id given above.
Python3
import pygame as py
title_py = "Scene 1 Starting scene"
frame = 50
green = ( 0 , 200 , 0 )
white = ( 255 , 255 , 255 )
font_size = None
py.init()
clock = py.time.Clock()
screen = py.display.set_mode([ 740 , 340 ])
py.display.set_caption(title_py)
screen_font = py.font.Font(font_size, 50 )
class Scene():
def __init__( self ):
self .next_scene = self
def process_input( self , events, press):
raise NotImplementedError
def update( self ):
raise NotImplementedError
def rendering( self ):
raise NotImplementedError
def terminate( self ):
self .next_scene = None
class starting_scene(Scene):
def __init__( self ):
super ().__init__()
def process_input( self , events, press):
for event in events:
if event. type = = py.KEYDOWN:
if event.key = = py.K_SPACE:
self .next_scene = EndScene()
def rendering( self ):
screen.fill(green)
text = screen_font.render(title_py, 1 , white)
rect = text.get_rect()
rect.centerx = 740 / / 2
rect.centery = 50
screen.blit(text, rect)
def update( self ):
pass
class EndScene(Scene):
def __init__( self ):
super ().__init__()
def process_input( self , events, press):
for event in events:
if event. type = = py.KEYDOWN:
if event.key = = py.K_SPACE:
self .next_scene = starting_scene()
def update( self ):
pass
def rendering( self ):
screen.fill(green)
text = screen_font.render( "Scene 2 Game Ending " , 1 , white)
rect = text.get_rect()
rect.centerx = 370
rect.centery = 50
screen.blit(text, rect)
class app_class():
def __init__( self ):
self .running_scene = starting_scene()
def control( self , event, press):
x_out = event. type = = py.QUIT
quit = press[py.K_q]
return x_out or (quit)
def run( self ):
while self .running_scene ! = None :
eve = []
press = py.key.get_pressed()
for event in py.event.get():
if self .control(event, press):
self .running_scene.terminate()
else :
eve.append(event)
self .running_scene.process_input(eve, press)
self .running_scene.update()
self .running_scene.rendering()
self .running_scene = self .running_scene.next_scene
py.display.flip()
clock.tick(frame)
if __name__ = = "__main__" :
let_check = app_class()
let_check.run()
py.quit()
|
Output:
Press the space bar to change the scene
scene2
Different Windows modes
There are three different modes of a window in Pygame in which an active window can be displayed they are:
- Fullscreen mode(As its name suggests it is a window with its full resizable capability)
- Resizable mode(resize is allowed in this type of mode)
- No frame mode(In this type of mode no title bar is present in the window)
Steps needed to set up these modes:
- First, we declare screen size and display mode flags inside the initialized app class method.
- Now we will create a screen surface for it
pygame_screen.init()
# for FULLSCREEN mode
display_surface = pygame_screen.display.set_mode((500,250), FULLSCREEN)
FULLSCREEN mode in pygame
# for RESIZABLE mode
display_surface = pygame_screen.set_mode((500, 250), RESIZABLE)
The RESIZABLE mode in pygame
# for NOFRAME mode
display_surface = pygame_screen.display.set_mode((500, 250), NOFRAME)
NOFRAME mode in pygame
- Now run the main loop to execute the QUIT and Update command for the screen
Code for the above modes:
Python3
import pygame as py
from pygame. locals import *
py.init()
display_surface = py.display.set_mode(( 500 , 250 ), RESIZABLE)
working = True
while working:
for event in py.event.get():
if event. type = = py.QUIT:
working = False
py.display.update()
py.quit()
|
Output:
Node Placement:
Node act as a container for graphical user Interface elements and objects. Node placement in Pygame requires four parameters that are:
- size: this helps to find the current size of the node on the screen
- pos: this helps to find the current position of the node
- dir: dir is a short name for direction. It itself consists of 3 parameters that are vertical, horizontal, and diagonal.
- gap: This refers to the space given in between two nodes in a Pygame.
Last Updated :
21 Feb, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...