Some Objects.

I really hope that the little bits of Object-Oriented Programming within Pygame that I’m learning will eventually pay dividends.

Mostly using my small amount of Python Classes knowledge and sjbrown’s awesome tutorial I’ve written the code appended at the bottom of this post.

It’s a lot of lines and took me several hours and all it does is draw the charactor and quit when you ask it to. You’re meant to be able to move the charactor with the arrow keys but that don’t work it’s very basic and the display updating still feels like a bit of hack. Lots of progress to do. I just now tried to get his emotions to work but that ain’t happening.

I’m assured that these harder methods at the start will yield better results once the project really gets going and grows out of itself. I sure hope so.

Here’s OOGame.py:

#! /bin/python
import os, sys, math, random, subprocess, pygame, charactor
from pygame.locals import *

#----Constants----
IP = '127.0.0.1'
PORT = 65563
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
#-----------------

class PumpEvent:
    def __init__(self):
        self.name = "Pump Event"

class QuitEvent:
    def __init__(self):
        self.name = "Quit Event"

class PlayerMoveEvent:
    def __init__(self, direction):
        self.name = "Player Move Event"
        self.direction = direction

class PlayerSpawnEvent:
    def __init__(self):
        self.name = "Player Spawn Event" 

class PlayerEmotionEvent:
    def __init__(self, emotion):
        self.name = "Player Emotion Event"
        self.eMover = emotion

class Manager:
    def __init__(self):
        printer("Manager Started")
        from weakref import WeakKeyDictionary
        self.listeners = WeakKeyDictionary([])
        self.remListeners = []
        self.addListeners = []
        self.eventQueue = []

    def addListener(self, listener):
        self.addListeners.append(listener)

    def remlistener(self, listener):
        self.remListeners.append(listener)

    def updateListenerLists(self):
        for i in self.addListeners:
            self.listeners[i] = 1
        for i in self.remListeners:
            if i in self.listeners:
                del self.listeners[i]

    def post(self, event):
        self.eventQueue.append(event)
        if isinstance(event, PumpEvent):
            self.updateListenerLists()
            self.doQueue()
        else:
            printer("Event: %s" % event.name)

    def doQueue(self):
        i = 0
        while i < len(self.eventQueue):
            event = self.eventQueue[i]
            for a in self.listeners:
                old = len(self.eventQueue)
                a.pump(event)
            i += 1
            if self.addListeners:
                self.updateListenerLists()
        self.eventQueue = []

class Controller:
    def __init__(self, manager):
        printer("Controller Started")
        self.manager = manager
        self.manager.addListener(self)

    def pump(self, event):
        if isinstance(event, PumpEvent):
            for i in pygame.event.get():
                if i.type == QUIT:
                    self.manager.post(QuitEvent())
                if i.type == KEYDOWN:
                    if i.key == K_ESCAPE:
                        self.manager.post(QuitEvent())
                    if i.key == K_LEFT:
                        self.manager.post(PlayerMoveEvent('left'))
                    if i.key == K_RIGHT:
                        self.manager.post(PlayerMoveEvent('right'))
                    if i.key == K_SPACE:
                        self.manager.post(PlayerSpawnEvent())
                    if i.key == K_UP:
                        self.manager.post(PlayerEmotionEvent(1))
                    if i.key == K_DOWN:
                        self.manager.post(PlayerEmotionEvent(-1))
                #if i.type == KEYUP:
                #   if i.key == K_LEFT:
                #       self.manager.post(Player

class Mouse:
    def __init__(self, manager):
        printer("Mouse Started")
        self.manager = manager
        self.manager.addListener(self)

    def pump(self, event):
        if isinstance(event, PumpEvent):
            self.x, self.y = pygame.mouse.get_pos()

class Charactor(pygame.sprite.Sprite):
    def __init__(self):
        printer("Charactor Started")

    def create(self, x, y, width, height, emotion, screen):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.emotion = emotion
        self.screen = screen
        self.draw()
        self.spawned = True

    def draw(self):
        self.screen.fill((0,0,0))
        self.charactor = charactor.charactor(self.x, self.y, self.width, self.height, self.emotion, self.screen)

    def move(self, direction):
        printer(self.x, self.y)
        printer(direction)
        if direction == 'left':
            self.x -= 50
            self.draw()
        elif direction == 'right':
            self.x += 50
            self.draw()

    def emotion(self, eMover):
        if eMover > 5:
            eMover = 1
        elif eMover < 1:
            eMover = 5
        self.emotion += eMover
        self.draw()

class View:
    def __init__(self, manager):
        printer("View Started")
        self.manager = manager
        self.manager.addListener(self)
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        self.dirtyRects = []

    def pump(self, event):
        if isinstance(event, PlayerSpawnEvent):
            myCharactor.create(0,200,200,160,3, self.screen)
            pygame.display.flip()
        if isinstance(event, PlayerMoveEvent):
            myCharactor.move(event.direction)
        #if isinstance(event, PlayerEmotionEvent):
         #   printer(event)
          #  myCharactor.emotion(event.eMover)
        self.update()

    def update(self):
        pygame.display.update()
        #printer("update")

class Looper:
    def __init__(self, manager):
        printer("Looper Started")
        self.manager = manager
        self.manager.addListener(self)
        self.looping = True

    def loop(self):
        while self.looping:
            self.manager.post(PumpEvent())

    def pump(self, event):
        if isinstance(event, QuitEvent):
            self.looping = False            

class Game:
    def __init__(self, manager):
        global myCharactor
        printer("Game Started")
        self.manager = manager
        self.manager.addListener(self)
        self.manager.post(PlayerSpawnEvent())
        myCharactor = Charactor()

    def pump(self, event):
        if isinstance(event, QuitEvent):
            pygame.quit()
            sys.exit()

def main():
    pygame.init()
    myManager = Manager()

    myController = Controller(myManager)
    myLooper = Looper(myManager)
    myView = View(myManager)
    myGame = Game(myManager)

    myLooper.loop()

def printer(*msg):
    print(msg)

if __name__ == '__main__':
    main()

And charactor.py as imported from OOGame.py:

import sys, os, subprocess, math, random
import pygame
from pygame.locals import *

def tri(posX, posY, triWidth, triHeight, flip, color, screen):
    x1 = posX
    x2 = posX + (triWidth/2)
    x3 = posX + triWidth
    if flip:
        y1 = posY - triHeight
        y2 = posY
        y3 = posY - triHeight
    else:
        y1 = posY
        y2 = posY - triHeight
        y3 = posY
    return pygame.draw.polygon(screen, color, [(x1,y1), (x2,y2), (x3,y3)]) 

def charactor(posX, posY, charWidth, charHeight, emotion, display):
    """
    Draws a charactor figure, with one of these five available emotions:
    1 = aghast
    2 = grumpy
    3 = normal
    4 = cool
    5 = happiest
    """
    footHeight = charHeight/4
    truPosY = posY
    posY = posY - footHeight
    #main body
    color = (20, 155, 15)
    tri(posX, posY, charWidth, charHeight, False, color, display) #body
    tri(posX + (charWidth/6), truPosY, charWidth/4, footHeight, True, color, display) #left foot
    tri(posX + (charWidth/1.69), truPosY, charWidth/4, footHeight, True, color, display) #right foot
    if emotion == 1 or emotion == 2:
        mouthFlip = False
        mouthPosX = posX + (charWidth/4.5)
        mouthPosY = posY - (charHeight/16)
        mouthWidth = charWidth/1.8
        mouthHeight = charHeight/3.5
        leftEyePosX = posX + (charWidth/2.8)
        rightEyePosX = posX + (charWidth/2)
        eyeWidth = charWidth/6.5
        eyeHeight = charHeight/6
        if emotion == 1:
            eyeFlip = False
            eyePosY = posY - (charHeight/2)
        else:
            eyeFlip = True
            eyePosY = posY - (charHeight/2.5)
    elif emotion == 3 or emotion == 4:
        mouthFlip = True
        mouthPosX = posX + (charWidth/4)
        mouthPosY = posY - (charHeight/16)
        mouthWidth = charWidth/2
        mouthHeight = charHeight/3.5
        leftEyePosX = posX + (charWidth/2.8)
        rightEyePosX = posX + (charWidth/2)
        eyeWidth = charWidth/6.5
        eyeHeight = charHeight/6
        if emotion == 3:
            eyeFlip = False
            eyePosY = posY - (charHeight/2)
        else:
            eyeFlip = True
            eyePosY = posY - (charHeight/2.5)
    else:
        mouthFlip = True
        eyeFlip = False
        mouthPosX = posX + (charWidth/4.4)
        mouthPosY = posY - (charHeight/18)
        mouthWidth = charWidth/1.8
        mouthHeight = charHeight/3
        leftEyePosX = posX + (charWidth/3)
        rightEyePosX = posX + (charWidth/2)
        eyePosY = posY - (charHeight/2)
        eyeWidth = charWidth/5.5
        eyeHeight = charHeight/4.5
    #face
    color = (0,0,0)
    tri(mouthPosX, mouthPosY, mouthWidth, mouthHeight, mouthFlip, color, display) #mouth
    tri(leftEyePosX, eyePosY, eyeWidth, eyeHeight, eyeFlip, color, display) #left eye
    tri(rightEyePosX, eyePosY, eyeWidth, eyeHeight, eyeFlip, color, display) #right eye

def enemy(posX, posY, charWidth, charHeight, screen):
    footHeight = charHeight/4
    truPosY = posY
    posY = posY - footHeight
    color = (20,155,150)
    tri(posX + (charWidth/6), truPosY, charWidth/4, footHeight + (charHeight/2), False, color, screen) #left foot
    tri(posX + (charWidth/1.69), truPosY, charWidth/4, footHeight + (charHeight/2), False, color, screen) #right foot
    tri(posX, posY, charWidth, charHeight, True, color, screen) #body
    color = (0,0,0)
    tri(posX + (charWidth/4), posY - (charHeight/1.7), charWidth/5.5, charHeight/5, True, color, screen) #left eye
    tri(posX + (charWidth/1.76), posY - (charHeight/1.7), charWidth/5.5, charHeight/5, True, color, screen) #right eye

def eventManager():
    global speaking, click, x, y
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            elif event.key == K_w:
                click = 1
            elif event.key == K_a:
                click = 2
            elif event.key == K_s:
                click = 3
            elif event.key == K_d:
                click = 4
            elif event.key == K_x:
                click = 5
        if event.type == MOUSEBUTTONDOWN:
            if click == 5:
                click = 1
            else:
                click += 1
        if event.type == MOUSEMOTION:
            x, y = event.pos

def draw():
    global x, y, click
    screen.fill((0,0,0))
    charactor(50, 200, 160, 120, 1, screen)
    charactor(250, 200, 160, 120, 2, screen)
    charactor(450, 200, 160, 120, 3, screen)
    charactor(650, 200, 160, 120, 4, screen)
    charactor(850, 200, 160, 120, 5, screen)
    enemy(50, 400, 160, 120, screen)
    charactor(x,y, 200, 160, click, screen)
    pygame.display.update()

def main():
    global screen, click, x, y
    pygame.init()
    screen = pygame.display.set_mode((1050, 480))
    pygame.display.set_caption("Charactor.py")
    x,y = 1,1
    print("Welcome to The Future! You're running: \n Python %s \n Pygame %s" % (sys.version, pygame.ver))
    while True:
        eventManager()
        draw()

click = 1

if __name__ == '__main__':
    main()
This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>