User Tools

Site Tools


user:bh011695:pygametutorial:worm.py
import random
import pygame
 
class worm:
    def __init__(self, surface, x, y):
        self.surface = surface  #pygame surface
        self.x = x              #worm head x pos
        self.y = y              #worm head y pos
        self.length = 200       #worm length
        self.dirX = 1           #worm x direction
        self.dirY = 0           #worm y direction
        self.body = []          #x, y pos for worm body pixels
        self.crashed = False    #if true, exits the main game loop
 
    def keyEvent(self, event):
        """Handles keyboard events for movement"""
 
        if event.key == pygame.K_UP and self.dirY != 1:
            self.dirX = 0
            self.dirY = -1
        elif event.key == pygame.K_DOWN and self.dirY != -1:
            self.dirX = 0
            self.dirY = 1
        elif event.key == pygame.K_LEFT and self.dirX != 1:
            self.dirX = -1
            self.dirY = 0
        elif event.key == pygame.K_RIGHT and self.dirX != -1:
            self.dirX = 1
            self.dirY = 0
 
    def move(self):
        """Moves the worm"""
 
        self.x += self.dirX #increment worm's x direction
        self.y += self.dirY #increment worm's y direction
 
        #Checks to see if the worm is in contact with anything other than
        #a black (background) or red (food) pixel, and if so, self.crashed
        #is set to true
 
        r, g, b, a = self.surface.get_at((self.x, self.y))
 
        if (r, g, b) == (0, 0, 0) or (r, g, b) == (255, 0, 0):
            self.crashed = False
        else:
            self.crashed = True
 
        self.body.insert(0, (self.x, self.y))
 
        #Compares the number of the worm's body pixels to the length. If
        #true, a pixel is removed from the worm.
        if len(self.body) > self.length:
            self.body.pop()
 
    def draw(self):
        """Draw the worm"""
 
        for x, y in self.body:
            self.surface.set_at((x, y), (255, 255, 255))
 
    def crashCheck(self):
        """Checks if the worm has crashed into an object)"""
        return self.crashed
 
    def getX(self):
        """Returns worms x pos"""
        return self.x
 
    def getY(self):
        """return worms y position"""
        return self.y
 
    def increaseLength(self):
        """increase worm length"""
        self.length += 4
 
class food:
    """Initialize food object"""
    def __init__(self, surface, sWidth, sHeight):
        self.surface = surface              #pygame surface
        self.color = (255, 0, 0)            #food's color: Red
        self.x = random.randint(0, sWidth)  #start x pos
        self.y = random.randint(0, sHeight) #start y pos
 
    def drop(self):
        """Prints a food item to the screen"""
        X_MAX = self.x + 5      #Max width of the food item
        Y_MAX = self.y + 5      #Max height of the food item
 
        #Draws a 5 X 5 food item to the screen
        for i in range (self.x, X_MAX):
            for j in range (self.y, Y_MAX):
                self.surface.set_at((i, j), self.color)
 
    #Returns food's color
    def getColor(self):
        return self.color
 
def drawObstacles(screen, width, height):
    GREEN = (0, 255, 0)
    startX = 100
    startY = 50
    stopX = 100
    stopY = 150
 
    pygame.draw.line(screen, GREEN, (startX, startY), (stopX, stopY))
    pygame.draw.line(screen, GREEN, (startX, startY + 200), (stopX, stopY + 200))
    pygame.draw.line(screen, GREEN, (startX + 200, startY), (stopX + 200, stopY))
    pygame.draw.line(screen, GREEN, (startX + 200, startY + 200), (stopX + 200, stopY + 200))
    pygame.draw.line(screen, GREEN, (startX + 400, startY), (stopX + 400, + stopY))
    pygame.draw.line(screen, GREEN, (startX + 400, startY + 200), (stopX + 400, stopY + 200))
    pygame.draw.line(screen, GREEN, (startX - 50, startY + 150), (stopX + 490, stopY + 50))
 
def checkEatenFood(r, g, b, w, chomp, foodColor):
    foodEaten = False
 
    if (r, g, b) == foodColor:
       w.increaseLength()
       chomp.play()
       foodEaten = True
 
    return foodEaten
 
def checkForCrash(w, running, crash, width, height):
    if w.crashCheck():
        print("Crash!")
        crash.play()
        running = False
    elif w.getX() <= 0:
        print("Crash!")
        crash.play()
        running = False
    elif w.getX() >= width - 1:
        print("Crash!")
        crash.play()
        running = False
    elif w.getY() <= 0:
        print("Crash!")
        crash.play()
        running = False
    elif w.getY() >= height - 1:
        print("Crash!")
        crash.play()
        running = False
    return running
 
def getEvents(running, w):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            w.keyEvent(event)
    return running
 
#Initialize variables
width = 640						#screen width
height = 400						#screen height
screen = pygame.display.set_mode((width, height))	#pygame surface
pygame.display.set_caption("Wormy wormy stuff")		#window title
clock = pygame.time.Clock()				#pygame clock
FPS = 90						#Game speed
running = True						#keeps main loop running
SCREEN_COLOR = (0, 0, 0)				#black screen color
itemsEaten = 0						#berries eaten by worm
 
#Initialize sounds
pygame.mixer.init()
chomp = pygame.mixer.Sound("atari.wav")
crash = pygame.mixer.Sound("crash.wav")
 
#Initialize worm and food objects w and f
w = worm(screen, int(width/2), int(height/2) - 10)
f = food(screen, width, height)
 
#main()
while running:
    screen.fill(SCREEN_COLOR)
 
    drawObstacles(screen, width, height)	#Draws green line obstacles
 
    f.drop()					#Drops a food item
    foodColor = f.getColor()			#stores food color
    w.draw()					#Draws the worm to the screen
    w.move()					#Let's the player move the worm
 
    #Gets the color of the worm's current x and y position on the screen
    i = w.getX()
    j = w.getY()
    r, g, b, a = w.surface.get_at((i, j))
 
    #Checks to see if the worm's current position color matches that
    #of the dropped food item. If yes, the number of eaten items is 
    #incremented by 1 and a new food item is dropped
    if checkEatenFood(r, g, b, w, chomp, foodColor):
            f = food(screen, width, height)
            itemsEaten += 1
 
    #Checks to see if the worm has crashed into something and sets
    #running accordingly.
    running = checkForCrash(w, running, crash, width, height)
 
    #Checks for events
    running = getEvents(running, w)
 
    pygame.display.flip()	#Updates the display
    clock.tick(FPS)		#Sets the game to run at X FPS
#end main()
 
print("You ate", itemsEaten, "food item(s).")
user/bh011695/pygametutorial/worm.py.txt · Last modified: 2010/12/17 12:53 by bh011695