Пример #1
0
def game_start():
    # initialisations
    pygame.init()
    status = functions.Status()
    st = Settings()

    screen = pygame.display.set_mode(st.screen_size)
    pygame.display.set_caption(st.screen_name)

    func = functions.Fucntions(st, screens.get_func_surface(screen, st))
    sqs = Squares(st, status, screens.get_sqs_surface(screen, st))

    AI = AI_player.AI()
    # main loop
    while True:
        pygame.display.flip()
        events.check_events(sqs, status, AI)
        if status.is_game_active():
            if sqs.update():
                screens.update_screen(screen, sqs, func, status, st)
        elif status.is_game_over():
            interface.game_over(screen, st)
        elif status.is_game_new():
            interface.start(screen, st)
        elif status.is_game_renew():
            AI_mode = status.new_AI
            status.refresh()
            status.game_status = status.ACTIVE
            sqs = Squares(st, status, screens.get_sqs_surface(screen, st))
            st = Settings()
            if AI_mode:
                status.AI = True
                sqs.st.adjust_for_AI()
        else:
            raise RuntimeError  # this should never happen
Пример #2
0
def run_game():
    pygame.init()
    # создание всех объектов
    (dt, clock, setting, animation, background_animation, screen, tiles, test,
     characters, healths, background_full, camera,
     idd) = challenging_objects()
    # основной цикл
    i = 0
    S = 0
    while True:
        # события
        events.check_events(test, setting, screen, characters, camera,
                            animation, healths, idd)

        # столкновения

        test.collide(characters, tiles)
        if len(characters) > 0:
            for character in characters:
                character.collide(tiles)

        # отображение
        display.update_screen(setting, screen, test, characters,
                              background_full, healths)

        test.update_test(dt)
        camera.move(characters, test)

        # счетчик времени для отображения
        dt = clock.tick(setting.fps)
Пример #3
0
def run_game():
    """
	Glowna funkcja gry
	"""
    size = int(input("Podaj ilosc pol w zakresie 3 - 10: "))
    while (size < 3 or size > 10):
        size = int(input("Podaj ilosc pol w zakresie 3 - 10: "))
    winCombo = int(
        input(
            "Podaj ilosc znakow w rzedzie wygrywajacych w zakresie od 3 do ilosci pol: "
        ))
    while (winCombo < 3 or winCombo > size):
        winCombo = int(
            input(
                "Podaj ilosc znakow w rzedzie wygrywajacych w zakresie od 3 do ilosci pol: "
            ))
    pg.init()  #inicjalizacja fukcji biblioteki PyGame
    wd = window.Window(size, winCombo)  #inicjalizacja okna gry
    wd.winArr()  #stworzenie wygrywajacych ukladow
    wd.draw_area()  #rysowanie planszy
    gm = game.Game(wd, winCombo)  #inicjalizacja mechaniki gry
    while True:
        events.check_events(wd, gm, size)  #sprawdzanie wydarzen
        wd.update_area(gm)  #odswiezanie planszy
        pg.display.update()  #wyswietlanie aktualnego stanu
Пример #4
0
 def paint(self, lcoord, pattern, c, border, background):
     """ Fill an area defined by a border attribute with a tiled pattern. """
     # 4-way scanline flood fill: http://en.wikipedia.org/wiki/Flood_fill
     # flood fill stops on border colour in all directions; it also stops on scanlines in fill_colour
     # pattern tiling stops at intervals that equal the pattern to be drawn, unless this pattern is
     # also equal to the background pattern.
     c, border = self.get_attr_index(c), self.get_attr_index(border)
     solid = (pattern is None)
     if not solid:
         tile = self.screen.mode.build_tile(pattern) if pattern else None
         back = self.screen.mode.build_tile(background) if background else None
     else:
         tile, back = [[c]*8], None
     bound_x0, bound_y0, bound_x1, bound_y1 = self.get_view()
     x, y = self.view_coords(*self.get_window_physical(*lcoord))
     line_seed = [(x, x, y, 0)]
     # paint nothing if seed is out of bounds
     if x < bound_x0 or x > bound_x1 or y < bound_y0 or y > bound_y1:
         return
     self.last_point = x, y
     # paint nothing if we start on border attrib
     if self.screen.get_pixel(x,y) == border:
         return
     while len(line_seed) > 0:
         # consider next interval
         x_start, x_stop, y, ydir = line_seed.pop()
         # extend interval as far as it goes to left and right
         x_left = x_start - len(self.screen.get_until(x_start-1, bound_x0-1, y, border))
         x_right = x_stop + len(self.screen.get_until(x_stop+1, bound_x1+1, y, border))
         # check next scanlines and add intervals to the list
         if ydir == 0:
             if y + 1 <= bound_y1:
                 line_seed = self.check_scanline(line_seed, x_left, x_right, y+1, c, tile, back, border, 1)
             if y - 1 >= bound_y0:
                 line_seed = self.check_scanline(line_seed, x_left, x_right, y-1, c, tile, back, border, -1)
         else:
             # check the same interval one scanline onward in the same direction
             if y+ydir <= bound_y1 and y+ydir >= bound_y0:
                 line_seed = self.check_scanline(line_seed, x_left, x_right, y+ydir, c, tile, back, border, ydir)
             # check any bit of the interval that was extended one scanline backward
             # this is where the flood fill goes around corners.
             if y-ydir <= bound_y1 and y-ydir >= bound_y0:
                 line_seed = self.check_scanline(line_seed, x_left, x_start-1, y-ydir, c, tile, back, border, -ydir)
                 line_seed = self.check_scanline(line_seed, x_stop+1, x_right, y-ydir, c, tile, back, border, -ydir)
         # draw the pixels for the current interval
         if solid:
             self.screen.fill_interval(x_left, x_right, y, tile[0][0])
         else:
             interval = tile_to_interval(x_left, x_right, y, tile)
             self.screen.put_interval(self.screen.apagenum, x_left, y, interval)
         # allow interrupting the paint
         if y%4 == 0:
             events.check_events()
     self.last_attr = c
Пример #5
0
 def loop(self):
     """ Run read-eval-print loop until control returns to user after a command. """
     try:
         while True:
             self.last_mode = state.basic_state.parse_mode, state.basic_state.auto_mode
             if state.basic_state.parse_mode:
                 try:
                     # may raise Break
                     events.check_events()
                     self.handle_basic_events()
                     # returns True if more statements to parse
                     if not statements.parse_statement():
                         state.basic_state.parse_mode = False
                 except error.RunError as e:
                     self.trap_error(e)
                 except error.Break as e:
                     # ctrl-break stops foreground and background sound
                     state.console_state.sound.stop_all_sound()
                     self.handle_break(e)
             elif state.basic_state.auto_mode:
                 try:
                     # auto step, checks events
                     self.auto_step()
                 except error.Break:
                     # ctrl+break, ctrl-c both stop background sound
                     state.console_state.sound.stop_all_sound()
                     state.basic_state.auto_mode = False
             else:
                 self.show_prompt()
                 try:
                     # input loop, checks events
                     line = console.wait_screenline(from_start=True)
                     self.prompt = not self.store_line(line)
                 except error.Break:
                     state.console_state.sound.stop_all_sound()
                     self.prompt = False
                     continue
             # change loop modes
             if self.switch_mode():
                 break
     except error.RunError as e:
         self.handle_error(e)
         self.prompt = True
     except error.Exit:
         raise
     except error.Reset:
         raise
     except Exception as e:
         if debug.debug_mode:
             raise
         debug.bluescreen(e)
Пример #6
0
    def files(self, pathmask):
        """ Write directory listing to console. """
        # forward slashes - file not found
        # GW-BASIC sometimes allows leading or trailing slashes
        # and then does weird things I don't understand.
        if b'/' in bytes(pathmask):
            raise error.RunError(error.FILE_NOT_FOUND)
        if not self.path:
            # undefined disk drive: file not found
            raise error.RunError(error.FILE_NOT_FOUND)
        drivepath, relpath, mask = self._native_path_elements(pathmask, path_err=error.FILE_NOT_FOUND)
        path = os.path.join(drivepath, relpath)

        mask = mask.upper() or b'*.*'
        # output working dir in DOS format
        # NOTE: this is always the current dir, not the one being listed
        dir_elems = [join_dosname(*short_name(path, e)) for e in self.cwd.split(os.sep)]
        console.write_line(self.letter + b':\\' + b'\\'.join(dir_elems))
        fils = []
        if mask == b'.':
            dirs = [split_dosname((os.sep+relpath).split(os.sep)[-1:][0])]
        elif mask == b'..':
            dirs = [split_dosname((os.sep+relpath).split(os.sep)[-2:][0])]
        else:
            all_names = safe(os.listdir, path)
            dirs = [filename_from_unicode(n) for n in all_names if os.path.isdir(os.path.join(path, n))]
            fils = [filename_from_unicode(n) for n in all_names if not os.path.isdir(os.path.join(path, n))]
            # filter according to mask
            dirs = filter_names(path, dirs + [b'.', b'..'], mask)
            fils = filter_names(path, fils, mask)
        if not dirs and not fils:
            raise error.RunError(error.FILE_NOT_FOUND)
        # format and print contents
        output = (
              [(b'%-8s.%-3s' % (t, e) if (e or not t) else b'%-8s    ' % t) + b'<DIR>' for t, e in dirs]
            + [(b'%-8s.%-3s' % (t, e) if e else b'%-8s    ' % t) + b'     ' for t, e in fils])
        num = state.console_state.screen.mode.width // 20
        while len(output) > 0:
            line = b' '.join(output[:num])
            output = output[num:]
            console.write_line(line)
            # allow to break during dir listing & show names flowing on screen
            events.check_events()
        console.write_line(b' %d Bytes free' % self.get_free())
Пример #7
0
def list_line(line, newline=True):
    """ Print a line from a program listing or EDIT prompt. """
    # no wrap if 80-column line, clear row before printing.
    # flow of listing is visible on screen
    events.check_events()
    # replace LF CR with LF
    line = line.replace('\n\r', '\n')
    cuts = line.split('\n')
    for i, l in enumerate(cuts):
        # clear_line looks back along wraps, use clear_rest_of_line instead
        clear_rest_of_line(state.console_state.row, 1)
        write(str(l))
        if i != len(cuts)-1:
            write('\n')
    if newline:
        write_line()
    # remove wrap after 80-column program line
    if len(line) == state.console_state.screen.mode.width and state.console_state.row > 2:
        state.console_state.screen.apage.row[state.console_state.row-3].wrap = False
Пример #8
0
 def run(self, command, run, quit, wait):
     """ Interactive interpreter session. """
     if command:
         self.store_line(command)
         self.loop()
     if run:
         # position the pointer at start of program and enter execute mode
         flow.jump(None)
         state.basic_state.parse_mode = True
         state.console_state.screen.cursor.reset_visibility()
     try:
         try:
             while True:
                 self.loop()
                 if quit and state.console_state.keyb.buf.is_empty():
                     break
         except error.Exit:
             # pause before exit if requested
             if wait:
                 signals.video_queue.put(signals.Event(signals.VIDEO_SET_CAPTION, 'Press a key to close window'))
                 signals.video_queue.put(signals.Event(signals.VIDEO_SHOW_CURSOR, False))
                 state.console_state.keyb.pause = True
                 # this performs a blocking keystroke read if in pause state
                 events.check_events()
         finally:
             # close interfaces
             signals.video_queue.put(signals.Event(signals.VIDEO_QUIT))
             signals.message_queue.put(signals.Event(signals.AUDIO_QUIT))
             # persist unplayed tones in sound queue
             state.console_state.tone_queue_store = [
                     signals.save_queue(q) for q in signals.tone_queue]
             state.save()
             # close files if we opened any
             devices.close_files()
             devices.close_devices()
     except error.Reset:
         # delete state if resetting
         state.delete()
Пример #9
0
def run_game():
    pygame.init()
    ai_set = Settings()
    bullet_grp = Group()
    aliens_grp = Group()

    screen = pygame.display.set_mode(
        (ai_set.screen_width, ai_set.screen_height))
    pygame.display.set_caption("Space Invadors")
    screen.fill(ai_set.bg_color)
    button = Button(screen, ai_set, "Play")
    stats = GameStats(ai_set, screen)

    ai_ship = Ship(screen)
    ai_alien = Alien(screen)

    # Mathematics of number of aliens and formation.
    x_space = (ai_set.screen_width - 2 * (ai_alien.rect.width))
    aliens_per_line = x_space / (2 * (ai_alien.rect.width))
    create_fleet(screen, aliens_per_line, ai_alien, aliens_grp)

    while True:
        check_events(ai_ship, screen, ai_set, bullet_grp, button)
        screen.fill(ai_set.bg_color)
        ai_ship.draw_ship()
        draw_bullets(bullet_grp, aliens_grp, ai_set, stats)
        if (ai_set.game_active == 1):
            if (len(aliens_grp) == 0):
                bullet_grp.empty()
                create_fleet(screen, aliens_per_line, ai_alien, aliens_grp)
                recenter_ship(ai_ship)
            for every_b in bullet_grp.sprites():
                every_b.update_bullet()
        else:
            button.draw_button()
        draw_fleet(aliens_grp, ai_set, ai_ship)
        stats.show_stats()
        pygame.display.flip()
Пример #10
0
    wall = Wall(settings, screen)
    particles = Group()
    events.create_gas(settings, screen, particles, wall)

    #Sets clock (used for fixed FPS) and timer (used to count collision rate)
    clock = pygame.time.Clock()
    pygame.time.set_timer(pygame.USEREVENT + 1, 1000)

    info = Info(settings, screen)
    info.prep_collisions()

    keepGoing = True
    while keepGoing:
        clock.tick(30) #30 FPS

        events.check_events(screen, settings, particles, info, wall)
        particles.clear(screen, background)

        for particle in particles:
            particle.update(wall) #updates vel and pos
            if particle.collision:
                info.collision_rate += 1
                particle.collision = False

        screen.fill(settings.bg_color) #cleans screen
        particles.draw(screen)
        wall.draw(screen)

        info.prep(wall, total_kinetic_energy(particles), len(particles))
        info.show()
Пример #11
0
def get_agent_and_check_events(account):
    agent = create_agent(account)
    check_events(account)
    return agent
Пример #12
0
def run_game():
    # initialize fonts
    clock = pygame.time.Clock()

    # initialize sound mixer
    pygame.mixer.pre_init(44100, -16, 2, 512)
    pygame.mixer.init()

    pygame.init()

    screen = pygame.display.set_mode((WIDTH, HEIGHT))

    # to hold all tiles from the map
    platforms_top = Group()
    platforms_bottom = Group()
    left_walls = Group()
    right_walls = Group()

    # actual game objects
    floor_tiles = Group()
    brick_tiles = Group()
    mystery_tiles = Group()
    pole = Group()
    fireballs = Group()
    pipes = Group()
    metal_tiles = Group()
    coins = Group()

    # background objects
    clouds = Group()
    hills = Group()
    bushes = Group()
    castle = Group()

    # create a viewport and pass all objects into it for
    # easier management
    viewport = Group()

    entity_gamemaster = EntityGameMaster()
    enemy_gamemaster = EnemyGameMaster()

    gui = GUI(screen)

    mario = Mario(screen, entity_gamemaster, gui)

    # create our map level and all objects within it
    map = Map(screen, 'resources/map.txt', platforms_top, platforms_bottom,
              left_walls, right_walls, floor_tiles, brick_tiles, mystery_tiles,
              pole, clouds, hills, bushes, pipes, metal_tiles, castle,
              enemy_gamemaster, mario, entity_gamemaster)

    # pass all objects groups into viewport so that they get updated with mario x movement creating a scrolling effect
    viewport.add(platforms_top)
    viewport.add(platforms_bottom)
    viewport.add(left_walls)
    viewport.add(right_walls)
    viewport.add(floor_tiles)
    viewport.add(brick_tiles)
    viewport.add(mystery_tiles)
    viewport.add(pole)
    viewport.add(clouds)
    viewport.add(hills)
    viewport.add(bushes)
    viewport.add(pipes)
    viewport.add(metal_tiles)
    viewport.add(castle)

    viewport.add(entity_gamemaster.fireflowers)
    viewport.add(entity_gamemaster.mushrooms)
    viewport.add(entity_gamemaster.one_up_mushrooms)
    viewport.add(entity_gamemaster.starmen)

    viewport.add(enemy_gamemaster.goombas)
    viewport.add(enemy_gamemaster.koopas)

    pygame.mixer.Channel(5).play(
        pygame.mixer.Sound('resources/sounds/themesong.wav'))

    while True:
        screen.fill(LIGHTBLUE)

        entity_gamemaster.update()

        e.check_events(mario, platforms_top, screen, fireballs, viewport)
        e.check_collisions(screen, mario, platforms_top, platforms_bottom,
                           left_walls, right_walls, fireballs, mystery_tiles,
                           brick_tiles, entity_gamemaster, viewport)

        # each collision part is independently handled------------------
        platforms_top.update()
        platforms_bottom.update()
        left_walls.update()
        right_walls.update()
        # --------------------------------------------------------------

        # actual game objects, images, sprites, etc..d..................
        floor_tiles.update()
        brick_tiles.update()
        coins.update()
        mystery_tiles.update()
        pole.update()
        clouds.update()
        hills.update()
        bushes.update()
        pipes.update()
        metal_tiles.update()
        castle.update()
        enemy_gamemaster.update()

        fireballs.update(platforms_top, left_walls, right_walls,
                         enemy_gamemaster)
        # -------------------------------------------------------------

        mario.update(viewport, pole)
        gui.show_score()
        pygame.display.flip()
        clock.tick(60)
Пример #13
0
def get_agent_and_check_events (account):
    agent = create_agent(account)
    check_events(account)
    return agent