Home » Basic pygame app

Basic pygame app

Spring Framework Basics Video Course
1 Year Subscription
Oracle Java Certification
Java SE 11 Programmer II [1Z0-816] Practice Tests
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]

The following is a very simple app that is built using PyGame

Installing:

The command is the following, the preferred method is using pip as per below

pip install pygame

Example

This is a very basic example which simply draws a basic window.

import pygame  
  
pygame.init()  
screen = pygame.display.set_mode((400,400))  
done = False  
  
while not done:  
    for event in pygame.event.get():  
        if event.type == pygame.QUIT:  
            done = True  
    pygame.display.flip()  

Breakdown

There are some important syntax to look at in the example above and go through it line by line.

 

import pygame – This is used to import the pygame framework.

pygame.init() – This is used to initialize all the required modules of the pygame.

pygame.display.set_mode((width, height)) – This is used to display a window of the desired size. The return value is a Surface object which is the object where we will perform graphical operations.

pygame.event.get()- This is used to empty the event queue. It is important to call this, if you do not do this then the window messages will start to pile up and the game will become unresponsive.

pygame.QUIT – This is used to terminate the event when we click on the close button.

pygame.display.flip() – Pygame is double-buffered, so this shifts the buffers. It is important to call this function in order to make any updates that we will make on the game screen.

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More