#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    3
    Rep Power
    0

    Adding Score that persists through scenes


    I am currently working on a platformer game that will have collectables and such that will add to a score. For the life of me I can't seem to get the score to change and then persist through the different levels.. At times I am having trouble getting the score to even have points added to it. Here is some of my code (the relevant parts at least)

    Code:
    import pygame, sys, os, math, random
    import functions
    import mainGame
    from pygame.locals import *
    from mainGame import *
    
    #Entity Class
    class Entity(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self)
    
    class Scene(object):
        def __init__(self):
            pass
    
        def render(self,screen):
            raise NotImplementedError
    
        def update(self):
            raise NotImplementedError
        def handle_events(self,events):
            raise NotImplementedError
    
    class GameScene(Scene):
        def __init__(self,levelno,score):
            super(GameScene, self).__init__()
            #Preloading the images that are going to be used
            image_cache = {}
            all_images=glob.glob('data/*.gif' or 'data/*.png')
            for image in all_images:
                functions.getImage(image,image_cache)
            self.image_cache = image_cache
            up = left = down = right = self.diLeft = False
            self.bg = Surface((32,32))
            self.bg.convert()
            self.bg.fill(Color(255, 255, 255))
            self.projectiles = pygame.sprite.Group()
            self.entities = pygame.sprite.Group()
            self.movingplats = pygame.sprite.Group()
            self.enemiesThatHaveHealth = pygame.sprite.Group()
            self.shottime = 10
            self.platforms = []
            self.score = score
            self.font = font.SysFont('Arial',15)
            x = y = 0
            if levelno == 0:            
                self.player = Player(32,32,image_cache, stats)
                #Start Screen
                level = [
                    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
                    "P                              P",
                    "P                              P",
                    "P       T                      P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P   z                    I     P",
                    "P   PPP                  PPP   P",
                    "P      P                P      P",
                    "P   H   P              P       P",
                    "P                          b   P",
                    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
                    "P                              P",
                    "P                              P",
                    "PSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSP",]
        def render(self,screen):
            for y in range(20):
                for x in range(34):
                    screen.blit(self.bg, (x*32,y*32))
            #update the player and draw everything else onto screen
            for m in self.movingplats:
                screen.blit(m.image, self.camera.apply(m))
            for e in self.entities:
                screen.blit(e.image, self.camera.apply(e))
                if e == self.player:
                    self.playerRect = self.camera.apply(e)
            for p in self.projectiles:
                screen.blit(p.image, self.camera.apply(p))
            for enemy in self.enemiesThatHaveHealth:
                enemyRect = self.camera.apply(enemy)
                enemy.healthRect.left = enemyRect.left+int((32-enemy.healthLength)/2)
                enemy.healthRect.top = enemyRect.top-10
                pygame.draw.rect(screen, (255,0,0), enemy.healthRect)
            self.updScore()
            screen.blit(self.scimg,(4,4))    
            self.player.healthRect.left = self.playerRect.left+int((32-self.player.healthLength)/2)
            self.player.healthRect.top = self.playerRect.top-10
            pygame.draw.rect(screen, (0,255,0), self.player.healthRect)
    
        def update(self,clock,events):
            for e in events:
                if e.type == KEYDOWN and e.key == K_z:
                    projectile = Projectile(self.player.rect.left,self.player.rect.top+16,self.diLeft,self.image_cache,"Pencil")
                    self.projectiles.add(projectile)
                if e.type == KEYDOWN and e.key == K_x:
                    if self.player.canBook:
                        projectile = Projectile(self.player.rect.left,self.player.rect.top+12,self.diLeft,self.image_cache,"Book")
                        self.projectiles.add(projectile)
                        self.player.bookCount -= 1
                        
            pressed = pygame.key.get_pressed()
            up,left,right,down = [pressed[key] for key in (K_UP,K_LEFT,K_RIGHT,K_DOWN)]
            if left:
                self.diLeft = True
            if right:
                self.diLeft = False
    
            self.enemiesThatHaveHealth.update(self.platforms,self.entities,self.enemiesThatHaveHealth,self.projectiles)
            self.projectiles.update(self.platforms,self.entities,self.projectiles,self.enemiesThatHaveHealth)
            self.movingplats.update()
            self.player.update(up,down,left,right,self.platforms,self.entities,clock.get_rawtime()/1000.0)
            self.camera.update(self.player)
            self.cameraRect = self.camera.state
            self.updScore()
    
        def lvl1(self):
            self.manager.go_to(GameScene(1,self.score))
    
        def lvl2(self):
            self.manager.go_to(GameScene(2,self.score))
    
        def bosslvl(self):
            self.manager.go_to(GameScene(4,self.score))
            
        def updScore(self):
            self.scimg = self.font.render("Targets Smashed: %08i" % self.score, True, (60,191,255))
        def addScore(self,value):
            self.score += value
            self.updScore
            
        def handle_events(self,events):
            for e in events:
                if e.type == KEYDOWN and e.key == K_ESCAPE:
                    pass #Menu or pause?
    
    class SceneManager(object):
        def __init__(self):
            self.go_to(GameScene(0,0))
    
        def go_to(self,scene):
            self.scene = scene
            self.scene.manager = self
    
    #Enemy Class
    class Enemy(Entity):
        def __init__(self,x,y,image_cache,enemy_type,health):
            Entity.__init__(self)
            self.image_cache = image_cache
            self.enemy_type = enemy_type
            self.maxHealth = health
            self.health = health
    
            #if enemy_type == nonStatics:
            self.x_vel = 0
            self.y_vel = 0
            self.onGround = False
            self.onRightWall = False
            self.onLeftWall = False
    
            #Loading Image for Enemy and specific enemy instance variables
            if self.enemy_type == "BottomSpike":
                self.image=functions.getImage('data/bottomspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "RightSpike":
                self.image=functions.getImage('data/rightwallspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "LeftSpike":
                self.image=functions.getImage('data/leftwallspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "TopSpike":
                self.image=functions.getImage('data/topspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "CenterSpike":
                self.image=functions.getImage('data/spikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "Target":
                self.image=functions.getImage('data/target.gif',image_cache)
                self.damage = 0
                self.recoveryTime = 10
            elif self.enemy_type == "Target2":
                self.image=functions.getImage('data/target2.gif',image_cache)
                self.damage = 0
                self.recoveryTime = 10
            else:
                #ADD MORE ENEMIES HERE
                pass
            self.image.convert_alpha()
            self.rect=Rect(x,y,32,32)
            if self.maxHealth > 0:
                self.healthLength = int(32*self.health/self.maxHealth)
                self.healthRect = Rect(x+int((32-self.healthLength)/2), y-10, self.healthLength, 5)
    
        def update(self,platforms,entities,projectiles,enemiesThatHaveHealth):
            if self.maxHealth > 0:
                #death condition
                if self.health <= 0 and self in entities:
                    platforms.remove(self)
                    self.kill()
    ##                if self.enemy_type == "Target":
    ##                    GameScene.self.addScore(1)
    ##                elif self.enemy_type == "Target2":
    ##                    GameScene.self.addScore(2)
    ##                else:
    ##                    pass
                else:
                    #include moving enemy code here***
                    pass
                #health box update
                self.healthLength = int(32*self.health/self.maxHealth)
                self.healthRect.width = self.healthLength
            else:
                pass
    there is a LOT more code, but this is what I think is relevant. I have tried having the score being passed though updates and then being modified like this:

    Code:
        def update(self,clock,events):
            for e in events:
                if e.type == KEYDOWN and e.key == K_z:
                    projectile = Projectile(self.player.rect.left,self.player.rect.top+16,self.diLeft,self.image_cache,"Pencil")
                    self.projectiles.add(projectile)
                if e.type == KEYDOWN and e.key == K_x:
                    if self.player.canBook:
                        projectile = Projectile(self.player.rect.left,self.player.rect.top+12,self.diLeft,self.image_cache,"Book")
                        self.projectiles.add(projectile)
                        self.player.bookCount -= 1
                        
            pressed = pygame.key.get_pressed()
            up,left,right,down = [pressed[key] for key in (K_UP,K_LEFT,K_RIGHT,K_DOWN)]
            if left:
                self.diLeft = True
            if right:
                self.diLeft = False
    
            self.enemiesThatHaveHealth.update(self.platforms,self.entities,self.enemiesThatHaveHealth,self.player,self.projectiles)
            self.projectiles.update(self.platforms,self.entities,self.projectiles,self.enemiesThatHaveHealth,self.score)
            self.movingplats.update()
            self.player.update(up,down,left,right,self.platforms,self.entities,clock.get_rawtime()/1000.0)
            self.camera.update(self.player)
            self.cameraRect = self.camera.state
            self.updScore()
    
    class Projectile(Entity):
        def __init__(self,x,y,diLeft,image_cache,projType):
            Entity.__init__(self)
            self.image_cache = image_cache
            self.projType=projType
            #Projectile type, set velocity image and damage
            if self.projType=="Pencil":
                if diLeft:
                    x -= 16
                    self.image=functions.getImage('data/pencil2.gif',image_cache)
                    self.x_vel = -6
                else:
                    x += 32
                    self.image=functions.getImage('data/pencil.gif',image_cache)
                    self.x_vel = 6
                self.image.convert_alpha()
                self.damage=2
                self.rect=Rect(x,y,16,8)
            elif self.projType=="Book":
                self.image=functions.getImage('data/book.gif',image_cache)
                if diLeft:
                    x -= 24
                    self.x_vel = -4
                else:
                    x += 32
                    self.x_vel = 4
                self.image.convert_alpha()
                self.damage=4
                self.rect=Rect(x,y,24,16)
            elif self.projType=="Fireball":
                self.image=functions.getImage('data/book.gif',image_cache)
                if diLeft:
                    x -= 24
                    self.x_vel = -6
                else:
                    x += 32
                    self.x_vel = 6
                self.image.convert_alpha()
                self.damage=10
                self.rect=Rect(x,y,24,16)
            else:
                #add more here with elif statement
                pass
        def update(self,platforms,entities,projectiles,enemiesThatHaveHealth,score):
            self.rect.x+=self.x_vel
            self.collide(platforms,entities,projectiles,enemiesThatHaveHealth,score)
    
        #Collisions
        def collide(self,platforms,entities,projectiles,enemiesThatHaveHealth,score):
            for p in platforms:
                if sprite.collide_rect(self,p):
                    if isinstance(p,Enemy) or isinstance(p,Boss1):
                        p.takeDamage(self.damage)
                        p.update(platforms,entities,projectiles,enemiesThatHaveHealth,score)
                    #projectiles.remove(self)
                    elif isinstance(p,Player):
                        p.takeDamage(self.damage,0)
                    self.kill()
    
    
    #Enemy Class
    class Enemy(Entity):
        def __init__(self,x,y,image_cache,enemy_type,health):
            Entity.__init__(self)
            self.image_cache = image_cache
            self.enemy_type = enemy_type
            self.maxHealth = health
            self.health = health
    
            #if enemy_type == nonStatics:
            self.x_vel = 0
            self.y_vel = 0
            self.onGround = False
            self.onRightWall = False
            self.onLeftWall = False
    
            #Loading Image for Enemy and specific enemy instance variables
            if self.enemy_type == "BottomSpike":
                self.image=functions.getImage('data/bottomspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "RightSpike":
                self.image=functions.getImage('data/rightwallspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "LeftSpike":
                self.image=functions.getImage('data/leftwallspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "TopSpike":
                self.image=functions.getImage('data/topspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "CenterSpike":
                self.image=functions.getImage('data/spikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "Target":
                self.image=functions.getImage('data/target.gif',image_cache)
                self.damage = 0
                self.recoveryTime = 10
            elif self.enemy_type == "Target2":
                self.image=functions.getImage('data/target2.gif',image_cache)
                self.damage = 0
                self.recoveryTime = 10
            else:
                #ADD MORE ENEMIES HERE
                pass
            self.image.convert_alpha()
            self.rect=Rect(x,y,32,32)
            if self.maxHealth > 0:
                self.healthLength = int(32*self.health/self.maxHealth)
                self.healthRect = Rect(x+int((32-self.healthLength)/2), y-10, self.healthLength, 5)
    
        def update(self,platforms,entities,projectiles,enemiesThatHaveHealth,score):
            if self.maxHealth > 0:
                #death condition
                if self.health <= 0 and self in entities:
                    platforms.remove(self)
                    self.kill()
                    if self.enemy_type == "Target":
                        score += 1
                    elif self.enemy_type == "Target2":
                        score += 2
                    else:
                        pass
                else:
                    #include moving enemy code here***
                    pass
                #health box update
                self.healthLength = int(32*self.health/self.maxHealth)
                self.healthRect.width = self.healthLength
            else:
                pass
    If this isn't enough code, I can post it all here but like I said.. there is a lot
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,704
    Rep Power
    480
    Let's look at the first block of code in post 1 using the emacs occur command.
    Code:
    14 matches for "score" in buffer: p.py
         25:    def __init__(self,levelno,score):
         43:        self.score = score
         88:        self.updScore()
        118:        self.updScore()
        121:        self.manager.go_to(GameScene(1,self.score))
        124:        self.manager.go_to(GameScene(2,self.score))
        127:        self.manager.go_to(GameScene(4,self.score))
        129:    def updScore(self):
        130:        self.scimg = self.font.render("Targets Smashed: %08i" % self.score, True, (60,191,255))
        131:    def addScore(self,value):
        132:        self.score += value
        133:        self.updScore
        209:##                    GameScene.self.addScore(1)
        211:##                    GameScene.self.addScore(2)
    Between this and browsing the code I learn that you're concerned with the score attribute of a GameScene object. The constructor sets attribute score to an initial value. Good. No problem there. The updScore method probably handles rendering. Looks reasonable. The addScore method changes the object's attribute. Good good.

    You've commented away the calls to addScore . That could be the problem. I think you know of these comments. That's not the answer.


    Instead of posting more code, try to help yourself. Open a file as a global and write useful information into where the score changes, within addScore and in GameScene . __init__ . Play the game some and see if you learn something from this score file afterward.
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,704
    Rep Power
    480
    oh hang on...if you were to execute those lines commented away...
    [code]Code tags[/code] are essential for python code and Makefiles!
  6. #4
  7. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    3
    Rep Power
    0
    Thank you for your reply. The commented out part is in the Enemy class and when it is called, it gives me an unbound method error, saying I have to assign GameScene to a variable within Enemy class (which would make no sense to do).

    If I was unclear about my exact problem before:

    How to I set the score in GameScene so that it is always on the screen (regardless of which scene it is) and it is always counting up until the game is restarted? I have targets set up in the game that you can break with projectiles that I have in the game. Targets are in Enemy Class, projectiles are a class of their own. How would I be able to have the self.score within GameScene add a point or 2 points (depending on type of target) when the target breaks. Here is more of my code:

    Code:
    import pygame, sys, os, math, random
    import functions
    import mainGame
    from pygame.locals import *
    from mainGame import *
    
    #Entity Class
    class Entity(pygame.sprite.Sprite):
        def __init__(self):
            pygame.sprite.Sprite.__init__(self)
    
    class Scene(object):
        def __init__(self):
            pass
    
        def render(self,screen):
            raise NotImplementedError
    
        def update(self):
            raise NotImplementedError
        def handle_events(self,events):
            raise NotImplementedError
    
    class GameScene(Scene):
        def __init__(self,levelno,score):
            super(GameScene, self).__init__()
            #Preloading the images that are going to be used
            image_cache = {}
            all_images=glob.glob('data/*.gif' or 'data/*.png')
            for image in all_images:
                functions.getImage(image,image_cache)
            self.image_cache = image_cache
            up = left = down = right = self.diLeft = False
            self.bg = Surface((32,32))
            self.bg.convert()
            self.bg.fill(Color(255, 255, 255))
            self.projectiles = pygame.sprite.Group()
            self.entities = pygame.sprite.Group()
            self.movingplats = pygame.sprite.Group()
            self.enemiesThatHaveHealth = pygame.sprite.Group()
            self.shottime = 10
            self.platforms = []
            self.score = score
            self.font = font.SysFont('Arial',15)
            x = y = 0
            if levelno == 0:            
                self.player = Player(32,32,image_cache, stats)
                #Start Screen
                level = [
                    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
                    "P                              P",
                    "P                              P",
                    "P       T                      P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P   z                    I     P",
                    "P   PPP                  PPP   P",
                    "P      P                P      P",
                    "P   H   P              P       P",
                    "P                          b   P",
                    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
                    "P                              P",
                    "P                              P",
                    "PSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSP",]
            elif levelno == 1:
                self.player = Player(100,(43*32),image_cache,stats)
                level = [
            #Platform testing level
                    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
                    "L RL          2                                                    R",
                    "L RL          PPP                                                  R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                     YYY                                          R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                                      YY          R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                YYY                               R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                             2                    R",
                    "L                                                                  R",
                    "L                                                               YY R",
                    "L                                         11                       R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L          MMMMM                                                   R",
                    "L                                                                  R",
                    "L                     KKKKKK        1                              R",
                    "L                                  2                               R",
                    "L                         ZZZZZZZZ                                 R",
                    "L                                  2                               R",
                    "L                                                                  R",
                    "L                   KKKKKKKK              1                        R",
                    "L                                                            Y     R",
                    "L              ZZZZZZZZZZZZZZZZZZZZZZZZZZZZ                        R",
                    "L                                                                  R",
                    "L                                                 YYYYYYYYYYY      R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                                                                  R",
                    "L                   YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY         R",
                    "L    UUUUUU           22                                           R",
                    "L                    11                             r              R",
                    "PPPPP      PPPPPPPP        PPPPPPPP        PPPPPPPPPPPPPPPPPPPPPPPPR",
                    "PPPPPBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",]
            elif levelno == 2:
                self.player = Player(32,32,image_cache, stats)
                level = [
                    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
                    "P                                  P",
                    "P                                  P",
                    "P          D       PPPPPPPPP       P",
                    "P                                P P",
                    "P                                P P",
                    "P          P           S        RP P",
                    "P          PPPP                  P P",
                    "P              P                 P P",
                    "P                                P P",
                    "P      PPPPPPPPPP     PPPPPPPPP  P P",
                    "P      T     T                   P P",
                    "P                  PP            P P",
                    "P          P  P  P            PPPP P",
                    "P       PP                   P   P P",
                    "PPPP                        P    P P",
                    "P  PPP             S       P     P P",
                    "P      PPPP               P      P P",
                    "P                                P P",
                    "PBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBP",]
            elif levelno == 4:            
                self.player = Player(32,32,image_cache, stats)
                #Boss Level
                level = [
                    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P                              P",
                    "P          MMMMM               P",
                    "P   PPP                  PPP   P",
                    "P      P                P      P",
                    "P   H   P              P       P",
                    "P                           !  P",
                    "PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP",
                    "P                              P",
                    "P                              P",
                    "PSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSP",]
    
                
            self.player.scene = self
                #Building the level
            for row in level:
                for col in row:
                    if col == "P":
                        p = Platform(x,y,image_cache,0,"none",0)
                        self.platforms.append(p)
                        self.entities.add(p)
                    if col == "C":
                        c = Chest(x,y,image_cache)
                        self.platforms.append(c)
                        self.entities.add(c)
                    if col == "E":
                        e = Checkpoint(x,y,image_cache)
                        self.platforms.append(e)
                        self.entities.add(e)
                    if col == "B":
                        s = Enemy(x,y,image_cache, "BottomSpike",0)
                        self.platforms.append(s)
                        self.entities.add(s)
                    if col == "T":
                        s = Enemy(x,y,image_cache, "TopSpike",0)
                        self.platforms.append(s)
                        self.entities.add(s)
                    if col == "L":
                        s = Enemy(x,y,image_cache, "LeftSpike",0)
                        self.platforms.append(s)
                        self.entities.add(s)
                    if col == "R":
                        s = Enemy(x,y,image_cache, "RightSpike",0)
                        self.platforms.append(s)
                        self.entities.add(s)
                    if col == "S":
                        s = Enemy(x,y,image_cache, "CenterSpike",0)
                        self.platforms.append(s)
                        self.entities.add(s)
                    if col == "D":
                        d = Boost(x,y,image_cache, "D")
                        self.platforms.append(d)
                        self.entities.add(d)
                    if col == "I":
                        i = Level1(x,y,image_cache)
                        self.platforms.append(i)
                        self.entities.add(i)
                    if col == "z":
                        z =  Level2(x,y,image_cache)
                        self.platforms.append(z)
                        self.entities.add(z)
                    if col == "b":
                        b = BossLvl(x,y,image_cache)
                        self.platforms.append(b)
                        self.entities.add(b)
                    if col == "!":
                        b = Boss1(x,y,image_cache,500)
                        self.platforms.append(b)
                        self.entities.add(b)
                        self.enemiesThatHaveHealth.add(b)
    ##                if col == "H":
    ##                    h = Start(x,y,image_cache, "H")
    ##                    self.platforms.append(h)
    ##                    self.entities.add(h)
    ##                if col == "T":
    ##                    t = Start(x,y,image_cache, "T")
    ##                    self.platforms.append(t)
    ##                    self.entities.add(t)
                    if col == "M":
                        #In order to create platforms that move different lengths and speeds
                        #you must create different letters to add to the level creator and change variables
                        p = Platform(x,y,image_cache,6,"right",2)
                        self.platforms.append(p)
                        self.movingplats.add(p)
                    if col == "U":
                        p = Platform(x,y,image_cache,8,"up",3)
                        self.platforms.append(p)
                        self.movingplats.add(p)
                    if col == "K":
                        p = Platform(x,y,image_cache,0,"slide",3)
                        self.platforms.append(p)
                        self.movingplats.add(p)
                    if col == "Z":
                        p = Platform(x,y,image_cache,0,"slide",-3)
                        self.platforms.append(p)
                        self.movingplats.add(p)
                    if col == "Y":
                        p = Platform(x,y,image_cache,0,"bounce",9)
                        self.platforms.append(p)
                        self.movingplats.add(p)
                    if col == "1":
                        t = Enemy(x,y,image_cache,"Target",8)
                        self.platforms.append(t)
                        self.entities.add(t)
                        self.enemiesThatHaveHealth.add(t)
                    if col == "2":
                        t = Enemy(x,y,image_cache,"Target2",16)
                        self.platforms.append(t)
                        self.entities.add(t)
                        self.enemiesThatHaveHealth.add(t)
                    if col == "r":
                        r = pickupItems(x,y,image_cache,"book",20)
                        self.platforms.append(r)
                        self.entities.add(r)
                    x+=32
                y+=32
                x=0
    
            total_level_width=len(level[0])*32
            total_level_height=len(level)*32
            self.camera=Camera(scrollingCamera,total_level_width,total_level_height)
    
            #Loading Player
            
            self.entities.add(self.player)
            self.platforms.append(self.player)
    
        def render(self,screen):
            for y in range(20):
                for x in range(34):
                    screen.blit(self.bg, (x*32,y*32))
            #update the player and draw everything else onto screen
            for m in self.movingplats:
                screen.blit(m.image, self.camera.apply(m))
            for e in self.entities:
                screen.blit(e.image, self.camera.apply(e))
                if e == self.player:
                    self.playerRect = self.camera.apply(e)
            for p in self.projectiles:
                screen.blit(p.image, self.camera.apply(p))
            for enemy in self.enemiesThatHaveHealth:
                enemyRect = self.camera.apply(enemy)
                enemy.healthRect.left = enemyRect.left+int((32-enemy.healthLength)/2)
                enemy.healthRect.top = enemyRect.top-10
                pygame.draw.rect(screen, (255,0,0), enemy.healthRect)
            self.updScore()
            screen.blit(self.scimg,(4,4))    
            self.player.healthRect.left = self.playerRect.left+int((32-self.player.healthLength)/2)
            self.player.healthRect.top = self.playerRect.top-10
            pygame.draw.rect(screen, (0,255,0), self.player.healthRect)
    
        def update(self,clock,events):
            for e in events:
                if e.type == KEYDOWN and e.key == K_z:
                    projectile = Projectile(self.player.rect.left,self.player.rect.top+16,self.diLeft,self.image_cache,"Pencil")
                    self.projectiles.add(projectile)
                if e.type == KEYDOWN and e.key == K_x:
                    if self.player.canBook:
                        projectile = Projectile(self.player.rect.left,self.player.rect.top+12,self.diLeft,self.image_cache,"Book")
                        self.projectiles.add(projectile)
                        self.player.bookCount -= 1
                        
            pressed = pygame.key.get_pressed()
            up,left,right,down = [pressed[key] for key in (K_UP,K_LEFT,K_RIGHT,K_DOWN)]
            if left:
                self.diLeft = True
            if right:
                self.diLeft = False
    
            self.enemiesThatHaveHealth.update(self.platforms,self.entities,self.enemiesThatHaveHealth,self.projectiles)
            self.projectiles.update(self.platforms,self.entities,self.projectiles,self.enemiesThatHaveHealth)
            self.movingplats.update()
            self.player.update(up,down,left,right,self.platforms,self.entities,clock.get_rawtime()/1000.0)
            self.camera.update(self.player)
            self.cameraRect = self.camera.state
            self.updScore()
    
        def lvl1(self):
            self.manager.go_to(GameScene(1,self.score))
    
        def lvl2(self):
            self.manager.go_to(GameScene(2,self.score))
    
        def bosslvl(self):
            self.manager.go_to(GameScene(4,self.score))
            
        def updScore(self):
            self.scimg = self.font.render("Targets Smashed: %08i" % self.score, True, (60,191,255))
        def addScore(self,value):
            self.score += value
            self.updScore
            
        def handle_events(self,events):
            for e in events:
                if e.type == KEYDOWN and e.key == K_ESCAPE:
                    pass #Menu or pause?
    
    class SceneManager(object):
        def __init__(self):
            self.go_to(GameScene(0,0))
    
        def go_to(self,scene):
            self.scene = scene
            self.scene.manager = self
    
            
    #Boost Class
    class Boost(Entity):
        def __init__(self,x,y,image_cache,boost_type):
            Entity.__init__(self)
            self.image_cache = image_cache
            self.boost_type = boost_type
    
            #Loading Image for Boost
            if self.boost_type == "D":
                self.image=functions.getImage('data/doubleJumpBoost.png',image_cache)
            else:
                #Add other boosts here
                pass
            self.image.convert_alpha()
            self.rect=Rect(x,y,32,32)
    
        def activate(self, player):
            if self.boost_type == "D":
                player.hasDoubleJumpBoost = True
            else:
                #Add other boosts here
                pass
    
    class Projectile(Entity):
        def __init__(self,x,y,diLeft,image_cache,projType):
            Entity.__init__(self)
            self.image_cache = image_cache
            self.projType=projType
            #Projectile type, set velocity image and damage
            if self.projType=="Pencil":
                if diLeft:
                    x -= 16
                    self.image=functions.getImage('data/pencil2.gif',image_cache)
                    self.x_vel = -6
                else:
                    x += 32
                    self.image=functions.getImage('data/pencil.gif',image_cache)
                    self.x_vel = 6
                self.image.convert_alpha()
                self.damage=2
                self.rect=Rect(x,y,16,8)
            elif self.projType=="Book":
                self.image=functions.getImage('data/book.gif',image_cache)
                if diLeft:
                    x -= 24
                    self.x_vel = -4
                else:
                    x += 32
                    self.x_vel = 4
                self.image.convert_alpha()
                self.damage=4
                self.rect=Rect(x,y,24,16)
            elif self.projType=="Fireball":
                self.image=functions.getImage('data/book.gif',image_cache)
                if diLeft:
                    x -= 24
                    self.x_vel = -6
                else:
                    x += 32
                    self.x_vel = 6
                self.image.convert_alpha()
                self.damage=10
                self.rect=Rect(x,y,24,16)
            else:
                #add more here with elif statement
                pass
        def update(self,platforms,entities,projectiles,enemiesThatHaveHealth):
            self.rect.x+=self.x_vel
            self.collide(platforms,entities,projectiles,enemiesThatHaveHealth)
    
        #Collisions
        def collide(self,platforms,entities,projectiles,enemiesThatHaveHealth):
            for p in platforms:
                if sprite.collide_rect(self,p):
                    if isinstance(p,Enemy) or isinstance(p,Boss1):
                        p.takeDamage(self.damage)
                        p.update(platforms,entities,projectiles,enemiesThatHaveHealth)
                    #projectiles.remove(self)
                    elif isinstance(p,Player):
                        p.takeDamage(self.damage,0)
                    self.kill()
                        
        
                    
    
            
    
    #Enemy Class
    class Enemy(Entity):
        def __init__(self,x,y,image_cache,enemy_type,health):
            Entity.__init__(self)
            self.image_cache = image_cache
            self.enemy_type = enemy_type
            self.maxHealth = health
            self.health = health
    
            #if enemy_type == nonStatics:
            self.x_vel = 0
            self.y_vel = 0
            self.onGround = False
            self.onRightWall = False
            self.onLeftWall = False
    
            #Loading Image for Enemy and specific enemy instance variables
            if self.enemy_type == "BottomSpike":
                self.image=functions.getImage('data/bottomspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "RightSpike":
                self.image=functions.getImage('data/rightwallspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "LeftSpike":
                self.image=functions.getImage('data/leftwallspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "TopSpike":
                self.image=functions.getImage('data/topspikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "CenterSpike":
                self.image=functions.getImage('data/spikes.png',image_cache)
                self.damage = 8
                self.recoveryTime = 10
            elif self.enemy_type == "Target":
                self.image=functions.getImage('data/target.gif',image_cache)
                self.damage = 0
                self.recoveryTime = 10
            elif self.enemy_type == "Target2":
                self.image=functions.getImage('data/target2.gif',image_cache)
                self.damage = 0
                self.recoveryTime = 10
            else:
                #ADD MORE ENEMIES HERE
                pass
            self.image.convert_alpha()
            self.rect=Rect(x,y,32,32)
            if self.maxHealth > 0:
                self.healthLength = int(32*self.health/self.maxHealth)
                self.healthRect = Rect(x+int((32-self.healthLength)/2), y-10, self.healthLength, 5)
    
        def update(self,platforms,entities,projectiles,enemiesThatHaveHealth):
            if self.maxHealth > 0:
                #death condition
                if self.health <= 0 and self in entities:
                    platforms.remove(self)
                    self.kill()
    ##                if self.enemy_type == "Target":
    ##                    GameScene.self.addScore(1)
    ##                elif self.enemy_type == "Target2":
    ##                    GameScene.self.addScore(2)
    ##                else:
    ##                    pass
                else:
                    #include moving enemy code here***
                    pass
                #health box update
                self.healthLength = int(32*self.health/self.maxHealth)
                self.healthRect.width = self.healthLength
            else:
                pass
    
        def takeDamage(self,damage):
            if self.maxHealth > 0:
                self.health -= damage
    
        def hit(self, player):
            if player.damageTimer == 0:
                tmp = self.enemy_type
                if (tmp == "BottomSpike" or
                    tmp == "LeftSpike" or
                    tmp == "RightSpike" or
                    tmp == "TopSpike" or
                    tmp == "CenterSpike"):
                    player.takeDamage(self.damage,self.recoveryTime)
                else:
                    #ADD MORE ENEMIES HERE
                    pass
            else:
                # make player flash while damageTimer > 0
                pass
    
    
    
    class pickupItems(Entity):
        def __init__(self,x,y,image_cache,objectType,quantity):
            Entity.__init__(self)
            self.image_cache = image_cache
            self.objectType = objectType
    
            self.x_vel = 0
            self.y_vel = 0
            self.onGround = False
            self.onRightWall = False
            self.onLeftWall = False
            self.quantity = quantity
    
            self.pickUpSound = pygame.mixer.Sound('pickupSound.wav')
            self.openChestSound = pygame.mixer.Sound('chestSound.wav')
            self.checkPointSound = pygame.mixer.Sound('checkPointSound.wav')
    
            #Loading Image for Enemy and specific enemy instance variables
            if self.objectType == "pencil":
                self.image=functions.getImage('data/pencil.png',image_cache)
            if self.objectType == "ruler":
                self.image=functions.getImage('data/ruler.png',image_cache)
            if self.objectType == "tray":
                self.image=functions.getImage('data/tray.png',image_cache)
            if self.objectType == 'healthBoost':
                self.image=functions.getImage('data/healthBoost.png',image_cache)
            if self.objectType == 'checkPoint':
                self.image=functions.getImage('data/checkPoint.png', image_cache)
            if self.objectType == 'book':
                self.image=functions.getImage('data/book.gif', image_cache)
            if self.objectType=='chest':
                self.image=functions.getImage('data/chest.gif', image_cache)
            if self.objectType == 'doubleJumpBoost':
                self.image=functions.getImage('data/doubleJumpBoost.png', image_cache)
    
            self.image.convert_alpha()
            self.rect=Rect(x,y,32,32)
    
        def pickUp(self,entities,player):
            if self.objectType == 'pencil':
                player.pencilCount += self.quantity
                self.pickUpSound.play()
            if self.objectType == 'ruler':
                player.rulerCount += self.quantity
                self.pickUpSound.play()
            if self.objectType == 'tray':
                player.trayCount += self.quantity
                self.pickUpSound.play()
            if self.objectType == 'healthBooster':
                player.health += self.quantity
                self.pickUpSound.play()
            if self.objectType == 'checkPoint':
                ##CODE HERE TO SAVE PROGRESS
                self.checkPointSound.play()
            if self.objectType == 'book':
                player.bookCount += self.quantity
                self.pickUpSound.play()
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,704
    Rep Power
    480

    sorry for the 3 successive posts. They make sense to me now.


    If you were to evaluate
    GameScene.self.addScore(1)

    GameScene is a class.
    GameScene does not have a self attribute.
    python should raise attribute error.


    Enemy objects need access to GameScene instances. You gave them access to GameScene the class.






    Unrelated, you should rewrite your Enemy class and constructor
    Code:
    class Enemy(Entity):
    
        enemy_data = dict(
            BottomSpike=('data/bottomspikes.png', 8, 10),
            RightSpike=('data/rightwallspikes.png', 8, 10),
            #ADD MORE ENEMIES HERE
            )
    
        def __init__(self,x,y,image_cache,enemy_type,health):
            Entity.__init__(self)
            self.image_cache = image_cache
            self.enemy_type = enemy_type
            self.maxHealth = health
            self.health = health
    
            #if enemy_type == nonStatics:
            self.x_vel = 0
            self.y_vel = 0
            self.onGround = False
            self.onRightWall = False
            self.onLeftWall = False
    
            #Loading Image for Enemy and specific enemy instance variables
            #replace the long train of elif with these two statements
            (image, self.damage, self.recoveryTime) = Enemy.enemy_data[enemy_type]
            self.image = functions.getImage(image, image_cache)
    
    
            self.image.convert_alpha()
            self.rect=Rect(x,y,32,32)
            if self.maxHealth > 0:
                self.healthLength = int(32*self.health/self.maxHealth)
                self.healthRect = Rect(x+int((32-self.healthLength)/2), y-10, self.healthLength, 5)
    [code]Code tags[/code] are essential for python code and Makefiles!
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2013
    Posts
    3
    Rep Power
    0
    You are correct, it did raise attribute error. How would I give them access to the instances? I tried to assign self.gamescene = GameScene(0,0) in the enemy class but that just messed things up further, saying that it reached its recursive limit. When I changed it to GameScene.addScore(1) it gave me

    TypeError: unbound method addScore() must be called with GameScene instance as first argument (got int instance instead)

    Thank you for advice on rewriting the constructor, I will do that.
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    191
    Rep Power
    2
    Skimmed over some of this, but the problem here is making certain data persist through scene changes, is it not?

    My scenes all have a method called cleanup and a method called startup. When a scene finishes, the scene manager calls cleanup on that scene. In the cleanup function (overloaded in the specific scene) information that needs to persist is added to a dictionary and returned. The scene manager then changes to the next scene and calls that scene's startup method passing that dictionary. In which it adds necessary persisting data to the scene.

    These are the generic cleanup/startup methods(they currently don't alter or use the dictionary and must be overloaded)
    python Code:
    def startup(self,current_time,persistant):
        """Add variables passed in persistant to the proper attributes and
        set the start time of the State to the current time."""
        self.persist = persistant
        self.start_time = current_time
     
    def cleanup(self):
        """Add variables that should persist to the self.persist dictionary.
        Then reset State.done to False."""
        self.done = False
        return self.persist

    And the state manager's flip_state method:
    python Code:
    def flip_state(self):
        """When a State changes to done necessary startup and cleanup functions
        are called and the current State is changed."""
        previous,self.state_name = self.state_name,self.state.next
        persist = self.state.cleanup()
        self.state = self.state_dict[self.state_name]
        self.state.startup(self.current_time,persist)
        self.state.previous = previous

    -Mek
    Last edited by Mekire; December 6th, 2013 at 09:20 PM.

IMN logo majestic logo threadwatch logo seochat tools logo