Saturday, March 9, 2013

Creating the skeleton of a Pygame program

The text below is the code for the skeleton of a Pygame program.
 

import sys,pygame
pygame.init()


screen = pygame.display.set_mode([640,480])

while True:
    screen.fill([255,255,255])
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.flip()


Your code should look like the code in the screenshot below.
 

---------------------------------------------------
The first line of code,
import sys,pygame
, imports the 'sys' module and the 'pygame' module. These modules are imported so that the program has access to the functions of those modules.

The third line of code,
screen = pygame.display.set_mode([640,480])
, creates the window that is displayed on the screen when the program is running. The code [640,480] is tells the program to make the width of the window 640 pixels wide and 480 pixels high. Those two numbers can be changed to adjust the size of the window.

The fifth line of code,
screen.fill([255,255,255])
, fills the background of the window with the colour white. If this line of code is removed, the background of the window will be black.

The eight and ninth lines of code,
pygame.quit()
sys.exit()

, are functions that close the program when the user clicks the exit button on the top-right corner. To use a function from a module that has been imported, type the name of the module followed by a full stop and then the name of the function with a pair of parentheses at the end.

The last line of code,
pygame.display.flip()
, is used to update any changes that have been made to objects displayed on the screen (Eg. an image's position has changed). The program cannot update any changes to objects displayed on the screen unless the 'flip' function is used.

When the program is run (press F5 to run the program), a window should open containing a blank white screen.

Author: Luke Mulder

No comments:

Post a Comment