Sample python programs


Here is a very simple sample program for python that reads input and and prints part of it out. It is heavily commented for the new learner who knows another language. To try this one out, copy everything between the two lines that start with ==== into its own python file, then run that file.

There is more below, so scroll down when you are done.


=======================sliceAndDice.py======================
##simple introductory python program to demo string manipulation especially
##the slice mechanism. For BSC students learning python as a second language.

#we will use random numbers in this program import the module
import random

def cutTheString(myString):
    #lets find out how many chars the string has
    biggest = len(myString)
    #now lets get a couple of random numbers. randint selects a number from
    #first param to second param inclusive
    #notice that since we just imported the random module, we haven't brought
    #the functions from that module into the default namespace, so we prefix
    #the function with the package name.
    num1 = random.randint(0, biggest - 1)
    num2 = random.randint(0, biggest - 1)
    first = 0
    second = 0
    #if this is the case num2 will be first,
    if num1 > num2:
        first = num2
        second = num1
    else:
        first = num1 # if the numbers are the same, we won't get any slice
        second = num2 # so it doesn't matter
    #now lets print the randomly selected substring
    print myString[first:second]


#this is the part that is always executed (since it is at the top level)
#first we are going to get input from the user
theString = raw_input("""This program will give you a random section of the text you type
please type in some text and press enter:""")
cutTheString(theString)
===========================end slice and dice python program===================

Here is a pygame demo with images and collisions
It was a proof of concept that I put together over the summer. I've commented out and removed the sound stuff since it doesn't work on the csdev01 server. The main source file will be reproduced below for your perusal before you download the zip file.

=========================from giggleGame.py=====================
import pygame
from Obstacle import *
#based on a few things in the l line game programming book

class Player(pygame.sprite.Sprite):
    """class for a moving image to bounce around the screen"""
    def __init__(self, name, disp, game):
        pygame.sprite.Sprite.__init__(self)
        self.game = game
        self.boundingDisplay = disp
        self.image = pygame.image.load(name)
        #convert to faster displaying image - convert_alpha for transparency
        self.image = self.image.convert_alpha()
        self.rect = self.image.get_rect()
        #nasty magic numbers as a starting loc
        self.rect.centerx = 100
        self.rect.centery = 100
        self.xVel = 0
        self.yVel = 0
        self.collState = 0


    def update(self):
        #first check collisions - if there was one
        if self.collState == 1:
            self.collState =2
        elif self.collState > 1:
            self.xVel = 0
            self.yVel = 0
            return
        #move horizontally
     #   newX = self.rect.left + self.xVel
        rightEdge = self.boundingDisplay.get_width()
        if self.xVel + self.rect.right > rightEdge:
            pass #do nothing if at the right edge
        elif self.rect.left < 0:
            self.rect.left = 0
        else:
            self.rect.left = self.rect.left+self.xVel
        #then move vertically
     #   newY = self.rect.top + self.yVel
        bottomEdge = self.boundingDisplay.get_height()
        if  self.yVel+ self.rect.bottom > bottomEdge:
            pass #do thing, at the bottom
        elif self.rect.top < 0:
            self.rect.top = 0
        else:
            self.rect.top =  self.rect.top+self.yVel
       

    def collide(self, collList):
        """handle collisions with background objects"""
        #for now lets take the easy way, we reverse the velocity
        self.yVel = -self.yVel
        self.xVel = -self.xVel
##        game.bumpSound.play()
        self.collState = 1
       

    def processKeyDown(self, event):
        if event.key == pygame.K_UP:
            self.yVel = -3
        elif event.key == pygame.K_DOWN:
            self.yVel = 3
        elif event.key == pygame.K_RIGHT:
            self.xVel = 3
        elif event.key == pygame.K_LEFT:
            self.xVel = -3

    def processKeyUp(self, event):
        self.collState = 0
        if event.key ==  pygame.K_UP or event.key == pygame.K_DOWN:
            self.yVel = 0
        elif event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT:
            self.xVel =0
       
       
       


class GraphicsWin:
    def setup(self):
        self.screen = pygame.display.set_mode((1024,768))
        pygame.display.set_caption("moving sprite")
        #gotta cover the whole screen
        self.background = pygame.Surface(self.screen.get_size())
        self.background = self.background.convert()#more optimization
        #now lets color the background
        self.background.fill(pygame.color.Color("Gray"))
        #create the clock
        self.clock = pygame.time.Clock()
##        self.setupSound()
        self.player = Player('boyCrawl.png', self.screen, self)
        bed =Furniture('small_cradle.png',  self.screen, 600, 450)
        tv = Furniture('smallTV.png',  self.screen, 100, 500)
        chest = Furniture('scabinet.png',  self.screen, 300, 100)
        self.backgroundSprites = pygame.sprite.Group(bed, tv, chest)
        self.playerSprites = pygame.sprite.Group(self.player)
        self.screen.blit(self.background,(0,0))

##     def setupSound(self):
##         if not pygame.mixer:
##             print "Huston, we have a sound problem!"
##         else:
##             pygame.mixer.init()
##             self.bumpSound = pygame.mixer.Sound("Hic.wav")
##             self.jGiggle1 = pygame.mixer.Sound("josephGiggle2.ogg")
##             self.rGiggle1 = pygame.mixer.Sound("RaphaelGiggle2.ogg")

    def runLoop(self):
        done = False
        count = 0
        switch = 1
        while not done:
            self.clock.tick(30)#throttle down to 30 fps
            if count ==0:
                if switch == 1:
                    switch = 0
##                    self.jGiggle1.play()
                else:
                    switch = 1
##                    self.rGiggle1.play()
            #event processing
            count = count+1
            if count > 500:
                count = 0
            for event in pygame.event.get():
                if event.type==pygame.QUIT:
                    done = True
                elif event.type == pygame.KEYDOWN :
                    self.player.processKeyDown(event)
                elif event.type == pygame.KEYUP:
                    self.player.processKeyUp(event)
            #find collisions between player and background objects. Don't kill the sprite
            collList=pygame.sprite.spritecollide(self.player, self.backgroundSprites, False)
            #if there is any collsions in the list returned
            if collList:
                self.player.collide(collList)#handle them
            self.backgroundSprites.clear(self.screen, self.background)
            self.backgroundSprites.draw(self.screen)
            self.playerSprites.clear(self.screen, self.background)
            self.playerSprites.update()
            self.playerSprites.draw(self.screen)
            pygame.display.flip()#actually show the screen




if __name__=='__main__':
    pygame.init()
    game = GraphicsWin()
    game.setup()
    game.runLoop()

==============================end giggleGame.py===================