Creating Pygame Games (for the complete Noob
 
 
Hosted By
Web Hosting by iPage
 
 
 

Your First Game

The first "game" I am going to show you has only the bare necessities needed to run a program using pygame. This program is aptly titled "Hello, World" (surprised?) but it bares little semblance to the "Hello, World"s of old.

Show me the graphics! This program will require at least one graphic. Pygame supports all different types of 2d graphics, but I prefer to use PNGs as they can be transparent saving you the work of making them transparent in python.

I have included an image HERE called world.png. It is nothing pretty and not geographically correct, but it will work for purposes of this demonstration. Okay, you're probably asking "Can I do this thing already?"

So without further ado...

import pygame #loads the pygame module
pygame.init() #initializes all modules in pygame

w = 300 #sets pygame screen width
h = 300 #sets pygame screen height
screen = pygame.display.set_mode((w, h)) #make and display screen (surface)

graphic = pygame.image.load("world.png").convert() #loads graphic and converts to surface

running = True
while running: #Loop this
    screen.blit(graphic, (0,0)) #Display image at top left
        pygame.display.flip() #Update screen

     for event in pygame.event.get(): #get user input
         if event.type == pygame.QUIT: #if user clicks the close X
    running = False #make running False to break out of loop

pygame.quit() #If you are using idle to run your programs, this line will close your programs without an error message

Make sure your graphic is in the same folder as the .py document and run it. Alright, so this is not much of a game, but we should have a window with a graphic on the screen.

Let's go through this. The first two lines of code enable pygame, so are essential. Technically we didn't need to assign the width and height of the screen to variables in the next line, but this becomes useful when making games. The line after assigns a surface of w width and h height to screen. On the following line you can see that we assign a loaded image to the variable graphic. The function convert() converts images to be compatible with your surface or screen even if they are of different types. We form a while loop next to loop through the program until the user quits. In this loop we have the screen.blit which puts the graphic on the screen at the given coordinates (x, y). x=0 being the leftmost bit of the screen and y = 0 being the topmost. flip() will update your screen.

Well now we can really start to have fun! In the next page of the tutorial we will go through animation.

 

 
 

 

 

 
 

Pygame Tutorial on drawing different shapes

Pygame Tutorial on Loading and Manipulating Images / Graphics

Contact Me