Hello world example with the pygame

In this task, we will learn the usage of pygame for game development. We will get started with an example that opens a blank window and write a couple of lines to monitor events so that we can quit the program if the window is closed.

We will go through the important features of the pygame module, which is necessary to build our arcade game, including playing sounds and controlling the menu.

Prepare for lift off

As mentioned earlier, this project is based on the book Making Games with Python & Pygame (http://inventwithpython.com/makinggames.pdf). In this task, we will go through select features of the pygame module. It is important that you familiarize yourself with the different features available under the pygame module.

Engage thrusters

  1. We will get started by importing the modules required for the Hello world example. We will import the pygame and the sys module:
    import pygame,sys
  2. Next, we will also import pygame.locals, since it contains several constant variables:
    from pygame.locals import *
  3. In order to make use of the functions of the pygame module, we need to initialize the module:
    pygame.init()
  4. We will set the window width and height parameters and create a pygame.Surface object that is stored in a variable called DISPLAYSURF:
    DISPLAYSURF = pygame.display.set_mode((400, 300))
  5. We will set the window title name:
    pygame.display.set_caption('Hello World!')
  6. Now, we will run a loop that waits for events inside the window and update the display through every cycle. In this example, we do not have anything to be updated. We will quit the program when the user closes the window:
    while True: # main game loop
      for event in pygame.event.get():
        if event.type == QUIT:
          pygame.quit()
          sys.exit()
    
      pygame.display.update()
  7. This should open up a blank window titled Hello World.

Playing sounds using the pygame module

Since the sound effects form the crux of an arcade game, we need to know how to play sounds using the pygame platform.

  1. We will declare a sound object to play the beeps.wav file, available along with the downloads of this file. The file needs to be copied into the same directory as the python script that runs the game as follows:
    soundObj = pygame.mixer.Sound('beeps.wav')
  2. The sound can be played in a loop by calling the play() method as follows:
    while True: # main game loop
      soundObj.play()
  3. We can stop playing the sound file by calling the stop() method.

Building menus using the pygame module

  1. We will need a simple menu for our desktop game. We will make use of the menu class (distributed under GNU GPL v3 license) written by Scott Barlow. Let's review the simple_example.py example. (http://www.pygame.org/project-MenuClass-1260-.html.)
  2. In this menu example, a menu object is created; when a menu option is selected using a keyboard, the selected option is highlighted and printed on a terminal when the return key is pressed. For example, when the down key is pressed to select Load Game and the return key pressed, the Load Game option is printed to the terminal.
  3. Let's discuss the parameters that need to be passed as arguments to create a menu object. According to the documentation available with the menu class, a menu object has to be defined with the following parameters:
    menu = cMenu(x, y, h_pad, v_pad, orientation, number, background,buttonList)
    • The parameters x and y refer to the location of the origin of the menu object on the game screen
    • The parameters h_pad and v_pad refer to the spacing between the buttons in the horizontal and vertical directions
    • The orientation parameter refers to the arrangement of the buttons on the screen, that is, 'horizontal' or 'vertical'
    • The number parameter refers to the number of buttons that can be accommodated in a single row (when arranged horizontally) or in a single column (when arranged vertically)
    • The background parameter refers to the surface on which the menu has to be created
    • The buttonList parameter refers to the list of buttons that we want on the screen
  4. We will get started by declaring a menu object and listing all the options we want in the menu, namely:
    menu = cMenu(50, 50, 20, 5, 'vertical', 100, screen,
      [('Start Game', 1, None),
      ('Score Board', 2, None),
      ('Exit', 3, None)])
  5. The menu needs to be centered on the surface of the screen:
    menu.set_center(True, True)
  6. The text of the menu buttons also needs to be aligned:
    menu.set_alignment('center', 'center')
  7. In order to display and update the menu and selection parameters, a simple state machine is used:
    state = 0
    prev_state = 1
  8. The pygame.event.wait() method detects any keyboard or mouse events and updates the current state accordingly.
  9. The menu is updated by the method (due to a key press event / return key press):
    pygame.event.post(pygame.event.Event(EVENT_CHANGE_STATE, key = 0))
    
  10. When the return key is pressed to select an option, the selected option is printed to the terminal and the menu is updated by highlighting the selected option (in red) by rect_list, state = menu.update(e, state):
    while True:
      if prev_state != state:
        pygame.event.post(pygame.event.Event(EVENT_CHANGE_STATE, key = 0))
        prev_state = state
    
      e = pygame.event.wait()
    
      if e.type == pygame.KEYDOWN or e.type == EVENT_CHANGE_STATE:
        if state == 0:
          rect_list, state = menu.update(e, state)
        elif state == 1:
          print 'Start Game!'
          state = 0
        elif state == 2:
          print 'Load Game!'
          state = 0
        elif state == 3:
          print 'Options!'
          state = 0
        else:
	print 'Exit!'
          pygame.quit()
          sys.exit()
      # Quit if the user presses the exit button
      if e.type == pygame.QUIT:
        pygame.quit()
        sys.exit()
    
      # Update the screen
      pygame.display.update()

Objective complete – mini debriefing

We have finished testing the pygame module and reviewed a simple menu design example along with testing the playing of sounds using the pygame module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.20.193