Beispiel #1
0
def run_game():
    pygame.init()
    settings = game_settings.Settings()
    screen = pygame.display.set_mode(settings.resolution)
    snake = Snake(screen, settings)
    pygame.display.set_caption("Snake")
    my_tail = []
    x, y = gf.generate_randoms()
    food = GroupSingle(Food(snake, screen, x, y))
    tails = OrderedUpdates()
    gf.initialise_snake(snake, screen, my_tail, tails, settings)
    button = Play_button(screen, settings, "Play")
    end_game_screen = EndGameScreen(screen, settings, "Game Over")
    score = Score(screen, settings)
    clock = pygame.time.Clock()
    gametime = GTime(clock)

    while True:
        screen.fill(settings.bg_color)
        score.draw_me()
        gf.check_events(snake, food, screen, my_tail, tails, settings, button,
                        gf, end_game_screen, score, gametime)
        if settings.game_active == False:
            if gf.lose_condition_met(snake, settings, tails,
                                     gametime) == False:
                button.draw_me()
        if settings.game_active == True:
            snake.update()
            tails.update()
            snake.draw_me()
            food.update()
            clock.tick(10)
            gametime.update()
            print(gametime.time)
        pygame.display.flip()
Beispiel #2
0
    def start(self):
        """ 
        Sets up and starts the level.
        """
        self.collision = Collision(self, self.game.window.resolution, 32)
        self.prefabs = OrderedUpdates()
        self.pathfinding = Pathfinding(self.game, self.collision)

        for args in self.data:
            name = args[0]
            x = int(args[1])
            y = int(args[2])

            prefab = Prefab(name, x, y)
            self.prefabs.add(prefab)

            if hasattr(prefab, "block"):
                # Block textures are 1 pixel wider to make a full border
                self.collision.block_rect(x, y, prefab.rect.width - 1,
                                          prefab.rect.height - 1)

        self.pathfinding.precompute(30)
        self.wave = Wave(self.game, 1)
        self.lives = 20
        self.money = 600
        self.time = 0
Beispiel #3
0
class Level:
    """ 从.level文件中加载关卡,包含关卡prefab、缓存路径和碰撞数据 """
    def __init__(self, game, name):
        """
        Args:
            game (Game): game实例
            name (str): 关卡名称
        """
        self.game = game
        self.name = name
        self.load_data()
        self.start()

    def load_data(self):
        """ 
        按名称加载关卡
        关卡数据保存在.level文件中,包含prefab类型和相应的位置,这些数据被用于定位关卡组件

        Returns:
            list[list[string]]: 该关卡的数据条目列表
        """
        try:
            with open("levels\\" + self.name + ".level", "r") as file:
                self.data = [
                    line.strip().split(" ") for line in file.readlines()
                    if len(line.strip()) > 0 and line[0] != "#"
                ]

        except IOError:
            print("Error loading level")

    def start(self):
        """ 设置并启动关卡 """
        self.collision = Collision(self, self.game.window.resolution, 32)
        self.prefabs = OrderedUpdates()
        self.pathfinding = Pathfinding(self.game, self.collision)

        for args in self.data:
            name = args[0]
            x = int(args[1])
            y = int(args[2])

            prefab = Prefab(name, x, y)
            self.prefabs.add(prefab)

            if hasattr(prefab, "block"):
                # 块纹理1个像素宽,以生成完整边框
                self.collision.block_rect(x, y, prefab.rect.width - 1,
                                          prefab.rect.height - 1)

        self.pathfinding.precompute(30)
        self.wave = Wave(self.game, 1)
        self.lives = 10
        self.money = 600
        self.time = 0

    def get_score(self):
        return int((self.time / 5)**1.4 + (self.game.wave.number - 1)**3)
class KoalaKross(Microgame):
    
    
    def __init__(self):
        Microgame.__init__(self)
        self.rect= Rect(0,0, locals.WIDTH, locals.HEIGHT)
##        surface=pygame.display.set_mode((1024,768))
##        surface.fill(Color(0,0,250))
        self.koala=Koala(self)
        self.panda1=Panda(self,200,100,randint(2,10),randint(5,15))
        self.panda2=Panda(self,500,100,randint(5,15),randint(10,25))
        self.panda3=Panda(self,800,100,randint(6,17),randint(20,30))
        self.bread=Bread(self,randint(400,1000),randint(100,600))
        self.background=Background()
        self.sprites=OrderedUpdates([self.background,self.koala,self.bread,self.panda1,self.panda2,self.panda3,self.background])
        self.clock=pygame.time.Clock()

    def start(self):
 ##       music.load(join('games','Koala_Kross','remix.ogg')
        music.load('games/Koala_Kross/remix.ogg')
        music.play()

    def stop(self):
        music.stop()

    def update(self):
##        time=pygame.time.get_ticks()
        self.sprites.update()
        for event in pygame.event.get():
      
            
            if event.type==KEYDOWN and event.key==K_DOWN:
                self.koala.velocity=(0,30)
            if event.type==KEYUP and event.key==K_DOWN:
                self.koala.velocity=(0,0)
                
            if  event.type==KEYDOWN and event.key==K_UP:
                self.koala.velocity=(0,-30)
            if event.type==KEYUP and event.key == K_UP:
                self.koala.velocity=(0,0)
                
            if event.type==KEYDOWN and event.key == K_LEFT:
                self.koala.velocity=(-30,0)
            if event.type==KEYUP and event.key==K_LEFT:
                self.koala.velocity=(0,0)
            if event.type==KEYDOWN and event.key==K_RIGHT:
                self.koala.velocity=(30,0)
            if event.type==KEYUP and event.key==K_RIGHT:
                self.koala.velocity=(0,0)
            if event.type==KEYDOWN and event.key == K_q:
                self.lose()
            
            

    def render (self, surface):
##        Surface=display.set_mode((1024,768))
        surface.fill(Color(0,0,0))
        self.sprites.draw(surface)
Beispiel #5
0
    def __init__(self, screen):
        """ Initialization of our lists """
        self.wall_list = Group()
        self.coin_list = Group()
        self.plat_move = Group()
        self.door_list = OrderedUpdates()

        # the screen and its rect
        self.screen = screen
        self.screct = self.screen.get_rect()

        # the room's size and image
        self.rect = Rect(0, 0, self.width, self.height)
        self.bckimg = gf.get_checkboard(20, 20, self.width, self.height,
                                        [WHITE, GREY])
    def __init__(self):
        Microgame.__init__(self)
        self.character_select = True
        self.player1_selector = Player1_Selector()
        self.player2_selector = Player2_Selector()
        self.falco = Falco_Selector()
        self.fox = Fox_Selector()
        self.samus = Samus_Selector()
        self.snake = Snake_Selector()
        self.pit = Pit_Selector()
        self.mewtwo = Mewtwo_Selector()
        self.zelda = Zelda_Selector()
        self.character_possibilities = Group(self.falco, self.fox, self.samus, self.snake, self.pit, self.mewtwo, self.zelda)
        self.sprites = OrderedUpdates(self.falco, self.fox, self.samus, self.snake, self.pit, self.mewtwo, self.zelda, self.player1_selector, self.player2_selector)
        self.player1 = Fox()
        self.player2 = Falco()
        self.p1victory = pygame.image.load(join('games', 'ssb', 'p1_win.png'))
        self.p2victory = pygame.image.load(join('games', 'ssb', 'p2_win.png'))

        self.platform = Final_Destination()

        self.p1win = False
        self.p2win = False
        self.wincondition = False

        self.a_track = False
        self.d_track = False
        self.lshift_track = False
        self.quote_track = False
        self.l_track = False
        self.rshift_track = False

        self.playergroup = Group(self.player1, self.player2)
        self.player1_projectiles = Group()
        self.player2_projectiles = Group()
Beispiel #7
0
    def __init__(self, game):
        """
        Constructor.

        Args:
            game (Game): The game instance.

        """
        super().__init__("menu", 0, 0)

        self.game = game
        self.leaderboard = Leaderboard()
        self.components = OrderedUpdates()
        self.clear()
        self.show_main_screen()
        self.visible = True
        self.leaderboard_name = None
    def __init__(self):
        Microgame.__init__(self)
        self.rect= Rect(0,0, locals.WIDTH, locals.HEIGHT)
##        surface=pygame.display.set_mode((1024,768))
##        surface.fill(Color(0,0,250))
        self.koala=Koala(self)
        self.panda1=Panda(self,200,100,randint(2,10),randint(5,15))
        self.panda2=Panda(self,500,100,randint(5,15),randint(10,25))
        self.panda3=Panda(self,800,100,randint(6,17),randint(20,30))
        self.bread=Bread(self,randint(400,1000),randint(100,600))
        self.background=Background()
        self.sprites=OrderedUpdates([self.background,self.koala,self.bread,self.panda1,self.panda2,self.panda3,self.background])
        self.clock=pygame.time.Clock()
Beispiel #9
0
    def __init__(self,level=0):
        pygame.init()
        
        self.screen = pygame.display.set_mode(self.screen_size)
        if self.title:
            pygame.display.set_caption(self.title)
        self.fps = 30

        #group definitions
        self.userPlacedObjects = Group()
        self.startItems = RenderUpdates()
        self.playerGroup = RenderUpdates()
        self.tails = RenderUpdates()
        self.blackHoles = RenderUpdates()
        self.obstacles = RenderUpdates()
        self.masslessObstacles = RenderUpdates()
        self.goalCollide = Group()
        self.toolbar = OrderedUpdates()

        #level/transition/player & enemy/obstacle creation hocus pocus
        self.goal = Goal(573,372,self.goalCollide,30)
        self.bar = ToolBar(0,626,self.toolbar,self.screen,self,self.goal)
        self.player = Player(50,535,self.screen,(255,0,0),self.playerGroup,1000,624,(2,-2),self.tails,self)
        
        self.level = level
        self.levelUp = True
        self.stars = Starfield(self.screen,1000,626,200)
        BlackHole(339,70,self.blackHoles,self.screen,80,71,16)
        temp = EarthRounder(513,313,self.masslessObstacles,self.screen,40,0)
        temp.rotate(55)
        temp = Alien(60,188,self.masslessObstacles,self.screen,34,1)
        temp.rotate(-15)
        temp = Alien(107,268,self.masslessObstacles,self.screen,35,1)
        temp.rotate(-75)
        temp = Alien(816,533,self.masslessObstacles,self.screen,39,0)
        temp.rotate(-13)
        temp = BlueUpAnDown(811,227,self.masslessObstacles,self.screen,34,1,97,239)
        temp.rotate(80)
        self.obstacles.add(self.blackHoles)
        self.obstacles.add(self.goalCollide)
        self.freeb = False
        self.gotoLevel = level
        self.loaded = False

        if system.thereIsASaveFile() and level == 0:
            self.intro_screen = Intro(0,0,self.startItems,str('title_w_file.png'))
            self.thereIsAFile = True
        elif level == 0:
            self.intro_screen = Intro(0,0,self.startItems)
            self.thereIsAFile = False
Beispiel #10
0
    def start(self):
        """ 设置并启动关卡 """
        self.collision = Collision(self, self.game.window.resolution, 32)
        self.prefabs = OrderedUpdates()
        self.pathfinding = Pathfinding(self.game, self.collision)

        for args in self.data:
            name = args[0]
            x = int(args[1])
            y = int(args[2])

            prefab = Prefab(name, x, y)
            self.prefabs.add(prefab)

            if hasattr(prefab, "block"):
                # 块纹理1个像素宽,以生成完整边框
                self.collision.block_rect(x, y, prefab.rect.width - 1,
                                          prefab.rect.height - 1)

        self.pathfinding.precompute(30)
        self.wave = Wave(self.game, 1)
        self.lives = 10
        self.money = 600
        self.time = 0
Beispiel #11
0
    def __init__(self, screen: pygame.Surface, json_map: str, tileset_dir: str,
                 resources_dir: str):
        self.n = 0
        self.resources_dir = resources_dir
        self.screen = screen
        self.tiled_map = tiledmap.TiledParser(json_map, tileset_dir)

        self.size_map = self.get_size_map()

        # если есть тайлсет
        if self.tiled_map.sets:
            self.image_sprites = self.tiled_map.get_subsprites(
                self.tiled_map.get_id_tiles())
        self.all_layers = game_groups.AllLayers()
        self.all_images = OrderedUpdates()
        self.bg_type = None
        self.name = os.path.splitext(os.path.basename(json_map))[0]
class Super_Saast_Bros(Microgame):
    def __init__(self):
        Microgame.__init__(self)
        self.character_select = True
        self.player1_selector = Player1_Selector()
        self.player2_selector = Player2_Selector()
        self.falco = Falco_Selector()
        self.fox = Fox_Selector()
        self.samus = Samus_Selector()
        self.snake = Snake_Selector()
        self.pit = Pit_Selector()
        self.mewtwo = Mewtwo_Selector()
        self.zelda = Zelda_Selector()
        self.character_possibilities = Group(self.falco, self.fox, self.samus, self.snake, self.pit, self.mewtwo, self.zelda)
        self.sprites = OrderedUpdates(self.falco, self.fox, self.samus, self.snake, self.pit, self.mewtwo, self.zelda, self.player1_selector, self.player2_selector)
        self.player1 = Fox()
        self.player2 = Falco()
        self.p1victory = pygame.image.load(join('games', 'ssb', 'p1_win.png'))
        self.p2victory = pygame.image.load(join('games', 'ssb', 'p2_win.png'))

        self.platform = Final_Destination()

        self.p1win = False
        self.p2win = False
        self.wincondition = False

        self.a_track = False
        self.d_track = False
        self.lshift_track = False
        self.quote_track = False
        self.l_track = False
        self.rshift_track = False

        self.playergroup = Group(self.player1, self.player2)
        self.player1_projectiles = Group()
        self.player2_projectiles = Group()

    def start(self):
        pygame.mixer.music.load(join('games', 'ssb', 'battlefield_melee.ogg'))
        pygame.mixer.music.play()

    def stop(self):
        pygame.mixer.music.stop()

    def update(self, events):
        if self.wincondition == False:
            if self.character_select == True:
                player_1_character = self.detect_character(self.player1_selector, self.character_possibilities)
                player_2_character = self.detect_character(self.player2_selector, self.character_possibilities)
                if player_1_character == self.falco:
                    self.player1 = Falco()
                elif player_1_character == self.fox:
                    self.player1 = Fox()
                elif player_1_character == self.samus:
                    self.player1 = Samus()
                elif player_1_character == self.snake:
                    self.player1 = Snake()
                elif player_1_character == self.pit:
                    self.player1 = Pit()
                elif player_1_character == self.mewtwo:
                    self.player1 = Mewtwo()
                elif player_1_character == self.zelda:
                    self.player1 = Zelda()

                if player_2_character == self.falco:
                    self.player2 = Falco()
                elif player_2_character == self.fox:
                    self.player2 = Fox()
                elif player_2_character == self.samus:
                    self.player2 = Samus()
                elif player_2_character == self.snake:
                    self.player2 = Snake()
                elif player_2_character == self.pit:
                    self.player2 = Pit()
                elif player_2_character == self.mewtwo:
                    self.player2 = Mewtwo()
                elif player_2_character == self.zelda:
                    self.player2 = Zelda()

                for event in events:
                    self.player1_selector_logic(event, self.player1_selector)
                    self.player2_selector_logic(event, self.player2_selector)
                    self.character_select_logic(event)

                self.sprites.update()

            if self.character_select == False:
                self.detect_hit(self.player2, self.player1_projectiles)
                self.detect_hit(self.player1, self.player2_projectiles)

                self.remove_projectiles(self.player1_projectiles, self.sprites)
                self.remove_projectiles(self.player2_projectiles, self.sprites)

                self.sprites.update()

                self.detect_floor()
                
                for event in events:
                    self.char_logic1(event, self.player1)
                    self.char_logic2(event, self.player2)

                self.player1.projectile_logic()
                self.player2.projectile_logic()

                y1 = self.player1.rect.top
                y2 = self.player2.rect.top

                if (y1 > 1200) or (y2 > 1200):
                    if y1 > 1200:
                        self.p2win = True
                    if y2 > 1200:
                        self.p1win = True
                    self.sprites.remove(self.platform, self.player1, self.player2)
                    self.wincondition = True
                    self.win_time = pygame.time.get_ticks()

        elif self.wincondition == True:
            if pygame.time.get_ticks() - self.win_time >= 3000:
                self.win()

    def player1_selector_logic(self, event, player_selector):
        if event.type == KEYDOWN:
            if event.key == K_w:
                player_selector.uvelocity -= 15
            elif event.key == K_d:
                player_selector.rvelocity += 15
            elif event.key == K_s:
                player_selector.dvelocity += 15
            elif event.key == K_a:
                player_selector.lvelocity -= 15
        if event.type == KEYUP:
            if event.key == K_w:
                player_selector.uvelocity += 15
            elif event.key == K_d:
                player_selector.rvelocity -= 15
            elif event.key == K_s:
                player_selector.dvelocity -= 15
            elif event.key == K_a:
                player_selector.lvelocity += 15

    def player2_selector_logic(self, event, player_selector):
        if event.type == KEYDOWN:
            if event.key == K_p:
                player_selector.uvelocity -= 15
            elif event.key == K_QUOTE:
                player_selector.rvelocity += 15
            elif event.key == K_SEMICOLON:
                player_selector.dvelocity += 15
            elif event.key == K_l:
                player_selector.lvelocity -= 15
        if event.type == KEYUP:
            if event.key == K_p:
                player_selector.uvelocity += 15
            elif event.key == K_QUOTE:
                player_selector.rvelocity -= 15
            elif event.key == K_SEMICOLON:
                player_selector.dvelocity -= 15
            elif event.key == K_l:
                player_selector.lvelocity += 15

    def detect_character(self, player_selector, character_possibilities):
        for character in pygame.sprite.spritecollide(player_selector, character_possibilities, False):
            return character

    def character_select_logic(self, event):
        if event.type == KEYDOWN:
            if event.key == K_t:
                self.character_select = False
                self.player1.direct = 'right'
                self.player2.direct = 'left'
                self.player1.image, self.player1.rect = _load_image(self.player1.idle[0], 250, 350)
                self.player2.image, self.player2.rect = _load_image(self.player2.idle[1], 650, 350)
                self.sprites.remove(self.falco, self.fox, self.samus, self.snake, self.pit, self.mewtwo, self.zelda, self.player1_selector, self.player2_selector)
                self.sprites.add(self.platform, self.player1, self.player2)
                self.playergroup.add(self.player1, self.player2)


    def detect_floor(self):
        for char in pygame.sprite.spritecollide(self.platform, self.playergroup, False):
            char.rect.y = (self.platform.rect.topleft[1] - char.rect.height)
            char.uvelocity = 0
            char.jumps = 2

    def detect_hit(self, receiver, hitboxes):
        for hitbox in pygame.sprite.spritecollide(receiver, hitboxes, True):
            receiver.percent += hitbox.damage
            receiver.knockback_calc(hitbox)

    def remove_projectiles(self, projectilegroup, spritegroup):
        for projectile in projectilegroup:
            x_left, _ = projectile.rect.topleft
            x_right, _ = projectile.rect.bottomright
            if (x_left <= 0) or (x_right >= locals.WIDTH):
                spritegroup.remove(projectile)


    def render(self, surface):
        surface.fill(Color(0, 0, 0))
        self.sprites.draw(surface)

        if self.p1win == True:
            surface.blit(self.p1victory, (0, 0))
        elif self.p2win == True:
            surface.blit(self.p2victory, (0, 0))

    def get_timelimit(self):
        return 60

    def char_logic1(self, event, charac):
        x, y = charac.rect.topleft
        if event.type == KEYDOWN:
            if event.key == K_w:
                self.jump_logic(charac)
            elif event.key == K_a:
                self.a_track = True
                charac.image, charac.rect = _load_image(charac.run[1], x, y)
                charac.lvelocity -= 10
                charac.direct = 'left'
            elif event.key == K_d:
                self.d_track = True
                charac.rvelocity += 10
                charac.image, charac.rect = _load_image(charac.run[0], x, y)
                charac.direct = 'right'
            elif event.key == K_LSHIFT:
                if charac.projectilecount > 0:
                    charac.projectilesound.play()
                    self.lshift_track = True
                    if charac.direct == 'right':
                        charac.image, charac.rect = _load_image(charac.gun[0], x, y)
                        x, y = charac.rect.topright
                        charac.make_projectile(x, y, charac)
                    elif charac.direct == 'left':
                        charac.image, charac.rect = _load_image(charac.gun[1], x, y)
                        x, y = charac.rect.topleft
                        charac.make_projectile(x, y, charac)
                    self.sprites.add(charac.projectile)
                    self.player1_projectiles.add(charac.projectile)
                    charac.projectilecount -= 1
                    if charac.projectilecount == 0:
                        charac.no_projectile_time = pygame.time.get_ticks()
        elif event.type == KEYUP:
            if event.key == K_a:
                charac.lvelocity += 10
                self.a_track = False
                if self.d_track == False:
                    if self.lshift_track == False:
                        if charac.direct == 'right':
                            charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
                        elif charac.direct == 'left':
                            charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
                    elif self.lshift_track == True:
                        if charac.direct == 'right':
                            charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
                        elif charac.direct == 'left':
                            charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
                elif self.d_track == True:
                    if self.lshift_track == False:
                            charac.image, charac.rect = _load_image(charac.run[0], x, y)
                            charac.direct = 'right'
                    elif self.lshift_track == True:
                        charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
            elif event.key == K_d:
                charac.rvelocity -= 10
                self.d_track = False
                if self.a_track == False:
                    if self.lshift_track == False:
                        if charac.direct == 'right':
                            charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
                        elif charac.direct == 'left':    
                            charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
                    elif self.lshift_track == True:
                        if charac.direct == 'right':
                            charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
                        elif charac.direct == 'left':
                            charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
                elif self.a_track == True:
                    if self.lshift_track == False:
                        charac.image, charac.rect = _load_image(charac.run[1], x, y)
                        charac.direct = 'left'
                    elif self.lshift_track == True:
                        charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
            elif event.key == K_LSHIFT:
                self.lshift_track = False
                if (self.a_track == False) and (self.d_track == False):
                    if charac.direct == 'right':
                        charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
                    elif charac.direct == 'left':    
                        charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
                elif (self.a_track == False) and (self.d_track == True):
                    charac.image, charac.rect = _load_image(charac.run[0], x, y)
                    charac.direct = 'right'
                elif (self.a_track == True) and (self.d_track == False):
                    charac.image, charac.rect = _load_image(charac.run[1], x, y)
                    charac.direct = 'left'
                elif (self.a_track == True) and (self.d_track == False):
                    if charac.direct == 'right':
                        charac.image, charac.rect = _load_image(charac.gun[0], x, y)
                    elif charac.direct == 'left':
                        charac.image, charac.rect = _load_image(charac.gun[1], x, y)

    def char_logic2(self, event, charac):
        x, y = charac.rect.topleft
        if event.type == KEYDOWN:
            if event.key == K_p:
                self.jump_logic(charac)
            elif event.key == K_l:
                self.l_track = True
                charac.image, charac.rect = _load_image(charac.run[1], x, y)
                charac.lvelocity -= 10
                charac.direct = 'left'
            elif event.key == K_QUOTE:
                self.quote_track = True
                charac.rvelocity += 10
                charac.image, charac.rect = _load_image(charac.run[0], x, y)
                charac.direct = 'right'
            elif event.key == K_RSHIFT:
                if charac.projectilecount > 0:
                    charac.projectilesound.play()
                    self.rshift_track = True
                    if charac.direct == 'right':
                        charac.image, charac.rect = _load_image(charac.gun[0], x, y)
                        x, y = charac.rect.topright
                        charac.make_projectile(x, y, charac)
                    elif charac.direct == 'left':
                        charac.image, charac.rect = _load_image(charac.gun[1], x, y)
                        x, y = charac.rect.topleft
                        charac.make_projectile(x, y, charac)
                    self.sprites.add(charac.projectile)
                    self.player2_projectiles.add(charac.projectile)
                    charac.projectilecount -= 1
                    if charac.projectilecount == 0:
                        charac.no_projectile_time = pygame.time.get_ticks()
        elif event.type == KEYUP:
            if event.key == K_l:
                charac.lvelocity += 10
                self.l_track = False
                if self.quote_track == False:
                    if self.rshift_track == False:
                        if charac.direct == 'right':
                            charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
                        elif charac.direct == 'left':
                            charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
                    elif self.rshift_track == True:
                        if charac.direct == 'right':
                            charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
                        elif charac.direct == 'left':
                            charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
                elif self.quote_track == True:
                    if self.rshift_track == False:
                            charac.image, charac.rect = _load_image(charac.run[0], x, y)
                            charac.direct = 'right'
                    elif self.rshift_track == True:
                        charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
            elif event.key == K_QUOTE:
                charac.rvelocity -= 10
                self.quote_track = False
                if self.l_track == False:
                    if self.rshift_track == False:
                        if charac.direct == 'right':
                            charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
                        elif charac.direct == 'left':    
                            charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
                    elif self.rshift_track == True:
                        if charac.direct == 'right':
                            charac.image, charac.rect = _load_image(charac.gun[0], x, y - 5)
                        elif charac.direct == 'left':
                            charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
                elif self.l_track == True:
                    if self.rshift_track == False:
                        charac.image, charac.rect = _load_image(charac.run[1], x, y)
                        charac.direct = 'left'
                    elif self.rshift_track == True:
                        charac.image, charac.rect = _load_image(charac.gun[1], x, y - 5)
            elif event.key == K_RSHIFT:
                self.rshift_track = False
                if (self.l_track == False) and (self.quote_track == False):
                    if charac.direct == 'right':
                        charac.image, charac.rect = _load_image(charac.idle[0], x, y - 10)
                    elif charac.direct == 'left':    
                        charac.image, charac.rect = _load_image(charac.idle[1], x, y - 10)
                elif (self.l_track == False) and (self.quote_track == True):
                    charac.image, charac.rect = _load_image(charac.run[0], x, y)
                    charac.direct = 'right'
                elif (self.l_track == True) and (self.quote_track == False):
                    charac.image, charac.rect = _load_image(charac.run[1], x, y)
                    charac.direct = 'left'
                elif (self.l_track == True) and (self.quote_track == False):
                    if charac.direct == 'right':
                        charac.image, charac.rect = _load_image(charac.gun[0], x, y)
                    elif charac.direct == 'left':
                        charac.image, charac.rect = _load_image(charac.gun[1], x, y)

    def jump_logic(self, ch):
        if ch.jumps == 2:
            ch.uvelocity = JUMP_BOOST
            ch.jumpsounds[randint(0, len(ch.jumpsounds) - 1)].play()
        elif ch.jumps == 1:
            ch.uvelocity = AIR_JUMP_BOOST
            ch.jumpsounds[randint(0, len(ch.jumpsounds) - 1)].play()
        ch.jumps -= 1
Beispiel #13
0
class Room:
    """ base class for all rooms """

    # these variables are set in the subclass
    width = None
    height = None

    def __init__(self, screen):
        """ Initialization of our lists """
        self.wall_list = Group()
        self.coin_list = Group()
        self.plat_move = Group()
        self.door_list = OrderedUpdates()

        # the screen and its rect
        self.screen = screen
        self.screct = self.screen.get_rect()

        # the room's size and image
        self.rect = Rect(0, 0, self.width, self.height)
        self.bckimg = gf.get_checkboard(20, 20, self.width, self.height,
                                        [WHITE, GREY])
        #self.bckimg.fill(WHITE)

    def draw(self):
        """ Draw the room on the screen"""
        self.screen.blit(self.bckimg, self.rect)
        self.wall_list.draw(self.screen)
        self.door_list.draw(self.screen)
        self.coin_list.draw(self.screen)

    def move_room(self, move_x, move_y):
        """ Move all walls in the room """
        self.move_obj(move_x, move_y)
        self.rect.x += move_x
        self.rect.y += move_y

    def move_obj(self, move_x, move_y):
        """ Move all objects in the room, but not the room itself """
        self.wall_list.update(move_x, move_y)
        self.door_list.update(move_x, move_y)
        self.coin_list.update(move_x, move_y)

    def reset(self, player=None):
        """ reset the room rect's topleft to the topleft of the screen and
        move everything accordingly. """

        displace_x = self.screct.x - self.rect.x
        displace_y = self.screct.y - self.rect.y

        self.move_room(displace_x, displace_y)

        if player:
            player.rect.x += displace_x
            player.rect.y += displace_y

    def old_set_around(self, player):
        """ Move the room so that the room and the player are in the right place"""
        plax = player.rect.x
        play = player.rect.y
        roox = self.rect.x
        rooy = self.rect.y

        # check horizontal position
        if player.rect.centerx < self.rect.left + self.screct.centerx:
            self.rect.left = self.screct.left
            dis_x = self.rect.x - roox
            self.move_obj(dis_x, 0)
            player.rect.x += dis_x
        elif player.rect.centerx > self.rect.right - self.screct.centerx:
            self.rect.right = self.screct.right
            dis_x = self.rect.x - roox
            self.move_obj(dis_x, 0)
            player.rect.x += dis_x
        else:
            player.rect.centerx = self.screct.centerx
            dis_x = player.rect.x - plax
            self.move_room(dis_x, 0)

        # check vertical position
        if player.rect.centery < self.rect.top + self.screct.centery:
            self.rect.top = self.screct.top
            dis_y = self.rect.y - rooy
            self.move_obj(0, dis_y)
            player.rect.y += dis_y
        elif player.rect.centery > self.rect.bottom - self.screct.centery:
            self.rect.bottom = self.screct.bottom
            dis_y = self.rect.y - rooy
            self.move_obj(0, dis_y)
            player.rect.y += dis_y
        else:
            player.rect.centery = self.screct.centery
            dis_y = player.rect.y - play
            self.move_room(0, dis_y)

    def reset_coins(self):
        """ reset all coins """

        # improve this so it doesn't have to keep removing sprites already in the group
        self.coin_list.empty()

        self.get_coins()

    def get_coins(self):
        """ get the coins for the room, overloaded in subclasses """
        pass
Beispiel #14
0
from game.combocounter import ComboCounter
from game.enemy       import Enemy
from game             import enemybullet
from game.enemybullet import EnemyBullet
from game             import enemysquadron
from game             import gamedata
from game.highscore   import HighScoreState
from game.hudobject   import HudObject, make_text
from game.player      import Ship, FlameTrail, LightColumn
from game.shipbullet  import ShipBullet
from game.ufo         import UFO

#if config.DEBUG: import core.vartracker

### Groups #####################################################################
BG            = OrderedUpdates()
BLOCKS        = Group()
ENEMIES       = Group()
ENEMY_BULLETS = Group()
HUD           = Group()
PARTICLES     = Group()
PLAYER        = Group()
UFO_GROUP     = Group()
################################################################################

### Constants ##################################################################
rect = config.SCREEN_RECT
ALARM          = config.load_sound('alarm.wav')
DEBUG_KEYS     = (K_u, K_c, K_f, K_F1, K_e, K_k, K_i)
FADE_TIME      = 2500  #In milliseconds
FIRE_LOCATION  = (rect.centerx - 192, rect.centery     )
Beispiel #15
0
 def __init__(self, *sprites):
     OrderedUpdates.__init__(self, *sprites)
Beispiel #16
0
# encoding: utf-8
#
# this module holds the 'state variables',
# the module is checked on save, so that
# any var named in the saveIncludes list is saved from the module.__dict__

from pygame.sprite import OrderedUpdates
from test.world.circle import circle

circles = OrderedUpdates()
lastPlayState = 'add-remove'
mb1Down = False
mb3Down = False

saveIncludes = ['circles', 'lastPlayState']
Beispiel #17
0
class EditorLevel(object):
  def __init__(self, editor, level_file=None):
    self.editor = editor
    self.font_manager = editor.font_manager

    if level_file is not None:
      (name, player_start, player_direction, board, enemies, powerups) = level_loader.load(level_file)
    else:
      player_start = None
      player_direction = None
      board = None
      enemies = []
      powerups = []

    self.board = Board(constants.HORIZONTAL_TILES, constants.VERTICAL_TILES)
    
    for x in xrange(0, constants.HORIZONTAL_TILES):
      for y in xrange(0, constants.VERTICAL_TILES):
        if board is None:
          if x == 0 or y == 0 or x == constants.HORIZONTAL_TILES - 1 or y == constants.VERTICAL_TILES - 1:
            tile = Tile("W", Point(x, y))
          else:
            tile = Tile("G", Point(x, y))
        else:
          tile = Tile(board.get_tile(x, y).type, Point(x, y))

        self.board.set_tile(x, y, tile) 
    self.tiles = OrderedUpdates([tile for tile in self.board])

    self.entities = Group()

    if player_start is not None:
      player_entity = Entity("PLAYER", editor_constants.ENTITY_DATA_MAP["PLAYER"], player_start, self.font_manager)
      player_entity.rotate(player_direction, 1)
      self.entities.add(player_entity)

    for (position, direction, waypoint_type, waypoints) in enemies:
      entity = Entity("ENEMY", editor_constants.ENTITY_DATA_MAP["ENEMY"], position, self.font_manager)
      entity.rotate(direction, 1)
      actual_waypoints = []
      for waypoint in waypoints:
        actual_waypoints.append(Entity("WAYPOINT", editor_constants.WAYPOINT_DATA, waypoint, self.font_manager))
      entity.waypoints.set_waypoints(actual_waypoints)
      self.entities.add(entity)

    for powerup in powerups:
      entity = Entity(powerup.type, editor_constants.ENTITY_DATA_MAP[powerup.type], powerup.position, self.font_manager)
      self.entities.add(entity)

    self.toolbars = Group()
    vertical_toolbar = VerticalToolbar(self, self.font_manager)
    self.toolbars.add(vertical_toolbar)

    self.player_exists = bool([entity for entity in self.entities if entity.name == "PLAYER"])
    self.entity_to_create = vertical_toolbar.selected.name
    self.mode = MODE_ADD

    self.rotating = False

    self.pending_actions = []
    self.action_stack = []
    self.undone_action_stack = []

    self.selected_entities = []
    self.waypoint_entity_selected = None      
  
  def add_action(self, action_type, *args):
    self.undone_action_stack = []
    self.pending_actions.append(action_type(self, *args))

  def get_entity(self, position):
    data = editor_constants.ENTITY_DATA_MAP[self.entity_to_create]
    return Entity(self.entity_to_create, data, position, self.font_manager)

  def add_entity(self, entity):
    if entity.name == "PLAYER":
      self.player_exists = True
    self.entities.add(entity)

  def remove_entity(self, entity):
    if entity.name == "PLAYER":
      self.player_exists = False
    self.entities.remove(entity)
    if entity in self.selected_entities:
      entity.select(False)
      self.selected_entities.remove(entity)
    
    if entity is self.waypoint_entity_selected:
      entity.select(False)
      self.waypoint_entity_selected = None

  def delete_selection(self):
    self.add_action(DeleteSelectionAction, list(self.selected_entities))

  def set_selection(self, entities):
    self.clear_selection()
    for entity in entities:
      if not entity in self.entities:
        raise Exception("Tried to select non-existent entity.")
      entity.select(True)
      self.selected_entities.append(entity)

  def clear_selection(self):
    for entity in self.selected_entities:
      entity.select(False)
    self.selected_entities = []

  def selection_click(self, entity, shift):
    if shift:
      if entity in self.selected_entities:
        entity.select(False)
        self.selected_entities.remove(entity)
      else:
        entity.select(True)
        self.selected_entities.append(entity)
    else:
      if entity in self.selected_entities:
        for entity in self.selected_entities:
          entity.select(False)
        self.selected_entities = []
      else:
        for other_entity in self.selected_entities:
          other_entity.select(False)
        entity.select(True)
        self.selected_entities = [entity]

  def left_click(self, position, pressed):
    for toolbar in self.toolbars:
      rect = pygame.Rect(toolbar.position, (toolbar.width, toolbar.height))
      if rect.collidepoint(position):
        toolbar.left_click(position, pressed)

    if self.mode == MODE_ADD:
      entity = self.get_entity(position)
      # make sure the entity doesn't intersect any others
      for other_entity in self.entities:
        if cd.sprite_collide(entity, other_entity):
          return
      # make sure the entity creation is in bounds
      if not sphere_in_bounds(position, entity.data.ratio / 2, editor_constants.EDITOR_AREA_BOUNDS):
        return
      if entity.name != "PLAYER" or not self.player_exists:
        self.add_action(AddEntityAction, entity)
    elif self.mode == MODE_SELECT:
      for entity in self.entities:
        if entity.contains_point(position):
          ctrl = (pressed[pygame.K_LCTRL] or pressed[pygame.K_RCTRL])
          self.selection_click(entity, ctrl)
          break
    elif self.mode == MODE_TILE:
      for tile in self.tiles:
        if cd.sprite_contains(tile, position.scale(constants.TILE_SIZE)):
          tile.toggle_type()
    elif self.mode == MODE_WAYPOINT:
      ctrl = (pressed[pygame.K_LCTRL] or pressed[pygame.K_RCTRL])
      if ctrl:
        if self.waypoint_entity_selected is not None:
          self.add_action(AddWaypointAction, self.waypoint_entity_selected, Entity("WAYPOINT", editor_constants.WAYPOINT_DATA, position, self.font_manager))
      else:
        for entity in self.entities:
          if entity.name == "ENEMY" and entity.contains_point(position):
            if self.waypoint_entity_selected is not None:
              self.waypoint_entity_selected.select(False)
            self.waypoint_entity_selected = entity
            entity.select(True)

  def switch_mode(self):
    if self.mode == MODE_ADD:
      self.mode = MODE_SELECT
    elif self.mode == MODE_SELECT:
      self.clear_selection()
      self.mode = MODE_WAYPOINT
    elif self.mode == MODE_WAYPOINT:
      if self.waypoint_entity_selected is not None:
        self.waypoint_entity_selected.select(False)
      self.waypoint_entity_selected = None
      self.mode = MODE_TILE
    elif self.mode == MODE_TILE:
      self.mode = MODE_ADD
    print self.mode

  def start_rotation(self, key):
    self.rotating = True
    self.total_rotation = 0
    for entity in self.selected_entities:
      entity.rotating = True
      entity.rotation_sign = (1 if key == pygame.K_RIGHT else -1)
    self.rotation_key = key

  def stop_rotation(self, key):
    self.rotating = False
    for entity in self.selected_entities:
      entity.rotating = False
    # directly append to action stack so that we 
    self.action_stack.append(RotateSelectionAction(self, self.selected_entities, self.total_rotation, (1 if key == pygame.K_RIGHT else -1)))

  def update(self, delta, events, pressed, mouse):
    if self.rotating:
      for event in events:
        if event.type == pygame.KEYUP and event.key == self.rotation_key:
          self.stop_rotation(event.key)
    else:
      for event in events:
        if event.type == pygame.KEYDOWN and (event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT) and event.mod & pygame.KMOD_CTRL and self.mode == MODE_SELECT and self.selected_entities:
          self.start_rotation(event.key)
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_m:
          self.switch_mode()
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_DELETE and self.mode == MODE_SELECT:
          self.delete_selection()
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_DELETE and self.mode == MODE_WAYPOINT:
          if self.waypoint_entity_selected is not None:
            self.add_action(DeleteWaypointsAction, self.waypoint_entity_selected)
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_y and event.mod & pygame.KMOD_CTRL:
          if self.undone_action_stack:
            action = self.undone_action_stack.pop()
            action.undo = False
            self.pending_actions.append(action)
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_z and event.mod & pygame.KMOD_CTRL:
          if self.action_stack:
            action = self.action_stack.pop()
            action.undo = True
            self.pending_actions.append(action)
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
          self.left_click(Point(event.pos[0], event.pos[1]).scale(1.0 / constants.TILE_SIZE), pressed)
        elif event.type == pygame.KEYDOWN:
          for toolbar in self.toolbars:
            toolbar.hotkey(event.key)

    for action in self.pending_actions:
      action.do()
      if action.undo:
        self.undone_action_stack.append(action)
      else:
        self.action_stack.append(action)
    self.pending_actions = []

    if self.rotating:
      self.total_rotation += 2 * math.pi * (delta / 1000.0)

    self.entities.update(delta)

  def draw(self, screen):
    self.tiles.draw(screen)
    self.entities.draw(screen)
    if self.waypoint_entity_selected is not None:
      self.waypoint_entity_selected.draw(screen)
    self.toolbars.draw(screen)
    for toolbar in self.toolbars:
      toolbar.draw(screen)
Beispiel #18
0
class Menu(Prefab):
    """
    Controls the menu system.
    """

    def __init__(self, game):
        """
        Constructor.

        Args:
            game (Game): The game instance.

        """
        super().__init__("menu", 0, 0)

        self.game = game
        self.leaderboard = Leaderboard()
        self.components = OrderedUpdates()
        self.clear()
        self.show_main_screen()
        self.visible = True
        self.leaderboard_name = None
        
    def show(self):
        """
        Shows the menu.
        """
        self.visible = True
        self.show_main_screen()

    def hide(self):
        """
        Hides the menu and enables in game icons.
        """
        self.visible = False
        self.clear()

        self.defence_buttons = [MenuButton(self, "menu_defence_button", self.game.defence_prototypes[i].display_name, (i + 1) * 64, 0, lambda: self.game.select_defence((pygame.mouse.get_pos()[0] - 64) // 64)) for i in range(len(self.game.defence_prototypes))]
        self.components.add(self.defence_buttons)

        self.wave_label = MenuLabel(self, "menu_pause_button", "Wave", 448, 0)
        self.lives_label = MenuLabel(self, "menu_pause_button", "Lives", 576, 0)
        self.money_label = MenuLabel(self, "menu_pause_button", "Money", 704, 0)
        self.score_label = MenuLabel(self, "menu_pause_button", "Score", 832, 0)
        self.components.add(self.wave_label)
        self.components.add(self.lives_label)
        self.components.add(self.money_label)
        self.components.add(self.score_label)

        self.components.add(MenuButton(self, "menu_pause_button", "Menu", 1088, 0, self.show))

        self.update()

    def clear(self):
        """
        Removes all components from the menu.
        """
        self.components.remove(self.components)
        self.component_next = self.top

    def update(self):
        """
        Called each frame.
        """
        if not self.visible:
            self.wave_label.set_text("Wave: " + str(self.game.wave.number))
            self.lives_label.set_text("Lives: " + str(self.game.level.lives))
            self.lives_label.highlighted = (self.game.level.lives < 5)
            self.money_label.set_text("Money: " + str(self.game.level.money))
            self.score_label.set_text("Score: " + str(self.game.level.get_score()))

            for i in range(len(self.defence_buttons)):
                self.defence_buttons[i].disabled = (self.game.defence_prototypes[i].cost > self.game.level.money)
                self.defence_buttons[i].selected = (self.game.defence_type == i)
        
        self.components.update()

    def clicked(self):
        """
        Called when a mouse button is pressed.
        """
        for component in self.components:
            if isinstance(component, MenuButton):
                component.clicked()

    def key_pressed(self, key):
        """
        Called when a key has been pressed.

        Args:
            key: The key that was pressed.

        """
        if self.leaderboard_name is None:
            return

        keys = { pygame.K_a: "a", pygame.K_b: "b", pygame.K_c: "c", pygame.K_d: "d", pygame.K_e: "e", pygame.K_f: "f", pygame.K_g: "g", pygame.K_h: "h", pygame.K_i: "i", 
                pygame.K_j: "j", pygame.K_k: "k", pygame.K_l: "l", pygame.K_m: "m", pygame.K_n: "n", pygame.K_o: "o", pygame.K_p: "p", pygame.K_q: "q", pygame.K_r: "r", 
                pygame.K_s: "s", pygame.K_t: "t", pygame.K_u: "u", pygame.K_v: "v", pygame.K_w: "w", pygame.K_x: "x", pygame.K_y: "y", pygame.K_z: "z",
                pygame.K_0: "0", pygame.K_1: "1", pygame.K_2: "2", pygame.K_3: "3", pygame.K_4: "4", pygame.K_5: "5", pygame.K_6: "6", pygame.K_7: "7",
                pygame.K_8: "8", pygame.K_9: "9" }

        if key in keys.keys():
            self.leaderboard_name.set_text(self.leaderboard_name.text + (keys[key].upper() if pygame.key.get_pressed()[pygame.K_LSHIFT] or pygame.key.get_pressed()[pygame.K_RSHIFT] else keys[key]))
        elif key is pygame.K_BACKSPACE and self.leaderboard_name.text != "":
            self.leaderboard_name.set_text(self.leaderboard_name.text[:-1])

    def draw(self, screen):
        """
        Draws the menu and its components.

        Args:
            screen (Surface): The surface that is blitted to.

        """
        if self.visible:
            screen.blit(self.image, (0, 0))

        self.components.draw(screen)

    def add_button(self, text, callback):
        """
        Adds a standard button to the menu screen.

        Args:
            text (str): The text to display on the button.
            callback (callable): The callback when the button is clicked.

        Returns:
            (MenuButton): The button.

        """
        button = MenuButton(self, "menu_button", text, 0, self.component_next, callback)
        button.rect.x = (self.rect.width - button.rect.width) / 2

        self.components.add(button)
        self.component_next += button.rect.height
        self.component_next += button.padding

        return button

    def add_level_button(self, level):
        """
        Adds a change level button to the menu screen.

        Args:
            level (str): The name of the level to display on the button.

        """
        button = MenuButton(self, "menu_level_" + level, level, 0, self.component_next, lambda: self.game.load_level(level))
        button.rect.x = (self.rect.width - button.rect.width) / 2
        
        self.components.add(button)
        self.component_next += button.rect.height
        self.component_next += button.padding

    def show_main_screen(self):
        """
        Shows the main menu screen.
        """
        self.clear()

        if self.game.level.time > 0:
            self.add_button("Continue", self.hide)
            self.add_button("Restart Game", lambda: self.game.load_level(self.game.level.name))
        else:
            self.add_button("Start Game", self.hide)

        self.add_button("How To Play", self.show_how_to_play_screen)
        self.add_button("Change Level", self.show_change_level_screen)
        self.add_button("Leaderboard", self.show_leaderboard_screen)
        self.add_button("Quit Game", self.game.quit)

    def show_how_to_play_screen(self):
        """
        Shows the how to play menu screen.
        """
        self.clear()
        self.add_button("Back", self.show_main_screen)

        instructions = Prefab("menu_how_to_play", 0, self.component_next)
        self.components.add(instructions)
        instructions.rect.x = (self.rect.width - instructions.rect.width) / 2

    def show_change_level_screen(self):
        """
        Shows the change level screen.
        """
        self.clear()
        self.add_button("Back", self.show_main_screen)

        if self.game.level.name != "basic":
            self.add_level_button("basic")

        if self.game.level.name != "path":
            self.add_level_button("path")

        if self.game.level.name != "maze":
            self.add_level_button("maze")

    def show_leaderboard_screen(self):
        """
        Shows the leaderboard screen.
        """
        self.leaderboard.retrieve()
        self.clear()
        self.add_button("Back", self.show_main_screen)

        if self.leaderboard.entries is None:
            self.add_button("Error Loading Leaderboard", None)
        else:
            for i in range(0, 4 if len(self.leaderboard.entries) > 6 else len(self.leaderboard.entries)):
                entry = self.leaderboard.entries[i]
                self.add_button(entry.name + "   Lvl=" + entry.level + "   Scr=" + str(entry.score) + "   Wve=" + str(entry.wave), None)

    def show_lose_screen(self):
        """
        Shows the game over screen.
        """
        self.show()
        self.clear()
        self.add_button("Game Over", None)
        self.add_button("You Reached Wave " + str(self.game.wave.number), None)
        self.add_button(str(self.game.level.get_score()) + " Points", None)
        self.add_button("Restart Game", lambda: self.game.load_level(self.game.level.name))
        self.add_button("Add To Leaderboard", self.show_add_to_leaderboard_screen)

    def show_add_to_leaderboard_screen(self):
        """
        Shows the add to leaderboard screen.
        """
        self.clear()
        self.add_button("Type Your Name", None)
        self.leaderboard_name = self.add_button("", None)
        self.add_button("Submit", self.submit_leaderboard)

    def submit_leaderboard(self):
        """
        Attempts to submit a score to the leaderboard.
        """
        if self.leaderboard_name.text != "":
            self.leaderboard.add(self.game.level.name, self.leaderboard_name.text, self.game.level.get_score(), self.game.wave.number)
            self.game.load_level(self.game.level.name)
            self.show_leaderboard_screen()
Beispiel #19
0
    def __init__(self, surface, width, height, song_filename):
        '''
        Constructor
        '''
        
        #progressively increase; must end with 1
        self.PROB_HEALTH = 0.4
        
        self.PROB_KI = 0.7
        
        self.PROB_SHIELD = 0.9
        self.PROB_SWORD = 1.0
        
        self.windowSurface = surface
        self.width = width
        self.height = height
        self.song_filename = song_filename
        board_size = (width, height)
        self.gameSurface = Surface(board_size) # This will be drawn every frame to the window
        
        song_file = open(song_filename)
        self.song_name = song_file.readline().strip()
        self.song_length = float(song_file.readline())
        self.pixels_per_second = float(song_file.readline())
        self.level_filename = song_file.readline().strip()
        self.music_filename = song_file.readline().strip()
        self.background_filename = song_file.readline().strip()
        
        
        self.pixel_offset = 0
        self.last_frame_time = -1
        self.frac_scroll = 0
#        print "{0}[{1}] : {2}".format(self.song_name, self.song_length, self.pixels_per_second)
        
#        self.background_width = (self.pixels_per_second * self.song_length) + width
        self.background_width = width + 96  # Jank scroll edition!
        background_size = (self.background_width, height)
        self.backgroundSurface = Surface(background_size)
        self.__render_background()
        
        self.backgroundSurface.set_colorkey((0,0,0),pygame.RLEACCEL)
        #self.backgroundSurface.set_colorkey((217,62,245),pygame.RLEACCEL)
        #self.backgroundSurface.set_alpha(100,pygame.RLEACCEL)
        
        self.mainScreenBackground,self.mainScreenBackgroundRect = load_image_from_folder('backgrounds', self.background_filename)
        
        #self.backgroundSurface.blit(mainScreenBackground, (0,0))
        #self.__render_background()
        
        possible_samurai_positions = []
        
        for i in range(0, 6):
            possible_samurai_positions.append(PATH_HEIGHT * i + 15)
        
        self.samurai = Samurai(possible_samurai_positions)
        self.samurai_sprite_group = Group(self.samurai)
        
        self.bridge_group = OrderedUpdates()
        self.mine_group = OrderedUpdates()
        self.enemy_group = OrderedUpdates()
        self.attack_group = OrderedUpdates()
        self.healthpack_group = OrderedUpdates()
        self.ki_potion_group = OrderedUpdates()
        self.shield_group = OrderedUpdates()
        self.sword_group = OrderedUpdates()
        self.explosion_group = OrderedUpdates()
        
#        tempSprite = self.samurai_sprite_group.sprites()
#        tempRect = tempSprite[0].get_rect()
#        self.testSword = VerticalSlash(tempRect.centerx,tempRect.centery, self.remove_attack)
#        self.attack_group.add(self.testSword)
        
        if sys.platform == "win32":
            # On Windows, the best timer is time.clock()
            self.default_timer = time.clock
        else:
            # On most other platforms, the best timer is time.time()
            self.default_timer = time.time
Beispiel #20
0
  def __init__(self, editor, level_file=None):
    self.editor = editor
    self.font_manager = editor.font_manager

    if level_file is not None:
      (name, player_start, player_direction, board, enemies, powerups) = level_loader.load(level_file)
    else:
      player_start = None
      player_direction = None
      board = None
      enemies = []
      powerups = []

    self.board = Board(constants.HORIZONTAL_TILES, constants.VERTICAL_TILES)
    
    for x in xrange(0, constants.HORIZONTAL_TILES):
      for y in xrange(0, constants.VERTICAL_TILES):
        if board is None:
          if x == 0 or y == 0 or x == constants.HORIZONTAL_TILES - 1 or y == constants.VERTICAL_TILES - 1:
            tile = Tile("W", Point(x, y))
          else:
            tile = Tile("G", Point(x, y))
        else:
          tile = Tile(board.get_tile(x, y).type, Point(x, y))

        self.board.set_tile(x, y, tile) 
    self.tiles = OrderedUpdates([tile for tile in self.board])

    self.entities = Group()

    if player_start is not None:
      player_entity = Entity("PLAYER", editor_constants.ENTITY_DATA_MAP["PLAYER"], player_start, self.font_manager)
      player_entity.rotate(player_direction, 1)
      self.entities.add(player_entity)

    for (position, direction, waypoint_type, waypoints) in enemies:
      entity = Entity("ENEMY", editor_constants.ENTITY_DATA_MAP["ENEMY"], position, self.font_manager)
      entity.rotate(direction, 1)
      actual_waypoints = []
      for waypoint in waypoints:
        actual_waypoints.append(Entity("WAYPOINT", editor_constants.WAYPOINT_DATA, waypoint, self.font_manager))
      entity.waypoints.set_waypoints(actual_waypoints)
      self.entities.add(entity)

    for powerup in powerups:
      entity = Entity(powerup.type, editor_constants.ENTITY_DATA_MAP[powerup.type], powerup.position, self.font_manager)
      self.entities.add(entity)

    self.toolbars = Group()
    vertical_toolbar = VerticalToolbar(self, self.font_manager)
    self.toolbars.add(vertical_toolbar)

    self.player_exists = bool([entity for entity in self.entities if entity.name == "PLAYER"])
    self.entity_to_create = vertical_toolbar.selected.name
    self.mode = MODE_ADD

    self.rotating = False

    self.pending_actions = []
    self.action_stack = []
    self.undone_action_stack = []

    self.selected_entities = []
    self.waypoint_entity_selected = None      
Beispiel #21
0
class Gameboard(object):
    '''
    classdocs
    '''

    def __init__(self, surface, width, height, song_filename):
        '''
        Constructor
        '''
        
        #progressively increase; must end with 1
        self.PROB_HEALTH = 0.4
        
        self.PROB_KI = 0.7
        
        self.PROB_SHIELD = 0.9
        self.PROB_SWORD = 1.0
        
        self.windowSurface = surface
        self.width = width
        self.height = height
        self.song_filename = song_filename
        board_size = (width, height)
        self.gameSurface = Surface(board_size) # This will be drawn every frame to the window
        
        song_file = open(song_filename)
        self.song_name = song_file.readline().strip()
        self.song_length = float(song_file.readline())
        self.pixels_per_second = float(song_file.readline())
        self.level_filename = song_file.readline().strip()
        self.music_filename = song_file.readline().strip()
        self.background_filename = song_file.readline().strip()
        
        
        self.pixel_offset = 0
        self.last_frame_time = -1
        self.frac_scroll = 0
#        print "{0}[{1}] : {2}".format(self.song_name, self.song_length, self.pixels_per_second)
        
#        self.background_width = (self.pixels_per_second * self.song_length) + width
        self.background_width = width + 96  # Jank scroll edition!
        background_size = (self.background_width, height)
        self.backgroundSurface = Surface(background_size)
        self.__render_background()
        
        self.backgroundSurface.set_colorkey((0,0,0),pygame.RLEACCEL)
        #self.backgroundSurface.set_colorkey((217,62,245),pygame.RLEACCEL)
        #self.backgroundSurface.set_alpha(100,pygame.RLEACCEL)
        
        self.mainScreenBackground,self.mainScreenBackgroundRect = load_image_from_folder('backgrounds', self.background_filename)
        
        #self.backgroundSurface.blit(mainScreenBackground, (0,0))
        #self.__render_background()
        
        possible_samurai_positions = []
        
        for i in range(0, 6):
            possible_samurai_positions.append(PATH_HEIGHT * i + 15)
        
        self.samurai = Samurai(possible_samurai_positions)
        self.samurai_sprite_group = Group(self.samurai)
        
        self.bridge_group = OrderedUpdates()
        self.mine_group = OrderedUpdates()
        self.enemy_group = OrderedUpdates()
        self.attack_group = OrderedUpdates()
        self.healthpack_group = OrderedUpdates()
        self.ki_potion_group = OrderedUpdates()
        self.shield_group = OrderedUpdates()
        self.sword_group = OrderedUpdates()
        self.explosion_group = OrderedUpdates()
        
#        tempSprite = self.samurai_sprite_group.sprites()
#        tempRect = tempSprite[0].get_rect()
#        self.testSword = VerticalSlash(tempRect.centerx,tempRect.centery, self.remove_attack)
#        self.attack_group.add(self.testSword)
        
        if sys.platform == "win32":
            # On Windows, the best timer is time.clock()
            self.default_timer = time.clock
        else:
            # On most other platforms, the best timer is time.time()
            self.default_timer = time.time
            
        
        
    def draw(self):
        self.gameSurface.fill((0,0,0))
        #self.gameSurface.fill((217,62,245))
        origin = (0, 0)
#        this_scroll = 0
        self.scroll_amount = 0
        if self.last_frame_time > 0:
            cur_time = self.default_timer()
            self.gap_time = cur_time - self.last_frame_time
#            print "Pixels per second: {0}\nGap Time: {1}\nScrollAmount: {2}".format(self.pixels_per_second, self.gap_time, this_scroll)
            self.last_frame_time = cur_time
        else:
            self.gap_time = 0
            self.last_frame_time = self.default_timer()
            
        this_scroll = self.pixels_per_second * self.gap_time
    
        self.frac_scroll += this_scroll
        if self.frac_scroll >= 1:
            self.scroll_amount = math.floor(self.frac_scroll)
            self.pixel_offset += self.scroll_amount
#            print "Now scrolling {0} pixel(s)".format(whole_part)
            self.frac_scroll -= self.scroll_amount

        if self.pixel_offset > 96:
            self.pixel_offset = self.pixel_offset - 96
            if self.pixel_offset < 0:
                self.pixel_offset = 0
                     
        self.gameSurface.blit(self.mainScreenBackground, origin)
        
        window_rect = Rect(self.pixel_offset, 0, self.gameSurface.get_width(), self.gameSurface.get_height()) 
#        print window_rect
        self.gameSurface.blit(self.backgroundSurface, origin, window_rect)
        
        #All other drawing
        self.bridge_group.update(self.scroll_amount)
        self.bridge_group.draw(self.gameSurface)
        
        self.mine_group.update(self.scroll_amount)
        self.mine_group.draw(self.gameSurface)
        
        self.enemy_group.update(self.scroll_amount)
        self.enemy_group.draw(self.gameSurface)
        
        self.samurai_sprite_group.update()
        self.samurai_sprite_group.draw(self.gameSurface) 
        
        self.healthpack_group.update(self.scroll_amount)
        self.healthpack_group.draw(self.gameSurface)
        
        self.ki_potion_group.update(self.scroll_amount)
        self.ki_potion_group.draw(self.gameSurface)
        
        self.shield_group.update(self.scroll_amount)
        self.shield_group.draw(self.gameSurface)
        
        self.sword_group.update(self.scroll_amount)
        self.sword_group.draw(self.gameSurface)
        
        #self.testSword = VerticalSlash(400,400)
        #self.attack_group.add(self.testSword)
        self.attack_group.update()
        self.attack_group.draw(self.gameSurface)
        
        self.explosion_group.update()
        self.explosion_group.draw(self.gameSurface)
        
#        self.testSword.draw(self.gameSurface)
        
        
        
        for bridge in self.bridge_group.sprites():
            if bridge.rect.left < 0:
                self.bridge_group.remove(bridge)
            
        
        #Annnnd blast it back to the screen
        window_origin = (0, 60)
        self.windowSurface.blit(self.gameSurface, window_origin)
        
        
    def add_bridge(self, bridge_num):
#        print "FAKE BRIDGE"
        
        new_bridge = Bridge(1101, bridge_num * PATH_HEIGHT + 39)
        self.bridge_group.add(new_bridge)
        
    def add_mine(self, string_num):
#        print "CREATE ZE LANDMINE"
        new_mine = Mine(1101, PATH_HEIGHT * string_num + 42)
        self.mine_group.add(new_mine)
    
    def add_powerup(self, string_num):
        r = random.random()
        if r < self.PROB_HEALTH:
            self.add_healthpack(string_num)
        elif r < self.PROB_KI:
            self.add_kiboost(string_num)
        elif r < self.PROB_SHIELD:
            self.add_shield(string_num)
        elif r < self.PROB_SWORD:
            self.add_sword(string_num)

    def add_healthpack(self, string_num):
#        print "such a healthy young man!"
        new_healthpack = Healthpack(1101, PATH_HEIGHT * string_num + 42)
        self.healthpack_group.add(new_healthpack)
        
    def add_shield(self, string_num):
        new_shield = Shield(1101, PATH_HEIGHT * string_num + 42)
        self.shield_group.add(new_shield)
        
    def add_sword(self, string_num):
        new_sword = MegaSword(1101, PATH_HEIGHT * string_num + 42)
        self.sword_group.add(new_sword)
        
    def add_kiboost(self, string_num):
        new_ki_potion = KiPotion(1101, PATH_HEIGHT * string_num + 42)
        self.ki_potion_group.add(new_ki_potion)
    
    def add_enemy(self, string_num):
        new_enemy = Enemy(1111, PATH_HEIGHT * string_num + 42)
        self.enemy_group.add(new_enemy)
        
    def add_male_groupie(self, string_num):
        new_enemy = MaleGroupie(1111, PATH_HEIGHT * string_num + 15)
        self.enemy_group.add(new_enemy)
        
    def add_lawyer(self, string_num):
        new_lawyer = Lawyer(1111, PATH_HEIGHT * string_num + 15)
        self.enemy_group.add(new_lawyer)
        
    def add_bodyguard(self, string_num):
        new_bodyguard = Bodyguard(1111, PATH_HEIGHT * string_num + 15)
        self.enemy_group.add(new_bodyguard)
        
    def remove_attack(self, attack):
        self.attack_group.remove(attack)
        
    def add_attack(self, attack):
        self.attack_group.add(attack)
        
    def add_explosion(self, y_val):
        new_explosion = Explosion(20, y_val, self.explosion_group)
        
        
    def __render_background(self):
        # Jank implementation that just uses that one sprite over and over again!
        # Jay's jank dirtBlockThingy is 96x48 pixels
        num_blocks = int(math.ceil(self.background_width / 96.0))
        cur_width = 0
        for bI in range(0, num_blocks):
            for hI in range(0, 6):
                my_location = (cur_width, (PATH_HEIGHT * hI + 35))
                dp = DirtPath(my_location)
#                print "DirtPath at {0}".format(my_location)
                self.backgroundSurface.blit(dp.image, my_location)
            cur_width += 96
Beispiel #22
0
class Level:
    """
    Represents a level loaded from a text based .level file.

    Contains level prefabs, cached paths and collision data.
    """
    def __init__(self, game, name):
        """ 
        Constructor. 
        
        Args:
            game (Game): The game instance.
            name (str): The name of the level being loaded (case sensitive).

        """
        self.game = game
        self.name = name
        self.load_data()
        self.start()

    def load_data(self):
        """ 
        Loads the level by its name. 

        Level data is saved in a text based .level file, containing prefab types 
        and their corresponding positions. This data is used by Level.restart()
        to position level components.

        Returns:
            list[list[string]]: A list of data entries for the level.

        """
        try:
            print("levels/" + self.name + ".level")
            with open("levels/" + self.name + ".level", "r") as file:
                self.data = [
                    line.strip().split(" ") for line in file.readlines()
                    if len(line.strip()) > 0 and line[0] != "#"
                ]

        except IOError:
            print("Error loading level")

    def start(self):
        """ 
        Sets up and starts the level.
        """
        self.collision = Collision(self, self.game.window.resolution, 32)
        self.prefabs = OrderedUpdates()
        self.pathfinding = Pathfinding(self.game, self.collision)

        for args in self.data:
            name = args[0]
            x = int(args[1])
            y = int(args[2])

            prefab = Prefab(name, x, y)
            self.prefabs.add(prefab)

            if hasattr(prefab, "block"):
                # Block textures are 1 pixel wider to make a full border
                self.collision.block_rect(x, y, prefab.rect.width - 1,
                                          prefab.rect.height - 1)

        self.pathfinding.precompute(30)
        self.wave = Wave(self.game, 1)
        self.lives = 20
        self.money = 600
        self.time = 0

    def get_score(self):
        return int((self.time / 5)**1.4 + (self.game.wave.number - 1)**3)
Beispiel #23
0
from pygame.constants import *
from pygame.sprite import Group, OrderedUpdates

from core import config
from core import settings
from core import color
from game import bg
from game.menustate import MenuState
from game.hudobject import make_text, HudObject
from game import enemy
from game import player
from game import ufo
from game import block

### Groups #####################################################################
GRID_BG = OrderedUpdates()
TEXT = Group()
SPRITES = Group()
################################################################################

### Constants ##################################################################
'''
@var DIST_APART: Vertical distance between text lines in pixels
@var TOP_LEFT: Coordinates of the top-left of the text, in pixels
'''
ALIEN_DIST = 12 + enemy.ENEMY_FRAMES[id(color.RED)][0].get_width()
ALIEN_Y = 24
BLOCK_Y = 72
DIST_APART = 24
TOP_LEFT = (16, 32)
################################################################################
Beispiel #24
0
class Game(object):
    title = 'Gravity'
    screen_size = 1000, 750
    
    def __init__(self,level=0):
        pygame.init()
        
        self.screen = pygame.display.set_mode(self.screen_size)
        if self.title:
            pygame.display.set_caption(self.title)
        self.fps = 30

        #group definitions
        self.userPlacedObjects = Group()
        self.startItems = RenderUpdates()
        self.playerGroup = RenderUpdates()
        self.tails = RenderUpdates()
        self.blackHoles = RenderUpdates()
        self.obstacles = RenderUpdates()
        self.masslessObstacles = RenderUpdates()
        self.goalCollide = Group()
        self.toolbar = OrderedUpdates()

        #level/transition/player & enemy/obstacle creation hocus pocus
        self.goal = Goal(573,372,self.goalCollide,30)
        self.bar = ToolBar(0,626,self.toolbar,self.screen,self,self.goal)
        self.player = Player(50,535,self.screen,(255,0,0),self.playerGroup,1000,624,(2,-2),self.tails,self)
        
        self.level = level
        self.levelUp = True
        self.stars = Starfield(self.screen,1000,626,200)
        BlackHole(339,70,self.blackHoles,self.screen,80,71,16)
        temp = EarthRounder(513,313,self.masslessObstacles,self.screen,40,0)
        temp.rotate(55)
        temp = Alien(60,188,self.masslessObstacles,self.screen,34,1)
        temp.rotate(-15)
        temp = Alien(107,268,self.masslessObstacles,self.screen,35,1)
        temp.rotate(-75)
        temp = Alien(816,533,self.masslessObstacles,self.screen,39,0)
        temp.rotate(-13)
        temp = BlueUpAnDown(811,227,self.masslessObstacles,self.screen,34,1,97,239)
        temp.rotate(80)
        self.obstacles.add(self.blackHoles)
        self.obstacles.add(self.goalCollide)
        self.freeb = False
        self.gotoLevel = level
        self.loaded = False

        if system.thereIsASaveFile() and level == 0:
            self.intro_screen = Intro(0,0,self.startItems,str('title_w_file.png'))
            self.thereIsAFile = True
        elif level == 0:
            self.intro_screen = Intro(0,0,self.startItems)
            self.thereIsAFile = False
      
    def quit(self):
        self.done = True
   
    def level_0(self):
        self.clock.tick(self.fps)
        pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750)))
        
        for evt in pygame.event.get():
            if evt.type == QUIT:
                self.quit()
            if evt.type == KEYDOWN:
                if evt.key == K_ESCAPE:
                    self.quit()
                elif evt.key == K_RETURN:
                    if not self.thereIsAFile:
                        self.transition = Transition(-1314,0,self.screen,self.startItems)
                        self.intro_screen.begin()
                    else:
                        loadingDial = system.Loading()
                        pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750)))
                        self.startItems.draw(self.screen)
                        loadingDial.draw(self.screen)
                        pygame.display.flip()
                        self.loadFile(system.loadFile())
                        
                elif evt.key == K_RIGHT:
                    self.intro_screen.instruct(True)
                elif evt.key == K_LEFT:
                    self.intro_screen.instruct(False)
                elif evt.key == K_n:
                    if self.thereIsAFile:
                        self.transition = Transition(-1314,0,self.screen,self.startItems)
                        self.intro_screen.begin()
                        self.transition = Transition(-1314,0,self.screen,self.startItems)
                elif evt.key == K_d:
                    if self.thereIsAFile:
                        os.remove('save.txt')
                        self.thereIsAFile = False
                        self.startItems.empty()
                        self.intro_screen = Intro(0,0,self.startItems)

       
        if self.intro_screen.next_level():
            self.level = 1
        
        
        self.startItems.update()
        self.stars.draw()
        self.goalCollide.draw(self.screen)
        self.toolbar.draw(self.screen)
        self.masslessObstacles.draw(self.screen)
        self.playerGroup.draw(self.screen)
        self.blackHoles.draw(self.screen)
        self.startItems.draw(self.screen)
        

        pygame.display.flip()

        

    def tick(self):
        self.clock.tick(self.fps)
        pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750)))
        pos = pygame.mouse.get_pos()

        #inputs queue
        for evt in pygame.event.get():
            if evt.type == QUIT:
                self.quit()
            elif evt.type == KEYDOWN:
                if evt.key == K_ESCAPE and not self.bar.itemsTab.open and self.bar.grabbed == None:
                    self.bar.menuWidget.dropped()
                elif evt.key == K_ESCAPE and self.bar.grabbed == None:
                    self.bar.itemsTab.dropped()
                    self.bar.menuWidget.dropped()
                                        
            elif evt.type == MOUSEBUTTONDOWN:
                #print pos
                should_freebie = self.bar.collision_test(pos,self.player,evt.button)
                if should_freebie and not self.freeb:
                    self.freebie()
                    self.freeb = True
                if evt.button == 1:
                    for obj in self.userPlacedObjects:
                        if obj.rect.collidepoint(pos) and not self.player.makeANew and not self.bar.menuWidget.open:
                            obj.grab(pos)
                elif evt.button == 3:
                    for obj in self.userPlacedObjects:
                        if obj.rect.collidepoint(pos) and not self.player.makeANew and not self.bar.menuWidget.open:
                            obj.remove()
            elif evt.type == MOUSEBUTTONUP:
                self.bar.clear_grabbed()
                for obj in self.userPlacedObjects:
                    obj.drop(self.blackHoles)
             
   
        if self.level == 4 and self.player.makeANew:
            self.masslessObstacles.update()
   
        #self.masslessObstacles.update(self.player.makeANew)
        self.stars.draw()
        self.player.drawTails()
        self.blackHoles.update()
        self.bar.update(pos)
        self.blackHoles.draw(self.screen)
        self.userPlacedObjects.update(pos)
        self.userPlacedObjects.draw(self.screen)
        self.masslessObstacles.draw(self.screen)
        self.goalCollide.draw(self.screen)
        self.toolbar.draw(self.screen)
        self.playerGroup.update()
        self.playerGroup.draw(self.screen)  

        if len(self.playerGroup) == 0 and self.player.lives >1:
            self.bar.lives_update()
            self.bar.score.update(-200)
            pygame.time.wait(750)
            self.player.lives -= 1
            if self.level == 4:
                self.asteroid.reset()
            self.player.add(self.playerGroup)
        elif len(self.playerGroup) == 0:
            self.bar.score.update(-200)
            self.bar.lives_update()
            self.over_screen = GameOverScreen(293,161,self.screen)
            if self.level == 4:
                self.asteroid.reset()
            self.gameOver()
                
        if pygame.sprite.collide_mask(self.player, self.goal):
            if self.loaded != 0:
                self.level = self.loaded
                self.loaded = 0
            self.next_level()
            

        for obj in self.blackHoles:
            if pygame.sprite.collide_mask(self.player,obj):
                self.player.blackHoleCollision(True,False)

        for obj in self.masslessObstacles:
            if  pygame.sprite.collide_mask(self.player,obj):
                self.player.update(True)
        
        for obj in self.userPlacedObjects:
            if pygame.sprite.collide_mask(self.player,obj) and not obj.grabbed:
                self.player.update(True)
        

        pygame.display.flip()


    def next_level(self,add_score_bool=True,trans_effect=True):
        if self.level < 5:
            print self.level,"pre-adding"
            self.level += 1
            print self.level,"post-adding"
        #print self.level
        if self.level == 5:
            return
        if trans_effect: self.transition.add_to_group()
        changed = False
        while True:
            self.clock.tick(self.fps)
            pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750)))
            
            for evt in pygame.event.get():
                if evt.type == QUIT:
                    self.quit()
                if evt.type == KEYDOWN:
                    if evt.key == K_ESCAPE:
                        self.quit()
                        
            if not trans_effect or self.transition.rect.x >= -50 and not changed:
                print self.level
                if self.level == 2:
                    self.make_level_two(add_score_bool)
                if self.level == 3:
                    self.make_level_three(add_score_bool)
                if self.level == 4:
                    self.make_level_four(add_score_bool)

                if add_score_bool:
                    self.bar.score.update(2000)


                self.player.restart(add_score_bool)
                changed = True      

            if not trans_effect:
                print self.level,"load" 
                break
                
            self.startItems.update()
            self.stars.draw()
            self.player.drawTails()
            self.goalCollide.draw(self.screen)
            self.masslessObstacles.draw(self.screen)
            self.userPlacedObjects.draw(self.screen)
            self.toolbar.draw(self.screen)
            self.blackHoles.draw(self.screen)
            self.playerGroup.draw(self.screen)  
            self.startItems.draw(self.screen)
            if self.transition.rect.x > 1000:
                self.transition.kill()
                break


            pygame.display.flip()
        if trans_effect:
            self.transition.reset(-1314)
        print self.level,"end o loop"
        return False

    
    def freebie(self):
        groupus = Group()
        groupus.add(self.blackHoles,self.goal)
        self.player.makeANew = True
        self.player.addTail = False
        while True:
            self.clock.tick(self.fps)
            pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750)))
            
            for evt in pygame.event.get():
                if evt.type == QUIT:
                    self.quit()
                if evt.type == KEYDOWN:
                    if evt.key == K_ESCAPE:
                        self.quit()
            
            
            for obj in self.blackHoles:
                if pygame.sprite.collide_mask(self.player,obj):
                    self.player.blackHoleCollision(True,False)

            for obj in self.masslessObstacles:
                if  pygame.sprite.collide_mask(self.player,obj):
                    self.player.update(True)
        
            for obj in self.userPlacedObjects:
                if pygame.sprite.collide_mask(self.player,obj) and not obj.grabbed:
                    self.player.update(True)
            

            self.startItems.update()
            #self.masslessObstacles.update()
            self.stars.draw()
            self.player.drawTails()
            self.goalCollide.draw(self.screen)
            self.masslessObstacles.draw(self.screen)
            self.userPlacedObjects.draw(self.screen)
            self.toolbar.draw(self.screen)
            self.blackHoles.draw(self.screen)
            self.player.update(False,groupus)
            self.playerGroup.draw(self.screen)  
            self.startItems.draw(self.screen)
            if len(self.playerGroup) < 1:
                self.player.addTail = True
                pygame.time.wait(750)
                self.player.add(self.playerGroup)
                break
            pygame.display.flip()
            

    def gameOver(self):
        overing = True
        self.bar.update()
        self.toolbar.draw(self.screen)
        self.over_screen.draw()
        pygame.display.flip()
        while overing:
            self.clock.tick(self.fps)
            
            for evt in pygame.event.get():
                if evt.type == QUIT:
                    overing = False
                    self.quit()
                if evt.type == KEYDOWN:
                    if evt.key == K_ESCAPE:
                        overing = False
                        self.quit()
                    if evt.key == K_RETURN:
                        overing = False
            
            
        
        self.player.add(self.playerGroup)
        self.bar.reset_lives_over()
        self.player.restart()
        self.over_screen.kill()

    def inStructionees(self):
        self.instructions = Instructions(0,-750,self.startItems)
        self.instructions.instruct(True)

        while True:
            self.clock.tick(self.fps)
            pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750)))

            if self.instructions.instruct and self.instructions.rect.y < 0:
                self.instructions.rect.y += 50

            elif not self.instructions.instruct and self.instructions.rect.y > -750:
                self.instructions.rect.y -= 50
            elif not self.instructions.instruct and self.instructions.rect.y <= -750:
                self.instructions.kill()
                return
            
            
            for evt in pygame.event.get():
                if evt.type == QUIT:
                    self.quit()
                    return
                elif evt.type == KEYDOWN:
                    if evt.key == K_RETURN:
                        self.instructions.instruct = False
                    elif evt.key == K_ESCAPE:
                        self.quit()
                        return

            self.stars.draw()
            self.player.drawTails()
            self.goalCollide.draw(self.screen)
            self.masslessObstacles.draw(self.screen)
            self.userPlacedObjects.draw(self.screen)
            self.toolbar.draw(self.screen)
            self.blackHoles.draw(self.screen)
            self.playerGroup.draw(self.screen)  
            self.startItems.draw(self.screen)
                
            pygame.display.flip()
    
    def saveFile(self):
        save_confirm = GameOverScreen(293,161,self.screen,str('filesaved.png'))
        save_confirm.draw()
        self.bar.menuWidget.dropped()
        system.saveFile(self.level,self.player.lives,self.bar.score.score)
        pygame.display.flip()
        while True:
            self.clock.tick(self.fps)
            pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750)))

            for evt in pygame.event.get():
                if evt.type == QUIT:
                    self.quit()
                    return
                elif evt.type == KEYDOWN:
                    if evt.key == K_RETURN:
                        return
                    elif evt.key == K_ESCAPE:
                        self.quit()
                        return

            
    def loadFile(self,file_tuple):
        gotoLevel,gotoLives,gotoScore = file_tuple
        self.level = gotoLevel
        if self.level > 1:
            self.loaded = self.level
        self.player.lives = gotoLives
        self.bar.lives.next_life = gotoLives+1
        self.bar.lives_update()
        self.bar.score.reset(gotoScore)
        if gotoLevel != 1:
            self.level -= 1
            self.next_level(False,False)
        self.startItems.empty()
        self.intro_screen = Intro(0,0,self.startItems,str('title_w_file.png'))
        self.intro_screen.begin()
        self.transition = Transition(-1314,0,self.screen,self.startItems)

        while True:
            self.clock.tick(self.fps)
            pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750)))
            
            
            if self.intro_screen.next_level():
                break
            
            self.startItems.update()
            self.startItems.update()
            self.stars.draw()
            self.goalCollide.draw(self.screen)
            self.toolbar.draw(self.screen)
            self.masslessObstacles.draw(self.screen)
            self.playerGroup.draw(self.screen)
            self.blackHoles.draw(self.screen)
            self.startItems.draw(self.screen)
            
            
            pygame.display.flip()

        
    def gameWinner(self):
        self.clock.tick(self.fps)
        pygame.draw.rect(self.screen,(0,0,0),((0,0),(1000,750)))
            
            
        for evt in pygame.event.get():
            if evt.type == QUIT:
                self.quit()
                
            elif evt.type == KEYDOWN:
                self.quit()
            
        self.winnerScreen.draw()
        pygame.display.flip()
        
    def run(self,level=0):
        self.done = False
        self.clock = pygame.time.Clock()
        if self.gotoLevel > 1 and self.gotoLevel < 4:
            self.transition = Transition(-1314,0,self.screen,self.startItems)
            self.tick()
            self.level = self.gotoLevel
            self.next_level()
        while not self.done:
            while self.level == 0 and not self.done:
                self.level_0()
            while self.level >= 1 and self.level < 5 and not self.done:
                self.tick()
            self.winnerScreen = WinScreen(0,0,self.screen)
            while not self.done:
                self.gameWinner()


    def make_level_two(self,reset_lives_bool):
        self.tails.empty()
        self.goal.next_level(self.level)
        self.bar.next_level(self.level,reset_lives_bool)
        self.userPlacedObjects.empty()
        self.blackHoles.empty()
        self.obstacles.empty()
        self.freeb = False
        self.bar.itemsTab.earth_item.light()
        self.masslessObstacles.empty()
        temp = Alien(55,143,self.masslessObstacles,self.screen,39,1)
        temp.rotate(-66)
        temp = Alien(189,98,self.masslessObstacles,self.screen,36,1)
        temp.rotate(23)
        temp = Alien(107,228,self.masslessObstacles,self.screen,32,1)
        temp.rotate(17)
        temp = BlueUpAnDown(249,244,self.masslessObstacles,self.screen,41,1,204,245)
        temp.rotate(80)
        temp = TwitchyOnes(898,541,self.masslessObstacles,self.screen,45,2)
        temp.rotate(22)
        temp = TwitchyOnes(730,545,self.masslessObstacles,self.screen,40,2)
        temp.rotate(-30)
        temp = Rotator(525,121,self.masslessObstacles,self.screen,50,0,-70)
        BlackHole(842,388,self.blackHoles,self.screen,80,71,16)
        hole = BlackHole(388,189,self.blackHoles,self.screen,80,71,16)
        hole.flip()
        self.obstacles.add(self.blackHoles)
        self.obstacles.add(self.goal)

    def make_level_three(self,reset_lives_bool):
        self.goal.next_level(self.level)
        self.bar.next_level(self.level,reset_lives_bool)
        self.userPlacedObjects.empty()
        self.blackHoles.empty()
        self.obstacles.empty()
        self.freeb = False
        self.bar.itemsTab.earth_item.light()
        self.masslessObstacles.empty()
        temp = Alien(519,257,self.masslessObstacles,self.screen,28,3)
        temp.rotate(18)
        temp = Alien(539,247,self.masslessObstacles,self.screen,27,3)
        temp.rotate(60)
        temp = Alien(555,240,self.masslessObstacles,self.screen,25,3)
        temp.rotate(-20)
        temp = Alien(568,281,self.masslessObstacles,self.screen,29,3)
        temp.rotate(-45)
        temp = Alien(549,291,self.masslessObstacles,self.screen,32,3)
        temp.rotate(10)
        temp = Alien(530,301,self.masslessObstacles,self.screen,26,3)
        temp = Alien(562,265,self.masslessObstacles,self.screen,27,3)
        temp.rotate(25)   
        temp = Alien(519,334,self.masslessObstacles,self.screen,25,3)
        temp.rotate(-70)
        temp = Alien(500,307,self.masslessObstacles,self.screen,25,3)
        temp.rotate(-80)
        temp = Alien(494,356,self.masslessObstacles,self.screen,25,3)
        temp.rotate(-3)
        temp = Alien(560,365,self.masslessObstacles,self.screen,25,3)
        temp.rotate(77)
        temp = Alien(525,374,self.masslessObstacles,self.screen,29,3)
        temp.rotate(33)
        temp = Alien(640,290,self.masslessObstacles,self.screen,26,3)
        temp.rotate(37)
        temp = Alien(607,250,self.masslessObstacles,self.screen,33,3)
        temp.rotate(-27)  
        temp = Alien(518,421,self.masslessObstacles,self.screen,24,3)
        temp.rotate(55)
        temp = Alien(473,419,self.masslessObstacles,self.screen,28,3)
        temp.rotate(-43)
        temp = Alien(480,453,self.masslessObstacles,self.screen,27,3)
        temp = Alien(512,479,self.masslessObstacles,self.screen,31,3)
        temp.rotate(4)
        temp = Alien(422,500,self.masslessObstacles,self.screen,32,3)
        temp = Alien(463,521,self.masslessObstacles,self.screen,27,3)
        temp.rotate(22)
        temp = Alien(471,486,self.masslessObstacles,self.screen,22,3)
        temp.rotate(80)
        temp = Alien(743,713,self.masslessObstacles,self.screen,25,3)
        temp.rotate(13)
        temp = Alien(527,532,self.masslessObstacles,self.screen,28,3)
        temp.rotate(-8)
        temp = Alien(568,559,self.masslessObstacles,self.screen,27,3)
        temp = Alien(527,593,self.masslessObstacles,self.screen,23,3)
        temp.rotate(-60)
        temp = Alien(652,552,self.masslessObstacles,self.screen,25,3)
        temp.rotate(-24)
        temp = Alien(636,581,self.masslessObstacles,self.screen,26,3)
        temp.rotate(-19)
        temp = Alien(714,596,self.masslessObstacles,self.screen,22,3)
        temp.rotate(-88)
        BlackHole(162,42,self.blackHoles,self.screen,80,71,29)
        self.obstacles.add(self.goal)
        self.obstacles.add(self.blackHoles)

    def make_level_four(self,reset_lives_bool):
        self.goal.next_level(self.level)
        self.bar.next_level(self.level,reset_lives_bool)
        self.userPlacedObjects.empty()
        self.blackHoles.empty()
        self.obstacles.empty()
        self.freeb = False
        self.bar.itemsTab.earth_item.light()
        self.masslessObstacles.empty()
        BlackHole(183,61,self.blackHoles,self.screen,80,71,16)
        BlackHole(101,157,self.blackHoles,self.screen,80,71,16)
        BlackHole(234,157,self.blackHoles,self.screen,80,71,16)
        BlackHole(178,250,self.blackHoles,self.screen,80,71,16)
        hole = BlackHole(683,41,self.blackHoles,self.screen,80,71,16)
        hole = BlackHole(577,41,self.blackHoles,self.screen,80,71,16)
        hole = BlackHole(646,133,self.blackHoles,self.screen,80,71,16)
        hole = BlackHole(747,133,self.blackHoles,self.screen,80,71,16)
        self.asteroid = Asteroid(840,530,self.masslessObstacles,self.screen,55,4)
        self.asteroid.rotate(137)

        self.obstacles.add(self.blackHoles)
        self.obstacles.add(self.goal)