[Pygame Tutorial] Basic Basics: Change the screen color.

[Pygame Tutorial] Basic Basics: Change the screen color.

Postby Mekire » Sun Feb 24, 2013 3:25 am

I would like to introduce a very simple Pygame example and walk through the code. Please consider the following:
Code: Select all
import os,sys  #used for sys.exit and os.environ
import pygame  #import the pygame module
from random import randint

class Control:
    def __init__(self):
        self.color = 0
    def update(self,Surf):
        self.event_loop()  #Run the event loop every frame
        Surf.fill(self.color) #Make updates to screen every frame
    def event_loop(self):
        for event in pygame.event.get(): #Check the events on the event queue
            if event.type == pygame.MOUSEBUTTONDOWN:
                #If the user clicks the screen, change the color.
                self.color = [randint(0,255) for i in range(3)]
            elif event.type == pygame.QUIT:
                #pygame.QUIT events are created when the user tries to close the window.

if __name__ == "__main__":
    os.environ['SDL_VIDEO_CENTERED'] = '1'  #Center the screen.
    pygame.init() #Initialize Pygame
    Screen = pygame.display.set_mode((500,500)) #Set the mode of the screen
    MyClock = pygame.time.Clock() #Create a clock to restrict framerate
    RunIt = Control()
    while 1:
        pygame.display.update() #Update the screen
        MyClock.tick(60) #Restrict framerate
All this does is change the color of the screen when the user clicks, but let's take a look at the details.

As should most code, we start here with our imports. Firstly every Pygame you write is going to need sys for the exit function in order to close cleanly. Additionally, if you want the window you create to start centered in the middle of the screen you will need os. Next of course we import pygame itself.

Now I would like to take this time to bring up the infamous * import. In other programmers' code, you will no doubt see this:
Code: Select all
from pygame.locals import *
included as well. I strongly encourage you not to do this. I used to do it myself, but when I started using a proper IDE and could actually see how many variables it added into the global namespace, I learned my lesson. If you really don't want to type pygame every time (and who does), do something like this instead:
Code: Select all
import pygame as pg #lazy but better than destroying namespace

Moving on; let's skip the class for now and move to:
Code: Select all
if __name__ == "__main__":
This tells the interpreter to only run the code below this line if the program is run directly (not if it is imported). Please accustom yourself to using it. Now we must set up and initialize our pygame session and window. Firstly you will see:
Code: Select all
os.environ['SDL_VIDEO_CENTERED'] = '1'  #Center the screen.
This, as I mentioned earlier, sets an environmental variable of your operating system telling it that this window should be centered. Next we have pygame.init() which initializes the pygame session; and then we set the mode of the display surface (passing it the desired window size) and assigning this to a name (here I used Screen).

This completes the initialization. In the next line I create a Clock instance. The clock will later allow me to restrict our games frame rate so that it doesn't just run as fast as your computers computation allows (this is unimportant for the given example but in every reasonable program it is necessary). Now in the next line I create an instance of the class we skipped over earlier, so lets hop back up and take a look at some of the details of that.

I will start with the (arguably) most important part of our program; the event loop. Whenever a user does anything (presses a key, moves the mouse, tries to close the window, etc) an event is placed on the event queue. There are several ways to get these events from the event queue, but I would say the most common (and useful) way is to iterate over pygame.event.get() with a for loop. This i what I do in the example in the class method event_loop. Now all events have constant values which are associated with names. The most commonly used ones are probably KEYDOWN, KEYUP, MOUSEBUTTONDOWN, MOUSEBUTTONUP, and QUIT. Here I check if a mouse button has been clicked with:
Code: Select all
if event.type == pygame.MOUSEBUTTONDOWN:
If true I assign a new random RGB color to self.color. I also check if a QUIT event has occurred with:
Code: Select all
elif event.type == pygame.QUIT:
All your pygame programs will have to include this or the user won't be able to end the program (through polite means).

Now lets look at the update function of the class. It simply calls the event_loop function, and then fills the Surface it was passed with the current color.

Now finally lets go back to the bottom of the code where I create the instance of Control. Here you will see an infinite loop. Within that loop we simply update control; then update any changes made to the entire screen; and then using the Clock we created earlier, restrict the framerate of the game. That's it.

One last thing I would like to say is, while learning pygame, as with any library or API, you will have to constantly consult the documentation.

It can be found here: Pygame Documentation

Good luck to any of you trying to write your first pygame. I will try to write some more advanced tutorials soon.
New Users, Read This
  • Use code tags when posting code.
  • Include any errors with your post (in code tags).
  • Describe your problem; not your chosen solution.
  • Make examples the minimum length to demonstrate your issue.
User avatar
Posts: 1711
Joined: Thu Feb 07, 2013 11:33 pm
Location: Tucson, Arizona

Return to Game Development

Who is online

Users browsing this forum: No registered users and 5 guests