Пример #1
0
def main(language_set=None):
    """
    Begin an interactive annotation session, where you are played snippets of
    audio in different languages and you have to mark whether or not they are
    representative samples.
    """
    _validate_language_set(language_set)

    metadata = load_metadata(language_set=language_set)
    session = Session()

    ui.clear_screen()
    ui.pause('Beginning annotation, press ENTER to hear the first clip...')

    for segment in RandomSampler(metadata, DEFAULT_DURATION_S,
                                 MAX_PER_SAMPLE):
        ann, quit = annotate(segment, session.user, metadata)

        if ann is not None:
            save_annotation(segment.sample, ann, metadata)
            session.annotated += 1

        else:
            print('Skipping...')
            session.skipped += 1

        print()

        if quit:
            break

    session.summarize()
Пример #2
0
def main(language_set=None):
    """
    Begin an interactive annotation session, where you are played snippets of
    audio in different languages and you have to mark whether or not they are
    representative samples.
    """
    _validate_language_set(language_set)

    metadata = load_metadata(language_set=language_set)
    session = Session()

    ui.clear_screen()
    ui.pause('Beginning annotation, press ENTER to hear the first clip...')

    for segment in RandomSampler(metadata, DEFAULT_DURATION_S, MAX_PER_SAMPLE):
        ann, quit = annotate(segment, session.user, metadata)

        if ann is not None:
            save_annotation(segment.sample, ann, metadata)
            session.annotated += 1

        else:
            print('Skipping...')
            session.skipped += 1

        print()

        if quit:
            break

    session.summarize()
Пример #3
0
def update(code, state):
    if code in k_exit \
            or (state.menu == ui.menu_main and code in k_esc) \
            or (blt.check(k_ctrl) and code == blt.TK_Q):
        ui.exit_game()

    if state.menu:
        if code in k_n:
            state.index = (state.index - 1) % len(state.menu.buttons)
        elif code in k_s:
            state.index = (state.index + 1) % len(state.menu.buttons)
        elif code in k_enter:
            state.menu.buttons[state.index].func(state)
        else:
            return False
    else:
        if code in k_esc:
            ui.pause(state)
        elif code in m_move:
            select_loc(state)
        elif code in k_center + k_enter + m_click:
            move(state)
        elif code in k_sw:
            select_add((1, -1), state)
        elif code in k_s:
            select_add((1, 0), state)
        elif code in k_se:
            select_add((1, 1), state)
        elif code in k_w:
            select_add((0, -1), state)
        elif code in k_e:
            select_add((0, 1), state)
        elif code in k_nw:
            select_add((-1, -1), state)
        elif code in k_n:
            select_add((-1, 0), state)
        elif code in k_ne:
            select_add((-1, 1), state)
        else:
            return False

    return True
Пример #4
0
def choose():
    inputs = ui.get_inputs(["Please enter a number"], "")
    option = inputs[0]
    table = data_manager.get_table_from_file(FILE_NAME)
    if option == '0':
        return False
    try:
        function_name = OPTIONS[int(option)-1][FUNCTION_INDEX]
        result = execute_function(function_name, table)
        if function_name == 'show_table':
            ui.pause()
        label = common.match_label(function_name)
        if label:
            ui.print_result(result, label)
    except IndexError:
        ui.print_error_message('There is no such option')
    except ValueError:
        ui.print_error_message('There is no such option')
    data_manager.write_table_to_file(FILE_NAME, table)
    return True
Пример #5
0
def main(language_set=None, strategy=None, only=None):
    """
    Begin an interactive annotation session, where you are played snippets of
    audio in different languages and you have to mark whether or not they are
    representative samples.
    """
    if only:
        is_language_included = set([only]).__contains__
    else:
        _validate_language_set(language_set)
        is_language_included = generate_language_filter(language_set)

    metadata = load_metadata(is_language_included)
    session = Session()

    ui.clear_screen()
    ui.pause('Beginning annotation, press ENTER to hear the first clip...')

    sampler = (GreedySampler(metadata, DEFAULT_DURATION_S, MAX_PER_SAMPLE)
               if strategy == 'greedy'
               else RandomSampler(metadata, DEFAULT_DURATION_S, MAX_PER_SAMPLE))

    for segment in sampler:
        ann, quit = annotate(segment, session.user, metadata)

        if ann is not None:
            save_annotation(segment.sample, ann, metadata)
            session.annotated += 1

        else:
            print('Skipping...')
            session.skipped += 1

        print()

        if quit:
            break

    session.summarize()
Пример #6
0
def main(language_set=None, strategy=None, only=None):
    """
    Begin an interactive annotation session, where you are played snippets of
    audio in different languages and you have to mark whether or not they are
    representative samples.
    """
    if only:
        is_language_included = set([only]).__contains__
    else:
        _validate_language_set(language_set)
        is_language_included = generate_language_filter(language_set)

    metadata = load_metadata(is_language_included)
    session = Session()

    ui.clear_screen()
    ui.pause('Beginning annotation, press ENTER to hear the first clip...')

    sampler = (GreedySampler(metadata, DEFAULT_DURATION_S, MAX_PER_SAMPLE)
               if strategy == 'greedy' else RandomSampler(
                   metadata, DEFAULT_DURATION_S, MAX_PER_SAMPLE))

    for segment in sampler:
        ann, quit = annotate(segment, session.user, metadata)

        if ann is not None:
            save_annotation(segment.sample, ann, metadata)
            session.annotated += 1

        else:
            print('Skipping...')
            session.skipped += 1

        print()

        if quit:
            break

    session.summarize()
    def start(self):
        """
        Starts the dscript for the current location.
        This method is called everytime the player moves to the location.
        """
        if self.has_changed:
            # If the location has changed since last visit, display examine text and run new
            # intro sequence if exists
            # TODO: Change from displaying examine text to a time printout like in PW:AA
            ui.speech_box(self.examine_text, dismissable=False)
            ui.pause(3)
            ui.clear_speech_box()

            # This allows you to have an intro where the player talks to
            # themself, but no other character is present
            if self.dscript:
                ui.read_dialog_script(self.dscript.get_intro())
            self.has_changed = False

        action = ui.display_actions(self, self.character)
        self.determine_action(action)
        # endlessly start this location until we move
        self.start()
Пример #8
0
def display_table(table):
    show_table(table)
    ui.pause()
Пример #9
0
# Or should it be [9, 0]?
#start = [random.randint(0, w - 1), random.randint(0, h - 1)]
start = [9, 0]
spaces[start[0]][start[1]] = 8

# Setup
board = map.Map(w, h)
p = ai.AIPlayer()
#p = player.Player()

# Initialisation
board.initialise(spaces)
p.setPos(board.getStart())

board.show(p)

# Loop
ui.pause()
while p.getPos() != goal:
    if (p.move(board)):
        ui.cls()
        board.show(p)
        ui.printThreats(p.getPos(), board)
    else:
        ui.suicide()
        break
if (p.getPos() == goal):
    ui.cls()
    board.show(p)
    ui.reachedGoal()
ui.pause()
Пример #10
0
 def show_guidelines(self, message):
     print(message)
     ui.pause()
     page(GUIDELINES)
     self.seen_guidelines = GUIDELINE_VERSION
     self.save()
Пример #11
0
def game(server, settings, benchmarks):
    dt = 0  # Tick
    df = 0  # Frame
    dc = 0  # Cursor
    ds = 0  # Selector
    dpos = False
    dinv = False  # Inventory
    dcraft = False  # Crafting
    FPS = 15  # Max
    MPS = 15  # Movement
    SPS = 5  # Mob spawns

    old_bk_objects = None
    old_edges = None
    redraw_all = True
    last_move = time()
    last_mob_spawn = time()
    inp = None
    jump = 0
    cursor = 0
    crafting = False
    crafting_sel = 0
    crafting_list = []
    inv_sel = 0
    cursor_hidden = True
    new_blocks = {}
    alive = True
    events = []

    crafting_list, crafting_sel = player.get_crafting(
        server.inv,
        crafting_list,
        crafting_sel
    )

    # Game loop
    with NonBlockingInput() as nbi:
        while server.game:
            x, y = server.pos
            dt = server.dt()
            frame_start = time()

            ## Input

            char = True
            inp = []
            while char:
                # Receive input if a key is pressed
                char = nbi.char()
                if char:
                    char = str(char).lower()

                    if char in 'wasdhkjliuoc-=\n ':
                        inp.append(char)

            # Hard pause
            if DEBUG and '\n' in inp:
                input()
                inp.remove('\n')

            # Pause game
            if ' ' in inp or '\n' in inp:
                server.redraw = True
                redraw_all = True
                if ui.pause(server, settings) == 'exit':
                    server.logout()
                    continue

            width = settings.get('width')
            height = settings.get('height')

            # Update player and mobs position / damage
            move_period = 1 / MPS
            while frame_start >= move_period + last_move and x in server.map_:

                dx, dy, jump = player.get_pos_delta_on_input(
                    inp, server.map_, x, y, jump, settings.get('flight'))
                if dx or dy:
                    dpos = True
                    x += dx
                    y += dy

                if x in server.map_ and not settings.get('flight'):
                    # Player falls when no solid block below it and not jumping
                    jump -= dt
                    if jump <= 0:
                        jump = 0
                        if not terrain.is_solid(server.map_[x][y + 1]):
                            # Fall
                            y += 1
                            dpos = True

                if 'h' in inp:
                    item = render.blocks[server.inv[inv_sel]['block']] if len(server.inv) else {}
                    server.player_attack(item.get('attack_radius', 5), item.get('attack_damage', 10))

                server.update_items()
                server.update_mobs()

                if server.health <= 0:
                    alive = False

                last_move += move_period

            ## Update Map

            # Finds display boundaries
            edges = (x - int(width / 2), x + int(width / 2))
            edges_y = (y - int(height / 2), y + int(height / 2))

            if edges_y[1] > data.world_gen['height']:
                edges_y = (data.world_gen['height'] - height, data.world_gen['height'])
            elif edges_y[0] < 0:
                edges_y = (0, height)

            extended_edges = (edges[0]-render.max_light, edges[1]+render.max_light)

            slice_list = terrain.detect_edges(server.map_, extended_edges)
            if slice_list:
                log('slices to load', slice_list)
                chunk_list = terrain.get_chunk_list(slice_list)
                server.get_chunks(chunk_list)
                server.unload_slices(extended_edges)

            # Moving view
            if not edges == old_edges or server.view_change:
                extended_view = terrain.move_map(server.map_, extended_edges)
                old_edges = edges
                server.redraw = True
                server.view_change = False

            # Sun has moved
            bk_objects, sky_colour, day = render.bk_objects(server.time, width, edges[0], settings.get('fancy_lights'))
            if not bk_objects == old_bk_objects:
                old_bk_objects = bk_objects
                server.redraw = True

            if settings.get('gravity'):
                blocks = terrain.apply_gravity(server.map_, extended_edges)
                if blocks: server.set_blocks(blocks)

            ## Crafting

            if 'c' in inp:
                server.redraw = True
                crafting = not crafting and len(crafting_list)

            dcraft, dcraftC, dcraftN = False, False, False
            if dinv: crafting = False
            if crafting:
                # Craft if player pressed craft
                server.inv, inv_sel, crafting_list, dcraftC = \
                    player.crafting(inp, server.inv, inv_sel,
                        crafting_list, crafting_sel)

                # Increment/decrement craft no.
                crafting_list, dcraftN = \
                    player.craft_num(inp, server.inv, crafting_list,
                        crafting_sel)

                dcraft = dcraftC or dcraftN

            # Update crafting list
            crafting_list, crafting_sel = \
                player.get_crafting(server.inv, crafting_list,
                                    crafting_sel, dcraftC)
            if not len(crafting_list): crafting = False

            dc = player.move_cursor(inp)
            cursor = (cursor + dc) % 6

            ds = player.move_sel(inp)
            if crafting:
                crafting_sel = ((crafting_sel + ds) % len(crafting_list)
                                   if len(crafting_list) else 0)
            else:
                inv_sel = ((inv_sel + ds) % len(server.inv)
                              if len(server.inv) else 0)


            if any((dpos, dc, ds, dinv, dcraft)):
                server.redraw = True
            if dpos:
                dpos = False
                server.pos = x, y
                cursor_hidden = True
            if dc:
                cursor_hidden = False

            ## Eating or placing blocks

            p_hungry = server.health < player.MAX_PLAYER_HEALTH

            new_blocks, server.inv, inv_sel, new_events, dhealth, dinv = \
                player.cursor_func(
                    inp, server.map_, x, y, cursor, inv_sel, server.inv, p_hungry
                )

            server.add_health(dhealth)

            if new_blocks:
                server.set_blocks(new_blocks)

            ## Process events

            events += new_events

            new_blocks = {}
            for i in range(int(dt)):
                new_blocks.update(process_events(events, server))
            if new_blocks:
                server.set_blocks(new_blocks)

            # If no block below, kill player
            try:
                block = server.map_[x][y+1]
            except IndexError:
                alive = False

            # Respawn player if dead
            if not alive:
                if ui.respawn() == 'exit':
                    server.logout()
                    continue
                server.redraw = True
                redraw_all = True
                alive = True
                server.respawn()

            ## Spawning mobs / Generating lighting buffer

            lights = render.get_lights(extended_view, bk_objects, x)

            spawn_period = 1 / SPS
            n_mob_spawn_cycles = int((frame_start - last_mob_spawn) // spawn_period)
            last_mob_spawn += spawn_period * n_mob_spawn_cycles
            server.spawn_mobs(n_mob_spawn_cycles, bk_objects, sky_colour, day, lights)

            ## Render

            if server.redraw:
                server.redraw = False

                # TODO: It would be nice to reuse any of the lighting_buffer generated for the mobs which overlaps with the screen
                render_interface.create_lighting_buffer(width, height, edges[0], edges_y[0], server.map_, server.slice_heights, bk_objects, sky_colour, day, lights)

                entities = {
                    'player': list(server.current_players.values()),
                    'zombie': list(server.mobs.values())
                }

                objects = player.entities_to_render_objects(
                    entities, x, int(width / 2), edges
                )

                objects += items_to_render_objects(server.items, x, int(width / 2))

                if not cursor_hidden:
                    cursor_colour = player.cursor_colour(
                        x, y, cursor, server.map_, server.inv, inv_sel
                    )

                    objects.append(player.assemble_cursor(
                        int(width / 2), y, cursor, cursor_colour
                    ))

                render_args = [
                    server.map_,
                    server.slice_heights,
                    edges,
                    edges_y,
                    objects,
                    bk_objects,
                    sky_colour,
                    day,
                    lights,
                    settings,
                    redraw_all
                ]
                render_map = lambda: render_interface.render_map(*render_args)

                if benchmarks:
                    timer = timeit.Timer(render_map)
                    t = timer.timeit(1)
                    log('Render call time = {}'.format(t), m="benchmarks")
                else:
                    render_map()

                redraw_all = False

                crafting_grid = render.render_grid(
                    player.CRAFT_TITLE, crafting, crafting_list,
                    height, crafting_sel
                )

                inv_grid = render.render_grid(
                    player.INV_TITLE, not crafting, server.inv,
                    height, inv_sel
                )

                label = (player.label(crafting_list, crafting_sel)
                        if crafting else
                        player.label(server.inv, inv_sel))

                health = 'Health: {}/{}'.format(round(server.health), player.MAX_PLAYER_HEALTH)

                render.render_grids(
                    [
                        [inv_grid, crafting_grid],
                        [[label]],
                        [[health]]
                    ],
                    width, height
                )

                in_game_log('({}, {})'.format(x, y), 0, 0)

            d_frame = time() - frame_start
            if d_frame < (1/FPS):
                sleep((1/FPS) - d_frame)
Пример #12
0
 def show_guidelines(self, message):
     print(message)
     ui.pause()
     page(GUIDELINES)
     self.seen_guidelines = GUIDELINE_VERSION
     self.save()
Пример #13
0
def game(blocks, meta, map_, save):
    x = meta['player_x']
    y = meta['player_y']
    dx = 0
    dy = 0
    dt = 0 # Tick
    df = 0 # Frame
    dc = 0 # Cursor
    ds = 0 # Selector
    dinv = False # Inventory
    dcraft = False # Crafting
    width = 40
    height = terrain.world_gen['height'] - 1
    FPS = 15 # Max
    TPS = 10 # Ticks
    IPS = 20 # Input
    MPS = 15 # Movement
    SUN_TICK = radians(1/32)

    old_bk_objects = None
    old_edges = None
    redraw = False
    last_frame = []
    last_out = time()
    last_tick = time()
    last_inp = time()
    last_move = time()
    inp = None
    jump = 0
    cursor = 0
    crafting = False
    crafting_sel = 0
    crafting_list = []
    inv_sel = 0
    c_hidden = True
    new_slices = {}
    alive = True
    events = []

    crafting_list, crafting_sel = player.get_crafting(
        meta['inv'],
        crafting_list,
        crafting_sel,
        blocks
    )

    # Game loop
    game = True
    with NonBlockingInput() as nbi:
        while game:
            # Finds display boundaries
            edges = (x - int(width / 2), x + int(width / 2))
            extended_edges = (edges[0]-render.max_light, edges[1]+render.max_light)

            # Generates new terrain
            slice_list = terrain.detect_edges(map_, extended_edges)
            for pos in slice_list:
                new_slices[pos] = terrain.gen_slice(pos, meta, blocks)
                map_[pos] = new_slices[pos]

            # Save new terrain to file
            if new_slices:
                saves.save_map(save, new_slices)
                new_slices = {}
                redraw = True

            # Moving view
            if not edges == old_edges:
                view = terrain.move_map(map_, edges)
                extended_view = terrain.move_map(map_, extended_edges)
                old_edges = edges
                redraw = True

            # Sun has moved
            bk_objects, sky_colour = render.bk_objects(meta['tick'], width)
            if not bk_objects == old_bk_objects:
                old_bk_objects = bk_objects
                redraw = True

            # Draw view
            if redraw and time() >= 1/FPS + last_out:
                df = 1
                redraw = False
                last_out = time()

                cursor_colour = player.cursor_colour(
                    x, y, cursor, map_, blocks, meta['inv'], inv_sel
                )

                objects = player.assemble_player(
                    int(width / 2), y, cursor, cursor_colour, c_hidden
                )

                lights = render.get_lights(extended_view, edges[0], blocks, bk_objects)

                out, last_frame = render.render_map(
                    view,
                    objects,
                    blocks,
                    bk_objects,
                    sky_colour,
                    lights,
                    meta['tick'],
                    last_frame
                )

                crafting_grid = render.render_grid(
                    player.CRAFT_TITLE, crafting, crafting_list, blocks,
                    height, crafting_sel
                )

                inv_grid = render.render_grid(
                    player.INV_TITLE, not crafting, meta['inv'], blocks,
                    height, inv_sel
                )

                label = (player.label(crafting_list, crafting_sel, blocks)
                        if crafting else
                        player.label(meta['inv'], inv_sel, blocks))

                out += render.render_grids(
                    [
                        [inv_grid, crafting_grid],
                        [[label]]
                    ],
                    width, height
                )

                print(out)
                in_game_debug('({}, {})'.format(x, y), 0, 0)
            else:
                df = 0

            # Respawn player if dead
            if not alive and df:
                alive = True
                x, y = player.respawn(meta)

            if dt:
                # Player falls when no solid block below it
                if jump > 0:
                    # Countdown till fall
                    jump -= 1
                elif not terrain.is_solid(blocks, map_[x][y+1]):
                    # Fall
                    y += 1
                    redraw = True

                new_new_slices = process_events(events, map_, blocks)
                new_slices.update(new_new_slices)
                map_.update(new_new_slices)

            # If no block below, kill player
            try:
                block = map_[x][y+1]
            except IndexError:
                alive = False

            # Receive input if a key is pressed
            char = str(nbi.char()).lower()
            inp = char if char in 'wadkjliuo-=' else None

            # Input Frame
            if time() >= (1/IPS) + last_inp and alive and inp:

                if time() >= (1/MPS) + last_move:
                    # Update player position
                    dx, dy, jump = player.get_pos_delta(
                        str(inp), map_, x, y, blocks, jump)
                    y += dy
                    x += dx

                    last_move = time()

                new_new_slices, meta['inv'], inv_sel, new_events, dinv = \
                    player.cursor_func(str(inp), map_, x, y, cursor, inv_sel, meta, blocks)

                map_.update(new_new_slices)
                new_slices.update(new_new_slices)

                events += new_events

                dcraft, dcraftC, dcraftN = False, False, False
                if dinv: crafting = False
                if crafting:
                    # Craft if player pressed craft
                    meta['inv'], inv_sel, crafting_list, dcraftC = \
                        player.crafting(str(inp), meta['inv'], inv_sel,
                            crafting_list, crafting_sel, blocks)

                    # Increment/decrement craft no.
                    crafting_list, dcraftN = \
                        player.craft_num(str(inp), meta['inv'], crafting_list,
                            crafting_sel, blocks)

                    dcraft = dcraftC or dcraftN

                # Update crafting list
                if dinv or dcraft:
                    crafting_list, crafting_sel = \
                        player.get_crafting(meta['inv'], crafting_list,
                                            crafting_sel, blocks, dcraftC)
                    if not len(crafting_list): crafting = False

                dc = player.move_cursor(inp)
                cursor = (cursor + dc) % 6

                ds = player.move_sel(inp)
                if crafting:
                    crafting_sel = ((crafting_sel + ds) % len(crafting_list)
                                       if len(crafting_list) else 0)
                else:
                    inv_sel = ((inv_sel + ds) % len(meta['inv'])
                                  if len(meta['inv']) else 0)

                if any((dx, dy, dc, ds, dinv, dcraft)):
                    meta['player_x'], meta['player_y'] = x, y
                    saves.save_meta(save, meta)
                    redraw = True
                if dx or dy:
                    c_hidden = True
                if dc:
                    c_hidden = False

                last_inp = time()
                inp = None

            if char in 'c':
                redraw = True
                crafting = not crafting and len(crafting_list)

            # Hard pause
            if DEBUG and char in '\n':
                input()
                char = '0'

            # Pause game
            if char in ' \n':
                meta['player_x'], meta['player_y'] = x, y
                saves.save_meta(save, meta)
                redraw = True
                last_frame = []
                if ui.pause() == 'exit':
                    game = False

            # Increase tick
            if time() >= (1/TPS) + last_tick:
                dt = 1
                meta['tick'] += SUN_TICK
                last_tick = time()
            else:
                dt = 0
Пример #14
0
def game(server, settings, benchmarks):
    dt = 0  # Tick
    df = 0  # Frame
    dc = 0  # Cursor
    ds = 0  # Selector
    dpos = False
    dinv = False  # Inventory
    dcraft = False  # Crafting
    FPS = 15  # Max
    MPS = 15  # Movement
    SPS = 5  # Mob spawns

    old_bk_objects = None
    old_edges = None
    redraw_all = True
    last_move = time()
    last_mob_spawn = time()
    inp = None
    jump = 0
    cursor = 0
    crafting = False
    crafting_sel = 0
    crafting_list = []
    inv_sel = 0
    cursor_hidden = True
    new_blocks = {}
    alive = True
    events = []

    crafting_list, crafting_sel = player.get_crafting(server.inv,
                                                      crafting_list,
                                                      crafting_sel)

    # Game loop
    with NonBlockingInput() as nbi:
        while server.game:
            x, y = server.pos
            dt = server.dt()
            frame_start = time()

            ## Input

            char = True
            inp = []
            while char:
                # Receive input if a key is pressed
                char = nbi.char()
                if char:
                    char = str(char).lower()

                    if char in 'wasdhkjliuoc-=\n ':
                        inp.append(char)

            # Hard pause
            if DEBUG and '\n' in inp:
                input()
                inp.remove('\n')

            # Pause game
            if ' ' in inp or '\n' in inp:
                server.redraw = True
                redraw_all = True
                if ui.pause(server, settings) == 'exit':
                    server.logout()
                    continue

            width = settings.get('width')
            height = settings.get('height')

            # Update player and mobs position / damage
            move_period = 1 / MPS
            while frame_start >= move_period + last_move and x in server.map_:

                dx, dy, jump = player.get_pos_delta_on_input(
                    inp, server.map_, x, y, jump, settings.get('flight'))
                if dx or dy:
                    dpos = True
                    x += dx
                    y += dy

                if x in server.map_ and not settings.get('flight'):
                    # Player falls when no solid block below it and not jumping
                    jump -= dt
                    if jump <= 0:
                        jump = 0
                        if not terrain.is_solid(server.map_[x][y + 1]):
                            # Fall
                            y += 1
                            dpos = True

                if 'h' in inp:
                    item = render.blocks[server.inv[inv_sel]['block']] if len(
                        server.inv) else {}
                    server.player_attack(item.get('attack_radius', 5),
                                         item.get('attack_damage', 10))

                server.update_items()
                server.update_mobs()

                if server.health <= 0:
                    alive = False

                last_move += move_period

            ## Update Map

            # Finds display boundaries
            edges = (x - int(width / 2), x + int(width / 2))
            edges_y = (y - int(height / 2), y + int(height / 2))

            if edges_y[1] > data.world_gen['height']:
                edges_y = (data.world_gen['height'] - height,
                           data.world_gen['height'])
            elif edges_y[0] < 0:
                edges_y = (0, height)

            extended_edges = (edges[0] - render.max_light,
                              edges[1] + render.max_light)

            slice_list = terrain.detect_edges(server.map_, extended_edges)
            if slice_list:
                log('slices to load', slice_list)
                chunk_list = terrain.get_chunk_list(slice_list)
                server.get_chunks(chunk_list)
                server.unload_slices(extended_edges)

            # Moving view
            if not edges == old_edges or server.view_change:
                extended_view = terrain.move_map(server.map_, extended_edges)
                old_edges = edges
                server.redraw = True
                server.view_change = False

            # Sun has moved
            bk_objects, sky_colour, day = render.bk_objects(
                server.time, width, edges[0], settings.get('fancy_lights'))
            if not bk_objects == old_bk_objects:
                old_bk_objects = bk_objects
                server.redraw = True

            if settings.get('gravity'):
                blocks = terrain.apply_gravity(server.map_, extended_edges)
                if blocks: server.set_blocks(blocks)

            ## Crafting

            if 'c' in inp:
                server.redraw = True
                crafting = not crafting and len(crafting_list)

            dcraft, dcraftC, dcraftN = False, False, False
            if dinv: crafting = False
            if crafting:
                # Craft if player pressed craft
                server.inv, inv_sel, crafting_list, dcraftC = \
                    player.crafting(inp, server.inv, inv_sel,
                        crafting_list, crafting_sel)

                # Increment/decrement craft no.
                crafting_list, dcraftN = \
                    player.craft_num(inp, server.inv, crafting_list,
                        crafting_sel)

                dcraft = dcraftC or dcraftN

            # Update crafting list
            crafting_list, crafting_sel = \
                player.get_crafting(server.inv, crafting_list,
                                    crafting_sel, dcraftC)
            if not len(crafting_list): crafting = False

            dc = player.move_cursor(inp)
            cursor = (cursor + dc) % 6

            ds = player.move_sel(inp)
            if crafting:
                crafting_sel = ((crafting_sel + ds) % len(crafting_list)
                                if len(crafting_list) else 0)
            else:
                inv_sel = ((inv_sel + ds) %
                           len(server.inv) if len(server.inv) else 0)

            if any((dpos, dc, ds, dinv, dcraft)):
                server.redraw = True
            if dpos:
                dpos = False
                server.pos = x, y
                cursor_hidden = True
            if dc:
                cursor_hidden = False

            ## Eating or placing blocks

            p_hungry = server.health < player.MAX_PLAYER_HEALTH

            new_blocks, server.inv, inv_sel, new_events, dhealth, dinv = \
                player.cursor_func(
                    inp, server.map_, x, y, cursor, inv_sel, server.inv, p_hungry
                )

            server.add_health(dhealth)

            if new_blocks:
                server.set_blocks(new_blocks)

            ## Process events

            events += new_events

            new_blocks = {}
            for i in range(int(dt)):
                new_blocks.update(process_events(events, server))
            if new_blocks:
                server.set_blocks(new_blocks)

            # If no block below, kill player
            try:
                block = server.map_[x][y + 1]
            except IndexError:
                alive = False

            # Respawn player if dead
            if not alive:
                if ui.respawn() == 'exit':
                    server.logout()
                    continue
                server.redraw = True
                redraw_all = True
                alive = True
                server.respawn()

            ## Spawning mobs / Generating lighting buffer

            lights = render.get_lights(extended_view, bk_objects, x)

            spawn_period = 1 / SPS
            n_mob_spawn_cycles = int(
                (frame_start - last_mob_spawn) // spawn_period)
            last_mob_spawn += spawn_period * n_mob_spawn_cycles
            server.spawn_mobs(n_mob_spawn_cycles, bk_objects, sky_colour, day,
                              lights)

            ## Render

            if server.redraw:
                server.redraw = False

                # TODO: It would be nice to reuse any of the lighting_buffer generated for the mobs which overlaps with the screen
                render_interface.create_lighting_buffer(
                    width, height, edges[0], edges_y[0], server.map_,
                    server.slice_heights, bk_objects, sky_colour, day, lights)

                entities = {
                    'player': list(server.current_players.values()),
                    'zombie': list(server.mobs.values())
                }

                objects = player.entities_to_render_objects(
                    entities, x, int(width / 2), edges)

                objects += items_to_render_objects(server.items, x,
                                                   int(width / 2))

                if not cursor_hidden:
                    cursor_colour = player.cursor_colour(
                        x, y, cursor, server.map_, server.inv, inv_sel)

                    objects.append(
                        player.assemble_cursor(int(width / 2), y, cursor,
                                               cursor_colour))

                render_args = [
                    server.map_, server.slice_heights, edges, edges_y, objects,
                    bk_objects, sky_colour, day, lights, settings, redraw_all
                ]
                render_map = lambda: render_interface.render_map(*render_args)

                if benchmarks:
                    timer = timeit.Timer(render_map)
                    t = timer.timeit(1)
                    log('Render call time = {}'.format(t), m="benchmarks")
                else:
                    render_map()

                redraw_all = False

                crafting_grid = render.render_grid(player.CRAFT_TITLE,
                                                   crafting, crafting_list,
                                                   height, crafting_sel)

                inv_grid = render.render_grid(player.INV_TITLE, not crafting,
                                              server.inv, height, inv_sel)

                label = (player.label(crafting_list, crafting_sel)
                         if crafting else player.label(server.inv, inv_sel))

                health = 'Health: {}/{}'.format(round(server.health),
                                                player.MAX_PLAYER_HEALTH)

                render.render_grids(
                    [[inv_grid, crafting_grid], [[label]], [[health]]], width,
                    height)

                in_game_log('({}, {})'.format(x, y), 0, 0)

            d_frame = time() - frame_start
            if d_frame < (1 / FPS):
                sleep((1 / FPS) - d_frame)
Пример #15
0
def game(server, settings):
    x, y = server.pos
    dx = 0
    dy = 0
    dt = 0  # Tick
    df = 0  # Frame
    dc = 0  # Cursor
    ds = 0  # Selector
    dinv = False  # Inventory
    dcraft = False  # Crafting
    FPS = 15  # Max
    IPS = 20  # Input
    MPS = 15  # Movement

    old_bk_objects = None
    old_edges = None
    last_frame = {}
    last_out = time()
    last_inp = time()
    last_move = time()
    inp = None
    jump = 0
    cursor = 0
    crafting = False
    crafting_sel = 0
    crafting_list = []
    inv_sel = 0
    c_hidden = True
    new_blocks = {}
    alive = True
    events = []

    crafting_list, crafting_sel = player.get_crafting(
        server.inv,
        crafting_list,
        crafting_sel
    )

    # Game loop
    with NonBlockingInput() as nbi:
        while server.game:
            x, y = server.pos

            width = settings.get('width')
            height = settings.get('height')

            sleep(1/1000)
            # Finds display boundaries
            edges = (x - int(width / 2), x + int(width / 2))
            edges_y = (y - int(height / 2), y + int(height / 2))

            if edges_y[1] > data.world_gen['height']:
                edges_y = (data.world_gen['height'] - height, data.world_gen['height'])
            elif edges_y[0] < 0:
                edges_y = (0, height)

            extended_edges = (edges[0]-render.max_light, edges[1]+render.max_light)

            slice_list = terrain.detect_edges(server.map_, extended_edges)
            if slice_list:
                log('slices to load', slice_list)
                chunk_list = terrain.get_chunk_list(slice_list)
                server.get_chunks(chunk_list)
                server.unload_slices(extended_edges)

            # Moving view
            if not edges == old_edges or server.view_change:
                extended_view = terrain.move_map(server.map_, extended_edges)
                old_edges = edges
                server.redraw = True
                server.view_change = False

            # Sun has moved
            bk_objects, sky_colour, day = render.bk_objects(server.time, width, settings.get('fancy_lights'))
            if not bk_objects == old_bk_objects:
                old_bk_objects = bk_objects
                server.redraw = True

            # Draw view
            if server.redraw and time() >= 1/FPS + last_out:
                df = 1
                server.redraw = False
                last_out = time()

                if settings.get('gravity'):
                    blocks = terrain.apply_gravity(server.map_, edges)
                    if blocks: server.set_blocks(blocks)

                cursor_colour = player.cursor_colour(
                    x, y, cursor, server.map_, server.inv, inv_sel
                )

                objects = player.assemble_players(
                    server.current_players, x, y, int(width / 2), edges
                )

                if not c_hidden:
                    objects.append(player.assemble_cursor(
                        int(width / 2), y, cursor, cursor_colour
                    ))

                lights = render.get_lights(extended_view, edges[0], bk_objects)

                out, last_frame = render.render_map(
                    server.map_,
                    server.slice_heights,
                    edges,
                    edges_y,
                    objects,
                    bk_objects,
                    sky_colour,
                    day,
                    lights,
                    last_frame,
                    settings.get('fancy_lights')
                )

                crafting_grid = render.render_grid(
                    player.CRAFT_TITLE, crafting, crafting_list,
                    height, crafting_sel
                )

                inv_grid = render.render_grid(
                    player.INV_TITLE, not crafting, server.inv,
                    height, inv_sel
                )

                label = (player.label(crafting_list, crafting_sel)
                        if crafting else
                        player.label(server.inv, inv_sel))

                out += render.render_grids(
                    [
                        [inv_grid, crafting_grid],
                        [[label]]
                    ],
                    width, height
                )

                print(out)
                in_game_log('({}, {})'.format(x, y), 0, 0)
            else:
                df = 0

            # Respawn player if dead
            if not alive and df:
                alive = True
                server.respawn()

            if dt and server.chunk_loaded(x):

                if not settings.get('flight'):
                    # Player falls when no solid block below it
                    if jump > 0:
                        # Countdown till fall
                        jump -= 1
                    elif not terrain.is_solid(server.map_[x][y+1]):
                        # Fall
                        y += 1
                        server.pos = x, y
                        server.redraw = True

                new_blocks = process_events(events, server.map_)

                if new_blocks:
                    server.set_blocks(new_blocks)

            # If no block below, kill player
            try:
                block = server.map_[x][y+1]
            except IndexError:
                alive = False

            # Receive input if a key is pressed
            char = str(nbi.char()).lower()
            inp = char if char in 'wasdkjliuo-=' else None

            # Input Frame
            if time() >= (1/IPS) + last_inp and alive and inp:

                if time() >= (1/MPS) + last_move:
                    # Update player position
                    dx, dy, jump = player.get_pos_delta(
                        str(inp), server.map_, x, y, jump, settings.get('flight'))
                    y += dy
                    x += dx

                    last_move = time()

                new_blocks, inv, inv_sel, new_events, dinv = \
                    player.cursor_func(
                        str(inp), server.map_, x, y, cursor, inv_sel, server.inv
                    )

                if dinv:
                    server.inv = inv

                if new_blocks:
                    server.set_blocks(new_blocks)

                events += new_events

                dcraft, dcraftC, dcraftN = False, False, False
                if dinv: crafting = False
                if crafting:
                    # Craft if player pressed craft
                    inv, inv_sel, crafting_list, dcraftC = \
                        player.crafting(str(inp), server.inv, inv_sel,
                            crafting_list, crafting_sel)
                    if dcraftC:
                        server.inv = inv

                    # Increment/decrement craft no.
                    crafting_list, dcraftN = \
                        player.craft_num(str(inp), server.inv, crafting_list,
                            crafting_sel)

                    dcraft = dcraftC or dcraftN

                # Update crafting list
                if dinv or dcraft:
                    crafting_list, crafting_sel = \
                        player.get_crafting(server.inv, crafting_list,
                                            crafting_sel, dcraftC)
                    if not len(crafting_list): crafting = False

                dc = player.move_cursor(inp)
                cursor = (cursor + dc) % 6

                ds = player.move_sel(inp)
                if crafting:
                    crafting_sel = ((crafting_sel + ds) % len(crafting_list)
                                       if len(crafting_list) else 0)
                else:
                    inv_sel = ((inv_sel + ds) % len(server.inv)
                                  if len(server.inv) else 0)

                if any((dx, dy, dc, ds, dinv, dcraft)):
                    server.pos = x, y
                    server.redraw = True
                if dx or dy:
                    c_hidden = True
                if dc:
                    c_hidden = False

                last_inp = time()
                inp = None

            if char in 'c':
                server.redraw = True
                crafting = not crafting and len(crafting_list)

            # Hard pause
            if DEBUG and char in '\n':
                input()
                char = '0'

            # Pause game
            if char in ' \n':
                server.pos = x, y
                server.redraw = True
                last_frame = {}
                if ui.pause(server, settings) == 'exit':
                    server.logout()

            dt = server.dt()