Esempio n. 1
0
    def attack(self, entity_lst):
        if self._inventory['equipment']['arm'] is not None:
            self._current_animation = 'attack'
            if self.__attack_count == 0:
                self._frame = 0
                self.__attack_count = 6
            elif self.__attack_count == 6:
                self.__attack_count = 12
            elif self.__attack_count == 12:
                self.__attack_count = FC_HERO_ATTACK

            for entity in entity_lst:
                if isinstance(entity, Monster):
                    if self.__side == RIGHT and self.position.x + 64 / TILE_SIZE[
                            0] <= entity.position.x <= self.position.x + 95 / TILE_SIZE[
                                0] and self.position.y - 13 <= entity.position.y <= self.position.y + 45 / TILE_SIZE[
                                    1]:
                        entity._health -= self._damage
                        if not entity.isDead():
                            Sounds().hit.play()
                    elif self.__side == LEFT and self.position.x - 61 / TILE_SIZE[
                            0] <= entity.position.x <= self.position.x - 32 / TILE_SIZE[
                                0] and self.position.y - 13 <= entity.position.y <= self.position.y + 45 / TILE_SIZE[
                                    1]:
                        entity._health -= self._damage
                        if not entity.isDead():
                            Sounds().hit.play()
Esempio n. 2
0
 def process_input(self, key, symbol, state: GameState, menu: Menu):
     if self.section == 'pause':
         if key == K_DOWN:
             self.__choice += 1
             Sounds().menu_selection.play()
             if self.__choice > 2:
                 self.__choice = 0
         elif key == K_UP:
             self.__choice -= 1
             Sounds().menu_selection.play()
             if self.__choice < 0:
                 self.__choice = 2
         elif key == K_RETURN:
             self.__select(menu)
         elif key == K_ESCAPE:
             self.__choice = 0
             self.is_active = False
             pygame.mixer.music.unpause()
     elif self.section == 'save':
         if key == K_RETURN:
             state.save(self.__savename)
             self.__savename = ''
             self.section = 'pause'
             self.is_active = False
             Sounds().menu_selection.play()
             pygame.mixer.music.unpause()
         elif key == K_BACKSPACE:
             self.__savename = self.__savename[:-1]
         else:
             self.__savename += symbol
Esempio n. 3
0
def apply(state):
    editor = SoundEditor(state)
    for cur in editor:
        next = cur.next
        if next.value is None:
            continue

        x, y = cur.value, next.value
        if x in Sounds('ac'):
            cur.value, next.value = ac_sandhi(x, y)
        elif x in Sounds('hal'):
            cur.value, next.value = hal_sandhi(x, y)

    yield editor.join()
Esempio n. 4
0
def hal_sandhi(x, y):
    """Apply the rules of hal sandhi to `x` as followed by `y`.

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

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

    # 6.1.66 lopo vyor vali
    if x in Sounds('v y') and y in Sounds('val'):
        x = ''

    return x, y
Esempio n. 5
0
def al_tasya(target, result):
    target = Sounds(target)
    result = Sounds(result)

    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)
    return func
 def _check_play_button(self, mouse_pos):
     """Запускает новую игру при нажатии кнопки Play."""
     button_clicked = self.play_button.rect.collidepoint(mouse_pos)
     if button_clicked and not self.stats.game_active:
         # Сброс игровых настроек.
         self.settings.initialize_dynamic_settings()
         # Сброс игровой статистики.
         self.stats.reset_stats()
         self.stats.game_active = True
         # Обнуление статистики
         self.sb.prep_score()
         # Отображение текущего уровня
         self.sb.prep_level()
         # отображение оставшихся кораблей игрока
         self.sb.prep_ships()
         # Очистка списков пришельцев и снарядов.
         self.aliens.empty()
         self.bullets.empty()
         # Создание нового флота и размещение корабля в центре.
         self._create_fleet()
         self.ship.center_ship()
         # Указатель мыши скрывается.
         pygame.mouse.set_visible(False)
         # Запускаем музыку сражения
         fighting_music = Sounds('sounds/fighting.mp3')
         fighting_music.playing_music()
Esempio n. 7
0
def run_game():
    # Initialize pygame, settings, and screen object.
    pygame.mixer.pre_init(44100, -16, 2, 2048)
    pygame.mixer.init()
    pygame.init()
    game_settings = GameSettings()
    screen = pygame.display.set_mode((game_settings.screen_width, game_settings.screen_height))
    pygame.display.set_caption("Pac Man Portal")

    # Open sprite sheet
    sprite_sheet = SpriteSheet(file_name='images/spritesheet.png')

    # Make the Play and Scores button.
    play_button = Button(screen=screen, msg="Play", order=0)
    score_button = Button(screen=screen, msg="High Scores", order=1)

    # Open high score file
    try:
        high_score_file = open("high_score_file.txt", "r+")
    except FileNotFoundError:
        high_score_file = open("high_score_file.txt", "w+")

    # Open maze layout file
    maze_file = open('mazelayout.txt', 'r')

    # Make sound manager
    sounds = Sounds()

    # Initialize game stats and scoreboard
    stats = GameStats(game_settings=game_settings)
    sb = Scoreboard(screen=screen, game_settings=game_settings, stats=stats, sprite_sheet=sprite_sheet,
                    high_score_file=high_score_file, sounds=sounds)

    # Initialize pacman
    pacman = Pacman(screen=screen, game_settings=game_settings, stats=stats, sb=sb,
                    image_list=sprite_sheet.pacman_image, death_anim_list=sprite_sheet.pacman_death_image,
                    sounds=sounds)

    # Initialize maze
    maze = Maze(screen=screen, game_settings=game_settings, maze_file=maze_file, sprite_sheet=sprite_sheet,
                pacman=pacman, sounds=sounds)

    # Initialize the event handler
    event_handler = EventHandler(pacman=pacman, play_button=play_button, score_button=score_button, stats=stats, sb=sb,
                                 maze=maze, sounds=sounds)

    # Initialize the display manager
    display = Display(screen=screen, game_settings=game_settings, stats=stats, sb=sb, sprite_sheet=sprite_sheet,
                      play_button=play_button, score_button=score_button, maze=maze, pacman=pacman,
                      event_handler=event_handler, sounds=sounds)

    # Start the main loop for the game
    while True:
        event_handler.check_events()
        if stats.game_active:
            pacman.update(maze=maze, display=display)
            maze.update_ghosts()
            maze.update_bullets()
            maze.update_portals()
        display.update_screen()
Esempio n. 8
0
    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Pacman Portal")
        self.screen = pygame.display.set_mode((800, 600))
        self.maze = Maze(screen=self.screen, maze_map_file='pacmanportalmaze.txt')
        self.clock = pygame.time.Clock()
        self.ghost_sounds = Sounds(sound_files=['ghost-blue.wav', 'ghost-eaten.wav', 'ghost-std.wav'],
                                                keys=['blue', 'eaten', 'std'],
                                                channel=Ghost.audio)

        self.stock = PacmanLives(screen=self.screen, ct_pos=((self.screen.get_width() // 3),
                                                                      (self.screen.get_height() * 0.965)),
                                          images_size=(self.maze.block_size, self.maze.block_size))
        self.score = ScoreController(screen=self.screen,
                                            sb_pos=((self.screen.get_width() // 5),
                                                    (self.screen.get_height() * 0.965)),
                                            items_image='cherry.png',
                                            itc_pos=(int(self.screen.get_width() * 0.6),
                                                     self.screen.get_height() * 0.965))
        self.next_level = NextLevel(screen=self.screen, score_controller=self.score)
        self.game_over = True
        self.pause = False
        self.player = Pacman(screen=self.screen, maze=self.maze)
        self.ghosts = Group()
        self.ghost_time = 2500
        self.ghosts_stack = None
        self.top_ghost = None
        self.arr_ghost = []
        self.spawn_ghosts()
        self.events = {PacmanPortal.START_EVENT: self.init_ghosts, PacmanPortal.REBUILD_EVENT: self.rebuild_maze, PacmanPortal.LEVEL_EVENT: self.clear_level}
    def __init__(self):
        """ iniciando el juego y recursos"""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion by David")

        self.bg_x = self.settings.bg_x_pos

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()

        self.sounds = Sounds()

        self.alien = Alien(self)
        self.aliens = pygame.sprite.Group()
        self._create_fleet()

        # crea el boton
        self.play_button = Button(self, 'Jugar')

        # crea una instancia de game stats
        self.stats = GameStats(self)
        # crea una insancia de Score
        self.sb = Scoreboard(self)
Esempio n. 10
0
def start_game():

    #needs to be called before pygame.init
    pygame.mixer.pre_init(22050, -16, 2, 1024)

    window = Window()
    window.init()

    pygame.init()

    sounds = Sounds()
    sounds.init()
    window.sounds = sounds
    pygame.mixer.set_num_channels(32)

    # meta game loop
    while True:
        sounds.play_music("intro", loop=1)
        intro_main(window, handle_events)

        # so we can mix more channels at once.  pygame defaults to 8.
        #sounds.play("jump1")
        #sounds.play("hit1")
        #sounds.play("goal1")
        sounds.set_music_tracks(['track-one', 'track-two'])

        world = World()
        world.stage = 2
        populate(world, window)

        def count_leaves():
            no_leaves = 0
            for item in world.items:
                if item.role == "Bough":
                    no_leaves = no_leaves + 1
            return no_leaves

        CleanUp_Event = pygame.event.Event(CLEANUP,
                                           message="Cleaning Up Your shit")
        pygame.time.set_timer(CLEANUP, 1000)

        TickTock = pygame.event.Event(
            TICK_TOCK, message="TickTock goes the Ticking Clock")
        pygame.time.set_timer(TICK_TOCK, int(90000 / count_leaves()))

        AddCherry = pygame.event.Event(ADDCHERRY, message="Ooooo Cherry")
        pygame.time.set_timer(ADDCHERRY, int(90000 / 5))

        AddOwange = pygame.event.Event(ADDOWANGE, message="Ooooo owange")
        pygame.time.set_timer(ADDOWANGE, int(1000 * 5))

        for i in range(3):
            event.post(AddOwange)

        pygame.time.set_timer(BIRDY, 1000 * 7)

        render = Render(window, world)
        quit = runloop(window, world, render)
        if quit:
            return
Esempio n. 11
0
    def __init__(self):
        """Initialize the game, and create game resources"""
        pygame.init()

        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption("Alien Invasion")

        # self.screen = pygame.display.set_mode((0,0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_hight = self.screen.get_rect().height

        # Create an instance to store game statistics,
        # and create a scoreboard.
        self.stats = GameStats(self)
        self.sb = Scoreboard(self)
        self.sounds = Sounds(self)

        self.ship = Ship(self)
        self.bullets = pygame.sprite.Group()
        self.aliens = pygame.sprite.Group()

        self._create_fleet()

        # Make the Play button.
        self.play_button = Button(self, "Play")
Esempio n. 12
0
def run_game():
    # Initialize pygame, settings, screen object, music channel
    pygame.init()
    sounds = Sounds()

    # Limit FPS
    clock = pygame.time.Clock()

    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    pygame.display.set_caption("Alien Invasion")

    # Create an instance to store game statistics and create a scoreboard.
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Create the start and highscore screen
    start_screen = StartScreen(ai_settings, screen)
    hs_screen = HighScoreScreen(ai_settings, screen, stats)

    # Make a ship, a group of ship_bullets, and a group of aliens
    ship = Ship(screen, ai_settings)
    ship_bullets = Group()
    aliens = Group()
    alien_bullets = Group()
    bunkers = Group()

    # Create the fleet of aliens and row of bunkers
    gf.create_fleet(ai_settings, screen, ship, aliens)
    gf.create_bunker_row(ai_settings, screen, ship, bunkers)

    # Start the main loop for the game
    while True:

        # Limit FPS
        clock.tick(60)

        # Watch for keyboard/mouse events
        gf.check_events(ai_settings, screen, stats, sb, start_screen, ship,
                        aliens, ship_bullets, sounds, bunkers, hs_screen)

        if stats.game_active:
            ship.update(stats.ships_left)
            ship_bullets.update()
            alien_bullets.update()
            bunkers.update()

            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bunkers, ship_bullets, alien_bullets, sounds)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             ship_bullets, alien_bullets, sounds)

        # Redraw the screen during each pass through the loop.
        # Make the most recently drawn screen visible
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens,
                         ship_bullets, alien_bullets, start_screen, bunkers,
                         hs_screen)
Esempio n. 13
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)
Esempio n. 14
0
def samyogapurva(term):
    """Filter on whether a term's final sound follows a conjunct."""
    value = term.value
    hal = Sounds('hal')
    try:
        return value[-3] in hal and value[-2] in hal
    except IndexError:
        return False
Esempio n. 15
0
def samyogadi(term):
    """Filter on whether a term begins with a conjunct."""
    value = term.value
    hal = Sounds('hal')
    try:
        return value[0] in hal and value[1] in hal
    except IndexError:
        return False
Esempio n. 16
0
def ekac(term):
    seen = False
    ac = Sounds('ac')
    for L in term.value:
        if L in ac:
            if seen:
                return False
            seen = True
    return True
Esempio n. 17
0
    def __kill_entities(self, entity_lst, i=0):
        if i == len(entity_lst):
            return

        if entity_lst[i].isDead():
            entity_lst.remove(entity_lst[i])
            Sounds().death.play()
            self.__kill_entities(entity_lst, i)
        else:
            self.__kill_entities(entity_lst, i + 1)
Esempio n. 18
0
 def __init__(self, w, h):
     pygame.init()
     self.size = w, h
     self.screen = pygame.display.set_mode(self.size)
     pygame.display.set_caption(TITLE)
     pygame.display.flip()
     self.hero_is_died = pygame.sprite.Sprite()
     self.hero_is_died.image = pygame.image.load("data/hero_died.png")
     self.hero_is_died.rect = self.hero_is_died.image.get_rect()
     self.hero_is_win = pygame.sprite.Sprite()
     self.hero_is_win.image = pygame.image.load("data/win.png")
     self.hero_is_win.rect = self.hero_is_died.image.get_rect()
     self.dead = pygame.sprite.Group()
     self.win_sp = pygame.sprite.Group()
     self.hero_is_win.add(self.win_sp)
     self.hero_is_died.add(self.dead)
     self.camera = Camera(w, h)
     self.win_m, self.dead_m = False, False
     self.music = [
         pygame.mixer.Sound("data/background_music_1.ogg"),
         pygame.mixer.Sound("data/background_music_2.ogg"),
         pygame.mixer.Sound("data/background_music_3.ogg")
     ]
     self.menu_music = pygame.mixer.Sound("data/music/main_menu.ogg")
     self.victory_music = pygame.mixer.Sound("data/Victory.wav")
     self.dead_music = pygame.mixer.Sound("data/dead.wav")
     self.menu_music.play(-1)
     self.hero_sprite = pygame.sprite.Group()
     self.enemy_sprites = pygame.sprite.Group()
     self.boss_sprite = pygame.sprite.Group()
     self.platform_sprites = pygame.sprite.Group()
     self.all_sprites = pygame.sprite.Group()
     self.princess_sprite = pygame.sprite.Group()
     self.info_sprites = pygame.sprite.Group()
     self.background_sprite = pygame.sprite.Group()
     self.buttons = pygame.sprite.Group()
     self.level_names = ["intro", "1", "2", "final"]
     self.level_state = 0
     self.new_game_btn = Button(self.buttons, "new_game_btn.png",
                                "new_game_btn_2.png", 208, 93,
                                "bookFlip2.ogg", "new_game")
     self.hero = Hero(self.hero_sprite, 60, 60,
                      Sounds().return_dict_of_sounds())
     self.hero.add(self.all_sprites)
     self.cursor_group = pygame.sprite.Group()
     self.cursor = Cursor(self.cursor_group)
     self.main_menu = True
     self.bg = Background(self.background_sprite)
     self.main_img = pygame.image.load("data/main_menu.png")
     pygame.mouse.set_visible(False)
     self.clock = pygame.time.Clock()
     self.fps = 40
     self.just_music = None
     self.left_state, self.up_state, self.attack = None, None, None
     self.running = True
Esempio n. 19
0
 def __select(self, menu: Menu):
     if self.__choice == 0:
         self.is_active = False
         pygame.mixer.music.unpause()
     elif self.__choice == 1:
         self.section = 'save'
     elif self.__choice == 2:
         menu.is_active = True
         self.is_active = False
     self.__choice = 0
     Sounds().select.play()
Esempio n. 20
0
    def __init__(self, modes):
        GPIO.setmode(
            GPIO.BCM)  #set up to use gpio port numbers (instead of pin #s)

        self.buttons = Buttons()
        self.optos = Optos()
        self.lights = Lights()
        self.outlets = Outlets()
        self.sounds = Sounds()
        self.clock = Countdown(12)

        self.modes = modes
        self.last_time = time.localtime()
Esempio n. 21
0
    def __init__(self):
        # 初始化
        pygame.init()

        # 设置
        self.settings = Settings()
        self.screen = pygame.display.set_mode(
            (self.settings.screen_width, self.settings.screen_height))
        pygame.display.set_caption(self.settings.caption)

        self.stats = Stats(self)
        self.sounds = Sounds(self)

        self.bullets = Group()  # 创建子弹编组

        self.player = Player(self)  # 创建玩家

        self.zombies = Group()  # 创建僵尸组
        #self.zombies.add(Zombie(self, (random()*200, random()*200)))

        self.level_control = Level_Control(self)

        self.ui = Group()  # 创建UI组
        self.ui.add(Scoreboard(self))  # 向UI组中添加计分板
        self.ui.add(Weapon_UI(self))  # 向UI组中添加武器状态
        self.ui.add(self.level_control)

        self.framerate = pygame.time.Clock()  # 实例化一个时钟对象

        while True:
            # 主循环
            self.framerate.tick(60)  # 设置60帧刷新

            self.check_events()

            if self.stats.restart:
                print('Restart')
                break

            if not self.stats.paused:
                self.update()

                if self.stats.game_over:
                    self.game_over()
                    print('Game Over')
                    break

            self.draw()

        with open(self.settings.score_path, 'w') as score_file:
            score_file.write(str(self.stats.highscore))
Esempio n. 22
0
 def process_input(self, key, state: GameState):
     if self.section == 'Main menu':
         if key == K_DOWN:
             self.__choice += 1
             Sounds().menu_selection.play()
             if self.__choice > 4:
                 self.__choice = 0
         elif key == K_UP:
             self.__choice -= 1
             Sounds().menu_selection.play()
             if self.__choice < 0:
                 self.__choice = 4
         elif key == K_RETURN:
             self.__select(state)
     elif self.section == 'Load save':
         if key == K_DOWN:
             self.__choice += 1
             Sounds().menu_selection.play()
             if self.__choice > len(Caretaker().saves) - 1:
                 self.__choice = 0
         elif key == K_UP:
             self.__choice -= 1
             Sounds().menu_selection.play()
             if self.__choice < 0:
                 self.__choice = len(Caretaker().saves) - 1
         elif key == K_RETURN:
             state.load(Caretaker().get_save(self.__savename))
             self.__choice = 0
             self.section = 'Main menu'
             self.is_active = False
             pygame.mixer.music.play(loops=-1, start=2)
         elif key == K_ESCAPE:
             self.__choice = 0
             self.section = 'Main menu'
     elif self.section == 'Hotkeys':
         pass
     elif self.section == 'Authors':
         pass
Esempio n. 23
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))
Esempio n. 24
0
 def __init__(self, screen, user, maze):
     self.screen = screen
     self.maze = maze
     self.user = user
     self.sounds = Sounds(
         sound_files=['portal-open.wav', 'portal-travel.wav'],
         keys=['open', 'travel'],
         channel=PortalController.PORTAL_AUDIO_CHANNEL)
     self.blue_portal = pygame.sprite.GroupSingle(
     )  # portals as GroupSingle, which only allows one per group
     self.blue_projectile = None
     self.orange_portal = pygame.sprite.GroupSingle()
     self.orange_projectile = None
     self.portal_directions = {'l': 'r', 'r': 'l', 'u': 'd', 'd': 'u'}
Esempio n. 25
0
def run_game():
    # create a screen and launch the game
    pygame.mixer.pre_init(44100, -16, 16, 2048)
    pygame.mixer.init()
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))

    pygame.display.set_caption("Alien Invasion")
    play_button = Button(ai_settings, screen, "Play")
    # make a ship, bullet, alien
    sounds = Sounds()
    images = Images()
    bullets = Group()
    aliens = Group()
    stars = Group()
    powerups = Group()
    ship = Ship(ai_settings, screen, images)
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    counter = Counter(ai_settings, screen, stats)

    # create a fleet
    if stats.game_active:
        gf.create_stars(ai_settings, screen, stars)
        gf.create_powerup(ai_settings, screen, powerups)

    # main game loop

    while True:
        gf.check_events(ai_settings, screen, stats, play_button, ship, bullets, sounds, images)
        gf.update_screen(ai_settings, screen, stats, sb, stars, ship, aliens, bullets,
                         play_button, counter, powerups, sounds)
        if stats.game_active:
            gf.update_bullets(ai_settings, screen, ship, aliens, bullets, sb, stats, sounds)
            gf.create_stars(ai_settings, screen, stars, images)
            gf.create_powerup(ai_settings, screen, powerups, images)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets, images)
            gf.update_stars(stars, ai_settings)
            gf.update_powerup(powerups, ai_settings)
            gf.update_timer(ai_settings)
            gf.powerup_check(ship, powerups, ai_settings, images, sounds, stats)
            bullets.update()
            stars.update()
            powerups.update()
            aliens.update()
            ship.update(bullets, ai_settings, screen, ship, sounds, images)
            screen.fill(ai_settings.bg_color)
Esempio n. 26
0
    def update(self):
        self._frame += 1

        if self._current_animation == 'attack':
            self._image = Assets().hero_animations[self._current_animation][
                self.frame // 4 % FC_HERO_ATTACK]
            if self.frame == 9 or self.frame == 29 or self.frame == 49:
                Sounds().sword_swing.play()
            if self.frame == 4 * self.__attack_count:
                self._frame = 0
                self.__attack_count = 0
                self._current_animation = 'move'
                self._image = Assets().hero_animations[
                    self._current_animation][FC_HERO_MOVE * int(
                        bool(self._inventory['equipment']['arm']))]
Esempio n. 27
0
 def __select(self, state: GameState):
     if self.__choice == 0:
         state.__init__()
         pygame.mixer.music.play(loops=-1, start=2)
         self.is_active = False
     elif self.__choice == 1:
         self.section = 'Load save'
     elif self.__choice == 2:
         self.section = 'Hotkeys'
     elif self.__choice == 3:
         self.section = 'Authors'
     elif self.__choice == 4:
         exit()
     self.__choice = 0
     Sounds().select.play()
Esempio n. 28
0
    def __init__(self):
        """Initialize game."""
        pygame.mixer.pre_init(44100, 16, 1, 4096)
        pygame.init()

        # Sound Channels.
        self.music_channel = pygame.mixer.Channel(1)

        self.screen = pygame.display.set_mode((800, 720))
        pygame.display.set_caption('Tetris')

        if platform.system() == 'Windows':
            # Ensure correct screen size to be displayed on Windows.
            ctypes.windll.user32.SetProcessDPIAware()

        # Game objects.
        self.settings = Settings()
        self.utils = Utilities(self.settings)
        self.sounds = Sounds()
        self.game_stats = GameStats(self.sounds)
        self.board = Board(self.screen, self.settings, self.sounds)
        self.scoreboard = Scoreboard(self.screen, self.settings,
                                     self.game_stats)
        self.music_selection = MusicSelection(self.screen, self.settings,
                                              self.sounds, self.music_channel)

        # Tetris shapes.
        self.current_shape = Shape(self.screen, self.settings, self.sounds,
                                   self.utils)
        self.next_shape = Shape(self.screen, self.settings, self.sounds,
                                self.utils, 600, 520)

        # Game flags.
        self.title_screen = True
        self.controls_screen = True
        self.select_music_screen = True
        self.game_over = False
        self.high_score_screen = True
        self.show_fps = False
        self.pause = False
        self.music_pause = False

        # Make a clock object to set fps limit.
        self.clock = pygame.time.Clock()

        # Database connection.
        self.db = DBConnection()
Esempio n. 29
0
 def __init__(self):
     self.bg = pygame.image.load("images/bg.jpg")
     self.bg = pygame.transform.scale(self.bg,
                                      (SCREEN_WIDTH, SCREEN_HEIGHT))
     self.bgrect = self.bg.get_rect()
     self.ball = Ball()
     self.human = Human()
     self.robot = Robot()
     self.goal = Goal(0)
     self.win = Win(0)
     self.lose = Lose(0)
     self.menu = Menu()
     self.mouse = (0, 0)
     self.sounds = Sounds()
     self.sounds.music()
     self.status = Game.MENU
     self.reset()
 def __init__(self, screen, score_controller, transition_time=5000):
     self.screen = screen
     self.score_controller = score_controller
     self.sound = Sounds(['pacman-beginning.wav'],
                         keys=['transition'],
                         channel=NextLevel.audio,
                         volume=0.6)
     self.font = pygame.font.Font('fonts/LuckiestGuy-Regular.ttf', 32)
     self.ready_msg = self.font.render('Get Ready!', True, Scoreboard.white)
     self.ready_msg_rect = self.ready_msg.get_rect()
     ready_pos = screen.get_width() // 2, int(screen.get_height() * 0.65)
     self.ready_msg_rect.centerx, self.ready_msg_rect.centery = ready_pos
     self.level_msg = None
     self.level_msg_rect = None
     self.transition_time = transition_time
     self.transition_begin = None
     self.transition_show = False