First PyGame program

Based on my previous post of researching viable applications to make a simple game in, I decided to delve a bit into PyGame.

Since my brain is so heavily inundated with making Processing sketches, I based the code structure around core Processing concepts (setup() function, draw() function, etc).  While it’s probably not the best solution for writing a PyGame app (the liberal usage of ‘global’ calls), it does actually run, which is all I wanted :)

What does it do?  Spawn a bunch of random circles and have them bounce around the screen.  Exciting?  Not very.  But, you gotta start somewhere 😉

# pyGameTest02.py
# Eric Pavey - 2009-04-06
# Writing a PyGame app that emulates the general program layout of a Processing sketch.
# Makes a bunch of random circles bounce around.

import pygame
from pygame.locals import *
import random

RES = [640, 480]
MAXCIR = 128
window = None
screen = None
circles = []

class Cir(object):
    # Make our circle objects

    def __init__(self):
        self.xPos = RES[0]/2
        self.yPos = RES[1]/2
        self.xDir = random.choice([random.uniform(0,2),random.uniform(-2,0)])
        self.yDir = random.choice([random.uniform(0,2),random.uniform(-2,0)])
        self.radius = random.uniform(8,64)
        self.width = random.uniform(2,8)

    def move(self):
        self.xPos = self.xPos + 1 * self.xDir
        if self.xPos + self.radius/2 + self.width > RES[0] or self.xPos < self.radius/2 + self.width:
            self.xDir = self.xDir * -1

        self.yPos = self.yPos + 1 * self.yDir
        if self.yPos + self.radius/2 + self.width > RES[1] or self.yPos < self.radius/2 + self.width:
            self.yDir = self.yDir * -1            

    def draw(self):
        # must make all vals int:
        pygame.draw.circle(screen, Color('white'), [int(self.xPos), int(self.yPos)], int(self.radius), int(self.width))

    def run(self):
        self.move()
        self.draw()

def setup():
    # Initialize startup parameters
    global window
    global screen

    pygame.init()
    window = pygame.display.set_mode(RES)
    pygame.display.set_caption('PyGame Test 02')
    screen = pygame.display.get_surface()
    screen.fill(Color('black'))

def draw():
    # Run main loop:
    global screen
    global circles

    run = True
    while run:
        screen.fill(Color('black'))
        for c in circles:
            c.run()
        if len(circles) < MAXCIR:
            circles.append(Cir())
        pygame.display.update()

        for e in pygame.event.get():
            if e.type == QUIT:
                run = False
                break

if __name__ == "__main__":
    setup()
    draw()
What to make a game in?
Visual guide to Tkinter widgets
Comment are closed.