コード例 #1
0
ファイル: ui.py プロジェクト: pwmarcz/madness
def init(game):
    global CON, CON_MAP, CON_BUFFER, CON_STATUS, CON_INV, MESSAGES, GAME
    GAME = game
    T.console_set_custom_font(*FONTS[FONT_INDEX])
    CON = T.console_init_root(SCREEN_W, SCREEN_H, TITLE, False)
    CON_MAP = T.console_new(MAP_W, MAP_H)
    CON_BUFFER = T.console_new(SCREEN_W, BUFFER_H)
    CON_STATUS = T.console_new(STATUS_W, STATUS_H)
    CON_INV = T.console_new(INV_W, INV_H)
    MESSAGES = []
コード例 #2
0
ファイル: conftest.py プロジェクト: HexDecimal/libtcod-cffi
def session_console(request):
    if(pytest.config.getoption("--no-window")):
        pytest.skip("This test needs a rendering context.")
    FONT_FILE = 'libtcod/terminal.png'
    WIDTH = 12
    HEIGHT = 10
    TITLE = 'libtcod-cffi tests'
    FULLSCREEN = False
    RENDERER = getattr(tcod, 'RENDERER_' + request.param)

    tcod.console_set_custom_font(FONT_FILE)
    with tcod.console_init_root(WIDTH, HEIGHT,
                                TITLE, FULLSCREEN, RENDERER) as con:
        yield con
コード例 #3
0
ファイル: console.py プロジェクト: millejoh/Islands
    def __init__(self, width=80, height=50, title=b'Stage',
                 background=tcod.darker_sepia,
                 font_file=tcod.default_font, font_flags=tcod.FONT_LAYOUT_TCOD | tcod.FONT_TYPE_GREYSCALE,
                 font_width=0, font_height=0,
                 datax='', fullscreen=False,
                 renderer=tcod.RENDERER_SDL, max_fps=30):
        """
        Create a RootConsole object.

        :param width:
        :param height:
        :param title:
        :param background:
        :param font_file:
        :param datax:
        :param fullscreen:
        :param renderer:
        :param max_fps:
        :return:
        """
        super().__init__()
        if not os.path.exists(font_file):
            path = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.path.normpath('data/fonts/'))
            font_file = os.path.join(path, font_file)
        if os.path.exists(font_file):
            tcod.console_set_custom_font(bytes(font_file, 'utf-8'),
                                         flags=font_flags,
                                         nb_char_horiz=font_width,
                                         nb_char_vertic=font_height)
        else:
            raise OSError("Font file {0} not found.".format(font_file))

        self._c = tcod.root_console
        self.width = width
        self.height = height
        self.title = title
        self.fullscreen = fullscreen
        self.renderer = renderer
        self.end_game = False
        self.max_fps = max_fps
        self.default_background_color = background
        self.clock = GameClock()
        self.clock.frame_callback = self.on_draw
コード例 #4
0
ファイル: engine.py プロジェクト: mraiur/PythonBeefRogue
def main():
    # Grabs all the various game constants
    constants = get_game_constants()

    # Sets font
    tcod.console_set_custom_font(
        'arial12x12.png', tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD)

    # Sets window parameters
    tcod.console_init_root(constants['screen_width'],
                           constants['screen_height'],
                           constants['game_title'],
                           False,
                           tcod.RENDERER_OPENGL2,
                           vsync=True)
    con = tcod.console_new(constants['screen_width'],
                           constants['screen_height'])
    panel = tcod.console_new(constants['screen_width'],
                             constants['panel_height'])

    # Sets saved game parameters to none
    player = None
    entities = []
    game_map = None
    message_log = None
    game_state = None

    # Menu and Load triggers
    show_main_menu = True
    show_load_error_message = False

    # Load main menu background
    main_menu_background_image = tcod.image_load('menu_background.png')

    # Inputs
    key = tcod.Key()
    mouse = tcod.Mouse()

    #
    # MAIN GAME LOOP
    #
    while not tcod.console_is_window_closed():
        # Check for events
        tcod.sys_check_for_event(tcod.EVENT_KEY_PRESS | tcod.EVENT_MOUSE, key,
                                 mouse)

        # Main menu
        if show_main_menu:
            main_menu(con, main_menu_background_image,
                      constants['screen_width'], constants['screen_height'])

            if show_load_error_message:
                message_box(con, 'No save game to load', 50,
                            constants['screen_width'],
                            constants['screen_height'])

            tcod.console_flush()

            action = handle_main_menu(key)

            # Actions for main menu
            new_game = action.get('new_game')
            load_saved_game = action.get('load_game')
            fullscreen = action.get('fullscreen')
            exit_game = action.get('exit')

            if show_load_error_message and (new_game or load_saved_game
                                            or exit_game):
                show_load_error_message = False

            # Starts a new game
            elif new_game:
                # Loads in player, inventory, map, and other such variables then sets turn to player
                player, entities, game_map, message_log, game_state = get_game_variables(
                    constants)
                game_state = GameStates.PLAYERS_TURN

                show_main_menu = False

            # Loads a saved game
            elif load_saved_game:
                try:
                    player, entities, game_map, message_log, game_state = load_game(
                    )
                    show_main_menu = False
                except FileNotFoundError:
                    show_load_error_message = True

            # Exits game
            elif exit_game:
                break

            # Toggles fullscreen
            elif fullscreen:
                tcod.console_set_fullscreen(not tcod.console_is_fullscreen())

        else:
            tcod.console_clear(con)
            play_game(player, entities, game_map, message_log, game_state, con,
                      panel, constants)

            show_main_menu = True
コード例 #5
0
        #show options and wait for the player's choice
        choice = menu('', ['Pway a new game!', 'Return to Daddy', 'Quit OwO'], 24)

        if choice == 0: #new game
            new_game()
            play_game()
        if choice == 1: #load last game
            try:
                load_game()
            except:
                msgbox('\n u dont have saved game \n', 24)
                continue
            play_game()
        elif choice == 2: #quit
            break

libtcod.console_set_custom_font('arial12x12.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)
libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, '~Woguey Wikey~', False)
libtcod.sys_set_fps(LIMIT_FPS)
con = libtcod.console_new(MAP_WIDTH, MAP_HEIGHT)
panel = libtcod.console_new(SCREEN_WIDTH, PANEL_HEIGHT)

main_menu()






コード例 #6
0
# Make sure 'arial10x10.png' is in the same directory as this script.
import tcod
import tcod.event

# Setup the font.
tcod.console_set_custom_font(
    "arial10x10.png",
    tcod.FONT_LAYOUT_TCOD | tcod.FONT_TYPE_GREYSCALE,
)
# Initialize the root console in a context.
with tcod.console_init_root(80, 60, order="F") as root_console:
    root_console.print_(x=0, y=0, string='Hello World!')
    while True:
        tcod.console_flush()  # Show the console.
        for event in tcod.event.wait():
            if event.type == "QUIT":
                raise SystemExit()
    # The libtcod window will be closed at the end of this with-block.

コード例 #7
0
def main():
    global current_game, root_console

    equipment.import_armour()
    equipment.import_weapons()

    tcod.console_set_custom_font(
        resource_path(CONFIG.get('font')),
        CONFIG.get('font_type') | tcod.FONT_TYPE_GREYSCALE,
    )

    root_console = tcod.console_init_root(CONFIG.get('full_screen_width'),
                                          CONFIG.get('full_screen_height'),
                                          CONFIG.get('window_title'),
                                          False,
                                          order='F',
                                          vsync=False)

    current_game.start_fresh_game()

    while True:
        root_console.clear(fg=COLORS.get('console_background'))

        if current_game.game_state == GameStates.GAME_EXIT:
            raise SystemExit()
        '''
                if show_main_menu:
                    root_console.clear(fg=(255, 255, 255))

                    main_menu(root_console, main_menu_background_image, CONFIG.get('full_screen_width'),
                              CONFIG.get('full_screen_height'))

                    if show_load_error_message:
                        message_box(map_console, 'No saved game to load', 50, CONFIG.get('full_screen_width'), constants['screen_height'])

                    tcod.console_flush()

                    action = handle_keys(key, GameStates.GAME_START)

                    if len(action) > 0:
                        result_type, result_data = unpack_single_key_dict(action)
                        if show_load_error_message and (result_type == InputTypes.GAME_LOAD):
                            show_load_error_message = False
                        elif result_type == InputTypes.GAME_NEW:
                            player, game_map, message_log, game_state = get_game_variables(constants)
                            game_map.create_floor(player)

                            show_main_menu = False
                        elif result_type == InputTypes.GAME_LOAD:
                            try:
                                player, game_map, message_log, game_state, pubsub.pubsub = load_game()
                                show_main_menu = False
                            except FileNotFoundError:
                                show_load_error_message = True
                        elif result_type == InputTypes.GAME_EXIT:
                            break
        '''
        #if self.game_state == GameStates.GAME_START:
        #    main_menu.on_draw()
        #else:
        current_game.on_draw()
        tcod.console_flush()

        #Uncomment the following line to take a screenshot each turn
        #tcod.sys_save_screenshot()

        if (current_game.game_state == GameStates.ENEMY_TURN
                or current_game.game_state == GameStates.PLAYER_SLEEP):
            current_game.process_turn(None, None)
        else:
            handle_events()
コード例 #8
0
ファイル: engine.py プロジェクト: Encoded77/py-roguelike
def main():
    constants = get_constants()

    libtcod.console_set_custom_font(
        './assets/arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(constants['screen_width'],
                              constants['screen_height'],
                              constants['window_title'], False)

    con = libtcod.console_new(constants['screen_width'],
                              constants['screen_height'])
    panel = libtcod.console_new(constants['screen_width'],
                                constants['panel_height'])

    player = None
    entities = []
    game_map = None
    message_log = None
    game_state = None

    show_main_menu = True
    show_load_error_message = False

    main_menu_background_image = libtcod.image_load(
        './assets/background_main_menu.png')

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(
            libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)

        if show_main_menu:
            main_menu(con, main_menu_background_image,
                      constants['screen_width'], constants['screen_height'])

            if show_load_error_message:
                message_box(con, 'No save game to load', 50,
                            constants['screen_width'],
                            int(math.ceil(constants['screen_height']) * 1.3))

            libtcod.console_flush()

            action = handle_main_menu(key)

            new_game = action.get('new_game')
            load_saved_game = action.get('load_game')
            exit_game = action.get('exit')
            fullscreen = action.get('fullscreen')

            if show_load_error_message and (new_game or load_saved_game
                                            or exit_game):
                show_load_error_message = False
            elif new_game:
                player, entities, game_map, message_log, game_state = get_game_variables(
                    constants)
                game_state = GameStates.PLAYERS_TURN

                show_main_menu = False
            elif load_saved_game:
                try:
                    player, entities, game_map, message_log, game_state = load_game(
                    )
                    show_main_menu = False
                except FileNotFoundError:
                    show_load_error_message = True

            elif fullscreen:
                libtcod.console_set_fullscreen(
                    not libtcod.console_is_fullscreen())

            elif exit_game:
                break

        else:
            libtcod.console_clear(con)
            play_game(player, entities, game_map, message_log, game_state, con,
                      panel, constants)

            show_main_menu = True
コード例 #9
0
def main():
    screen_width = 80
    screen_height = 50
    map_width = 80
    map_height = 45

    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150)
    }

    player = Entity(int(screen_width / 2), int(screen_height / 2), '@',
                    libtcod.white)
    npc = Entity(
        int(screen_width / 2) - 5, int(screen_height / 2), '@', libtcod.yellow)
    entities = [npc, player]

    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GRAYSCALE | libtcod.FONT_LAYOUT_TCOD)
    libtcod.console_init_root(screen_width, screen_height,
                              'libtcod tutorial revised', False)

    con = libtcod.console_new(screen_width, screen_height)

    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, player)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)

        render_all(con, entities, game_map, screen_width, screen_height,
                   colors)
        libtcod.console_flush()

        clear_all(con, entities)

        action = handle_keys(key)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        if move:
            dx, dy = move
            if not game_map.is_blocked(player.x + dx, player.y + dy):
                player.move(dx, dy)

        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
コード例 #10
0
from ardor.consoles import (EventConsole, WorldConsole, HUDConsole,
                            InventoryConsole, WinConsole, ControlsConsole,
                            IntroConsole, GameOverConsole)
from ardor.states import State
from ardor.worlds import World
from ardor.worlds import World1, World2, World3

from typing import List, Iterator, MutableSet, Tuple, Type  # noqa

ROOT_WIDTH = 80
ROOT_HEIGHT = 50

TORCH_DRAIN = 1.25

font = os.path.join('data/fonts/consolas12x12_gs_tc.png')
tcod.console_set_custom_font(font,
                             tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD)

MOVE_KEYS = {
    ord('k'): (0, -1),
    ord('h'): (-1, 0),
    ord('j'): (0, 1),
    ord('l'): (1, 0),
}

MOVE_VKEYS = {
    tcod.KEY_UP: (0, -1),
    tcod.KEY_LEFT: (-1, 0),
    tcod.KEY_DOWN: (0, 1),
    tcod.KEY_RIGHT: (1, 0)
}
コード例 #11
0
def main():

    print(sys.platform)
    screen_width = 80
    screen_height = 50
    map_width = 80
    map_height = 45

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150)
    }

    player = Entity(int(screen_width / 2), int(screen_height / 2), '@',
                    libtcod.white)
    npc = Entity(int(screen_width / 2 - 5), int(screen_height / 2), '@',
                 libtcod.yellow)
    entities = [npc, player]

    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(screen_width, screen_height,
                              'libtcod tutorial revised', False)

    con = libtcod.console_new(screen_width, screen_height)

    game_map = GameMap(map_width, map_height)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    # Game loop, closes when windows is closed

    while not libtcod.console_is_window_closed():
        # captures user input
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)

        render_all(con, entities, game_map, screen_width, screen_height,
                   colors)

        #presents everything to screen
        libtcod.console_flush()

        clear_all(con, entities)

        # We're capturing the return value of handle_keys in the variable action
        # (which should be a dictionary, no matter what we pressed), and checking
        # what keys are inside it. If it contains a key called 'move',
        # then we know to look for the (x, y) coordinates. If it contains 'exit',
        # then we know we need to exit the game.
        action = handle_keys(key)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        if move:
            dx, dy = move

            if not game_map.is_blocked(player.x + dx, player.y + dy):
                player.move(dx, dy)

        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
コード例 #12
0
def main(debug=False):
    screen_width = 80
    screen_height = 80
    map_width = 60
    map_height = 60
    menu_width = 20
    menu_height = 80
    action_width = 60
    action_height = 20

    cur_level_idx = 0
    cur_level = levels[cur_level_idx]
    player = Player()
    cur_level.add_player(player)
    tutorial_map = cur_level.get_map()
    player.add_map(tutorial_map)
    ui_manager = UIManager(player, screen_width, screen_height)
    cur_level.add_ui_manager(ui_manager)
    
    tcod.console_set_custom_font(
        'tileset/cp437_10x10.png',
        tcod.FONT_TYPE_GRAYSCALE | tcod.FONT_LAYOUT_ASCII_INROW
    )

    root_console = tcod.console_init_root(
        screen_width, screen_height, 'Crypt Hero', False,
        tcod.RENDERER_SDL2, order='F', vsync=True)

    renderer = Renderer(root_console, ui_manager, debug=debug)
    cur_level.add_renderer(renderer)

    recompute = True
    while True:
        if recompute and cur_level.recalculate_fov:
            recompute = False
            tutorial_map.compute_fov(player.x, player.y, player.fov, True, 0)

        renderer.render_level(player, cur_level.entities, tutorial_map, colors=cur_level.show_colors)

        actions = handle_events()

        move = actions.get('move')
        pass_time = actions.get('pass_time')
        exit = actions.get('exit')
        act = actions.get('act')
        restart = actions.get('restart')
        fullscreen = actions.get('fullscreen')
        god_mod = actions.get('god_mod')

        if god_mod and debug:
            player.activate_god_mod()

        if move and player.can_move and not ui_manager.popup:
            recompute = True
            player.move(*move)
            cur_level.pass_turn(move)
        
        if pass_time:
            cur_level.pass_turn((0, 0))

        if exit:
            if ui_manager.popup:
                ui_manager.remove_popup()
            else:
                return True
            if player.dead or cur_level.ended:
                return True
        
        if act:
            handle_action(act, renderer, cur_level, ui_manager)
        
        if restart and (player.dead or cur_level.ended):
            reset_levels()
            player = Player(char=ord(' '))
            ui_manager = UIManager(player, screen_width, screen_height)
            renderer = Renderer(root_console, ui_manager)
            cur_level_idx = 0
            cur_level = levels[cur_level_idx]
            cur_level.add_player(player)
            tutorial_map = cur_level.get_map()
            player.add_map(tutorial_map)
            cur_level.add_ui_manager(ui_manager)
            cur_level.add_renderer(renderer)
            recompute = True

        if fullscreen:
            tcod.console_set_fullscreen(not tcod.console_is_fullscreen())

        if player.is_on_exit():
            cur_level_idx += 1
            cur_level = levels[cur_level_idx]
            cur_level.add_player(player)
            tutorial_map = cur_level.get_map()
            player.add_map(tutorial_map)
            cur_level.add_ui_manager(ui_manager)
            cur_level.add_renderer(renderer)
            recompute = True

        if player.dead:
            ui_manager.show_popup('You are dead', 'This world falls into crumbles.\nMay you be more lucky next time.', 'Press r to reset or ESC to quit')
コード例 #13
0
ファイル: main.py プロジェクト: Zolo101/minesweeper
        if event.sym == 1073741905 or event.sym == 115:  # down
            MovePL(Point(PLAYER_LOCATION.x, PLAYER_LOCATION.y + 1))
        if event.sym == 1073741903 or event.sym == 100:  # right
            MovePL(Point(PLAYER_LOCATION.x + 1, PLAYER_LOCATION.y))
        if event.sym == 13:  # open the tile the PLAYER_LOCATION is on
            OpenTile(PLAYER_LOCATION)
        if event.sym == 114:
            Restart()


state = State()

CreateField()

tcod.console_set_custom_font(
    FONT_IMG,
    tcod.FONT_LAYOUT_TCOD | tcod.FONT_TYPE_GRAYSCALE,
)

with tcod.console_init_root(WIDTH + ORIGIN.x,
                            HEIGHT + ORIGIN.y,
                            "Zelo's Minesweeper",
                            order="F",
                            vsync=True) as root_console:
    while True:  # run every frame
        root_console.clear()
        PrintMenu(root_console)
        PrintMine(root_console, ORIGIN)
        tcod.console_flush()
        for event in tcod.event.wait():
            CheckWon()
            mouse_state = state.dispatch(event)
コード例 #14
0
def main():

    # Screen Params
    screen_width = 80
    screen_height = 50

    # UI Params
    bar_width = 20
    panel_height = 7
    panel_y = screen_height - panel_height

    # Message Log Params
    message_x = bar_width + 2
    message_width = screen_height - bar_width - 2
    message_height = panel_height - 1

    # Map Params
    map_width = 80
    map_height = 43

    # Room Params
    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    # Field of View Params
    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 10

    # Monsters & Items Params
    max_monsters_per_room = 3
    max_items_per_room = 2

    # Colors for tiles
    colors = {
        'dark_wall': tcod.Color(0, 0, 100),
        'dark_ground': tcod.Color(50, 50, 150),
        'light_wall': tcod.Color(130, 110, 50),
        'light_ground': tcod.Color(200, 180, 50)
    }

    # Entities initialization
    fighter_component = Fighter(hp=30, defense=2, power=5)
    player = Entity(0,
                    0,
                    '@',
                    tcod.white,
                    'Player',
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    fighter=fighter_component)
    entities = [player]

    # Game Window initialization
    tcod.console_set_custom_font(
        'arial10x10.png', tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD)
    tcod.console_init_root(screen_width, screen_height,
                           'Move Fast & Kill Things', False)
    con = tcod.console_new(screen_width, screen_height)

    # UI Panel initialization
    panel = tcod.console_new(screen_width, panel_height)

    # Map initialization
    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, player, entities, max_monsters_per_room,
                      max_items_per_room)

    # Field of View Map Computation
    fov_recompute = True
    fov_map = initialize_fov(game_map)

    # Message log initialization
    message_log = MessageLog(message_x, message_width, message_height)

    # Keyboard & Mouse initialization
    key = tcod.Key()
    mouse = tcod.Mouse()

    # Game State initialized to player's turn
    game_state = GameStates.PLAYERS_TURN

    # GAME LOOP
    while not tcod.console_is_window_closed():
        tcod.sys_check_for_event(tcod.EVENT_KEY_PRESS | tcod.EVENT_MOUSE, key,
                                 mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, fov_radius,
                          fov_light_walls, fov_algorithm)

        render_all(con, panel, entities, player, game_map, fov_map,
                   fov_recompute, message_log, screen_width, screen_height,
                   bar_width, panel_height, panel_y, mouse, colors)

        fov_recompute = False

        tcod.console_flush()

        clear_all(con, entities)

        action = handle_keys(key)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        player_turn_results = []

        if move and game_state == GameStates.PLAYERS_TURN:
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy
            if not game_map.is_blocked(destination_x, destination_y):
                target = get_blocking_entities_at_location(
                    entities, destination_x, destination_y)

                if target:
                    # Attack enemy
                    attack_results = player.fighter.attack(target)
                    player_turn_results.extend(attack_results)
                else:
                    # Move player
                    player.move(dx, dy)
                    # Recompute field of vision
                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN

        if exit:
            return True

        if fullscreen:
            tcod.console_set_fullscreen(not tcod.console_is_fullscreen())

        # Handling action results log for player
        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')

            if message:
                message_log.add_message(message)

            if dead_entity:
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity)
                else:
                    message = kill_monster(dead_entity)

                message_log.add_message(message)

        # Handling enemy movement & actions
        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(
                        player, fov_map, game_map, entities)

                    for enemy_turn_result in enemy_turn_results:
                        message = enemy_turn_result.get('message')
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            message_log.add_message(message)

                        if dead_entity:
                            if dead_entity == player:
                                message, game_state = kill_player(dead_entity)
                            else:
                                message = kill_monster(dead_entity)

                            message_log.add_message(message)

                    if game_state == GameStates.PLAYER_DEAD:
                        break
            else:
                game_state = GameStates.PLAYERS_TURN
コード例 #15
0
def main():
    constants = get_constants()

    libtcod.sys_set_fps(30)

    # Animate
    anim_time = libtcod.sys_elapsed_milli()
    anim_frame = 0

    libtcod.console_set_custom_font(
        'sprite-font.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD, 32, 48)
    libtcod.console_init_root(constants['screen_width'],
                              constants['screen_height'],
                              constants['window_title'], False)
    libtcod.console_set_default_background(0, colors.get('dark'))

    load_customfont()

    con = libtcod.console_new(constants['map_width'] * 3,
                              constants['map_height'] * 2)
    panel = libtcod.console_new(constants['panel_width'],
                                constants['screen_height'])
    tooltip = libtcod.console_new(constants['screen_width'], 1)
    messages_pane = libtcod.console_new(constants['message_width'], 1000)
    inventory_pane = libtcod.console_new(constants['message_width'], 40)

    player = None
    entities = []
    game_map = None
    message_log = None
    game_state = None

    show_main_menu = True
    show_load_error_message = False

    main_menu_background_image_0 = libtcod.image_load('menu_background_0.png')
    main_menu_background_image_1 = libtcod.image_load('menu_background_1.png')
    main_menu_background_image_2 = libtcod.image_load('menu_background_2.png')
    main_menu_background_image_3 = libtcod.image_load('menu_background_3.png')

    log_scroll = 0
    inv_scroll = 0

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    while not libtcod.console_is_window_closed():

        anim_frame, anim_time = animation(anim_frame, anim_time)

        if anim_frame == 0:
            main_menu_background_image = main_menu_background_image_0
        elif anim_frame == 1:
            main_menu_background_image = main_menu_background_image_1
        elif anim_frame == 2:
            main_menu_background_image = main_menu_background_image_2
        else:
            main_menu_background_image = main_menu_background_image_3

        libtcod.sys_check_for_event(
            libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)

        if show_main_menu:
            main_menu(con, main_menu_background_image,
                      constants['screen_width'], constants['screen_height'],
                      constants['window_title'])

            if show_load_error_message:
                message_box(con, 'No save game to load', 50,
                            constants['screen_width'],
                            constants['screen_height'])

            libtcod.console_flush()

            action = handle_main_menu(key)

            new_game = action.get('new_game')
            load_saved_game = action.get('load_game')
            exit_game = action.get('exit')

            if show_load_error_message and (new_game or load_saved_game
                                            or exit_game):
                show_load_error_message = False
            elif new_game:
                player, entities, game_map, message_log, game_state = get_game_variables(
                    constants)
                game_state = GameStates.PLAYERS_TURN

                show_main_menu = False
            elif load_saved_game:
                try:
                    player, entities, game_map, message_log, game_state = load_game(
                    )
                    show_main_menu = False
                except FileNotFoundError:
                    show_load_error_message = True
            elif exit_game:
                break

        else:
            libtcod.console_clear(con)
            cam_x, cam_y = update_cam(player, constants)

            log_height, inv_height = update_panels_heights(
                player, constants['panel_height'])
            log_scroll = 0
            inv_scroll = 0
            inv_selected = 0

            play_game(player, entities, game_map, message_log, con, panel,
                      tooltip, messages_pane, inventory_pane, constants, cam_x,
                      cam_y, anim_frame, anim_time, log_scroll, log_height,
                      inv_scroll, inv_height, inv_selected)

            show_main_menu = True
コード例 #16
0
ファイル: engine.py プロジェクト: mdgregoire/roguelike
def main():
    # Needed Variables
    screen_width = 80
    screen_height = 50
    map_width = 80
    map_height = 43

    # health bar
    bar_width = 20
    panel_height = 7
    panel_y = screen_height - panel_height

    # rooms
    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    # fov
    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 10

    # monsters
    max_monsters_per_room = 3

    # items
    max_items_per_room = 10

    # message log
    message_x = bar_width + 2
    message_width = screen_width - bar_width - 2
    message_height = panel_height - 1

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150),
        'light_wall': libtcod.Color(130, 110, 50),
        'light_ground': libtcod.Color(200, 180, 50)
    }

    fighter_component = Fighter(hp=30, defense=2, power=5)
    inventory_component = Inventory(26)
    player = Entity(0,
                    0,
                    '@',
                    libtcod.white,
                    'Player',
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    fighter=fighter_component,
                    inventory=inventory_component)
    entities = [player]

    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    # Creates initial console
    libtcod.console_init_root(screen_width, screen_height,
                              'libtcod tutorial revised', False)

    # Sets default console to draw to.
    console = libtcod.console_new(screen_width, screen_height)
    # hp panel console
    panel = libtcod.console_new(screen_width, panel_height)

    # Creates game map, draws rooms, populates them with monsters and items
    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, player, entities, max_monsters_per_room,
                      max_items_per_room)

    fov_recompute = True
    fov_map = initialize_fov(game_map)

    message_log = MessageLog(message_x, message_width, message_height)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    game_state = GameStates.PLAYERS_TURN
    # Tracks the old game state, used when opening menus
    previous_game_state = game_state

    targeting_item = None

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(
            libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, fov_radius,
                          fov_light_walls, fov_algorithm)

        render_all(console, panel, entities, player, game_map, fov_map,
                   fov_recompute, message_log, screen_width, screen_height,
                   bar_width, panel_height, panel_y, mouse, colors, game_state)

        fov_recompute = False

        libtcod.console_flush()

        clear_all(console, entities)

        action = handle_keys(key, game_state)
        mouse_action = handle_mouse(mouse)

        # Player actions
        move = action.get('move')
        pickup = action.get('pickup')
        # Inventory actions
        show_inventory = action.get('show_inventory')
        drop_inventory = action.get('drop_inventory')
        # Used when interacting with inventory
        inventory_index = action.get('inventory_index')
        # Out of game actions, do not take a turn
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')
        # Mouse clicks
        left_click = mouse_action.get('left_click')
        right_click = mouse_action.get('right_click')

        player_turn_results = []

        if move and game_state == GameStates.PLAYERS_TURN:
            dx, dy = move

            destination_x = player.x + dx
            destination_y = player.y + dy

            if not game_map.is_blocked(destination_x, destination_y):
                target = get_blocking_entities_at_location(
                    entities, destination_x, destination_y)

                if target:
                    attack_results = player.fighter.attack(target)
                    player_turn_results.extend(attack_results)
                else:
                    player.move(dx, dy)

                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN

        elif pickup and game_state == GameStates.PLAYERS_TURN:
            for entity in entities:
                if entity.item and entity.x == player.x and entity.y == player.y:
                    pickup_results = player.inventory.add_item(entity)
                    player_turn_results.extend(pickup_results)

                    break
            else:
                message_log.add_message(
                    Message('There is nothing here to pick up.',
                            libtcod.yellow))

        if show_inventory:
            previous_game_state = game_state
            game_state = GameStates.SHOW_INVENTORY

        if drop_inventory:
            previous_game_state = game_state
            game_state = GameStates.DROP_INVENTORY

        if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len(
                player.inventory.items):
            item = player.inventory.items[inventory_index]
            if game_state == GameStates.SHOW_INVENTORY:
                player_turn_results.extend(
                    player.inventory.use(item,
                                         entities=entities,
                                         fov_map=fov_map))
            elif game_state == GameStates.DROP_INVENTORY:
                player_turn_results.extend(player.inventory.drop_item(item))

        if game_state == GameStates.TARGETING:
            if left_click:
                target_x, target_y = left_click

                item_use_results = player.inventory.use(targeting_item,
                                                        entities=entities,
                                                        fov_map=fov_map,
                                                        target_x=target_x,
                                                        target_y=target_y)
                player_turn_results.extend(item_use_results)
            elif right_click:
                player_turn_results.append({'targeting_cancelled': True})

        if exit:
            if game_state in (GameStates.SHOW_INVENTORY,
                              GameStates.DROP_INVENTORY):
                game_state = previous_game_state
            elif game_state == GameStates.TARGETING:
                player_turn_results.append({'targeting_cancelled': True})
            else:
                return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())

        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')
            item_added = player_turn_result.get('item_added')
            item_consumed = player_turn_result.get('consumed')
            item_dropped = player_turn_result.get('item_dropped')
            targeting = player_turn_result.get('targeting')
            targeting_cancelled = player_turn_result.get('targeting_cancelled')

            if message:
                message_log.add_message(message)

            if targeting_cancelled:
                game_state = previous_game_state

                message_log.add_message(Message('Targeting Cancelled'))

            if dead_entity:
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity)
                else:
                    message = kill_monster(dead_entity)

                message_log.add_message(message)

            if item_added:
                entities.remove(item_added)
                game_state = GameStates.ENEMY_TURN

            if item_consumed:
                game_state = GameStates.ENEMY_TURN

            if targeting:
                previous_game_state = GameStates.PLAYERS_TURN
                game_state = GameStates.TARGETING

                targeting_item = targeting

                message_log.add_message(targeting_item.item.targeting_message)

            if item_dropped:
                entities.append(item_dropped)
                game_state = GameStates.ENEMY_TURN

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(
                        player, fov_map, game_map, entities)

                    for enemy_turn_result in enemy_turn_results:
                        message = enemy_turn_result.get('message')
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            message_log.add_message(message)

                        if dead_entity:
                            if dead_entity == player:
                                message, game_state = kill_player(dead_entity)
                            else:
                                message = kill_monster(dead_entity)

                            message_log.add_message(message)

                        if game_state == GameStates.PLAYER_DEAD:
                            break

                    if game_state == GameStates.PLAYER_DEAD:
                        break

                    else:
                        game_state = GameStates.PLAYERS_TURN
コード例 #17
0
ファイル: engine.py プロジェクト: Shreddan/Python-LibTcodTest
def main():
    screen_width = 100
    screen_height = 60
    map_width = 100
    map_height = 55

    room_max_size = 15
    room_min_size = 10
    max_rooms = 20

    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 10

    Max_Monsters_Per_Room = 3

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150),
        'light_wall': libtcod.Color(130, 110, 50),
        'light_ground': libtcod.Color(200, 180, 50)
    }

    fighter_component = Fighter(hp=30, defense=2, power=5)
    player = Entity(0,
                    0,
                    '@',
                    libtcod.white,
                    'Danicron',
                    blocks=True,
                    render_order=RenderOrder.Actor,
                    fighter=fighter_component)
    entities = [player]

    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(screen_width, screen_height,
                              'Dans Libtcod Experience', False)

    con = libtcod.console_new(screen_width, screen_height)

    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, player, entities, Max_Monsters_Per_Room)

    fov_recompute = True

    fov_map = initialize_fov(game_map)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    Game_State = GameStates.Player_Turn

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, fov_radius,
                          fov_light_walls, fov_algorithm)

        render_all(con, entities, player, game_map, fov_map, fov_recompute,
                   screen_width, screen_height, colors)

        fov_recompute = False
        libtcod.console_put_char(0, player.x, player.y, '@',
                                 libtcod.BKGND_NONE)
        libtcod.console_flush()
        clear_all(con, entities)

        action = handle_keys(key)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        player_turn_results = []

        if move and Game_State == GameStates.Player_Turn:
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy
            if not game_map.is_blocked(destination_x, destination_y):
                target = get_blocking_entities_at_location(
                    entities, destination_x, destination_y)

                if target:
                    attack_results = player.fighter.attack(target)
                    player_turn_results.extend(attack_results)
                else:
                    player.move(dx, dy)
                    fov_recompute = True

                Game_State = GameStates.Enemy_Turn

        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())

        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')

            if message:
                print(message)

            if dead_entity:
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity)
                else:
                    message = kill_monster(dead_entity)

                print(message)

        if Game_State == GameStates.Enemy_Turn:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(
                        player, fov_map, game_map, entities)

                    for enemy_turn_result in enemy_turn_results:
                        message = enemy_turn_result.get('message')
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            print(message)

                        if dead_entity:
                            if dead_entity == player:
                                message, game_state = kill_player(dead_entity)
                            else:
                                message = kill_monster(dead_entity)

                            print(message)

                            if game_state == GameStates.PLAYER_DEAD:
                                break

                        if game_state == GameStates.PLAYER_DEAD:
                            break

        else:
            Game_State = GameStates.Player_Turn
コード例 #18
0
ファイル: main.py プロジェクト: dan-oppenheim/XPLoader
raw_data = xp_file.read()
xp_file.close()

xp_data = xp_loader.load_xp_string(raw_data)

screen_width = xp_data['width']
screen_height = xp_data['height']
limit_fps = 20

####################
# The default libtcod font sheet format is missing quite a few codepage 437 characters - if you want to use REXPaint, you'll need to find or make make a sprite sheet with those characters
# Currently using the 10x10 default REXPaint sheet courtesy of Kyzrati
####################

libtcod.console_set_custom_font(
    'cp437_10x10.png',
    libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_ASCII_INROW)
libtcod.console_init_root(screen_width, screen_height, 'REXPaint Import Demo',
                          False)
libtcod.sys_set_fps(limit_fps)

####################
# Loads the layer data to offscreen consoles. You can load a layer to the main console by passing in 0 instead of a console
####################

layer_0_console = libtcod.console_new(xp_data['layer_data'][0]['width'],
                                      xp_data['layer_data'][0]['height'])
layer_1_console = libtcod.console_new(xp_data['layer_data'][1]['width'],
                                      xp_data['layer_data'][1]['height'])

xp_loader.load_layer_to_console(layer_0_console, xp_data['layer_data'][0])
コード例 #19
0
ファイル: snippets.py プロジェクト: rukisama/arcturus_2019
def main():

    tcod.console_set_custom_font(
        "potash_10x10.png",
        tcod.FONT_LAYOUT_ASCII_INROW | tcod.FONT_TYPE_GREYSCALE)
    root_console = tcod.console_init_root(width,
                                          height,
                                          title,
                                          renderer=renderer,
                                          order=order,
                                          vsync=vsync)
    tcod.sys_set_fps(30)

    num_particles = randint(35, 100)

    edges = []
    for x in range(0, width):
        edges.append((x, 0))
        edges.append((x, height - 1))
    for y in range(0, height):
        edges.append((0, y))
        edges.append((width - 1, y))

    p_list = []
    for i in range(num_particles):
        xo = width // 2
        yo = height // 2
        xd, yd = choice(edges)
        p_list.append(Particle(xo, yo, xd, yd))

    # for p in p_list:
    #     p.print_path()

    while True:
        for event in tcod.event.get():
            if event.type == "QUIT" or (event.type == "KEYDOWN"
                                        and event.sym == tcod.event.K_ESCAPE):
                raise SystemExit()

        # Test code here

        for particle in p_list:
            try:
                x, y = particle.next()
                root_console.ch[x, y] = particle.glyph
                root_console.fg[x, y] = particle.color
            except StopIteration:
                p_list.remove(particle)
                xo = width // 2
                yo = height // 2
                xd, yd = choice(edges)
                p_list.append(Particle(xo, yo, xd, yd))
                if len(p_list) > 100:
                    p_list = p_list[0:100]

        root_console.ch[width // 2, height // 2] = 0
        root_console.ch[width // 2 - 3:width // 2 + 3, height // 2] = 0
        root_console.ch[width // 2, height // 2 - 3:height // 2 + 3] = 0
        root_console.ch[width // 2 - 2:width // 2 + 3,
                        height // 2 - 2:height // 2 + 3] = 0

        tcod.console_flush()
        root_console.clear()
コード例 #20
0
ファイル: menu.py プロジェクト: kkairos/unnamed-rl-base
def menu(target_console, menu_console):

    menu_selection = 0
    while True:
        menu_print(menu_console)
        re.draw_s(menu_console, menu_selection)
        re.draw_con(target_console, menu_console,
                    (target_console.width - menu_console.width) // 2,
                    (target_console.height - menu_console.height) // 2 - 1)
        tcod.console_flush()
        re.clear_s(menu_console, menu_selection)
        for event in tcod.event.wait():
            if event.type == "KEYDOWN":
                action = key_input(event.sym)
                move = False
                exit = False
                pause = False
                pause = action.get('pause')
                exit = action.get('exit')
                move = action.get('move')
                if move:
                    dx, dy = move
                    if dx == 0:
                        menu_selection = (menu_selection + dy) % len(
                            cx.SETTINGS)
                    tmp_sel = [cx.SETTINGS[1]["sel"]]
                    if (dy == 0 and
                            cx.SETTINGS[menu_selection]["sel"] != "NO_SEL"):
                        cx.SETTINGS[menu_selection]["sel"] = (
                            cx.SETTINGS[menu_selection]["sel"] + dx) % len(
                                cx.DESC[cx.SETTINGS[menu_selection]["desc"]])
                    if [cx.SETTINGS[1]["sel"]] != tmp_sel:
                        temp_console = []
                        for x_store in range(0, target_console.width):
                            temp_console.append([])
                            for y_store in range(0, target_console.height):
                                temp_console[x_store].append([
                                    target_console.ch[x_store][y_store],
                                    (target_console.fg[x_store][y_store][0],
                                     target_console.fg[x_store][y_store][1],
                                     target_console.fg[x_store][y_store][2]),
                                    (target_console.bg[x_store][y_store][0],
                                     target_console.bg[x_store][y_store][1],
                                     target_console.bg[x_store][y_store][2])
                                ])
                        tcod.console_set_custom_font(
                            cx.FONT_FILE[cx.SETTINGS[1]["sel"]],
                            tcod.FONT_TYPE_GREYSCALE
                            | tcod.FONT_LAYOUT_ASCII_INROW, 32, 8)
                        target_console = tcod.console_init_root(
                            target_console.width, target_console.height,
                            "D@N ROGUE", False, 3, "F", True)
                        for y_store in range(0, target_console.height):
                            for x_store in range(0, target_console.width):
                                target_console.ch[x_store][
                                    y_store] = temp_console[x_store][y_store][
                                        0]
                                target_console.fg[x_store][
                                    y_store] = temp_console[x_store][y_store][
                                        1]
                                target_console.bg[x_store][
                                    y_store] = temp_console[x_store][y_store][
                                        2]
                if exit or pause:
                    return
コード例 #21
0
ファイル: engine.py プロジェクト: dnoparker/RLDPython
def main():
    screen_width = 80
    screen_height = 50
    map_width = 80
    map_height = 45

    room_max_size = 12
    room_min_size = 8
    max_rooms = 35

    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 10

    max_monsters_per_room = 3

    colours = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150),
        'light_wall': libtcod.Color(130, 110, 50),
        'light_ground': libtcod.Color(200, 180, 50),
        'corridor': libtcod.Color(255, 0, 0)
    }

    player = Entity(0, 0, '@', libtcod.white, 'Player', blocks=True)
    entities = [player]

    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(screen_width, screen_height, 'Roguelike', False)

    con = libtcod.console_new(screen_width, screen_height)

    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, player, entities, max_monsters_per_room)

    fov_recompute = True
    fov_map = initialize_fov(game_map)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    game_state = GameStates.PLAYERS_TURN

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, fov_radius,
                          fov_light_walls, fov_algorithm)

        render_all(con, entities, game_map, fov_map, fov_recompute,
                   screen_width, screen_height, colours)

        fov_recompute = False

        libtcod.console_flush()

        clear_all(con, entities)

        action = handle_keys(key)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        if move and game_state == GameStates.PLAYERS_TURN:
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy

            if not game_map.is_blocked(destination_x, destination_y):
                target = get_blocking_entities_at_location(
                    entities, destination_x, destination_y)

                if target:
                    print('You kick the ' + target.name +
                          ' in the shins, much to its annoyance!')
                else:
                    player.move(dx, dy)

                    fov_recompute = True

            game_state = GameStates.ENEMY_TURN

        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())

            return True

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity != player:
                    print('The ' + entity.name +
                          ' ponders the meaning of its existence.')

            game_state = GameStates.PLAYERS_TURN
コード例 #22
0
            libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)
        render_all()
        libtcod.console_flush()
        check_level_up()
        for object in objects:
            object.clear()
    #handle keys and exit game if needed
        player_action = handle_keys()
        if player_action == 'exit':
            save_game()
            break
        if game_state == 'playing' and player_action != 'didnt-take-turn':
            for object in objects:
                if object.ai:
                    object.ai.take_turn()


#############################################
# Initialization & Main Loop
#############################################
libtcod.console_set_custom_font(
    'font-6.png',
    (libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_ASCII_INROW), 0, 0)
libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT,
                          'python/libtcod tutorial', False)
libtcod.sys_set_fps(LIMIT_FPS)
con = libtcod.console_new(MAP_WIDTH, MAP_HEIGHT)
panel = libtcod.console_new(SCREEN_WIDTH, PANEL_HEIGHT)

main_menu()
コード例 #23
0
def main():

    player = Player(1, 1, 'O', tcod.green)

    tcod.console_set_custom_font(
        'arial10x10.png', tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD)
    tcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'Maze', False,
                           tcod.RENDERER_SDL2)

    con = tcod.console.Console(MAP_WIDTH, MAP_HEIGHT)
    tcod.sys_set_fps(LIMIT_FPS)

    fov_map = tcod.map.Map(MAP_WIDTH, MAP_HEIGHT)
    global compute_fov
    compute_fov = False

    cells = [[Cell() for y in range(MAP_COLS)] for x in range(MAP_ROWS)]

    makeMap(cells)

    choice = 0

    (wall_set, cells_finished, cells) = prim.init_variables(MAP_ROWS, MAP_COLS)

    while len(cells_finished) != MAP_ROWS * MAP_COLS:
        cells = prim.generate_maze(wall_set, cells_finished, cells, MAP_ROWS,
                                   MAP_COLS)

    makeMap(cells)

    for y in range(MAP_HEIGHT):
        for x in range(MAP_WIDTH):
            fov_map.walkable[:]
            fov_map.transparent[:]

    render(player, con, fov_map, True)
    tcod.console_blit(con, 0, 0, MAP_WIDTH, MAP_HEIGHT, 0, 0, 0)
    tcod.console_flush()

    while not tcod.console_is_window_closed():

        if player.xPos == MAP_WIDTH - 2 and player.yPos == MAP_HEIGHT - 2:
            render(player, con, fov_map, False)
            tcod.console_put_char_ex(con, 1, 1, 'S', tcod.pink, tcod.black)
            player.draw(con)
            tcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0)
            tcod.console_flush()

            key = tcod.console_wait_for_keypress(True)
            break

        render(player, con, fov_map, fog_of_war)

        tcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0)
        tcod.console_flush()

        player.erase(con)

        quit = keyboard_input(player, con)

        if quit:
            render(player, con, fov_map, True, qui)
            tcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0)
            tcod.console_flush()

            key = tcod.console_wait_for_keypress(True)

            if key.vk == tcod.KEY_ESCAPE:
                render(player, con, fov_map, False, qui)
                player.draw(con)
                tcod.console_blit(con, 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0,
                                  0)
                tcod.console_flush()

                key = tcod.console_wait_for_keypress(True)
                break
コード例 #24
0
def main():
    screen_width = 80
    screen_height = 50

    map_width = 80
    map_height = 50

    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 6

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150),
        'light_wall': libtcod.Color(130, 110, 50),
        'light_ground': libtcod.Color(200, 180, 50)
    }

    player = Entity(int(screen_width / 2), int(screen_height / 2), '@',
                    libtcod.white)
    npc = Entity(int(screen_width / 2), int(screen_height / 2 - 5), '@',
                 libtcod.green)
    entities = [npc, player]

    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(screen_width, screen_height, 'Roguelike Test',
                              False)

    con = libtcod.console_new(screen_width, screen_height)

    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, player)

    fov_recompute = True

    fov_map = initialize_fov(game_map)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, fov_radius,
                          fov_light_walls, fov_algorithm)

        render_all(con, entities, game_map, fov_map, fov_recompute,
                   screen_width, screen_height, colors)

        fov_recompute = False

        libtcod.console_flush()

        clear_all(con, entities)

        action = handle_keys(key)
        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        if move:
            dx, dy = move

            if not game_map.is_blocked(player.x + dx, player.y + dy):
                player.move(dx, dy)

                fov_recompute = True

        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
コード例 #25
0
ファイル: engine.py プロジェクト: Nicocchi/rougelike
def main():
    constants = get_constants()

    libtcodpy.console_set_custom_font(
        'data/terminal10x10_gs_tc.png',
        libtcodpy.FONT_TYPE_GREYSCALE | libtcodpy.FONT_LAYOUT_TCOD)

    libtcodpy.console_init_root(constants['screen_width'],
                                constants['screen_height'],
                                constants['window_title'], False)

    con = libtcodpy.console_new(constants['screen_width'],
                                constants['screen_height'])
    panel = libtcodpy.console_new(constants['screen_width'],
                                  constants['panel_height'])

    player = None
    entities = []
    game_map = None
    message_log = None
    game_state = None

    show_main_menu = True
    show_load_error_message = False

    main_menu_background_image = libtcodpy.image_load(
        'data/menu_background.png')

    key = libtcodpy.Key()
    mouse = libtcodpy.Mouse()
    menu_index = 0

    while not libtcodpy.console_is_window_closed():
        libtcodpy.sys_check_for_event(
            libtcodpy.EVENT_KEY_PRESS | libtcodpy.EVENT_MOUSE, key, mouse)

        if show_main_menu:
            main_menu(con, main_menu_background_image,
                      constants['screen_width'], constants['screen_height'],
                      game_state, menu_index)

            if show_load_error_message:
                message_box(con, 'No save game to load', 50,
                            constants['screen_width'],
                            constants['screen_height'])

            libtcodpy.console_flush()

            action = handle_main_menu(key)

            new_game = action.get('new_game')
            load_saved_game = action.get('load_game')
            exit_game = action.get('exit')
            up = action.get('up')
            down = action.get('down')
            enter = action.get('enter')

            if show_load_error_message and (new_game or load_saved_game
                                            or exit_game):
                show_load_error_message = False
            elif up:
                if menu_index <= 0:
                    menu_index = 0
                else:
                    menu_index -= 1
            elif down:
                if menu_index >= 2:
                    menu_index = 2
                else:
                    menu_index += 1
            elif enter:
                if menu_index == 0:
                    player, entities, game_map, message_log, game_state = get_game_variables(
                        constants)
                    game_state = GameStates.PLAYERS_TURN

                    show_main_menu = False
                elif menu_index == 1:
                    try:
                        player, entities, game_map, message_log, game_state = load_game(
                        )
                        show_main_menu = False
                    except FileNotFoundError:
                        show_load_error_message = True
                elif menu_index == 2:
                    break
            elif new_game:
                player, entities, game_map, message_log, game_state = get_game_variables(
                    constants)
                game_state = GameStates.PLAYERS_TURN

                show_main_menu = False
            elif load_saved_game:
                try:
                    player, entities, game_map, message_log, game_state = load_game(
                    )
                    show_main_menu = False
                except FileNotFoundError:
                    show_load_error_message = True
            elif exit_game:
                break

        else:
            libtcodpy.console_clear(con)
            play_game(player, entities, game_map, message_log, game_state, con,
                      panel, constants)

            show_main_menu = True
コード例 #26
0
ファイル: engine.py プロジェクト: psizek/quaffquest
def main():

    rootDir = Path(__file__).parent.parent
    fontpath = rootDir / 'gfx' / 'arial10x10.png'
    tcod.console_set_custom_font(
        str(fontpath), tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD)

    with tcod.console_init_root(c.SCREEN_WIDTH, c.SCREEN_HEIGHT,
                                c.WINDOW_TITLE, False,
                                tcod.RENDERER_SDL2) as root_con:

        con: tcod.console.Console = tcod.console.Console(
            c.SCREEN_WIDTH, c.SCREEN_HEIGHT)
        panel: tcod.console.Console = tcod.console.Console(
            c.SCREEN_WIDTH, c.PANEL_HEIGHT)

        player = None
        entities = []
        game_map = None
        message_log = None
        game_state = None

        show_main_menu: bool = True
        show_load_error_message: bool = False

        main_menu_img_background = tcod.image_load('menu_background.png')

        state = MainMenu_State()

        while True:
            for event in tcod.event.wait():
                state.dispatch(event)

                if show_main_menu:
                    main_menu(root_con, main_menu_img_background)

                    if show_load_error_message:
                        message_box(root_con, 'No save game to load', 50)

                    tcod.console_flush()

                    if state.action:
                        new_game = state.action.get('new_game')
                        load_saved_game = state.action.get('load_game')
                        exit_game = state.action.get('exit')

                        if show_load_error_message and (new_game
                                                        or load_saved_game
                                                        or exit_game):
                            show_load_error_message = False
                        elif new_game:
                            player, entities, game_map, message_log, game_state = get_game_variables(
                            )
                            game_state = GameStates.PLAYERS_TURN
                            show_main_menu = False
                        elif load_saved_game:
                            try:
                                player, entities, game_map, message_log, game_state = load_game(
                                )
                                show_main_menu = False
                            except FileNotFoundError:
                                show_load_error_message = True
                        elif exit_game:
                            return
                else:
                    root_con.clear()
                    play_game(player, entities, game_map, message_log,
                              game_state, root_con, con, panel)

                    return
コード例 #27
0
def main():
    #System stuff
    keySys = KeybindingSystem()

    #Screen stuff
    screen_width = 80
    screen_height = 50

    #Map genration stuff
    map_width = 80
    map_height = 50
    room_max_size = 10
    room_min_size = 6
    max_rooms = 30
    maxMonPerRoom = 3

    #FOV stuff
    fov_radius_base = 5
    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = fov_radius_base  #Set to base so it can be modified by the game for torches etc

    colors = {
        'player': tcd.Color(50, 255, 50),
        'enemy': tcd.Color(255, 50, 255),
        'friendly': tcd.Color(75, 255, 75),
        'dark_wall': tcd.Color(0, 0, 100),
        'dark_ground': tcd.Color(50, 50, 150),
        'light_wall': tcd.Color(130, 110, 50),
        'light_ground': tcd.Color(200, 100, 50)
    }
    fightComp = Fighter(0, 0, 0, 0, 0, 0)
    ply = Entity(0,
                 0,
                 '@',
                 colors.get('player'),
                 'Player',
                 blocks=True,
                 fighter=fightComp)
    entities = [ply]

    tcd.console_set_custom_font('font.png',
                                tcd.FONT_TYPE_GREYSCALE | tcd.FONT_LAYOUT_TCOD)

    tcd.console_init_root(screen_width, screen_height, 'Rougelike Chicken',
                          False)
    con = tcd.console_new(screen_width, screen_height)

    #Map stuff
    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, ply, entities, maxMonPerRoom)

    #FOV Stuff
    fov_recompute = True
    fov_map = initialize_fov(game_map)

    #Input Shnizzle
    key = tcd.Key()
    mouse = tcd.Mouse()

    #Game state stuff
    game_state = GameStates.PLAYERS_TURN

    while not tcd.console_is_window_closed():
        tcd.sys_check_for_event(tcd.EVENT_KEY_PRESS, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, ply.x, ply.y, fov_radius, fov_light_walls,
                          fov_algorithm)

        render_all(con, entities, game_map, fov_map, fov_recompute,
                   screen_width, screen_height, colors)

        fov_recompute = False

        tcd.console_flush()

        clear_all(con, entities)

        action = keySys.handleKeys(key)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        if move and game_state == GameStates.PLAYERS_TURN:
            dx, dy = move
            xDest = ply.x + dx  #Where we are going to bes X
            yDest = ply.y + dy  #Where we are going to be Y
            if not game_map.is_blocked(xDest, yDest):
                target = get_blocking_entities_at_location(
                    entities, xDest, yDest)

                if target:
                    ply.fighter.physAttack(target)
                else:
                    ply.move(dx, dy)

                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN

        if exit:
            return True

        if fullscreen:
            tcd.console_set_fullscreen(not tcd.console_is_fullscreen())

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    entity.ai.take_turn(ply, fov_map, game_map, entities)

            game_state = GameStates.PLAYERS_TURN
コード例 #28
0
ファイル: ui.py プロジェクト: pwmarcz/madness
def cycle_font():
    global FONT_INDEX
    FONT_INDEX = (FONT_INDEX + 1) % len(FONTS)
    T.console_set_custom_font(*FONTS[FONT_INDEX])
    T.console_init_root(SCREEN_W, SCREEN_H, TITLE, False)
コード例 #29
0
def main():
    screen_width = 80
    screen_height = 50
    map_width = 80
    map_height = 45

    fov_algorithm = 2
    fov_light_walls = True
    fov_radius = 10

    max_monsters_per_room = 10

    time_moved_last = time.time()

    colors = {
        'dark_wall': libtcod.Color(10, 45, 25),
        'dark_ground': libtcod.Color(12, 60, 37),
        'light_wall': libtcod.Color(40, 80, 20),
        'light_ground': libtcod.Color(45, 115, 50)
    }

    fighter_component = Fighter(hp=30, defense=2, power=5, speed=10)
    player = Entity(0, 0, '@', libtcod.white, 'Player', blocks=True, fighter=fighter_component)
    entities = [player]
    
    libtcod.console_set_custom_font('arial12x12.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(screen_width, screen_height, 'libtcod tutorial revised', False)

    con = libtcod.console_new(screen_width, screen_height)

    game_map = GameMap(map_width, map_height)
    game_map.make_map(player, entities, max_monsters_per_room)

    fov_recompute = True

    fov_map = initialize_fov(game_map)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm)

        render_all(con, entities, game_map, fov_map, fov_recompute, screen_width, screen_height, colors)

        fov_recompute = False

        libtcod.console_flush()

        clear_all(con, entities)

        action = handle_keys(key)

        move = action.get('move')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')
        smooth = action.get('smooth')

        if move:
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy
            if not game_map.is_blocked(destination_x, destination_y):
                target = get_blocking_entities_at_location(entities, destination_x, destination_y)

                if(time.time() - time_moved_last > (1/player.fighter.speed)):
                    if target:
                        print('You kick the ' + target.name + ' in the shins, much to its annoyance!')
                    else:
                        player.move(dx, dy)
                        fov_recompute = True
                    time_moved_last = time.time()

        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
        
        if smooth:
            game_map.smooth_tiles()
コード例 #30
0
ファイル: engine.py プロジェクト: Julioevm/tcod_roguelike
def main():
    screen_width = 80
    screen_height = 50

    bar_width = 20
    panel_height = 7
    panel_y = screen_height - panel_height

    message_x = bar_width + 2
    message_width = screen_width - bar_width - 2
    message_height = panel_height - 1

    map_width = 80
    map_height = 43

    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 10

    max_monsters_per_room = 3
    max_items_per_room = 2

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150),
        'light_wall': libtcod.Color(130, 110, 50),
        'light_ground': libtcod.Color(200, 180, 50),
    }

    # Initialize entities
    fighter_component = Fighter(hp=30, defense=2, power=5)
    inventory_component = Inventory(26)
    player = Entity(0,
                    0,
                    '@',
                    libtcod.white,
                    'Player',
                    blocks=True,
                    render_order=RenderOrder.ACTOR,
                    fighter=fighter_component,
                    inventory=inventory_component)
    entities = [player]

    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GRAYSCALE | libtcod.FONT_LAYOUT_TCOD)
    # Initialize console
    libtcod.console_init_root(screen_width, screen_height,
                              'libtcod roguelike!', False)
    con = libtcod.console_new(screen_width, screen_height)
    panel = libtcod.console_new(screen_width, panel_height)

    # Initialize Map
    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width,
                      map_height, player, entities, max_monsters_per_room,
                      max_items_per_room)

    fov_recompute = True

    fov_map = initialize_fov(game_map)

    message_log = MessageLog(message_x, message_width, message_height)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    game_state = GameStates.PLAYER_TURN

    while not libtcod.console_is_window_closed():
        # Read input
        libtcod.sys_check_for_event(
            libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, fov_radius,
                          fov_light_walls, fov_algorithm)

        # Draw entities
        render_all(con, panel, entities, player, game_map, fov_map,
                   fov_recompute, message_log, screen_width, screen_height,
                   bar_width, panel_height, panel_y, mouse, colors)

        libtcod.console_flush()

        clear_all(con, entities)

        action = handle_keys(key)

        move = action.get('move')
        pickup = action.get('pickup')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        player_turn_results = []

        # Movement
        if move and game_state == GameStates.PLAYER_TURN:
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy

            if not game_map.is_blocked(destination_x, destination_y):
                target = get_blocking_entities_at_location(
                    entities, destination_x, destination_y)

                if target:
                    attack_results = player.fighter.attack(target)
                    player_turn_results.extend(attack_results)
                else:
                    player.move(dx, dy)
                    fov_recompute = True

                # End player turn
                game_state = GameStates.ENEMY_TURN
        elif pickup and game_state == GameStates.PLAYER_TURN:
            for entity in entities:
                if entity.item and entity.x == player.x and entity.y == player.y:
                    pickup_results = player.inventory.add_item(entity)
                    player_turn_results.extend(pickup_results)

                    break
            else:
                message_log.add_message(
                    Message("There's nothing to pick up here.",
                            libtcod.yellow))
        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())

        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')
            item_added = player_turn_result.get('item_added')

            if message:
                message_log.add_message(message)

            if dead_entity:
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity)
                else:
                    message = kill_monster(dead_entity)

                message_log.add_message(message)

            if item_added:
                entities.remove(item_added)

                game_state = GameStates.ENEMY_TURN

        # Enemy turn
        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(
                        player, fov_map, game_map, entities)

                    for enemy_turn_result in enemy_turn_results:
                        message = enemy_turn_result.get('message')
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            message_log.add_message(message)

                        if dead_entity:
                            if dead_entity == player:
                                message, game_state = kill_player(dead_entity)
                            else:
                                message = kill_monster(dead_entity)

                        message_log.add_message(message)

                        if game_state == GameStates.PLAYER_DEAD:
                            break

                    if game_state == GameStates.PLAYER_DEAD:
                        break
            else:
                game_state = GameStates.PLAYER_TURN
コード例 #31
0
ファイル: engine.py プロジェクト: sbackus/RogueLike
def main():

    arial_font_path = app_path('assets', 'images', 'arial10x10.png')

    libtcod.console_set_custom_font(
        arial_font_path,
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(Constants.screen_width, Constants.screen_height,
                              'Rogue Possession', False)

    con = libtcod.console_new(Constants.screen_width, Constants.screen_height)
    panel = libtcod.console_new(Constants.screen_width, Constants.panel_height)

    player = None
    entities = []
    game_map = None
    message_log = None
    game_state = None

    show_main_menu = True
    show_load_error_message = False

    bg_path = app_path('assets', 'images', 'menu_fire_background.png')
    main_menu_background_image = libtcod.image_load(bg_path)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    while not libtcod.console_is_window_closed():
        libtcod.sys_check_for_event(
            libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)

        if show_main_menu:
            main_menu(con, main_menu_background_image, Constants.screen_width,
                      Constants.screen_height)

            if show_load_error_message:
                message_box(con, 'No save game to load', 50,
                            Constants.screen_width, Constants.screen_height)

            libtcod.console_flush()

            action = handle_main_menu(key)

            new_game = action.get('new_game')
            load_saved_game = action.get('load_game')
            exit_game = action.get('exit')

            if show_load_error_message and (new_game or load_saved_game
                                            or exit_game):
                show_load_error_message = False
            elif new_game:
                player, entities, game_map, message_log, game_state = get_game_variables(
                    Constants)
                game_state = GameStates.PLAYERS_TURN

                show_main_menu = False
            elif load_saved_game:
                try:
                    player, entities, game_map, message_log, game_state = load_game(
                    )
                    show_main_menu = False
                except FileNotFoundError:
                    show_load_error_message = True
            elif exit_game:
                break

        else:
            libtcod.console_clear(con)
            play_game(player, entities, game_map, message_log, game_state, con,
                      panel, Constants)

            show_main_menu = True
コード例 #32
0
ファイル: 1rl.py プロジェクト: cpiod/1rl
def main():
    screen_width = 128
    screen_height = 48

    sch_height = 3
    sch_width = 27

    # Inventory
    inv_height = screen_height - sch_height
    inv_width = sch_width

    # Log
    log_height = 10
    log_width = screen_width - inv_width

    # Size of the map
    map_width = screen_width - inv_width
    map_height = screen_height - log_height - 1

    # Popup size
    popup_width = round(7 * map_width / 12)
    popup_height = round(7 * map_height / 12)

    # tcod init
    tcod.console_set_custom_font(resource_path('font.png'),
                                 tcod.FONT_LAYOUT_ASCII_INROW)
    root_console = tcod.console_init_root(screen_width, screen_height,
                                          '1RL v1.2 – 7DRL 2019')
    tcod.console_set_default_background(root_console, const.base03)

    # map console
    con = tcod.console.Console(map_width, map_height)
    tcod.console_set_default_background(con, const.base03)

    # description console
    des_panel = tcod.console.Console(log_width, 1)
    tcod.console_set_default_background(des_panel, const.base03)

    # log console
    log_panel = tcod.console.Console(log_width, log_height)
    tcod.console_set_default_background(log_panel, const.base03)

    # popup console
    popup_panel = tcod.console.Console(popup_width, popup_height)
    tcod.console_set_default_background(popup_panel, const.base03)

    # scheduling console
    sch_panel = tcod.console.Console(sch_width, sch_height)
    tcod.console_set_default_background(sch_panel, const.base03)

    # inventory console
    inv_panel = tcod.console.Console(inv_width, inv_height)
    tcod.console_set_default_background(inv_panel, const.base03)

    # scheduling
    turns = sch.Scheduling()

    # map generation
    game_map = gmap.GameMap(map_width, map_height, con)

    # log init
    msglog = log.Log(log_width - 2, log_height - 2)

    # splash image
    splash_img = tcod.image_load(resource_path("splash.png"))

    while not tcod.console_is_window_closed():
        tcod.console_clear(con)
        tcod.console_clear(des_panel)
        tcod.console_clear(log_panel)
        tcod.console_clear(popup_panel)
        tcod.console_clear(sch_panel)
        tcod.console_clear(inv_panel)
        const.n_bugs_max = [[5, 0, 0], [2, 5, 1]]
        player = entity.Player(None, None)
        entities = [player]
        msglog.reset()
        turns.reset()
        turns.add_turn(
            0, const.TurnType.MSG,
            log.Msg(
                "They say the hardest part is actually choosing to make a game.  So I guess I've already won?",
                const.green, const.desat_green2))
        turns.add_turn(0, const.TurnType.PLAYER, player)
        turns.add_turn(
            3600 * 24, const.TurnType.MSG,
            log.Msg("You have 6 days left.", const.green, const.desat_green2))
        turns.add_turn(
            3600 * 24 * 2, const.TurnType.MSG,
            log.Msg("You have 5 days left.  Keep going.", const.green,
                    const.desat_green2))
        turns.add_turn(
            3600 * 24 * 3, const.TurnType.MSG,
            log.Msg("You have 4 days left.  Don't be too ambitious!",
                    const.orange, const.desat_orange))
        turns.add_turn(
            3600 * 24 * 4, const.TurnType.MSG,
            log.Msg("You have 3 days left.  That's less than half a week...",
                    const.orange, const.desat_orange))
        turns.add_turn(
            3600 * 24 * 5, const.TurnType.MSG,
            log.Msg("You have 2 days left.  Don't panic.", const.orange,
                    const.desat_orange))
        turns.add_turn(
            3600 * 24 * 6, const.TurnType.MSG,
            log.Msg("Only 1 day left.  OK, maybe it's time to panic.",
                    const.red, const.desat_red))
        turns.add_turn(
            3600 * 24 * 6.5, const.TurnType.MSG,
            log.Msg("Only 12 hours left!  You need to finish this NOW!",
                    const.red, const.desat_red))
        turns.add_turn(3600 * 24 * 7, const.TurnType.GAME_OVER, None)
        i = 0
        for fslot in const.FeatureSlot:
            turns.add_turn(int(i), const.TurnType.SPAWN, fslot)
            i += const.spawn_interval / len(const.FeatureSlot)

        # game_map.make_boss_map(turns, entities, player)
        game_map.make_map_bsp(turns, entities, player)

        # Splash
        tcod.console_clear(root_console)
        splash_img.blit_2x(root_console, 10, 5)
        tcod.console_set_default_foreground(root_console, const.yellow)
        tcod.console_print_ex(
            root_console, 85, 15, tcod.BKGND_NONE, tcod.CENTER,
            "Press any key to create your\nfirst roguelike!")
        tcod.console_print_ex(root_console, int(screen_width / 2),
                              screen_height - 2, tcod.BKGND_NONE, tcod.CENTER,
                              "By a cheap plastic imitation of a game dev")
        tcod.console_print_ex(root_console, int(screen_width / 2),
                              screen_height - 1, tcod.BKGND_NONE, tcod.CENTER,
                              "during the 7DRL 2019")

        again = True
        while again:
            tcod.console_flush()
            for event in tcod.event.wait():
                if event.type == "QUIT":
                    raise SystemExit()
                elif event.type == "KEYDOWN" or event.type == "MOUSEBUTTONDOWN":
                    again = False

        # give a level 1 feature
        first_feature = random_loot.get_random_feature(random.choice(
            list(const.FeatureSlot)),
                                                       turns,
                                                       player,
                                                       level=1)
        key = player.add_to_inventory(first_feature)

        # no hack as first weapon
        first_weapon = random_loot.get_random_weapon(random.choice(
            [const.WeaponSlot.slow, const.WeaponSlot.fast]),
                                                     turns,
                                                     player,
                                                     level=1)
        # first_weapon = random_loot.get_random_weapon(random.choice([const.WeaponSlot.slow, const.WeaponSlot.fast]), turns, player, level=3) # DEBUG
        key = player.add_to_inventory(first_weapon)

        # first_weapon = random_loot.get_random_weapon(const.WeaponSlot.hack, turns, player, level=1)# DEBUG
        # key = player.add_to_inventory(first_weapon)

        # initial render
        render.render_map(root_console, con, entities, player, game_map,
                          screen_width, screen_height)
        render.render_log(root_console, log_panel, msglog, map_height)
        render.render_des(root_console, des_panel, map_height, "")
        render.render_sch(root_console, sch_panel, turns, map_width, 0)
        render.render_inv(root_console, inv_panel, player, map_width,
                          sch_height)
        menu_state = const.MenuState.POPUP
        render.render_popup(root_console, popup_panel, map_width, map_height,
                            const.intro_strings)

        tcod.console_flush()
        fov_recompute = False
        render_inv = False  # render inventory
        force_log = False  # force to pass log
        new_turn = True  # end of the turn
        render_map = False  # render all the map
        need_flush = False
        mouse = (500, 500)  #OOB
        new_mouse = False  # did the mouse move
        boss = None  # is it the final fight?
        boss_confirm = False  # did the player confirm they are ready?
        last_boss_hp = 0
        while not tcod.console_is_window_closed():
            if new_turn:

                # The boss is defeated
                if boss and boss.hp <= 0:
                    msglog.add_log(
                        "Congratulations!  You defeated your self-doubt and completed your game!",
                        const.green, const.green)
                    msglog.add_log(
                        "You ascend to the status of RL game dev...",
                        const.green, const.green)
                    msglog.add_log("Score: " + str(10 * player.get_score()),
                                   const.green, const.green)
                    render.render_boss_hp(root_console, des_panel, map_height,
                                          boss)
                    render.render_log(root_console, log_panel, msglog,
                                      map_height)
                    tcod.console_flush()
                    break

                # A bunch of assert to be sure there are no serious bugs
                assert turns.nb_turns(
                    const.TurnType.PLAYER) == 1, turns.nb_turns(
                        const.TurnType.PLAYER)
                assert turns.nb_turns(
                    const.TurnType.SPAWN) == 5, turns.nb_turns(
                        const.TurnType.SPAWN)
                assert turns.nb_turns(const.TurnType.ENEMY) == len([
                    e for e in entities if isinstance(e, entity.Monster)
                ]), (turns.nb_turns(const.TurnType.ENEMY),
                     len([
                         e for e in entities if isinstance(e, entity.Monster)
                     ]), entities, turns.turns)

                current_turn = turns.get_turn()

                if current_turn.ttype == const.TurnType.PLAYER:
                    # reset the attack counter
                    for e in entities:
                        if isinstance(e, entity.Monster):
                            e.reset_nb_atk()

                    render.render_sch(root_console, sch_panel, turns,
                                      map_width, player.time_malus)
                    need_flush = True
                new_turn = False

            if current_turn.ttype == const.TurnType.PLAYER:
                if fov_recompute:
                    game_map.recompute_fov(player.x, player.y)
                    new_ent = []
                    for e in entities:
                        if not e.is_seen and game_map.is_visible(e.x, e.y):
                            if isinstance(e, entity.Weapon) or isinstance(
                                    e, entity.Feature):
                                new_ent.append(e.name)
                            e.is_seen = True
                    if new_ent:
                        if len(new_ent) > 1:
                            last = new_ent.pop()
                            new_ent = ', a '.join(new_ent) + ' and a ' + last
                        else:
                            new_ent = new_ent[0]
                        msglog.add_log("You discover a " + new_ent + ".")

                if fov_recompute or render_map:
                    # maybe what is under the mouse changed
                    new_mouse = True
                    render.render_map(root_console, con, entities, player,
                                      game_map, screen_width, screen_height)
                    need_flush = True
                    render_map = False

                if new_mouse and not boss:  # and menu_state != const.MenuState.POPUP:
                    render.render_des(
                        root_console, des_panel, map_height,
                        render.get_names_under_mouse(mouse, entities, game_map,
                                                     log_width))
                    need_flush = True
                    new_mouse = False

                if boss and last_boss_hp != boss.hp:
                    last_boss_hp = boss.hp
                    render.render_boss_hp(root_console, des_panel, map_height,
                                          boss)
                    need_flush = True

                fov_recompute = False

                if force_log or msglog.is_there_new():
                    render.render_log(root_console, log_panel, msglog,
                                      map_height, force_log)
                    need_flush = True
                    force_log = False

                if render_inv:
                    render.render_inv(root_console, inv_panel, player,
                                      map_width, sch_height)
                    render_inv = False
                    need_flush = True

                if need_flush:
                    tcod.console_flush()
                    need_flush = False

                for event in tcod.event.wait():
                    key = None
                    modifiers = []
                    if event.type == "QUIT":
                        raise SystemExit()

                    elif event.type.startswith("WINDOW"):
                        need_flush = True

                    elif event.type == "KEYDOWN":
                        for m in tcod.event_constants._REVERSE_MOD_TABLE:
                            if m & event.mod != 0:
                                modifiers.append(
                                    tcod.event_constants._REVERSE_MOD_TABLE[m])
                        key = tcod.event_constants._REVERSE_SYM_TABLE.get(
                            event.sym)

                    elif event.type == "MOUSEMOTION":
                        if event.tile != mouse:
                            mouse = event.tile
                            new_mouse = True
                        continue

                    elif event.type == "MOUSEBUTTONDOWN" and event.button == tcod.event.BUTTON_LEFT:
                        if menu_state == const.MenuState.STANDARD:
                            e = render.get_object_under_mouse(
                                mouse, turns, player, entities, game_map,
                                screen_width, map_width)
                            if e:
                                menu_state = const.MenuState.POPUP
                                render.render_popup(
                                    root_console, popup_panel, map_width,
                                    map_height,
                                    [render.capitalize(e.name)] + e.describe())
                                need_flush = True
                            else:
                                msglog.add_log(
                                    "There is nothing to describe here.")
                        elif menu_state == const.MenuState.POPUP:
                            render.render_map(root_console, con, entities,
                                              player, game_map, screen_width,
                                              screen_height)
                            render.render_log(root_console, log_panel, msglog,
                                              map_height)
                            if boss:
                                render.render_boss_hp(root_console, des_panel,
                                                      map_height, boss)
                            else:
                                render.render_des(root_console, des_panel,
                                                  map_height, "")
                            render.render_sch(root_console, sch_panel, turns,
                                              map_width, player.time_malus)
                            render.render_inv(root_console, inv_panel, player,
                                              map_width, sch_height)
                            menu_state = const.MenuState.STANDARD
                            need_flush = True

                    else:
                        # nothing interesting
                        continue

                    if menu_state == const.MenuState.STANDARD:
                        action = keys.handle_player_turn_keys(key, modifiers)
                    elif menu_state == const.MenuState.DROP:
                        action = keys.handle_drop_keys(key, modifiers)
                    elif menu_state == const.MenuState.EQUIP:
                        action = keys.handle_equip_keys(key, modifiers)
                    elif menu_state == const.MenuState.POPUP:
                        action = keys.handle_popup_keys(key, modifiers)
                    else:
                        assert False

                    use_weapon = action.get('use_weapon')
                    if use_weapon:
                        previous_active = player.active_weapon
                        new_active = player.wequiped.get(use_weapon)
                        if not new_active:
                            msglog.add_log("You don't have this weapon.")
                        elif previous_active == new_active:
                            msglog.add_log("This weapon is already wielded.")
                        else:
                            player.change_active_weapon(new_active)
                            player.active_weapon.equip_log(msglog)
                            render_map = True
                            render_inv = True

                    help_popup = action.get('help')
                    if help_popup:
                        menu_state = const.MenuState.POPUP
                        render.render_popup(root_console, popup_panel,
                                            map_width, map_height,
                                            const.help_strings)
                        need_flush = True

                    fullscreen = action.get("fullscreen")
                    if fullscreen:
                        tcod.console_set_fullscreen(
                            not tcod.console_is_fullscreen())

                    descend = action.get('descend')
                    if descend:
                        stairs = game_map.is_stairs(player.x, player.y)
                        boss_stairs = game_map.is_boss_stairs(
                            player.x, player.y)
                        assert not (stairs and boss_stairs)
                        if stairs or boss_stairs:
                            if boss_stairs and (not player.can_go_boss()
                                                or not boss_confirm):
                                if not player.can_go_boss():
                                    msglog.add_log(
                                        "This is the release exit.  But you don't have five stable features!"
                                    )
                                elif not boss_confirm:
                                    msglog.add_log(
                                        "You feel anxious about this.  Are you really sure that you are ready to release your game?  If not, find the other stairs to continue your adventure."
                                    )
                                    boss_confirm = True
                            else:
                                if stairs:
                                    msglog.add_log("You go down the stairs.")
                                for e in entities:
                                    if isinstance(e, entity.Monster):
                                        e.dead(stabilize=False)
                                        turns.remove_turn(e)
                                entities = [player]
                                if stairs:
                                    game_map.make_map_bsp(
                                        turns, entities, player)
                                else:
                                    boss = game_map.make_boss_map(
                                        turns, entities, player)
                                    const.n_bugs_max = [
                                        const.boss_level_invok,
                                        const.boss_level_invok
                                    ]
                                    msglog.add_log(
                                        "To release your game, you need to fight your inner ennemy: self-doubt.",
                                        const.red)
                                turns.add_turn(
                                    player.time_malus + player.time_move,
                                    const.TurnType.PLAYER, player)
                                player.reset_time_malus()
                                render_map = True
                                new_turn = True
                                break
                        else:
                            msglog.add_log("You see no stairs.")

                    grab = action.get('pickup')
                    if grab:
                        if game_map.is_there_item_on_floor(player):
                            if game_map.is_weapon_on_floor_directly_equipable(
                                    player):
                                (item, key) = game_map.get_item_on_floor(
                                    player, entities)
                                player.wequip(item, key)
                                msglog.add_log("You equip a " + item.name +
                                               ".")
                                render_inv = True
                            elif player.is_inventory_full():
                                msglog.add_log("Your inventory is full.")
                                assert not render_inv
                            else:
                                item, _ = game_map.get_item_on_floor(
                                    player, entities)
                                msglog.add_log("You pick up a " + item.name +
                                               ".")
                                render_inv = True
                            if render_inv:
                                if isinstance(item, entity.Weapon):
                                    l = item.wego.value.get("fego")
                                    msglog.add_log("It is effective against " +
                                                   l[0].value.get("name") +
                                                   ", " +
                                                   l[1].value.get("name") +
                                                   " and " +
                                                   l[2].value.get("name") +
                                                   " bugs.")
                                elif isinstance(item, entity.Feature):
                                    wego = [
                                        wego for wego in const.WeaponEgo
                                        if item.fego in wego.value.get("fego")
                                    ]
                                    assert len(wego) == 1
                                    wego = wego[0]
                                    msglog.add_log(
                                        "Its bugs are squashed by " +
                                        wego.value.get("name") + " weapons.")
                                else:
                                    assert False
                                # render_inv = True
                        else:
                            msglog.add_log(
                                "There is nothing on the floor to pick up.")

                    drop = action.get('drop')
                    if drop:
                        if player.is_inventory_empty():
                            msglog.add_log("Your inventory is empty.")
                        elif game_map.is_there_item_on_floor(player):
                            msglog.add_log("There is already something there.")
                        else:
                            msglog.add_log("What do you want to drop? [abcde]")
                            menu_state = const.MenuState.DROP

                    equip = action.get('equip')
                    if equip:
                        if player.is_inventory_empty():
                            msglog.add_log("Your inventory is empty.")
                        else:
                            msglog.add_log(
                                "What do you want to equip? [abcde]")
                            menu_state = const.MenuState.EQUIP

                    drop_unknow = action.get('drop_unknow')
                    # we didn't understand what the player want to drop
                    if drop_unknow:
                        msglog.add_log("What do you want to drop? [abcde]")

                    equip_unknow = action.get('equip_unknow')
                    # we didn't understand what the player want to equip
                    if equip_unknow:
                        msglog.add_log("What do you want to equip? [abcde]")

                    drop_key = action.get('drop_key')
                    if drop_key:
                        item = player.inventory.get(drop_key)
                        if item:
                            msglog.add_log("You drop a " + item.name + ".")
                            game_map.drop_item_on_floor(
                                player, entities, item, drop_key)
                            menu_state = const.MenuState.STANDARD
                            render_inv = True
                        else:
                            msglog.add_log("You don't have this item!")
                            menu_state = const.MenuState.STANDARD

                    equip_key = action.get('equip_key')
                    if equip_key:
                        item = player.inventory.get(equip_key)
                        if item:
                            menu_state = const.MenuState.STANDARD
                            previous_active = player.active_weapon
                            if isinstance(item, entity.Feature):
                                out = player.fequip(item, equip_key)
                                synergy = out.get("synergy")
                                if synergy:
                                    if synergy == 2:
                                        msglog.add_log(
                                            "You feel a small synergy between your two "
                                            + item.fego.value.get("name") +
                                            " features.",
                                            color_active=const.green,
                                            color_inactive=const.desat_green2)
                                    elif synergy == 3:
                                        msglog.add_log(
                                            "You feel a good synergy between your three "
                                            + item.fego.value.get("name") +
                                            " features.",
                                            color_active=const.green,
                                            color_inactive=const.desat_green2)
                                    elif synergy == 4:
                                        msglog.add_log(
                                            "You feel a great synergy between your four "
                                            + item.fego.value.get("name") +
                                            " features!",
                                            color_active=const.green,
                                            color_inactive=const.desat_green2)
                                    elif synergy == 5:
                                        msglog.add_log(
                                            "You feel an incredible synergy between your five "
                                            + item.fego.value.get("name") +
                                            " features!",
                                            color_active=const.green,
                                            color_inactive=const.desat_green2)
                                    else:
                                        assert False

                            elif isinstance(item, entity.Weapon):
                                out = player.wequip(item, equip_key)
                                render_map = True  # update telepathy
                            else:
                                assert False
                            previous = out.get("unstable-previous")
                            level_problem_no_previous = out.get(
                                "level-problem-no-previous")
                            level_problem_previous = out.get(
                                "level-problem-previous")
                            inheritance = out.get("inheritance")
                            if inheritance:
                                msglog.add_log(
                                    "You upgraded your " +
                                    item.fego.value.get("name") + " " +
                                    item.fslot.value.get("name") +
                                    ": it is already quite stable!",
                                    color_active=const.green,
                                    color_inactive=const.desat_green2)
                                item.stability = min(
                                    item.max_stability,
                                    max(item.stability, inheritance.stability))
                                render_inv = True
                                turns.add_turn(
                                    player.time_malus + const.time_equip,
                                    const.TurnType.PLAYER, player)
                                player.reset_time_malus()
                                render_map = True
                                new_turn = True
                                break
                            elif level_problem_previous:
                                msglog.add_log(
                                    "You cannot equip a v" + str(item.level) +
                                    " feature on a v" +
                                    str(level_problem_previous.level) +
                                    " feature.")
                            elif level_problem_no_previous:
                                msglog.add_log("You need to equip a v1 " +
                                               item.fslot.value.get("name") +
                                               " feature first.")
                            elif not previous:
                                msglog.add_log("You equip a " + item.name +
                                               ".")
                                if isinstance(item, entity.Weapon):
                                    msglog.add_log(
                                        "You can change your active weapon with [123]."
                                    )
                                    if not previous_active:
                                        render_map = True
                                        player.active_weapon.equip_log(msglog)
                                render_inv = True
                                turns.add_turn(
                                    player.time_malus + const.time_equip,
                                    const.TurnType.PLAYER, player)
                                player.reset_time_malus()
                                render_map = True
                                new_turn = True
                                break
                            else:
                                msglog.add_log(
                                    "You try to equip the " + item.name +
                                    " but your " + previous.name +
                                    " is too unstable to be removed!")

                        else:
                            msglog.add_log("You don't have this item!")
                            menu_state = const.MenuState.STANDARD

                    cancel = action.get('cancel')
                    if cancel:
                        if menu_state == const.MenuState.POPUP:
                            render.render_map(root_console, con, entities,
                                              player, game_map, screen_width,
                                              screen_height)
                            render.render_log(root_console, log_panel, msglog,
                                              map_height)
                            if boss:
                                render.render_boss_hp(root_console, des_panel,
                                                      map_height, boss)
                            else:
                                render.render_des(root_console, des_panel,
                                                  map_height, "")
                            render.render_sch(root_console, sch_panel, turns,
                                              map_width, player.time_malus)
                            render.render_inv(root_console, inv_panel, player,
                                              map_width, sch_height)
                            need_flush = True
                        else:
                            msglog.add_log("Nevermind.")
                        menu_state = const.MenuState.STANDARD

                    move = action.get('move')
                    if move:
                        dx, dy = move

                        if (dx, dy) == (0, 0):
                            turns.add_turn(
                                player.time_malus + player.time_move,
                                const.TurnType.PLAYER, player)
                            player.reset_time_malus()
                            render_map = True
                            new_turn = True
                            force_log = True
                            break
                        else:
                            destination_x = player.x + dx
                            destination_y = player.y + dy

                            target = entity.get_blocking_entities_at_location(
                                entities, destination_x, destination_y)

                            if target and target != player:
                                weapon = player.active_weapon
                                if not weapon:
                                    msglog.add_log(
                                        "You have no weapon to attack with! Equip with w."
                                    )
                                else:
                                    if target == boss and weapon.wslot.value.get(
                                            "unstable"):
                                        msglog.add_log(
                                            "Your hack has no effect on " +
                                            boss.name + ".",
                                            color_active=const.red,
                                            color_inactive=const.desat_red)
                                        duration = weapon.duration
                                        dmg = 0
                                    else:
                                        (dmg, duration, more_stable,
                                         less_stable) = attack(
                                             weapon, target, msglog, player,
                                             entities, turns)
                                        # stability may have changed
                                        if more_stable or less_stable:
                                            render_inv = True
                                    turns.add_turn(
                                        player.time_malus + duration,
                                        const.TurnType.PLAYER, player)
                                    player.reset_time_malus()
                                    new_turn = True
                                    if dmg > 0 and target != boss:
                                        render_map = True
                                    break

                            elif not game_map.is_blocked(
                                    destination_x, destination_y):
                                player.move(dx, dy)
                                des = game_map.description_item_on_floor(
                                    player)
                                if des:
                                    msglog.add_log("You see a " + des +
                                                   " on the floor.")
                                turns.add_turn(
                                    player.time_malus + player.time_move,
                                    const.TurnType.PLAYER, player)
                                player.reset_time_malus()
                                render_map = True
                                fov_recompute = True
                                new_turn = True
                                force_log = True
                                break

            elif current_turn.ttype == const.TurnType.ENEMY:
                e = current_turn.entity
                assert e.hp > 0, e.hp
                if e in entities:
                    if e.distance_to(player) >= 2:
                        # if close, attack
                        moved = e.move_astar(player, entities, game_map, turns)
                        if moved and (game_map.is_visible(e.x, e.y) or
                                      (player.active_weapon and isinstance(
                                          player.active_weapon,
                                          entity.TelepathicWeapon))):
                            render_map = True
                        turns.add_turn(e.speed_mov, const.TurnType.ENEMY, e)
                    else:
                        # if far, move
                        turns.add_turn(e.speed_atk, const.TurnType.ENEMY, e)
                        d = e.attack(player, turns)
                        delta_malus = d.get("dmg")
                        invok = d.get("invok")
                        if invok:
                            # the boss invoks minions
                            msglog.add_log(e.name + " invokes " +
                                           invok.value.get("name") + " bugs!")
                            for level in range(1, 4):
                                nb = const.boss_level_invok[level - 1]
                                for n in range(nb):
                                    new_e = game_map.spawn_boss(
                                        entities, invok, level, player)
                                    if new_e:
                                        turns.add_turn(e.speed_mov,
                                                       const.TurnType.ENEMY,
                                                       new_e)
                        elif delta_malus:
                            assert int(delta_malus) == delta_malus, delta_malus
                            player.add_time_malus(delta_malus, e.fslot)

                        else:
                            missed = d.get("missed")
                            # basic passive attack
                            if missed and player.active_weapon and isinstance(
                                    player.active_weapon,
                                    entity.BasicWeapon) and not isinstance(
                                        e, entity.Boss) and random.randint(
                                            1, 3) < 3:
                                msglog.add_log("The " + e.name +
                                               " is burned by your " +
                                               player.active_weapon.name + "!")
                                (dmg, duration, more_stable,
                                 less_stable) = attack(player.active_weapon,
                                                       e,
                                                       msglog,
                                                       player,
                                                       entities,
                                                       turns,
                                                       log_effective=False,
                                                       passive=True)
                                # stability may have changed
                                if more_stable or less_stable:
                                    render_inv = True
                                if dmg > 0:
                                    render_map = True
                new_turn = True

            elif current_turn.ttype == const.TurnType.SPAWN:
                # regurlarly, we spawn bugs
                if not boss:
                    creator = player.fequiped.get(current_turn.entity)
                    # stable features don't generate bugs
                    if creator and not creator.is_stable() and sum(
                            creator.n_bugs) < sum(
                                const.n_bugs_max[creator.level - 1]):
                        # the more stable, the slower it generates bugs
                        chance = 1 - creator.stability / creator.max_stability / const.stability_threshold + 0.4
                        if random.random() < chance:
                            e = game_map.spawn(entities, creator)
                            if e:
                                turns.add_turn(e.speed_mov,
                                               const.TurnType.ENEMY, e)
                turns.add_turn(const.spawn_interval, const.TurnType.SPAWN,
                               current_turn.entity)
                new_turn = True

            elif current_turn.ttype == const.TurnType.MSG:
                # a message to this particular date
                msglog.add_log(current_turn.entity.string,
                               current_turn.entity.color_active,
                               current_turn.entity.color_inactive)
                new_turn = True

            elif current_turn.ttype == const.TurnType.GAME_OVER:
                # :(
                msglog.add_log(
                    "Your self-doubt is too strong.  You don't feel your game is worth showing to the world.  Who said releasing a game was easy?",
                    const.red, const.red)
                msglog.add_log("Score: " + str(player.get_score()), const.red,
                               const.red)
                msglog.add_log("Game over.", const.red, const.red)
                render.render_log(root_console, log_panel, msglog, map_height)
                render.render_sch(root_console, sch_panel, turns, map_width,
                                  -1)
                tcod.console_flush()
                break

        # That's the end.
        again = True
        while again:
            for event in tcod.event.wait():
                key = None
                modifiers = []

                if event.type == "QUIT":
                    raise SystemExit()

                elif event.type == "KEYDOWN":
                    for m in tcod.event_constants._REVERSE_MOD_TABLE:
                        if m & event.mod != 0:
                            modifiers.append(
                                tcod.event_constants._REVERSE_MOD_TABLE[m])
                    key = tcod.event_constants._REVERSE_SYM_TABLE.get(
                        event.sym)

                    action = keys.handle_popup_keys(key, modifiers)
                    if action.get("cancel"):
                        again = False

                tcod.console_flush()
コード例 #33
0
ファイル: engine.py プロジェクト: billturner/roguelike_tcod
def main():
    # load base variables and colors
    constants = get_constants()

    tcod.console_set_custom_font(
        "assets/consolas12x12.png",
        tcod.FONT_TYPE_GREYSCALE | tcod.FONT_LAYOUT_TCOD)
    tcod.console_init_root(constants['screen_width'],
                           constants['screen_height'],
                           constants['window_title'],
                           fullscreen=False,
                           renderer=tcod.RENDERER_SDL2,
                           order='F',
                           vsync=False)

    con = tcod.console.Console(constants['screen_width'],
                               constants['screen_height'])
    panel = tcod.console.Console(constants['screen_width'],
                                 constants['panel_height'])

    player = None
    entities = []
    game_map = None
    message_log = None
    game_state = GameStates.MAIN_MENU

    input_handler = InputHandler()

    show_load_error_message = False

    main_menu_background_image = tcod.image_load('assets/menu_background.png')

    while True:
        if game_state == GameStates.MAIN_MENU:
            input_handler.set_game_state(game_state)

            main_menu(con, main_menu_background_image,
                      constants['screen_width'], constants['screen_height'])

            if show_load_error_message:
                message_box(con, 'No save game to load', 50,
                            constants['screen_width'],
                            constants['screen_height'])

            tcod.console_flush()

            for event in tcod.event.get():
                input_handler.dispatch(event)

            user_input = input_handler.get_user_input()

            new_game = user_input.get('new_game')
            load_save = user_input.get('load_game')
            exit_game = user_input.get('exit_game')

            if show_load_error_message and (new_game or load_save
                                            or exit_game):
                show_load_error_message = False
            elif new_game:
                player, entities, game_map, message_log, game_state = get_game_variables(
                    constants)
                game_state = GameStates.PLAYERS_TURN

                show_main_menu = False
            elif load_save:
                try:
                    player, entities, game_map, message_log, game_state = load_game(
                    )
                    show_main_menu = False
                except FileNotFoundError:
                    show_load_error_message = True
            elif exit_game:
                raise SystemExit()

        else:
            con.clear()
            play_game(player, entities, game_map, message_log, game_state, con,
                      panel, constants)

            show_main_menu = True
コード例 #34
0
def main():
    screen_width = 80
    screen_height = 50

    bar_width = 20
    panel_height = 7
    panel_y = screen_height - panel_height

    message_x = bar_width + 2
    message_width = screen_width - bar_width - 2
    message_height = panel_height - 1

    map_width = 80
    map_height = 43

    room_max_size = 10
    room_min_size = 6
    max_rooms = 30

    fov_algorithm = 0
    fov_light_walls = True
    fov_radius = 10

    max_monsters_per_room = 3
    max_items_per_room = 2

    colors = {
        'dark_wall': libtcod.Color(0, 0, 100),
        'dark_ground': libtcod.Color(50, 50, 150),
        'light_wall': libtcod.Color(130, 110, 50),
        'light_ground': libtcod.Color(200, 180, 50)
    }

    fighter_component = Fighter(hp=30, defense=2, power=5)
    inventory_component = Inventory(26)
    player = Entity(0, 0, '@', libtcod.lighter_amber, 'Player', blocks=True, render_order=RenderOrder.ACTOR,
                    fighter=fighter_component, inventory=inventory_component)
    entities = [player]

    libtcod.console_set_custom_font('arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)

    libtcod.console_init_root(screen_width, screen_height, 'libtcod tutorial revised', False)  # TODO: New name

    con = libtcod.console_new(screen_width, screen_height)
    panel = libtcod.console_new(screen_width, panel_height)

    game_map = GameMap(map_width, map_height)
    game_map.make_map(max_rooms, room_min_size, room_max_size, map_width, map_height, player,
                      entities, max_monsters_per_room, max_items_per_room)

    fov_recompute = True

    fov_map = initialize_fov(game_map)

    message_log = MessageLog(message_x, message_width, message_height)

    key = libtcod.Key()
    mouse = libtcod.Mouse()

    game_state = GameStates.PLAYERS_TURN
    previous_game_state = game_state

    while not libtcod.console_is_window_closed():  # main game loop
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)

        if fov_recompute:
            recompute_fov(fov_map, player.x, player.y, fov_radius, fov_light_walls, fov_algorithm)

        render_all(con, panel, entities, player, game_map, fov_map, fov_recompute, message_log, screen_width,
                   screen_height, bar_width, panel_height, panel_y, mouse, colors, game_state)

        fov_recompute = False

        libtcod.console_flush()

        clear_all(con, entities)

        action = handle_keys(key, game_state)

        move = action.get('move')
        pickup = action.get('pickup')
        show_inventory = action.get('show_inventory')
        drop_inventory = action.get('drop_inventory')
        inventory_index = action.get('inventory_index')
        exit = action.get('exit')
        fullscreen = action.get('fullscreen')

        player_turn_results = []

        if move and game_state == GameStates.PLAYERS_TURN:
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy

            if not game_map.is_blocked(destination_x, destination_y):
                target = get_blocking_entities_at_location(entities, destination_x, destination_y)

                if target:
                    attack_results = player.fighter.attack(target)
                    player_turn_results.extend(attack_results)
                else:
                    player.move(dx, dy)
                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN

        elif pickup and game_state == GameStates.PLAYERS_TURN:
            for entity in entities:
                if entity.item and entity.x == player.x and entity.y == player.y:
                    pickup_results = player.inventory.add_item(entity)
                    player_turn_results.extend(pickup_results)

                    break
            else:
                message_log.add_message(Message('There is nothing here to pickup.', libtcod.yellow))

        if show_inventory:
            previous_game_state = game_state
            game_state = GameStates.SHOW_INVENTORY

        if drop_inventory:
            previous_game_state = game_state
            game_state = GameStates.DROP_INVENTORY

        if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len(
                player.inventory.items):
            item = player.inventory.items[inventory_index]

            if game_state == GameStates.SHOW_INVENTORY:
                player_turn_results.extend(player.inventory.use(item))
            elif game_state == GameStates.DROP_INVENTORY:
                player_turn_results.extend(player.inventory.drop_item(item))
        if exit:
            if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY):
                game_state = previous_game_state
            else:
                return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())

        for player_turn_result in player_turn_results:
            message = player_turn_result.get('message')
            dead_entity = player_turn_result.get('dead')
            item_added = player_turn_result.get('item_added')
            item_consumed = player_turn_result.get('consumed')
            item_dropped = player_turn_result.get('item_dropped')

            if message:
                message_log.add_message(message)

            if dead_entity:
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity)
                else:
                    message = kill_monster(dead_entity)

            if item_added:
                entities.remove(item_added)

                game_state = GameStates.ENEMY_TURN

            if item_consumed:
                game_state = GameStates.ENEMY_TURN

            if item_dropped:
                entities.append(item_dropped)

                game_state = GameStates.ENEMY_TURN

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(player, fov_map, game_map, entities)

                    for enemy_turn_result in enemy_turn_results:
                        message = enemy_turn_result.get('message')
                        dead_entity = enemy_turn_result.get('dead')

                        if message:
                            message_log.add_message(message)

                        if dead_entity:
                            if dead_entity == player:
                                message, game_state = kill_player(dead_entity)
                            else:
                                message = kill_monster(dead_entity)

                            message_log.add_message(message)

                            if game_state == GameStates.PLAYER_DEAD:
                                break

                    if game_state == GameStates.PLAYER_DEAD:
                        break
            else:
                game_state = GameStates.PLAYERS_TURN
コード例 #35
0
 
    elif libtcod.console_is_key_pressed(libtcod.KEY_DOWN):
        playery += 1
 
    elif libtcod.console_is_key_pressed(libtcod.KEY_LEFT):
        playerx -= 1
 
    elif libtcod.console_is_key_pressed(libtcod.KEY_RIGHT):
        playerx += 1
 
 
#############################################
# Initialization & Main Loop
#############################################
 
libtcod.console_set_custom_font('arial10x10.png', libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)
libtcod.console_init_root(SCREEN_WIDTH, SCREEN_HEIGHT, 'python/libtcod tutorial', False)
libtcod.sys_set_fps(LIMIT_FPS)
 
playerx = SCREEN_WIDTH//2
playery = SCREEN_HEIGHT//2
 
while not libtcod.console_is_window_closed():
 
    libtcod.console_set_default_foreground(0, libtcod.white)
    libtcod.console_put_char(0, playerx, playery, '@', libtcod.BKGND_NONE)
 
    libtcod.console_flush()
 
    libtcod.console_put_char(0, playerx, playery, ' ', libtcod.BKGND_NONE)
 
コード例 #36
0
    def create_console(title: str, console_width: int, console_height: int, font_file: str, fps_limit: int):
        libtcod.console_set_custom_font(fontFile=font_file, flags=libtcod.FONT_LAYOUT_ASCII_INROW)
        libtcod.console_init_root(w=console_width, h=console_height, title=title, fullscreen=False)
        libtcod.sys_set_fps(fps_limit)

        return libtcod.console_new(w=console_width, h=console_height)