Starting Pygame: Game Template

October 22, 2016

 

Pygame is one of the best places to learn how to program and create games.  This tutorial will show you how to create something with pygame, giving you everything from the very basics to more advanced features. This page assumes that you know the very basics of programming (i.e. how variables work, types of loops etc.)

The Basics

These are the things you will need for every pygame application.

 

import pygame

 

This imports the pygame library to be access by your code. You can import many other libraries, for example, 'time'.

 

import time

 

These should always be placed before you use the libraries and it is good practice to import all the libraries before any other code.

 

pygame.init()

 

This initiates pygame, allowing you to create the pygame window.

 

xSize, ySize = 600, 450
screen = pygame.display.set_mode((xSize, ySize))

 

The first line creates the variables 'xSize' and 'ySize' and assigns their values to 600 and 450 respectively. This can be done in two lines, but is more efficient to do it in one. The second line creates the variable 'screen'. This line creates the window to display your graphics with width 'xSize' and height 'ySize' in pixels. I would recommend storing these values as varibles rather than typing the numbers into the brackets so you can use these values later in your code to and size your graphics.


pygame.display.set_caption("Pygame Template")

 

This line sets the caption for your window, like this:

 

Now that we have created the window, it is time to start the game logic. Games in pygame are based around big loops. Each time time round the loop is a frame. Each time the loop is run, you will clear the screen and draw everything again.

 

#-----------------Main Loop-----------------#

 

This line is a comment. It will not be read or executed when the program is run. Its only purpose is to make the programming clearer and easier to understand for the programmer. 

 

Let's create a few more variables just before the loop:


mouseHold = False

clock = pygame.time.Clock()
frameCount = 0
done = False

 

The 'mouseHold' will allow us to check with the user is holding a mouse click. The 'clock' allows us to set the maximum number of frames (or times round the loop) per second. The 'frameCount' is what it says on the tin. It is very useful for moving items that are drawn. Next, 'done' is a variable which we will set to true when we want to leave the loop (and possibly the game). 


while not done:

 

This commences the game loop and will repeat while the variable 'done' is equal to false. Everything inside the loop from here on should be indented.

 

frameCount += 1

 

This is an obvious first step. Until the first repeat, the variable 'frameCount' will be set to 1.

 

for event in pygame.event.get():
    if event.type == pygame.QUIT:
        done = True
    if event.type == pygame.MOUSEBUTTONDOWN:
        mouseHold = True

    if event.type == pygame.MOUSEBUTTONUP:
        mouseHold = False
         

The section of code looks at what the user has inputted using the keyboard and mouse. The code 'pygame.event.get()' contains all the inputs the user has made for this frame. The for loop means the subsequent indented code will be repeated once for every item contained in 'pygame.event.get()', each time setting the variable 'event' as one of the items that it contains. The following if statements will check what type of input was applied by the user. The first one, 'pygame.QUIT' is the x in the top right corner of the window. If that is pressed, we want the window to close. The variable 'done' is set to true so the main loop will not repeat anymore. The next two check whether the mouse left click has been pressed or lifted respectively. Each one will set 'mouseHold' to true or false meaning 'mouseHold' will be true for the duration of every click.


screen.fill([0,0,0])

 

This will fill the screen black. The three zeros refer to the red, green, blue colour code, each with a maximum of 255. For example, the colour blue would be [0,0,255] and yellow would be [255,255,0] and grey could be [150,150,150]. You want to colour the screen every frame so the graphics from the previous frames aren't still showing.

 

At this point, you want to create all of you graphics and execute all of you game logic.

 

pygame.display.flip()

 

This line takes everything you have drawn and sends it to the pygame window all at once.


clock.tick(60)

 

This sets the maximum frame rate to 60 fps. Your main loops has now finished

 

pygame.quit()

 

This closes the pygame window (make sure it is not indented).

 

Here is the template:

 

import pygame
import time

 

pygame.init()

 

xSize, ySize = 600, 450
screen = pygame.display.set_mode((xSize, ySize))
pygame.display.set_caption("Pygame Template")

 

#----------------------Main Loop----------------------#

 

mouseHold = False
clock = pygame.time.Clock()
frameCount = 0
done = False
while not done:
    frameCount += 1
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouseHold = True
        if event.type == pygame.MOUSEBUTTONUP:
            mouseHold = False
            
    screen.fill([255,255,0])

    pygame.display.flip()
    clock.tick(60)

 

pygame.quit()

 

Other Things to Add

These are not necessary for the running of pygame and are not vital for every single program but you may find them useful.

 

os.system('mode con: cols=70 lines=50')

 

This adjusts the number of lines and columns when the program is run in CMD. You will need to import 'os':

 

import os

 

This adjusts the number of lines and columns when the program is run in CMD. You will need to import 'os':

 

dir_path = os.path.dirname(os.path.realpath(__file__))

 

This sets the variable dir_path to the directory path of the program running, which is useful for accessing images and sounds to bring into your graphics.

 

os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (200,100)

 

This moves the window to position (200,100) on your monitor and should be done before pygame is initialised.

 

pygame.mixer.pre_init(44100, -16, 1, 512)

 

This initialises the sound in pygame. Setting the right values can stop delays. These values seem to work for me. This should be done before pygame is initialised.

 

winPos = windll.user32.SetWindowPos
winPos(pygame.display.get_wm_info()['window'], -1, 400, 300, 0, 0, 0x0001)

 

This will cause the pygame window to start in front of all other windows. You will need to import 'windll' from 'ctypes' like this:

 

from ctypes import windll

 

This will cause the pygame window to start in front of all other windows. You will need to import 'windll' from 'ctypes' like this:

 

infoObject = pygame.display.Info()
scrW, scrH = infoObject.current_w, infoObject.current_h

 

This gets the current monitor width and height in pixels. This is useful for fullscreen:

 

screen = pygame.display.set_mode((scrW, scrH), pygame.NOFRAME | pygame.FULLSCREEN)

 

If you use 'pygame.fullscreen' be sure to set the window size to the monitor size to avoid a bad-looking, scaled resolution.

 

Inside the main loop, include:

 

mx, my = pygame.mouse.get_pos()

 

This will get the cursor position and set the variables 'mx' and 'my' to the mouse x and y coordinates.

There are many more things to include in your pygame, but these are the ones that I have found most useful for a large number of programs.

Please reload

Read more:

iOSDC Japan 2018

September 7, 2018

Making an iOS Newsletter App with Updating Content using JSON and Swift 4

July 25, 2018

1/14
Please reload

    © 2019 Tech Kingdom

    Contact us : official.techkingdom@gmail.com