Ejemplo n.º 1
0
 def __init__(self, window_title, width, height, fps_limit=20):
     tdl.set_font('arial10x10.png', greyscale=True, altLayout=True)
     self.console = tdl.init(width,
                             height,
                             title=window_title,
                             fullscreen=False)
     tdl.set_fps(fps_limit)
Ejemplo n.º 2
0
    def __init__(self, args):
        Game.args = args

        # Configure game settings
        config = configparser.ConfigParser()
        cfg_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                'config.cfg')
        config.read(cfg_path)
        Game.config = config

        # Configure tdl
        tdl.set_font(Game.config['ENGINE']['font'])
        tdl.set_fps(int(Game.config['ENGINE']['fps']))
        self.console = tdl.init(54,
                                30,
                                'lunch break roguelike',
                                renderer=Game.config['ENGINE']['renderer'])
        self._last_time = time.time()

        Game.seconds_per_tick = float(Game.config['GAME']['turn'])

        if not Game.instance:
            Game.instance = self
            instances.register('game', self)

        # Twitch Observer
        nickname = Game.config['TWITCH']['Nickname']
        password = Game.config['TWITCH']['Password']
        self.channel = Game.config['TWITCH']['Channel']
        self.observer = Observer(nickname, password)
        self.observer.start()
        self.observer.join_channel(self.channel)

        self.start_time = time.time()
        Game.scene_root = gamescene.GameScene()
Ejemplo n.º 3
0
 def init_root(self, width=80, height=26, show_credits=False):
     self.root = tdl.init(width, height)
     self.scratch = tdl.Console(width, height)
     self.temp_console = tdl.Console(width, height)
     self.width, self.height = width, height
     tdl.set_fps(30)
     if show_credits:
         tcod.console_credits()
Ejemplo n.º 4
0
 def init_root(self, width=80, height=26, show_credits=False):
     self.root = tdl.init(width, height)
     self.canvas = tdl.Console(width, height)
     self.temp_console = tdl.Console(width, height)
     self.width, self.height = width, height
     tdl.set_fps(30)
     if show_credits:
         tcod.console_credits()
Ejemplo n.º 5
0
 def __init__(self):
     tdl.set_font('assets/arial10x10.png', greyscale=True, altLayout=True)
     self.root = tdl.init(self.screen.width,
                          self.screen.height,
                          title="Dungeon Run",
                          fullscreen=False)
     self.con = tdl.Console(self.screen.width, self.screen.height)
     tdl.set_fps(30)
Ejemplo n.º 6
0
def char_finder():
    w_display = 16
    h_display = 16
    w_info = 15
    h_info = 16
    margin = 1
    w = w_display + w_info + margin
    h = 16

    highlight = (0, 0)

    tdl.set_font("mononoki_16-19.png",
                 columns=16,
                 rows=16,
                 greyscale=True,
                 altLayout=False)
    tdl.set_fps(30)
    root = tdl.init(w, h, title="char picker")
    display = tdl.Console(w_display, h_display)
    info = tdl.Console(w_info, h_info)
    display.set_colors(FG, BG)
    info.set_colors(FG, BG)

    running = True

    while running:
        display.clear()
        info.clear()

        c = 0
        for y in range(0, 16):
            for x in range(0, 16):
                color = FG
                if highlight == (x, y):
                    color = HIGHLIGHT
                display.draw_char(x, y, c, fg=color)
                c += 1

        for event in tdl.event.get():
            if event.type == "KEYDOWN":
                running = False
                break
            elif event.type == "MOUSEDOWN":
                print(event.cell)
                highlight = event.cell

        info.draw_str(0, 0, "cell: %dx%d" % highlight)
        info.draw_str(0, 1, "char: %d" % get_char(*highlight))

        root.blit(display, 0, 0, 16, 16, 0, 0)
        root.blit(info, w_display + margin, 0, w_info, h_info, 0, 0)
        tdl.flush()
Ejemplo n.º 7
0
    def __init__(
            self,
            height=60,
            width=90,
            fps=30,
            panel_height=PANEL_HEIGHT,
            hp_bar_width=BAR_WIDTH,
            alt_layout=False,
            font='guildmaster/fonts/terminal16x16_gs_ro.png',
            # font='guildmaster/fonts/hack15x15.png,
            vim_bindings=VIM_BINDINGS):
        self.width = width
        self.height = height
        self.map_height = height - panel_height
        self.panel_height = panel_height
        self.panel_y = self.height - self.panel_height
        self.hp_bar_width = hp_bar_width
        self.message_width = width - hp_bar_width - 2

        self.fps = fps
        self.font = font
        self.alt_layout = alt_layout

        self.vim_bindings = vim_bindings

        # Initialise the player
        # TODO : character creation screen
        self.player = new_PC('Player', 'Human')

        self.visible_tiles = set()
        self.visible_tiles2 = set()
        self.magically_visible = set()

        # initialise message queue
        self.messages = []

        tdl.set_font(self.font,
                     greyscale=True,
                     altLayout=self.alt_layout,
                     columns=16,
                     rows=16)
        tdl.event.set_key_repeat(delay=500, interval=50)
        self.root = tdl.init(self.width,
                             self.height,
                             title="Guild Master",
                             fullscreen=False)
        self.con = tdl.Console(self.width, self.map_height)
        self.panel = Panel(self.width, self.panel_height, self.hp_bar_width)
        tdl.set_fps(self.fps)
Ejemplo n.º 8
0
    def init_game(self):
        # Other fonts: https://github.com/HexDecimal/python-tdl/tree/master/fonts/libtcod
        tdl.set_font(self.font,
                     columns=16,
                     rows=16,
                     greyscale=True,
                     altLayout=False)
        self.root = tdl.init(self.screen_width,
                             self.screen_height,
                             title="PyRo",
                             fullscreen=False)
        tdl.set_fps(20)

        # load game data
        gamedata.load()

        self.current_scene = StartScreen()
        self.current_scene.setup(self)
Ejemplo n.º 9
0
 def __init__(self):
     self.width, self.height = 120, 80
     self.console = tdl.init(
         self.width, self.height,
         title="importANT", fullscreen=False, renderer=u'OPENGL'
     )
     self.console.set_colors(
         fg=(255, 225, 200), bg=(50, 30, 10)
     )
     tdl.set_fps(15)
     self.mouse_pos = (0, 0)
     self.paused = False
     self.mouse_state = dict(
         LEFT=False,
         RIGHT=False
     )
     self.world = World(self)
     self.active_window = self.world.window
     self.settings = SettingsWindow(self)
     self.pher_window = InfoWindow(
         self, self.width - 2, self.height - 2
     )
     self.height_window = InfoWindow(
         self, self.width - 2, self.height - 2, type="height"
     )
     self.windows = dict(
         world=self.world.window,
         settings=self.settings.console,
         pher=self.pher_window.console,
         height=self.height_window.console
     )
     self.symbols = dict(
         diag1=chr(227),
         diag2=chr(226),
         horizontal=chr(229),
         vertical=chr(228)
     )
     self.draw_borders()
     self.world.render()
Ejemplo n.º 10
0
 def set_fps(self, change=0, value=0):
     if value:
         if value >= 1:
             tdl.set_fps(int(value))
     elif change:
         fps = tdl.get_fps() + change
         if fps >= 1:
             tdl.set_fps(fps)
         else:
             tdl.set_fps(1)
Ejemplo n.º 11
0
def test_fps():
    tdl.set_fps(0)
    tdl.get_fps()
Ejemplo n.º 12
0
                        neighbours += 1
                except IndexError:
                    # we don't want error when we are checking border of map
                    X = self.x + x_  # just a debugging help
                    Y = self.y + y_  # just a debugging help
                    # print(X, Y)
        self.neighbours = neighbours
        # print(neighbours)

    def set_visibility(self):
        if not self.visibility:
            if self.neighbours == 3:
                self.next_step_visibility = True
        else:
            if self.neighbours > 3:
                self.next_step_visibility = False
            elif self.neighbours < 2:
                self.next_step_visibility = False

    def draw(self, console):
        self.visibility = self.next_step_visibility
        if self.visibility:
            console.draw_char(self.x, self.y, self.sprite, self.colour)

if __name__ == '__main__':
    tdl.set_fps(FPS)
    game = Game()
    game.load_board('board.txt')
    game.run()
    # print('')
Ejemplo n.º 13
0
from rogue import settings
from rogue.utils import colors
from rogue.utils.controls import get_char_or_cancel

tdl.set_font(settings.GAME_FONT,
             greyscale=settings.GAME_FONT_GREYSCALE,
             altLayout=settings.GAME_FONT_ALTLAYOUT)

root_console = tdl.init(settings.GAME_SCREEN_WIDTH,
                        settings.GAME_SCREEN_HEIGHT,
                        title=settings.GAME_TITLE,
                        fullscreen=settings.GAME_FULLSCREEN)

console = tdl.Console(settings.GAME_MAP_WIDTH, settings.GAME_MAP_HEIGHT)

tdl.set_fps(settings.GAME_FPS)

panel = tdl.Console(settings.GAME_SCREEN_WIDTH, settings.IFACE_PANEL_HEIGHT)

overlay = tdl.Console(settings.GAME_SCREEN_WIDTH, settings.GAME_SCREEN_HEIGHT)


def print_str(x, y, msg, bg=None, fg=colors.white, fg_alpha=1.0, bg_alpha=0):
    """Prints a string

    This function will blit the string on the root console right away

    """
    _console = tdl.Console(len(msg), 1)
    _console.draw_str(0, 0, msg, bg=bg, fg=fg)
    root_console.blit(_console,
Ejemplo n.º 14
0
#!/usr/bin/env python3
"""
    An interactive example of what events are available.
"""

import tdl

WIDTH, HEIGHT = 80, 60

console = tdl.init(WIDTH, HEIGHT)

# the scrolling text window
textWindow = tdl.Window(console, 0, 0, WIDTH, -2)

# slow down the program so that the user can more clearly see the motion events
tdl.set_fps(24)

while 1:
    event = tdl.event.wait()
    print(event)
    if event.type == 'QUIT':
        raise SystemExit()
    elif event.type == 'MOUSEMOTION':
        # clear and print to the bottom of the console
        console.draw_rect(0, HEIGHT - 1, None, None, ' ')
        console.draw_str(
            0, HEIGHT - 1,
            'MOUSEMOTION event - pos=%i,%i cell=%i,%i motion=%i,%i cellmotion=%i,%i'
            % (event.pos + event.cell + event.motion + event.cellmotion))
        continue  # prevent scrolling
Ejemplo n.º 15
0
    This function draws all Renderable objects
    :param renderable_list: The list of objects to render.
    """

    main_console.clear()

    for re in renderable_list:
        re.draw(main_console)

    root.clear()
    root.blit(main_console)


if __name__ == '__main__':
    root = tdl.init(SCREEN_WIDTH, SCREEN_HEIGHT)
    tdl.set_fps(LIMIT_FPS)

    gamestate = state.MainState()

    actors = []
    player = actor.Actor("Player", (1, 1), '@')
    actors.append(player)

    main_console = tdl.Console(SCREEN_WIDTH, SCREEN_HEIGHT)

    draw(actors)
    tdl.flush()

    while not tdl.event.is_window_closed():
        key_ev = tdl.event.key_wait()
        gamestate.handle_input(key_ev, player)
Ejemplo n.º 16
0

def choose_race():
    global player_race

    root.clear()

    race_list = [Human(), Golem(), Denizen(), Demon()]

    options = [race.name for race in race_list]

    player_race = menu('And your race?', options, INVENTORY_WIDTH, y_pos=20, x_pos=20)
    return race_list[player_race]


def msgbox(text, width=50):
    menu(text, [], width)

#######################
#Init and Main Loop   #
#######################


tdl.set_font('Fonts/dejavu_wide16x16_gs_tc.png', greyscale=True, altLayout=True)
root = tdl.init(SCREEN_WIDTH, SCREEN_HEIGHT, title="PyRL", fullscreen=False)
con = tdl.Console(SCREEN_WIDTH, SCREEN_HEIGHT)
panel = tdl.Console(SCREEN_WIDTH, PANEL_HEIGHT)

tdl.set_fps(30)

main_menu()
Ejemplo n.º 17
0
def main():
    G = Engine()
    colors = G.colors
    mact_counter = 0
    menu_cursor = 0

    # TDL init
    tdl.set_font(G.font, greyscale=G.greyscale, altLayout=G.altLayout)
    root_console = tdl.init(G.screen_width, G.screen_height, title=G.title)
    tdl.set_fps(30)

    # Console
    con = tdl.Console(G.screen_width, G.screen_height)

    # Player init
    pc = G.return_player()

    if not G.started:
        G.state = State.MENU
        G.gen_dungeon(G.dungeon_levels)
        G.started = True

    # Draw
    while not tdl.event.is_window_closed():
        con.clear()

        # Drawing on screen in menu
        if G.state == State.MENU:
            draw_menu(con, G)
            text = "teste teste [1, 2, 3]{Color.Red} mais uma [véz]{Color.Green}."
            print(draw_colored_line(con, 2, 3, text))

        # Drawing on screen in room
        if G.state == State.ROOM_PHASE:
            draw_room(con, G)

        # Drawing on screen during battle
        if G.state == State.BATTLE_PHASE:
            draw_battle(con, G, pc)
            root_console.blit(con, 0, 0, G.screen_width, G.screen_height, 0, 0)

        # Drawing on screen after battle
        if G.state == State.UPGD_PHASE:
            draw_upgd(con, G, pc)

        # Drawing on screen on game ending phase
        if G.state == State.ENDING:
            draw_ending(con, G)

        root_console.blit(con, 0, 0, G.screen_width, G.screen_height, 0, 0)
        tdl.flush()

        # Handle events
        G.mousedown = False
        for event in tdl.event.get():
            if event.type == 'KEYDOWN':
                user_input = event
                break
            elif event.type == 'MOUSEMOTION':
                G.mouse = event.cell
                G.mouse_x, G.mouse_y = G.mouse
            if event.type == 'MOUSEDOWN':
                G.mousedown = True
        # If no input matches KEYDOWN, set user_input to None
        else:
            user_input = None

        # Handling events in different G.states
        if G.state == State.BATTLE_PHASE:
            enemy = G.current_level.entity
            results = []

            if G.combat_locked:
                # Player
                for skill in pc.skills:
                    if skill.timeout < skill.max_timeout:
                        skill.timeout += 1

                for buff in pc.buffs:
                    if buff.timeout > 0:
                        buff.timeout -= 1
                    else:
                        del pc.buffs[pc.buffs.index(buff)]

                # Handles user attack inputs
                if user_input:
                    if user_input.keychar == '1' or user_input.keychar == '2' or user_input.keychar == '3' or user_input.keychar == '4':
                        skill = pc.skills[int(user_input.keychar) - 1]
                        if skill.timeout == skill.max_timeout:
                            results = skill.activate(pc, enemy)

                # Enemy
                for skill in enemy.skills:
                    if skill.timeout < skill.max_timeout:
                        skill.timeout += 1

                for buff in enemy.buffs:
                    if buff.timeout > 0:
                        buff.timeout -= 1
                    else:
                        del enemy.buffs[enemy.buffs.index(buff)]

                # Making the enemy attack
                if mact_counter < 50:
                    mact_counter += 1
                else:
                    skill = random.choice(enemy.skills)
                    if skill.timeout >= skill.max_timeout:
                        results = skill.activate(enemy, pc)
                    mact_counter = 0

                # Handling results
                for result in results:
                    dead_entity = result.get('dead')

                    if dead_entity:
                        G.combat_locked = False
                        if dead_entity != pc:
                            mact_counter = 0
                            pc.level_up_by(1)
                            G.endtext = Message("Victory!",
                                                colors.get('green'))

                        elif dead_entity == pc:
                            mact_counter = 0
                            G.endtext = Message("DEAD!", colors.get('red'))
                            G.over = True

            if not G.combat_locked:
                if user_input and user_input.key == 'ENTER':
                    if not G.over:
                        for skill in pc.skills:
                            skill.timeout = skill.max_timeout
                        if G.current_level == G.dungeon[-1]:
                            G.state = State.ENDING
                        else:
                            G.state = State.UPGD_PHASE
                        print("go")
                    else:
                        G.over = False
                        G.reset()
                        pc = G.return_player()
                        G.state = State.MENU

        elif G.state == State.ROOM_PHASE:
            if user_input and user_input.key == 'ENTER':
                if G.current_level.entity:
                    G.state = State.BATTLE_PHASE
                    G.combat_locked = True

        elif G.state == State.UPGD_PHASE:
            if user_input and user_input.key == 'ENTER':
                if G.upgd_selec:
                    pc.upgd_skillset(G.upgd_selec)
                    G.upgd_selec = ''
                    G.next_level()
                    G.state = State.ROOM_PHASE

        elif G.state == State.MENU:
            if user_input and user_input.key == 'ENTER':
                G.state = State.ROOM_PHASE

        elif G.state == State.ENDING:
            if user_input and user_input.key == 'ENTER':
                G.over = False
                G.reset()
                pc = G.return_player()
                G.state = State.MENU

        # Controls
        if user_input and user_input.key == 'ESCAPE':
            return True

        if user_input and user_input.key == 'ENTER' and user_input.alt:
            tdl.set_fullscreen(not tdl.get_fullscreen())
Ejemplo n.º 18
0
def main():
    tdl.set_font('terminal16x16.png', greyscale=True,
                 altLayout=False)  # Load the font from a png.
    tdl.set_fps(100)

    map_width = 20
    map_height = 20

    room_width = 30
    room_height = 30

    screen_width = room_width + 22
    screen_height = room_height + 22

    root_console = tdl.init(screen_width, screen_height, title='7DRL 2019')
    top_panel_console = tdl.Console(screen_width, 10)
    view_port_console = tdl.Console(room_width, room_height)
    bottom_panel_console = tdl.Console(screen_width, 10)
    message_log = MessageLog(0, 0, screen_width, 9)

    entities = []

    game_map = GameMap(map_width, map_height)

    sword_stats = Weapon(2, 10)
    player_weapon = Item(game_map,
                         "0x0",
                         0,
                         0,
                         "Sword",
                         "|", (255, 255, 255),
                         weapon=sword_stats)
    player_stats = Fighter(hits=10, left_hand=player_weapon)
    player = Actor(game_map,
                   "2x2",
                   15,
                   10,
                   "Player",
                   "@", (255, 255, 255),
                   fighter=player_stats)
    entities.append(player)

    generate_map(game_map, entities, player)

    all_consoles = [
        root_console, view_port_console, bottom_panel_console,
        top_panel_console
    ]

    fov_algorithm = "BASIC"
    fov_light_walls = True
    fov_radius = 50
    fov_recompute = True

    game_state = GameStates.PLAYER_TURN

    while not tdl.event.is_window_closed():
        if fov_recompute:  # Compute the field of view to show changes.
            game_map.rooms[player.map_x][player.map_y]\
                .compute_fov(player.room_x, player.room_y,
                             fov=fov_algorithm, radius=fov_radius, light_walls=fov_light_walls, sphere=True)

            render_all(all_consoles, game_map, entities, player, fov_recompute,
                       message_log)
            tdl.flush()
            clear_all(view_port_console, entities)
            fov_recompute = False

        for event in tdl.event.get():
            if event.type == 'KEYUP':
                user_input = event
                break

        else:
            user_input = None

        if not user_input:
            continue

        action = handle_keys(user_input)

        move = action.get('move')
        exit_game = action.get('exit_game')
        select_hand = action.get('select_hand')
        drop_item = action.get('drop_item')
        pickup_item = action.get('pickup_item')
        shuffle_rooms = action.get('shuffle_rooms')

        player_turn_results = []

        if shuffle_rooms:
            message = game_map.shuffle_rooms(player, entities)
            message_log.add_message(message)
            fov_recompute = True

        # TODO at the moment these functions are doing all the leg work and player_turn_results isn't used. Rectify.

        if select_hand and game_state == GameStates.PLAYER_TURN:
            player.fighter.selected_hand = select_hand
            fov_recompute = True

        if drop_item and game_state == GameStates.PLAYER_TURN:
            message = player.fighter.drop_item(game_map, entities)
            message_log.add_message(message)
            game_state = GameStates.ENEMY_TURN
            fov_recompute = True

        if pickup_item and game_state == GameStates.PLAYER_TURN:
            message = player.fighter.pickup_item(entities)
            message_log.add_message(message)
            game_state = GameStates.ENEMY_TURN
            fov_recompute = True

        if move and game_state == GameStates.PLAYER_TURN:
            dx, dy = move
            destination_room_x = player.room_x + dx
            destination_room_y = player.room_y + dy

            if destination_room_x < 0:
                dx = 0

                if player.map_x - 1 < 0:
                    player.map_x = map_width - 1
                else:
                    player.map_x -= 1

                player.room_x = room_width - 1

            if destination_room_x == room_width:
                destination_room_x -= 1
                dx = 0

                if player.map_x + 1 > map_width - 1:
                    player.map_x = 0
                else:
                    player.map_x += 1

                player.room_x = 0

            if destination_room_y < 0:
                dy = 0

                if player.map_y - 1 < 0:
                    player.map_y = map_height - 1
                else:
                    player.map_y -= 1

                player.room_y = room_height - 1

            if destination_room_y == room_height:
                destination_room_y -= 1
                dy = 0

                if player.map_y + 1 > map_height - 1:
                    player.map_y = 0
                else:
                    player.map_y += 1

                player.room_y = 0

            if game_map.rooms[player.map_x][player.map_y].walkable[
                    destination_room_x, destination_room_y]:
                target = get_blocking_entities_at_location(
                    entities, player.map_x, player.map_y, destination_room_x,
                    destination_room_y)

                if target:  # Combat here
                    attack_results = player.fighter.attack(target)
                    player_turn_results.extend(
                        attack_results
                    )  # Add the result of the last turn to the list
                    fov_recompute = True

                else:
                    player.move(dx, dy)  # Or just move
                    player.set_current_room(game_map)

                    # TODO: Bug with the new room layouts - some cause change of room to break.
                    print("MapPos: ",
                          player.map_x,
                          ",",
                          player.map_y,
                          end=" / ")
                    print("RoomPos: ", player.room_x, ",", player.room_y)
                    fov_recompute = True

                game_state = GameStates.ENEMY_TURN  # Switch over the enemy's turn.

        if exit_game:
            return True

        for player_turn_result in player_turn_results:
            message = player_turn_result.get("message")  # Pull any messages
            dead_entity = player_turn_result.get(
                "dead")  # Or anything that died

            if message:
                message_log.add_message(
                    message
                )  # Add the message (if any) to the message log to print on screen.

            if dead_entity:  # If anything died...
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity)  # Game over
                else:
                    message = kill_monster(
                        dead_entity
                    )  # Print a death message for monster, add exp

                message_log.add_message(message)  # Print messages to screen.

        player_turn_results.clear()  # Clear ready for next turn.

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.map_x == player.map_x and entity.map_y == player.map_y:
                    if entity.ai:  # If the entity has some intelligence (monsters, npc)
                        enemy_turn_results = entity.ai.take_turn(
                            player, game_map, entities)

                        for enemy_turn_result in enemy_turn_results:  # Same deal as the player turns
                            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

                        enemy_turn_results.clear()

                    if game_state == GameStates.PLAYER_DEAD:
                        break

            else:
                game_state = GameStates.PLAYER_TURN
Ejemplo n.º 19
0
from engine import *

import tdl

import pdb

if __name__ == '__main__':
    eng = Engine()
    eng.initialization()
    tdl.set_fps(60)
    tdl.flush()

    while not tdl.event.isWindowClosed():
        stop = eng.update()

        if stop:
            break

        eng.rendering()
        tdl.flush()
Ejemplo n.º 20
0
SCREEN_SIZE = (32, 32)
LIMIT_FPS = 240
game_over = False


def nn_sort_func(creature):
    return creature.score


tdl.set_font('arial10x10.png', greyscale=True, altLayout=True)
console = tdl.init(SCREEN_SIZE[0],
                   SCREEN_SIZE[1],
                   title="Snake",
                   fullscreen=False)
tdl.set_fps(LIMIT_FPS)

count = 0

#last_best =

#generation[0].mutate()


def learn():
    global game_over
    snake = game.Snake()
    generation = []
    generation_size = 120
    nn_sizes = [16, 4]
    for _ in range(int(generation_size / 4)):
Ejemplo n.º 21
0
def play_game(player, entities, game_map, message_log, game_state,
              root_console, con, panel, constants):

    tdl.set_font('terminal.png',
                 columns=16,
                 rows=16,
                 columnFirst=False,
                 greyscale=True)
    tdl.set_fps(constants['target_fps'])

    fov_recompute = True

    mouse_coordinates = (0, 0)

    targeting_item = None

    previous_game_state = game_state

    animations = []

    while not tdl.event.is_window_closed():
        if fov_recompute:
            game_map.compute_fov(player.x,
                                 player.y,
                                 fov=constants['fov_algorithm'],
                                 radius=constants['fov_radius'],
                                 light_walls=constants['fov_light_walls'])
        render_all(con, panel, entities, player, game_map, fov_recompute,
                   root_console, message_log, constants['screen_width'],
                   constants['screen_height'], constants['bar_width'],
                   constants['panel_height'], constants['panel_y'],
                   mouse_coordinates, constants['colors'], game_state,
                   animations)

        tdl.flush()

        clear_all(con, entities)
        fov_recompute = False

        for event in tdl.event.get():
            if event.type == 'KEYDOWN':
                user_input = event
                break
            elif event.type == 'MOUSEMOTION':
                mouse_coordinates = event.cell
            elif event.type == 'MOUSEDOWN':
                user_mouse_input = event
                break
        else:
            user_input = None
            user_mouse_input = None

        if not (user_input or user_mouse_input):
            continue

        action = handle_keys(user_input, game_state)
        mouse_action = handle_mouse(user_mouse_input)

        move = action.get('move')
        wait = action.get('wait')
        pickup = action.get('pickup')
        show_inventory = action.get('show_inventory')
        drop_inventory = action.get('drop_inventory')
        inventory_index = action.get('inventory_index')
        level_up = action.get('level_up')
        show_char_screen = action.get('show_character_screen')
        exit = action.get('exit')
        take_stairs = action.get('take_stairs')
        fullscreen = action.get('fullscreen')

        left_click = mouse_action.get('left_click')
        right_click = mouse_action.get('right_click')

        player_turn_results = []

        #if move:
        if move and game_state == GameStates.PLAYERS_TURN:
            dx, dy = move
            destination_x = player.x + dx
            destination_y = player.y + dy
            if game_map.walkable[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 wait:
            game_state = GameStates.ENEMY_TURN

        # pick up item:
        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, constants['colors'])
                    player_turn_results.extend(pickup_results)
                    break
            else:
                message_log.add_message(
                    Message('There is nothing here to pick up.',
                            constants['colors'].get('yellow')))

        # show inventory
        if show_inventory:
            previous_game_state = game_state
            game_state = GameStates.SHOW_INVENTORY

        # show drop inventory
        if drop_inventory:
            previous_game_state = game_state
            game_state = GameStates.DROP_INVENTORY

        # use inventory item
        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,
                                         constants['colors'],
                                         entities=entities,
                                         game_map=game_map))
            elif game_state == GameStates.DROP_INVENTORY:
                player_turn_results.extend(
                    player.inventory.drop_item(item, constants['colors']))

        # take stairs
        if take_stairs and game_state == GameStates.PLAYERS_TURN:
            for entity in entities:
                if entity.stairs and entity.x == player.x and entity.y == player.y:
                    game_map, entities = next_floor(player, message_log,
                                                    entity.stairs.floor,
                                                    constants)
                    fov_recompute = True
                    con.clear()

                    break
            else:
                message_log.add_message(
                    Message('There are no stairs here.',
                            constants['colors'].get('yellow')))

        # level up
        if level_up:
            if level_up == 'hp':
                player.fighter.base_max_hp += 20
                player.fighter.hp += 20
            elif level_up == 'str':
                player.fighter.base_power += 1
            elif level_up == 'def':
                player.fighter.base_defense += 1
            game_state = previous_game_state

        # show character screen
        if show_char_screen:
            previous_game_state = game_state
            game_state = GameStates.CHAR_SCREEN

        # targeting
        if game_state == GameStates.TARGETING:
            # targeting_effect = Targeting_Circle(con, root_console, colors, mouse_coordinates, 5)
            # animations.append(targeting_effect)
            if left_click:
                target_x, target_y = left_click
                item_use_results = player.inventory.use(targeting_item,
                                                        constants['colors'],
                                                        entities=entities,
                                                        game_map=game_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,
                              GameStates.CHAR_SCREEN):
                game_state = previous_game_state
            elif game_state == GameStates.TARGETING:
                player_turn_results.append({'targeting_cancelled': True})
            else:
                save_game(player, entities, game_map, message_log, game_state)
                return True

        if fullscreen:
            tdl.set_fullscreen(not tdl.get_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')
            effect = player_turn_result.get('effect')
            item_dropped = player_turn_result.get('item_dropped')
            equip = player_turn_result.get('equip')
            targeting = player_turn_result.get('targeting')
            targeting_cancelled = player_turn_result.get('targeting_cancelled')
            xp = player_turn_result.get('xp')

            if message:
                message_log.add_message(message)
            if dead_entity:
                if dead_entity == player:
                    message, game_state = kill_player(dead_entity,
                                                      constants['colors'])
                else:
                    message = kill_monster(dead_entity, constants['colors'])

                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 item_dropped:
                entities.append(item_dropped)
                game_state = GameStates.ENEMY_TURN
            if equip:
                equip_results = player.equipment.toggle_equip(equip)
                for equip_result in equip_results:
                    equipped = equip_result.get('equipped')
                    dequipped = equip_result.get('dequipped')

                    if equipped:
                        message_log.add_message(
                            Message('You equipped the {0}'.format(
                                equipped.name)))
                    if dequipped:
                        message_log.add_message(
                            Message('You dequipped the {0}'.format(
                                dequipped.name)))
                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 targeting_cancelled:
                # targeting_effect.endself()
                game_state = previous_game_state
                message_log.add_message(Message('Targeting cancelled'))

            if xp:
                leveled_up = player.level.add_xp(xp)
                message_log.add_message(Message('You gain {0} xp.'.format(xp)))

                if leveled_up:
                    message_log.add_message(
                        Message(
                            'Your skills grow stronger! You reached level {0}'.
                            format(player.level.current_level) + '!',
                            constants['colors'].get('yellow')))
                    previous_game_state = game_state
                    game_state = GameStates.LEVEL_UP

            if effect:
                effect_funct = effect.get('type')
                new_effect = effect_funct(con, root_console,
                                          constants['colors'],
                                          effect.get('coords'),
                                          effect.get('radius'),
                                          effect.get('duration'),
                                          effect.get('char'),
                                          effect.get('color'))
                animations.append(new_effect)

        if game_state == GameStates.ENEMY_TURN:
            for entity in entities:
                if entity.ai:
                    enemy_turn_results = entity.ai.take_turn(
                        player, game_map, entities)
                    if enemy_turn_results:
                        fov_recompute = True
                    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, constants['colors'])
                            else:
                                message = kill_monster(dead_entity,
                                                       constants['colors'])

                            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