def __init__(self, elapsedTime, levelPath=None): super().__init__(elapsedTime) # if we paused and want to return to this state, we need to subtract the time # spent while paused self.pauseTime = 0 self.player = None self.platform = None # create groups self.terrainGroup = pygame.sprite.Group() self.allRenderedObjs = pygame.sprite.RenderUpdates() # assign classes to groups #Spacecraft.containers = allRenderedObjs #TerrainUnit.containers = allRenderedObjs, terrainGroup if levelPath is not None: self.load_level(levelPath) else: # by default, just create one giant rectangle at the bottom of the # screen terrainUnit = Entities.TerrainUnit( \ 0, 3.*Globals.WINDOWRECT.height/4, # y = 3/4ths the height of # the window Globals.WINDOWRECT.width, Globals.WINDOWRECT.height / 4) # place the platform at the center self.platform = Entities.LandingPlatform( \ Globals.WINDOWRECT.centerx, terrainUnit.rect.y) self.allRenderedObjs.add(self.platform) self.allRenderedObjs.add(terrainUnit) self.terrainGroup.add(terrainUnit) # finally, place the player just above the platform self.player = Entities.Spacecraft( \ Globals.WINDOWRECT.centerx, Globals.WINDOWRECT.centery) self.allRenderedObjs.add(self.player)
def load_level(self, path): f = open(path, "r") for line in f: matches = findall("[0-9]+", line) if len(matches) == 2 and self.player is None: # define the spacecraft self.player = Entities.Spacecraft( \ int(matches[0]), int(matches[1])) self.allRenderedObjs.add(self.player) elif len(matches) == 2 and self.platform is None: #define the platform self.platform = Entities.LandingPlatform( \ int(matches[0]), int(matches[1])) self.allRenderedObjs.add(self.platform) platformDefined = True elif len(matches) == 4: # define the terrain units terrainUnit = Entities.TerrainUnit( \ int(matches[0]), int(matches[1]), int(matches[2]), int(matches[3])) self.allRenderedObjs.add(terrainUnit) self.terrainGroup.add(terrainUnit) terrainDefined = True else: print("Error: reading level file,", len(matches), "fields matched") raise RuntimeError if not(self.player is not None \ and self.platform is not None \ and len(self.terrainGroup) > 0): print( "Error: there must be a location definition for at least one of each:", "spacecraft, platform, terrain") raise RuntimeError