Monday 7 December 2015

Pygame: Hello World application

Following is the step-by-step procedure to work with pygame.

Step 1: Import pygame library.
import pygame

Step 2: Initialize game engine.
pygame.init()

Step 3: Open a window. Following lines are used to open a window.
size = (800, 600)
screen = pygame.display.set_mode(size)

‘size’ represents (width, height) of the window. ‘set_mode’ method is used to initialize a window or screen for display.

Step 4: Set title to the window. Following method set the current window caption.
pygame.display.set_caption("Hello World")

Step 5: Write some code to interact with user.

dead=False

while(dead==False):
         for event in pygame.event.get():
        if event.type == pygame.QUIT:
            dead = True

Above code makes window visible, until you close the window. ‘pygame.event.get()’ get events from the queue, whatever user do on the window can be accessed as events. ‘pygame.QUIT’ is sent when the user has requested the program to shutdown.

Step 6: Shutdown the display module.
pygame.display.quit()

pygame_hello.py

#import pygame
import pygame

#initialize game engine
pygame.init()

#Open a window
size = (800, 600)
screen = pygame.display.set_mode(size)

#Set title to the window
pygame.display.set_caption("Hello World")

dead=False

while(dead==False):
 for event in pygame.event.get(): 
  if event.type == pygame.QUIT:
   dead = True 

#Shutdown display module
pygame.display.quit()

Run ‘pygame_hello.py’, you will get following screen.






Previous                                                 Next                                                 Home

No comments:

Post a Comment