Tutorial 03: Full sourcecode

#!/usr/bin/python

# This example runs in Python 2.6 and 3.1 using Pygame 1.9
# This example builds on the stars.py example included in pygame
# Its located at: [python install]\Lib\site-packages\pygame\example

# Imports
import sys
import pygame
import random
from pygame.locals import * 
    
# Constants
WHITE   = 255, 240, 200
BLACK   =   0,   0,   0
RED     = 255,   0,   0
GREEN   =   0, 255,   0
BLUE    =   0,   0, 255
STAR_SIZE = 3
COLORS = [BLACK, # Varies the stars colors
    WHITE,
    RED,
    GREEN,
    BLUE]

WIDTH   = 800 # Use these values to adjust window size
HEIGHT  = 600 # 800 by 600 will give you an idea of how  
              # things would look at full-screen.
N_STAR = 100  # Frequency of stars displayed
FPS = 30      # Drawing frame rate
SPEED = 10    # Player speed, larger means faster

class Player(pygame.sprite.Sprite):
    """
    Base object to contain the player. 
    """
    def __init__( self ):
        # Initialize Sprite, which is our base class
        # Use pygame.Sprite to create our Player
        pygame.sprite.Sprite.__init__( self )   
        # graphic representation of Player
        self.image = pygame.image.load('paint_color01.png')     
        # Used for collision detection(with the window)
        self.rect = self.image.get_rect()                       
        # Starts Player at the bottom-middle
        self.rect.center = (WIDTH/2,HEIGHT)                     
        self.x_velocity = 0
        self.y_velocity = 0

    def update( self ):
        """ This is the simple "collision detection" for 
        the player.  If the player nears the border of his 
        intended area of movement, he is kept from leavind 
        that area.
        """
        self.rect.move_ip( (self.x_velocity, self.y_velocity) )

        # Horizontal restrictions
        if self.rect.left < 0:                                  
            self.rect.left = 0
        elif self.rect.right > WIDTH:
            self.rect.right = WIDTH

        # Vertical restrictions
        if self.rect.top < 0:                                   
            self.rect.top = 0
        #if self.rect.top < HEIGHT/2:   # Comment out the 2 lines above
        #    self.rect.top = HEIGHT/2   # Un-comment these lines
        elif self.rect.bottom > HEIGHT: # to restrict the player
            self.rect.bottom = HEIGHT   # to the lower-half of window

def initialize_stars():
    """ Creates a list of stars, each star will receive
    a random pair of x and y coordinates for its position.
    """
    star_list = []
    for i in range(N_STAR):
        x = random.randrange(0,WIDTH)
        y = random.randrange(0,HEIGHT)
        star_list.append([x,y])
    
    return star_list


def draw_stars(surface, star_list):
    """ This function takes a list of stars and 
    displays them on the pygame surface.
    """
    for i in range(len(star_list)):
        starColor = random.randrange(0, 4) # For white stars comment out
        color = COLORS[starColor]          # For white stars set to WHITE
        #color = WHITE
        # Set to 0 for no effect
        shimmerEffect = random.randrange(0,STAR_SIZE)   
        pygame.draw.circle(surface, color, star_list[i],shimmerEffect)


def move_stars(surface, star_list, color):
    """ This function generates the star movement, if the star has 
    fallen below the height of the window, the star is recreated with 
    new x and y coordinates, then added back into the list.
    """
    for i in range(len(star_list)):
        pygame.draw.circle(surface, color, star_list[i],STAR_SIZE)
        star_list[i][1] += 1
        
        # loop the top/bottom of the window
        if star_list[i][1] > HEIGHT:
            # randomize before the star enters the window
            y = random.randrange(-HEIGHT/2, -HEIGHT/16)  
            star_list[i][1] = y
            x = random.randrange(0,WIDTH)
            star_list[i][0] = x
    
    
def main():
    """ This code creates the Player and assembles the starfield, then 
    sends them to pygame.
    """
    clock = pygame.time.Clock()
    random.seed()
    stars = initialize_stars()
    # Entry point to pygame
    pygame.init()                                             
    # Create window
    screen = pygame.display.set_mode([WIDTH,HEIGHT])          
    # Create window title
    pygame.display.set_caption('Tut03: Adding the player...') 
        
    # Player setup
    playerSprite = pygame.sprite.RenderClear()
    player = Player()
    playerSprite.add(player)
        
    # The main game loop
    while 1:                                            
        # the bottom "layer" background
        screen.fill(BLACK)                              
        clock.tick(FPS)
        
        # Wait until input is generated
        for entry in pygame.event.get():                
            if entry.type == pygame.KEYDOWN:
                if entry.key == pygame.K_LEFT:
                    player.x_velocity = -SPEED
                elif entry.key == pygame.K_RIGHT:
                    player.x_velocity = SPEED
                elif entry.key == pygame.K_UP:
                    player.y_velocity = -SPEED
                elif entry.key == pygame.K_DOWN:
                    player.y_velocity = SPEED
            
            elif entry.type == pygame.KEYUP:
                if entry.key == pygame.K_LEFT:
                    player.x_velocity = 0
                elif entry.key == pygame.K_RIGHT:
                    player.x_velocity = 0
                elif entry.key == pygame.K_UP:
                    player.y_velocity = 0
                elif entry.key == pygame.K_DOWN:
                    player.y_velocity = 0
            
            if entry.type == QUIT or \
            (entry.type == KEYUP and entry.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
                           
       
        # Hide stars prior to move
        draw_stars(screen, stars)                       
        move_stars(screen, stars,BLACK)
        # Show stars after move
        draw_stars(screen, stars)                       
            
        playerSprite.update() 
        playerSprite.draw(screen)
     
        pygame.display.update()
        #pygame.display.flip()          


# Stand-alone execution
if __name__ == '__main__':      
    main()

Advertisements
  1. Note about tutorials « Savalia Studios

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: