Back to Math Projects

Python Starter Code

Python-Pygame Starter Code Instructions:

Use the code below to start any python project with the pygame library. Change the name of the main function 'myMain()' to anything you like, just be sure to change the call-out of the function below in the if statement at the end which begins the execution of the program. This is why large games and applications take a little bit to load, all functions and other instructions are loaded up in memory, then executed at the end of the code.

#-------------------------------------------------------------------------------
# Name:        Starter Code for Python-Pygame projects
# Purpose:     to copy and paste for quick start to coding
#
# Author:      David @ ElectricTeaching.com
#
# Created:     11/12/2011
#-------------------------------------------------------------------------------

# we first import pygame and initialize this library 
import pygame
from pygame import *                        
pygame.init()


# set up a window to place objects using the pygame library.
# I usually call my windows "screen" and I use variables almost everywhere.
# Variables used at the module level are automatically global
width, height = 600, 400
screen = pygame.display.set_mode((width, height))

# title bar text
pygame.display.set_caption('My Program or Game Title')      

def myMain():
    # this is where the program runs in an infinite loop: keep doing while "true"
    active = True
    while active:

        #keyboard and mouse actions are here. pygame events: get, waits for action
        # then we just ask what action it was with if
        for event in pygame.event.get():
            if event.type == pygame.QUIT:       # I left this one 'pygame.' to  show
                active = False                  # what is needed if dont import * at top

            elif event.type == KEYDOWN:             #from pygame.
                if event.key == K_SPACE:            #from pygame.
                    active = False

    # if exited out of active loop, then we must be quitting
    pygame.quit()

if __name__ == '__main__':
    myMain()


                        
David Johns and Electric Teaching ~ All Rights Reserved © 2013