Example #1
0
def run_game():
    # 初始化游戏并创建窗口对象
    pygame.init()
    ai_settings = Settings()
    # 创建一个surface对象,surface是屏幕的一部分,用于显示游戏元素(外星人或飞船)
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    ship = Ship(ai_settings, screen)
    bullets = Group()  # 在主循环外创建元素组,避免同时创建过多元素阻塞了主循环
    aliens = Group()
    stats = GameStats(ai_settings)
    play_button = Button(ai_settings, screen, "Play")
    score_board = Scoreboard(ai_settings, screen, stats)
    clock = pygame.time.Clock()
    gf.create_fleet(ai_settings, screen, ship, aliens)

    while True:
        gf.check_events(ai_settings, screen, stats, score_board, ship, bullets,
                        play_button)  # 监控输入设备事件

        if stats.game_active:
            ship.update()
            gf.update_bullets(bullets)  # 更新子弹数据
            gf.update_aliens(ai_settings, stats, screen, aliens, ship, bullets)
            gf.check_bullet_alien_collisions(ai_settings, screen, stats, ship,
                                             aliens, bullets, score_board)
            gf.check_alien_ship_collisions(ai_settings, stats, screen, aliens,
                                           ship, bullets)
        gf.update_screen(ai_settings, screen, stats, ship, bullets, aliens,
                         play_button, score_board)  # 动态更新窗口(背景及元素)
        clock.tick(30)
Example #2
0
def run_game():
    pygame.init()
    # 设置size
    screen = pygame.display.set_mode((1200, 800))
    # 设置title
    pygame.display.set_caption('Alien')
    # init ship
    ship = Ship(screen)
    # init monster
    monster = Group()
    bullets = Group()
    # 随机怪物的数量
    monsters_num = random.uniform(0, 10)
    gf.create_alien(screen, monster, monsters_num)
    while True:
        # 检测键盘事件
        gf.check_events(ship, screen, bullets)
        # 改变自己位置
        ship.update()
        bullets.update()
        monster.update()
        for bullet in bullets.copy():
            if bullet.rect.bottom <= 0:
                print("删除消失的子弹")
                bullets.remove(bullet)
        # 判断怪物是不是被杀死了
        gf.check_bullet_alien_collisions(screen, monster, bullets)
        # 如果自己移动,重绘屏幕
        gf.update_screen(screen, ship, bullets, monster)
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    ship = Ship(screen, ai_settings)
    bullets = Group()
    aliens = Group()
    stats = GameStats(ai_settings)
    play_button = Button(ai_settings, screen, "Play")
    sb = Scoreboard(ai_settings, screen, stats)

    gf.create_fleet(ai_settings, screen, aliens, ship)

    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(bullets)
            gf.check_bullet_alien_collisions(ai_settings, screen, stats, sb,
                                             ship, aliens, bullets)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                             bullets)

        gf.update_screen(ai_settings, screen, stats, ship, aliens, bullets,
                         play_button, sb)
Example #4
0
def run_game():
    #初始化游戏并创建一个屏幕对象
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # create a ship
    ship = Ship(ai_settings, screen)

    # set the color of background
    bg_color = ai_settings.bg_color

    # 创建一个用于存储子弹的编组,一个外星人编组
    bullets = Group()
    aliens = Group()

    # 创建外星人群
    # alien = Alien(ai_settings, screen)
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Start the game's main loop
    while True:

        # monitor the keyboard events
        gf.check_events(ai_settings, screen, ship, bullets)
        ship.update()
        gf.update_bullets(bullets)
        gf.update_aliens(ai_settings, aliens)
        gf.check_bullet_alien_collisions(ai_settings, screen, ship, aliens,
                                         bullets)

        #  redraw the screen at every iteration
        gf.update_screen(ai_settings, screen, ship, aliens, bullets)
Example #5
0
 def test_fleet_regeneration_and_level_up(self):
     """Fleet should be recreated when it's len reaches zero."""
     self.aliens.empty()
     prev_ship_speed = self.ai_settings.ship_speed_factor
     gf.check_bullet_alien_collisions(self.ai_settings, self.screen,
                                      self.ship, self.aliens, self.bullets)
     actual = (self.ai_settings.ship_speed_factor > prev_ship_speed
               and len(self.aliens) > 0)
     self.assertEqual(True, actual)
Example #6
0
def update_bullets(ai_game):
    """
    Update the position of the bullets and get rid of old bullets
    """
    # Update the bullets position
    ai_game.bullets.update()

    # Get rid of the bullets that have disappeared
    for bullet in ai_game.bullets.copy():
        if bullet.rect.bottom <= 0:
            ai_game.bullets.remove(bullet)

    # Check for collisions and fleet destruction
    game_functions.check_bullet_alien_collisions(ai_game)
Example #7
0
def run_game():
    # Initialize game and create a screen object.
    pygame.init()

    # Create settings instance
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Make the play button
    play_button = Button(ai_settings, screen, "Play")

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

    # Make a ship, a group of bullets, and a group of aliens.
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()
    stars = Group()

    # Create the fleet of aliens.
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # # Create stars
    # gf.create_stars(ai_settings, screen, stars)

    # Start the main loop for the game.
    while True:

        # Respond to keyboard and mouse events.
        gf.check_events(ai_settings, screen, stats, sb, ship, aliens, bullets,
                        play_button)

        if stats.game_active:
            ship.update()
            # Update bullets positions and get rid of old bullets.
            gf.update_bullets(bullets)
            gf.check_bullet_alien_collisions(ai_settings, screen, stats, sb,
                                             ship, bullets, aliens)
            gf.update_aliens(ai_settings, stats, screen, sb, aliens, ship,
                             bullets)
            # gf.update_stars(stars)

        # Update images on the screen and flip to the new screen.
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button, stars)
Example #8
0
def run_game():

    #初始化游戏并创建一个屏幕对象
    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 按钮
    play_button = Button(ai_settings, screen, "Play")

    #创建一个用于存储游戏统计信息的实例
    stats = GameStats(ai_settings)

    #创建记分牌
    sb = Scoreboard(ai_settings, screen, stats)

    #创建一艘飞船
    ship = Ship(ai_settings, screen)

    #创建一个存储子弹的编组
    bullets = Group()

    #创建外星人编组
    aliens = Group()

    gf.create_fleet(ai_settings, screen, ship, aliens)

    #开始游戏的主循环
    while True:
        gf.check_events(ai_settings, screen, stats, play_button, ship, aliens,
                        bullets, sb)
        if stats.game_active:
            ship.update()
            bullets.update()
            gf.update_bullets(bullets)
            gf.update_aliens(ai_settings, screen, stats, ship, aliens, bullets,
                             sb)
            gf.check_bullet_alien_collisions(ai_settings, screen, ship, aliens,
                                             bullets, stats, sb)
        gf.update_screen(ai_settings, screen, stats, ship, aliens, bullets,
                         play_button, sb)
Example #9
0
def run_game():
    # 初始化并创建一个屏幕对象
    pygame.init()
    ai_setting = Settings()
    screen = pygame.display.set_mode(
        (ai_setting.screen_width, ai_setting.screen_height))
    pygame.display.set_caption('Alien Invasion')

    # 创建一艘飞船
    ship = Ship(ai_setting, screen)
    # 创建一个储存子弹的编组
    bullets = Group()
    # 创建一个储存外星人的编组
    aliens = Group()
    # 创建外星人群
    gf.creat_fleet(ai_setting, screen, ship, aliens)
    # 创建游戏统计信息和记分牌
    stats = GameStats(ai_setting)
    sb = ScoreBoard(ai_setting, screen, stats)
    # 创建按钮
    play_button = Button(ai_setting, screen, "Play")

    # 开始游戏主循环
    while True:
        # 检查鼠标键盘事件
        gf.check_events(ai_setting, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        # 判断游戏是否失败
        if stats.game_active:
            # 更新飞船位置
            ship.update()
            # 更新子弹位置
            gf.update_bullets(ai_setting, screen, stats, sb, ship, bullets,
                              aliens)
            # 更新外星人位置
            gf.update_aliens(ai_setting, stats, sb, screen, ship, aliens,
                             bullets)
            # 检查子弹与外星人的碰撞
            gf.check_bullet_alien_collisions(ai_setting, screen, stats, sb,
                                             ship, bullets, aliens)
            # 检查飞船与外星人的碰撞
            gf.check_alien_condition(ship, aliens)
        # 刷新屏幕
        gf.update_screen(ai_setting, screen, stats, sb, ship, bullets, aliens,
                         play_button)
Example #10
0
def run_game():
    # инициализация игры , settings и объекта экрана
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")

    # Создание экземпляра для хранения игровой статистики и создаём экзмпляр счёта
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Создание корабля.

    ship = Ship(ai_settings, screen)

    # создание группы пуль
    bullets = Group()

    # создание кнопки play
    play_button = Button(ai_settings, screen, "играть")

    # создание группы пришельцев
    aliens = Group()

    # создание флота пришельцев
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # Запуск основного цикла игры.
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.check_bullet_alien_collisions(ai_settings, screen, stats, sb,
                                             ship, aliens, bullets)
            gf.update_aliens(ai_settings, stats, sb, screen, ship, aliens,
                             bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Example #11
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption('Alien Invasion')

    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    # gf.create_fleet(ai_settings, screen, ship, aliens)

    stats = GameStats(ai_settings)
    play_button = Button(ai_settings, screen, 'Play')
    sb = ScoreBoard(ai_settings, screen, stats)

    gf.init_game(ai_settings, stats, sb)

    while True:
        t0 = time()
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            ship.update()
            gf.update_bullets(bullets)
            gf.update_aliens(ai_settings, aliens)
            # 子弹碰撞外星人
            gf.check_bullet_alien_collisions(ai_settings, screen, stats, sb,
                                             ship, aliens, bullets)
            # 外星人碰撞飞船
            gf.check_ship_hit(ai_settings, stats, sb, screen, ship, bullets,
                              aliens)

        gf.update_screen(ai_settings, screen, stats, ship, bullets, aliens,
                         play_button, sb)
        t = time() - t0
        if t < 0.01:
            sleep(0.01 - t)
        else:
            print(t)
Example #12
0
def run_game():
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption('Alien invasion')

    bullets = Group()
    aliens = Group()
    ticker = pygame.time.Clock()

    ship = Ship(ai_settings, screen)
    gf.weapons_init(ai_settings, screen, ship, bullets, aliens)

    buttons = Group()
    stats = GameStats(screen, ai_settings)

    gf.create_fleet(ai_settings, screen, ship, aliens, stats.alien_level)
    start_button = StartButton(ai_settings, screen, 'Start!', stats, ship)
    buttons.add(start_button)

    while True:
        gf.check_events(ai_settings, screen, ship, bullets, buttons)

        if stats.game_active:
            ship.move()
            ship.restore()
            gf.update_bullets(ai_settings, screen, ship, bullets, aliens)
            gf.update_weapon(ship)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)
            gf.check_bullet_alien_collisions(ai_settings, screen, stats, ship,
                                             aliens, bullets)
            stats.scoreboard -= 0.1

        gf.update_screen(ai_settings, screen, ship, aliens, bullets, stats,
                         buttons)
        gf.clear_bullets(ai_settings, bullets)
        ticker.tick(ai_settings.default_fps)
Example #13
0
def run_game():
    # initialize game and create a screen object
    pygame.init()
    pygame.mixer.music.load('sounds/crossing_the_chasm.mp3')
    pygame.mixer.music.play(-1)
    ai_settings = Settings()  # Settings instance
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption('Alien Invasion')
    # make the play button
    play_button = Button(ai_settings, screen, 'Play')
    # create an instance to store game statistics
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)
    # make a ship, a group of bullets, and a group of aliens
    ship = Ship(ai_settings, screen)
    bullets = Group()
    aliens = Group()

    # Create the fleet of aliens
    gf.create_fleet(ai_settings, screen, ship, aliens)

    # start the main loop for the game
    while True:
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens,
                              bullets)
            gf.check_bullet_alien_collisions(ai_settings, screen, stats, sb,
                                             ship, aliens, bullets)
            gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens,
                             bullets)

        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
Example #14
0
def run_game():
    ''' Функция сoздает игрoвые oбъекты, настраивает их и запускает игрoвoй цикл. '''
    # Инициализирует игру.
    pygame.init()
    # Инициализируем oбъект класса Settings, хранящий настрoйки игры.
    ai_settings = settings.Settings()
    # Инициализирует пoверхнoсть для oтрисoвки кадрoв.
    icon = pygame.image.load('images/icon.png')
    pygame.display.set_icon(icon)
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    pygame.display.set_caption("Alien Invasion")
    ''' Сoздаем игрoвые oбъекты. '''
    # Cоздаем экземпляр игровой статистики.
    stats = GameStats(ai_settings)
    # Cоздаем корабль.
    ship = Ship(ai_settings, screen)
    # Сoздаем группу для хранения всех пуль.
    bullets = Group()
    # Группа для хранения пришельцев.
    aliens = Group()
    # Cоздание флота пришельцев.
    gf.create_fleet(ai_settings, screen, ship, aliens)
    # Создание корабля.
    # Группа для хранения фонoвых oбъектoв.
    backgrounds = Group()
    # Сoздаем начальный фoн, кoтoрый затем запустит самooрганизацию фoна.
    start_bg1 = Background(ai_settings, screen, -ai_settings.bg_speed)
    # Дoбавляем егo в группу фoнoв.
    backgrounds.add(start_bg1)
    # Загружаем изoбражения для анимирoваннoгo спрайта.
    images = []
    for i in range(0, 4):
        text = 'images/fire/{0}.png'.format(i)
        images.append(pygame.image.load(text))
    # Загружаем изoбражения для взрыва.
    images_explosion = []
    for i in range(0, 13):
        text = 'images/explosion/{0}.png'.format(i)
        images_explosion.append(pygame.image.load(text))
    # Группа для хранения VFX.
    vfxs = Group()
    # Группа для взрывoв.
    exps = Group()
    # Сoздаем VFX-oбъекты и дoбавляем их в группу.
    for x in ship.fire_x:
        new_vfx = FireFX(screen, images, 4, x, (ship.rect.top + 1))
        vfxs.add(new_vfx)
    # Создаю часы для фиксации FPS.
    clock = pygame.time.Clock()
    # Сoздание кнoпки 'Play'.
    play_button = Button(ai_settings, screen, 'Play')
    ''' Запуск oснoвнoгo цикла игры. '''
    while True:
        # Фиксирую FPS игры.
        clock.tick(120)
        # Прoверка действий игрoка и реакция на них.
        gf.check_events(ai_settings, stats, screen, play_button, ship, aliens,
                        bullets, exps)
        ''' Части игры, которые выполняются лишь при game_active = True. '''
        if stats.game_active == True:

            # Расчеты для прoрисoвки нoвoгo кадра.
            gf.update_bg(backgrounds, ai_settings, screen)
            ship.update()
            # пули рисуются на фoне, нo пoд кoраблем
            gf.fire_cooldown(ship)
            gf.fire_bullet(ai_settings, screen, ship, bullets, vfxs)
            gf.update_bullets(ai_settings, screen, ship, aliens, bullets)
            gf.update_aliens(ai_settings, stats, screen, ship, aliens, bullets)
            gf.check_bullet_alien_collisions(ai_settings, ship, bullets,
                                             aliens, screen, images_explosion,
                                             4, exps)
            # Расчеты для эффектoв oгня.
            gf.update_count_frames(vfxs)
            gf.update_indeces(vfxs)
            gf.update_frames(vfxs, ship)
            # Расчеты для взрывoв.
            gf.update_lifetimes(exps)
            gf.delete_exps(exps)
            gf.update_count_frames(exps)
            gf.update_indeces(exps)
            gf.update_frames_exps(exps)
        ''' Прорисовка нового кадра. '''
        gf.update_screen(ai_settings, stats, screen, ship, aliens, bullets,
                         backgrounds, vfxs, exps, play_button)