Example #1
0
    def __init__(self):
        pygame.init()
        self.background_sound = Sound()

        pygame.key.set_repeat(50, 50)
        size = [SCREEN_WIDTH, SCREEN_HEIGHT]

        self.screen = pygame.display.set_mode(size)
        pygame.display.set_caption(TITLE)

        self.clock = pygame.time.Clock()
        self.font_name = pygame.font.match_font(FONT)

        self.running = True
        self.isover = False
        self.gameispaused = False
        self.levels = {
            1: Level_01,
            2: Level_02,
            3: Level_03,
            4: Level_04,
            5: Level_05,
            6: Level_06,
            7: Level_07,
            8: Level_08,
            9: Level_09,
            10: Level_10
        }

        self.show_start_screen()
Example #2
0
    def func(state, index, locus):
        term = state[index]
        term_value = term.get_at(locus)
        new_value = None
        add_part = False

        # 1.1.54 ādeḥ parasya
        if adi:
            try:
                new_value = sthani.value + term_value[1:]
            except AttributeError:
                new_value = sthani + term_value[1:]

        elif isinstance(sthani, basestring):
            # 1.1.52 alo 'ntyasya
            # 1.1.55 anekālśit sarvasya
            if len(sthani) <= 1:
                new_value = term_value[:-1] + sthani
            else:
                new_value = sthani

        elif not hasattr(sthani, 'value'):
            # 1.1.50 sthāne 'ntaratamaḥ
            last = Sound(term.antya).closest(sthani)
            new_value = term_value[:-1] + last

        # 1.1.47 mid aco 'ntyāt paraḥ
        elif 'mit' in sthani.samjna:
            ac = Sounds('ac')
            for i, L in enumerate(reversed(term_value)):
                if L in ac:
                    break
            new_value = term_value[:-i] + sthani.value + term_value[-i:]
            add_part = True

        # 1.1.46 ādyantau ṭakitau
        elif 'kit' in sthani.samjna:
            new_value = term_value + sthani.value
            add_part = True
        elif 'wit' in sthani.samjna:
            new_value = sthani.value + term_value
            add_part = True

        # 1.1.52 alo 'ntyasya
        # 1.1.53 ṅic ca
        elif len(sthani.value) == 1 or 'Nit' in sthani.samjna:
            new_value = term_value[:-1] + sthani.value

        # 1.1.55 anekālśit sarvasya
        elif 'S' in sthani.it or len(sthani.value) > 1:
            new_value = sthani.value

        if new_value is not None:
            new_term = term.set_at(locus, new_value)
            if add_part:
                new_term = new_term.add_part(sthani.raw)
            return state.swap(index, new_term)

        raise NotImplementedError(sthani)
Example #3
0
 def func(value):
     letters = list(value)
     for i, L in enumerate(letters):
         if L in target:
             letters[i] = Sound(L).closest(result)
             # 1.1.51 ur aṇ raparaḥ
             if L in 'fF' and letters[i] in Sounds('aR'):
                 letters[i] += 'r'
             break
     return ''.join(letters)
Example #4
0
 def on_create(self):
     """Called when an object is created"""
     self.sound_player = Sound("FOREST")
     self.set_background()
     self.set_hero()
     self.set_blocks()
     self.set_enemies()
     self.set_coins()
     self.set_healing()
     self.set_checkpoints()
     self.set_spritegroups()
Example #5
0
    def __init__(self, parent, name='Anonymus'):
        Location.__init__(self, parent, background)
        pygame.key.set_repeat(10)
        pygame.mouse.set_visible(mouse_enabled)

        self.sound = Sound()

        self.doodle = Doodle(name)
        self.allsprites = pygame.sprite.Group()
        self.allsprites.add(self.doodle)

        for i in range(0, platform_count):
            self.allsprites.add(self.randomPlatform(False))
        for platform in self.allsprites:
            if isinstance(platform, Platform) and platform.spring != None:
                self.allsprites.add(platform.spring)

        self.score = Score(50, 25, self.doodle.name, 45, (0, 0, 0))
        self.allsprites.add(self.score)
        self.window.blit(self.background, (0, 0))
Example #6
0
    def _random(self):
        # We need to create a first instance of the sound to get its duration
        self._sound = Sound(self.get_single_path(), self.volume)
        sound_duration = self._sound.get_duration()

        while not self.stop_event.is_set():
            r = random.random()

            if r <= self.random:
                self._play_sound()

            self.stop_event.wait(sound_duration + 1)

        logger.debug('[%s] Stopping rand', self.path)
Example #7
0
    def load_sounds(self, score_cutoff=None, base_cost_cutoff=None):

        self.sounds = OrderedDict()

        sound_list = self.db.execute("SELECT * from sounds order by votes desc, name asc")

        for dbsound in sound_list:
            sound = Sound(
                name=dbsound["name"],
                file_name=dbsound["path"],
                votes=dbsound["votes"],
                cost=dbsound["cost"],
                base_cost=dbsound["base_cost"],
                downvotes=dbsound["downvotes"],
                date_added=dt.datetime.fromtimestamp(dbsound["date_added"]),
                sound_player=self.sound_player,
            )
            if score_cutoff and sound.get_score() < score_cutoff:
                continue
            if base_cost_cutoff and sound.base_cost > base_cost_cutoff:
                continue
            self.sounds[sound.name] = sound

        return self.sounds
Example #8
0
 def __init__(self, caption=None, icon=None):
     super().__init__(caption, icon)
     self.snake = Snake()
     self.food = Food()
     self.food_consumed_sound = Sound("consumed.wav")
     self.death_sound = Sound("death.mp3")
     self.bg_sound = Sound("background.mp3")
     self.background = Background()
     self.play = False
     self.score = 0
     self.game_over = False
     self.delay = 3
     self.snake_die_time = None
Example #9
0
def samprasarana(value):
    rev_letters = list(reversed(value))
    found = False
    for i, L in enumerate(rev_letters):
        # 1.1.45 ig yaNaH saMprasAraNAm
        # TODO: enforce short vowels automatically
        if L in Sounds('yaR'):
            rev_letters[i] = Sound(L).closest('ifxu')
            found = True
            break

    if not found:
        return value

    # 6.4.108 saMprasAraNAc ca
    try:
        L = rev_letters[i - 1]
        if L in Sounds('ac'):
            rev_letters[i - 1] = ''
    except IndexError:
        pass

    return ''.join(reversed(rev_letters))
Example #10
0
def ac_sandhi(x, y):
    """Apply the rules of ac sandhi to `x` as followed by `y`.

    These rules are from 6.1. A rule is part of ac sandhi iff the first
    letter is a vowel.

    :param x: the first letter.
    :param y: the second letter.
    """

    # 6.1.97 ato guNe
    if x == 'a' and y in Sounds('at eN'):
        x = ''

    # 6.1.101 akaH savarNe dIrghaH
    elif Sound(x).savarna(y):
        x = ''
        y = dirgha(y)

    # 6.1.77 iko yaN aci
    elif x in Sounds('ik') and y in Sounds('ac'):
        x = iko_yan_aci(x)

    # 6.1.78 eco 'yavAyAvaH
    elif x in Sounds('ec') and y in Sounds('ac'):
        converter = dict(zip('eEoO', 'ay Ay av Av'.split()))
        x = converter[x]

    elif x in 'aA' and y in Sounds('ic'):
        x = ''

        # 6.1.87 Ad guNaH
        # 6.1.88 vRddhir eci
        y = vrddhi(y) if y in Sounds('ec') else guna(y)

    return x, y
Example #11
0
class GameLocation(Location):

    def __init__(self, parent, name='Anonymus'):
        Location.__init__(self, parent, background)
        pygame.key.set_repeat(10)
        pygame.mouse.set_visible(mouse_enabled)

        self.sound = Sound()

        self.doodle = Doodle(name)
        self.allsprites = pygame.sprite.Group()
        self.allsprites.add(self.doodle)

        for i in range(0, platform_count):
            self.allsprites.add(self.randomPlatform(False))
        for platform in self.allsprites:
            if isinstance(platform, Platform) and platform.spring != None:
                self.allsprites.add(platform.spring)

        self.score = Score(50, 25, self.doodle.name, 45, (0, 0, 0))
        self.allsprites.add(self.score)
        self.window.blit(self.background, (0, 0))

    def randomPlatform(self, top=True):
        x = random.randint(0, screen_width - platform_width)
        bad_y = []

        for spr in self.allsprites:
            bad_y.append((spr.y - platform_y_padding, spr.y + platform_y_padding + spr.rect.height))
    
        good = 0
        while not good:
            if top:
                y = random.randint(-100, 100)
            else:
                y = random.randint(0, screen_height)

            good = 1
            for bad_y_item in bad_y:
                if bad_y_item[0] <= y <= bad_y_item[1]:
                    good = 0
                    break

        dig = random.randint(0, 100)
        if dig < 35:
            return MovingPlatform(x, y)
        elif 35 <= dig < 50:
            return CrashingPlatform(x, y) 
        else:
            return Platform(x, y)

    def draw(self):
        if self.doodle.alive:

            self.allsprites.clear(self.window, self.background)

            mousePos = pygame.mouse.get_pos()
            self.doodle.inc_y_speed(-gravitation)
            if mouse_enabled:
                self.doodle.set_x(mousePos[0])
            else:
                if transparent_walls:
                    if self.doodle.x < 0:
                        self.doodle.set_x(screen_width)
                    elif self.doodle.x > screen_width:
                        self.doodle.set_x(0)

            self.doodle.move_y(-self.doodle.ySpeed)

            for spr in self.allsprites:
                if isinstance(spr, Spring) and self.doodle.get_legs_rect().colliderect(spr.get_top_surface()) and self.doodle.ySpeed <= 0:
                    self.sound.play_spring_sound()
                    spr.compress()
                    self.doodle.ySpeed = spring_speed
                    

                if isinstance(spr, Platform) and self.doodle.get_legs_rect().colliderect(spr.get_surface_rect()) and self.doodle.ySpeed <= 0:
                    if isinstance(spr, CrashingPlatform):
                        if not spr.is_playing:
                            spr.is_playing = True
                            self.sound.play_crashing_sound()
                        spr.crash()
                        break

                    self.sound.play_jump_sound()
                    self.doodle.ySpeed = jump_speed

                if isinstance(spr, Platform):
                    if spr.y >= screen_height:
                        self.allsprites.remove(spr)
                        platform = self.randomPlatform()
                        self.allsprites.add(platform)
                        if isinstance(platform, Platform) and platform.spring != None:
                            self.allsprites.add(platform.spring)

                if isinstance(spr,MovingPlatform) or (isinstance(spr,CrashingPlatform) and spr.crashed == 1):
                    spr.move()

            if self.doodle.y < horizont:
                self.doodle.inc_score(self.doodle.ySpeed)
                for spr in self.allsprites:
                    if not isinstance(spr, Score):
                        spr.move_y(self.doodle.ySpeed)

            self.allsprites.draw(self.window)
            self.score.set_text("   %s" % (int(self.doodle.score/10)))
            # self.window.blit()
        else:
            self.sound.play_falling_sound()
            # self.parent.location = GameLocation(self.parent, self.doodle.name)
            # self.parent.location = StartLocation(self.parent)
            self.parent.location = EndLocation(self.parent, int(self.doodle.score/10))

    def event(self, event):
        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                self.doodle.set_x(self.doodle.x - 10)
            elif event.key == K_RIGHT:
                self.doodle.set_x(self.doodle.x + 10)
Example #12
0
def asiddha_helper(state):
    """Chapter 8.2 of the Ashtadhyayi starts the 'asiddha' section of
    the text:

        8.2.1 pUrvatrAsiddham

    The asiddha section lasts until the end of the text, and for that
    reason, it is often called the tripAdI ("having three pAdas").

    The rules in the tripAdI are treated as not having taken effect
    ('asiddha') as far as the prior rules are concerned. This is an
    abstract notion, but practically it means that these are the last
    rules we apply in a derivation.

    :param state:
    """

    had_rs = False

    editor = SoundEditor(state)
    for c in editor:
        p = c.prev
        n = c.next
        n2 = n.next

        w, x, y, z = (p.value, c.value, n.value, n2.value)

        # 8.2.29 skoH saMyogAdyor ante ca
        # TODO: pada end
        if x in 'sk' and y in Sounds('hal') and z in Sounds('Jal'):
            x = '_'

        if y in Sounds('Jal'):
            # 8.2.30 coH kuH
            cu = Sounds('cu')
            if x in cu and y in Sounds('Jal') and y not in cu:
                x = Sound(x).closest(Sounds('ku'))

            # 8.2.31 ho DhaH
            elif x == 'h':
                x = 'Q'

            # 8.2.36 vrazca-bhrasja-sRja-mRja-yaja-rAja-bhrAjacCazAM SaH
            roots = {'vraSc', 'Brasj', 'sfj', 'mfj', 'yaj', 'rAj', 'BrAj'}
            if c.last and (c.term.value in roots or c.term.antya in 'SC'):
                x = 'z'

        # 8.2.40 (TODO: not dhA)
        if w in Sounds('Jaz') and x in 'tT':
            x = 'D'
        elif x == 'D' and y in 'tT':
            continue

         # 8.2.41 SaDhoH kaH si
        elif x in 'zQ' and y == 's':
            x = 'k'

        # 8.2.41 SaDhoH kaH si
        if x in 'zQ' and y == 's':
            x = 'k'

        # 8.3.23 mo 'nusvAraH
        # elif x == 'm' and y in Sounds('hal'):
        #     x = 'M'

        # 8.3.24 naz cApadAntasya jhali
        elif x in 'mn' and y in Sounds('Jal'):
            x = 'M'

        # 8.3.59 AdezapratyayayoH
        if w in Sounds('iN ku'):
            if not c.last and x == 's' and (c.term.raw[0] == 'z'
                                            or 'pratyaya' in c.term.samjna):
                x = 'z'

        # 8.3.78 iNaH SIdhvaMluGliTAM dho 'GgAt
        # 8.3.79 vibhASeTaH
        # TODO: SIdhvam, luG
        if (x == 'D'
                and w in Pratyahara('iR', second_R=True)
                and c.first  # not triggered by iT
                and 'li~w' in c.term.lakshana):
            x = 'Q'

        # 8.4.1 raSAbhyAM no NaH samAnapade
        # 8.4.2 aTkupvAGnuMvyavAye 'pi
        # According to commentary, 8.4.1 also applies to 'f' and 'F'.
        # TODO: AG, num
        if x in 'rzfF':
            had_rs = True
        elif x == 'n' and had_rs and p.term.value != 'kzuB':
            x = 'R'
            had_rs = False
        elif x not in Sounds('aw ku pu'):
            had_rs = False

        stu = Sounds('s tu')
        if x in stu:

            # 8.4.40 stoH zcunA zcuH
            # 8.4.44 zAt (na)
            scu = Sounds('S cu')
            if w == 'S':
                pass
            elif w in scu or y in scu:
                x = Sound(x).closest(scu)

            # 8.4.41 STunA STuH
            zwu = Sounds('z wu')
            if w in zwu or y in zwu:
                x = Sound(x).closest(zwu)

        if x in Sounds('Jal'):
            x_ = x

            # 8.4.53 jhalAM jaz jhazi
            if y in Sounds('JaS'):
                x = Sound(x_).closest(Sounds('jaS'))

            # 8.4.54 abhyAse car ca
            if 'abhyasa' in c.term.samjna and c.first:
                x = Sound(x_).closest(Sounds('car jaS'))

            # 8.4.55 khari ca
            if y in Sounds('Kar'):
                x = Sound(x_).closest(Sounds('car'))

        # 8.4.58 anusvArasya yayi parasavarNaH
        if x == 'M' and y in Sounds('yay'):
            x = Sound(x).closest(Sound(y).savarna_set)

        c.value = x if x != '_' else ''

    yield editor.join()
Example #13
0
 def __init__(self):
     pygame.init()
     self.__GameModel = GameModel(self)
     self.__GameView = GameView(self, self.__GameModel)
     self.__sounds = Sound()
Example #14
0
class GameController:
    def __init__(self):
        pygame.init()
        self.__GameModel = GameModel(self)
        self.__GameView = GameView(self, self.__GameModel)
        self.__sounds = Sound()

    def start_screen(self):
        self.__sounds.princess_hit_sound()
        self.__sounds.background_sound()
        waiting = True
        while waiting:
            self.__GameView.draw_start_screen()
            self.start_events()

    def game_over_screen(self):
        self.__sounds.orc_sound()
        waiting = True
        new_highscore = False
        if self.__GameModel.score > self.__GameModel.highscore.data:
            self.__GameModel.highscore.new_hs(self.__GameModel.score)
            new_highscore = True

        self.__GameView.draw_game_over(new_highscore)
        #time.sleep para fazer com que a tela não desapareça mto rápido
        #um draw antes pra paralisar na tela correta
        time.sleep(1.1)
        while waiting:
            self.__GameView.draw_game_over(new_highscore)
            for sprite in self.__GameModel.all_sprites:
                sprite.kill()
            self.start_events()

    def win_screen(self):
        waiting = True
        new_highscore = False
        if self.__GameModel.score > self.__GameModel.highscore.data:
            self.__GameModel.highscore.new_hs(self.__GameModel.score)
            new_highscore = True

        self.__GameView.draw_win_screen(new_highscore)
        #time.sleep para fazer com que a tela não desapareça mto rápido
        #um draw antes pra paralisar na tela correta
        time.sleep(1.1)
        while waiting:
            self.__GameView.draw_win_screen(new_highscore)
            for sprite in self.__GameModel.all_sprites:
                sprite.kill()
            self.start_events()

    def start_game(self):
        self.__GameModel.score = 0
        self.__GameModel.load_map()

        playing = True
        while playing:
            self.game_events()
            self.__GameModel.update_positions()
            self.__GameView.draw_game()

            enemy_hits = pygame.sprite.spritecollide(
                self.__GameModel.princess, self.__GameModel.enemies, False,
                pygame.sprite.collide_mask)
            door_found = pygame.sprite.collide_rect(self.__GameModel.princess,
                                                    self.__GameModel.door_tile)

            if enemy_hits or door_found:
                if enemy_hits:
                    self.game_over_screen()
                if door_found:
                    self.win_screen()

    def game_events(self):
        # Eventos do jogo
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

    def start_events(self):
        #self.__sounds.background_sound()
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYUP:
                self.start_game()
Example #15
0
class Game(Foundation):
    """
    A class that is responsible for running the game and handling all the
    game related activities.
    """
    def __init__(self, caption=None, icon=None):
        super().__init__(caption, icon)
        self.snake = Snake()
        self.food = Food()
        self.food_consumed_sound = Sound("consumed.wav")
        self.death_sound = Sound("death.mp3")
        self.bg_sound = Sound("background.mp3")
        self.background = Background()
        self.play = False
        self.score = 0
        self.game_over = False
        self.delay = 3
        self.snake_die_time = None
        # self.bg = pygame.Surface((440, 440))

    def draw_grid(self):
        border = 0  # Settings.BLOCK_SIZE * 2 - 1
        h = Settings.SCREEN_HEIGHT - border
        w = Settings.SCREEN_WIDTH - border

        for row in range(border, h, Settings.BLOCK_SIZE):
            pygame.draw.line(self.screen, Colors.GREY.value, (border, row),
                             (w, row))

        for col in range(border, w, Settings.BLOCK_SIZE):
            pygame.draw.line(self.screen, Colors.GREY.value, (col, border),
                             (col, h))

    def play_game(self, key_pressed):
        """
        Start game on pressing the space bar key.
        :param key_pressed:
        :return: None
        """

        if key_pressed == K_SPACE and not self.play:
            self.snake.head_direction = 'Left'
            self.play = True
            # Setup the background sound but pause it by default
            self.bg_sound.play_sound(loops=-1, vol=0.01)
            self.bg_sound.pause_sound()
            self.background.create_background()

    def quit_game(self, key_pressed):
        """
        Quit game on pressing the escape key.
        :return: None
        """

        if key_pressed == K_ESCAPE:
            self.running = False

    def render_score(self):
        text = "Score: " + str(self.score)
        score_surf = self.font.render(text, True, Colors.GREY.value)
        score_surf.set_alpha(127)
        self.screen.blit(score_surf, (0, 0))

    def game_over_render_delay(self):
        current_time = pygame.time.get_ticks()
        if current_time >= self.snake_die_time + self.delay*1000:
            self.running = False

    def render_game_over(self):
        text = "Game Over!"
        game_over_surf = self.font.render(text, True, Colors.RED.value)
        surf_rect = game_over_surf.get_rect(center=self.screen.get_rect().center)
        self.screen.blit(game_over_surf, surf_rect)
        self.game_over_render_delay()

    def snake_hit_food(self):
        head = self.snake.blocks_pos[0]
        if head == self.food.position:
            self.food_consumed_sound.play_sound(vol=0.1)
            self.snake.increase_snake_length()
            self.score += 1
            return True
        return False

    def snake_hit_itself(self):
        head = self.snake.blocks_pos[0]
        if head in self.snake.blocks_pos[1:]:
            self.death_sound.play_sound(vol=0.3)
            pygame.time.delay(1000)
            # self.running = False
            self.play = False
            self.game_over = True
            self.snake_die_time = pygame.time.get_ticks()
            return True
        return False

    def update_game_state(self):
        """
        Update states of the game objects.
        :return: None
        """
        if self.play:
            self.background.update()
            hit_food = self.snake_hit_food()
            hit_itself = self.snake_hit_itself()
            if not hit_food and not hit_itself:
                self.snake.update()
            # Update food position until food is not one of the snake block
            if hit_food and not hit_itself:
                while True:
                    self.food.update()
                    if self.food.position not in self.snake.blocks_pos:
                        break

    def render_objects(self):
        """
        Draw all the game objects to the main game window/screen
        :return: None
        """

        self.screen.fill(Settings.BG_COLOR)  # Not needed if creating tiles.
        if self.play:
            # self.draw_grid()
            self.background.render(self.screen)
            self.snake.render(self.screen)
            self.food.render(self.screen)
            self.render_score()

        elif self.game_over:
            self.render_game_over()

        # Todo: Dirty rectangles
        pygame.display.flip()  # Updates the entire screen

    def handle_keydown_events(self, event):
        """
        Handle all key press events.
        :param event: Event requested by user
        :return: None
        """

        self.play_game(event.key)
        self.quit_game(event.key)

        if self.play:
            if event.key == K_RIGHT and self.snake.head_direction != 'Left':
                self.snake.head_direction = 'Right'
            elif event.key == K_LEFT and self.snake.head_direction != 'Right':
                self.snake.head_direction = 'Left'
            elif event.key == K_DOWN and self.snake.head_direction != 'Up':
                self.snake.head_direction = 'Down'
            elif event.key == K_UP and self.snake.head_direction != 'Down':
                self.snake.head_direction = 'Up'
            elif event.key == K_p:
                self.bg_sound.pause_sound()

    def handle_keyup_events(self, event):
        """
        Handle all key release events.
        :param event: Event requested by user
        :return: None
        """

        pass
Example #16
0
 def _play_sound(self):
     self._sound = Sound(self.get_single_path(), self.volume)
     self._sound.play(loop=self.loop)
Example #17
0
class SceneSound(object):
    def __init__(self, path):
        self.path = path
        self.loop = False
        self.start_at = 0
        self.volume = 100
        self.random = 0
        self.fade_in = 0
        self.workers = []
        self.stop_event = Event()
        self._sound = None
        self.bind_to = None
        self.auto_start = True

    def play(self):
        if self.start_at == 0:
            self._play_no_delay()
        else:
            p = Thread(target=self._play_delayed)
            self.workers.append(p)
            p.start()

    def play_now(self):
        self._play_no_delay(ignore_random=True)

    def stop(self):
        logger.debug("[%s] Received stop", self.path)
        self.stop_event.set()

        for process in self.workers:
            process.join()

        if self._sound is not None:
            self._sound.destroy()

        self.workers = []
        self.stop_event = Event()
        self._sound = None

    def get_single_path(self):
        """
        Returns the path of the file to play. The path can either be a string,
        or a list. In the latter case, one of the paths in the list will be
        picked randomly.
        """
        if isinstance(self.path, list):
            return random.choice(self.path)

        return self.path

    def _play_no_delay(self, ignore_random=False):
        # This is useful in the case where a thread comes out from sleep
        # and tries to play a sound while it has been stopped in the
        # meantime (eg. delayed play)
        if self.stop_event.is_set():
            logger.debug("[%s] Wanted to be played but not doing so"
                         " because it\'s been stopped", self.path)
            return

        if self.random == 0 or ignore_random:
            if self.fade_in > 0:
                logger.debug("[%s] Playing sound with volume=0 and running"
                             " fade in process", self.path)
                target_volume = self.volume
                self.volume = 0
                self._play_sound()

                p = Thread(target=self._fade_in, args=(target_volume,))
                self.workers.append(p)
                p.start()
            else:
                logger.debug("[%s] Playing", self.path)
                self._play_sound()
        else:
            # Random sounds can't be looped because it would make no sense
            self.loop = False

            logger.debug("[%s] Running random play thread", self.path)
            p = Thread(target=self._random)
            self.workers.append(p)
            p.start()

    def _play_sound(self):
        self._sound = Sound(self.get_single_path(), self.volume)
        self._sound.play(loop=self.loop)

    def _play_delayed(self):
        logger.debug("[%s] Delaying for %s seconds", self.path, self.start_at)
        self.stop_event.wait(self.start_at)
        logger.debug("[%s] It's time to play", self.path)
        self._play_no_delay()

    def _random(self):
        # We need to create a first instance of the sound to get its duration
        self._sound = Sound(self.get_single_path(), self.volume)
        sound_duration = self._sound.get_duration()

        while not self.stop_event.is_set():
            r = random.random()

            if r <= self.random:
                self._play_sound()

            self.stop_event.wait(sound_duration + 1)

        logger.debug('[%s] Stopping rand', self.path)

    def _fade_in(self, target_volume):
        step = 2
        step_delay = float(self.fade_in) / float(target_volume)

        while self.volume < target_volume and not self.stop_event.is_set():
            self._sound.set_volume(self.volume + step)
            self.volume += step
            self.stop_event.wait(step_delay)
Example #18
0
        cur_time = counter - (time.time() - start_time)
        output = "%d.%3d" % (cur_time,score)
#        print(output)
        leds.update(output)
        if cur_time <= 1 and not thread_started:
            print("start capture thread")
            cam_thread.start()
            thread_started = True

    cam_thread.join()
    detach_int()


if __name__ == '__main__':

    win_sound = Sound('win.wav')
    win_sound.play()
    end_sound = Sound('game_over.wav')
    start_sound = Sound('start.wav')
    #load high score
    #pickle.dump(0,open("score.pk",'wb'))
    try:
        high_score = pickle.load(open("score.pk",'rb'))
    except:
        high_score = 0

    print("high score = %d" % high_score)
    setup()
    leds = driver.driver()
    leds.set_pwm(max_pwm)
    while True:
Example #19
0
class Game:
    def __init__(self):
        pygame.init()
        self.background_sound = Sound()

        pygame.key.set_repeat(50, 50)
        size = [SCREEN_WIDTH, SCREEN_HEIGHT]

        self.screen = pygame.display.set_mode(size)
        pygame.display.set_caption(TITLE)

        self.clock = pygame.time.Clock()
        self.font_name = pygame.font.match_font(FONT)

        self.running = True
        self.isover = False
        self.gameispaused = False
        self.levels = {
            1: Level_01,
            2: Level_02,
            3: Level_03,
            4: Level_04,
            5: Level_05,
            6: Level_06,
            7: Level_07,
            8: Level_08,
            9: Level_09,
            10: Level_10
        }

        self.show_start_screen()

    def new(self, level=0):
        self.player = Player()
        self.active_sprite_list = pygame.sprite.Group()
        self.active_sprite_list.add(self.player)
        self.level = level + 1
        self.current_level = self.levels[self.level](self.player)
        self.player.level = self.current_level
        self.background_sound.next_song()
        self.run()

    def run(self):
        self.playing = True
        while self.playing:
            self.events()
            self.update()
            self.draw()
        self.end_game()

    def update(self):
        if self.player.iskill:
            self.playing = False
            self.isover = True
            self.gameover()
            return

        if not self.gameispaused and self.running:
            self.active_sprite_list.update()
            self.current_level.update()
            # If the player gets near the right side, shift the world left (-x)
            if self.player.rect.right >= 500:
                diff = self.player.rect.right - 500
                self.player.rect.right = 500
                self.current_level.shift_world(-diff)

            # If the player gets near the left side, shift the world right (+x)
            if self.player.rect.left <= 120:
                diff = 120 - self.player.rect.left
                self.player.rect.left = 120
                self.current_level.shift_world(diff)

            # If the player gets to the end of the level, go to the next level
            current_position = (self.player.rect.x +
                                self.current_level.world_shift)
            if current_position < self.current_level.level_limit:
                self.player.rect.x = 120
                if self.level < len(self.levels) - 1:
                    self.level += 1
                    self.current_level = self.levels[self.level](self.player)
                    self.player.level = self.current_level
                else:
                    self.end_screen()
        else:
            return

    def events(self):
        for bullet in self.player.bullets:
            for enemies in self.current_level.enemy_list:
                if (bullet.y - bullet.radius < enemies.rect.y + 147
                        and bullet.y + bullet.radius > enemies.rect.y):
                    if (bullet.x + bullet.radius > enemies.rect.x and
                            bullet.x - bullet.radius < enemies.rect.x + 52):
                        enemies.loseenergy(self.player.power)
                        if bullet in self.player.bullets:
                            self.player.bullets.remove(bullet)
            if bullet.x < SCREEN_WIDTH and bullet.x > 0:
                bullet.x += bullet.vel
            else:
                if bullet in self.player.bullets:
                    self.player.bullets.remove(bullet)

        for event in pygame.event.get():
            if event.type == pygame.USEREVENT:
                self.background_sound.next_song()
            if event.type == pygame.QUIT:
                if self.playing:
                    self.playing = False
                self.running = False
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_p:
                    self.gameispaused = True
                    self.pause_screen()

                if event.key == pygame.K_LEFT:
                    self.player.sprint(self.player.direction)
                    self.player.go_left()

                if event.key == pygame.K_RIGHT:
                    self.player.sprint(self.player.direction)
                    self.player.go_right()

                if event.key == pygame.K_UP:
                    self.last_key_pressed = pygame.K_UP
                    if self.level < 2:
                        self.draw_text(GRAVITY_WARN, 24, RED, SCREEN_WIDTH / 2,
                                       SCREEN_HEIGHT / 2)

                        self.draw_text(OPTIONS, 22, RED, SCREEN_WIDTH / 2,
                                       SCREEN_HEIGHT * 3 / 4)

                        pygame.display.flip()
                        self.wait_for_key()
                    else:
                        self.player.jump()

                if event.key == pygame.K_SPACE:
                    self.player.increasepower()
                    self.player.shoot()

                if event.key == pygame.K_DOWN:
                    self.player.invisibility()

            if event.type == pygame.KEYUP:
                self.player.stop()

    def draw(self):
        self.screen.fill(BLACK)
        self.current_level.draw(self.screen)
        font = pygame.font.SysFont(FONT, 20, True)

        if not self.player.invisible:
            self.active_sprite_list.draw(self.screen)
            text = font.render(HEALTH.format(self.player.health), 1, RED)

            self.screen.blit(
                text, (self.player.rect.x - 10, self.player.rect.y - 20))

            text = font.render(PRESS_ME, 1, WHITE)

            self.screen.blit(text, (SCREEN_WIDTH - 200, 10))

        for bullet in self.player.bullets:
            bullet.draw(self.screen)

        self.clock.tick(FPS)

        for enemies in self.current_level.enemy_list:
            enemies.draw(self.screen)
            if enemies.power is not 0:
                text = font.render(LEVEL.format(enemies.power), 1, WHITE)

                self.screen.blit(text,
                                 (enemies.rect.x - 10, enemies.rect.y - 20))

        pygame.display.flip()
        pygame.display.update()

    def show_start_screen(self):
        self.screen.fill(WHITE)

        self.draw_text(TITLE, 48, BLACK, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4)

        self.draw_text(START, 32, BLACK, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2)

        self.draw_text(TIP_LVL, 12, BLACK, SCREEN_WIDTH / 5,
                       SCREEN_HEIGHT - 21)

        pygame.display.flip()
        self.wait_for_key()

    def gameover(self):
        self.background_sound.stop_music()
        self.screen.fill(WHITE)
        self.draw_text(GAME_OVER, 48, BLACK, SCREEN_WIDTH / 2,
                       SCREEN_HEIGHT / 4)

        self.draw_text(OPTIONS, 22, BLACK, SCREEN_WIDTH / 2,
                       SCREEN_HEIGHT * 3 / 4)

        pygame.display.flip()
        self.wait_for_key()

    def pause_screen(self):
        self.current_level.tip(self.screen)
        self.draw_text(GAME_PAUSED, 22, WHITE, SCREEN_WIDTH / 2,
                       SCREEN_HEIGHT / 4)

        self.draw_text(OPTIONS, 22, WHITE, SCREEN_WIDTH / 2,
                       SCREEN_HEIGHT * 1 / 2)

        pygame.display.flip()
        self.wait_for_key()

    def wait_for_key(self):
        waiting = True
        while waiting:
            self.clock.tick(FPS)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    waiting = False
                    self.running = False
                if event.type == pygame.KEYUP:
                    if event.key == pygame.K_q:
                        self.running = False
                        self.playing = False
                        waiting = False

                    if event.key == pygame.K_RETURN:
                        waiting = False
                        if self.gameispaused:
                            self.gameispaused = False
                        if self.isover:
                            self.isover = False
                            self.new()

    def end_screen(self):
        self.screen.fill(WHITE)
        self.isover = True
        self.draw_text(GAME_WIN, 40, BLACK, SCREEN_WIDTH / 2,
                       SCREEN_HEIGHT / 2)

        self.draw_text(OPTIONS, 22, BLACK, SCREEN_WIDTH / 2,
                       SCREEN_HEIGHT * 3 / 4)

        pygame.display.flip()
        self.wait_for_key()

    def draw_text(self, text, size, color, x, y):
        font = pygame.font.Font(self.font_name, size)
        text_surface = font.render(text, True, color)
        text_rect = text_surface.get_rect()
        text_rect.midtop = (x, y)
        self.screen.blit(text_surface, text_rect)

    def end_game(self):
        if self.isover and not self.running:
            pygame.quit()