Esempio n. 1
0
 def __init__(self, screen_width, screen_height):
     self.display = pygame.display.set_mode((screen_width, screen_height))
     self.fpsClock = pygame.time.Clock()
     self.char = Character(
         0, 510, 6, self.load_image("adventurer/adventurer-idle-00.png",
                                    -1))
     self.wall_list = [Wall(0, 500, screen_width, 100)]
     self.background = pygame.Surface(self.display.get_size())
     self.background = pygame.image.load("res/background.png")
     self.background = self.background.convert()
     self.sprites = pygame.sprite.RenderPlain(self.char)
Esempio n. 2
0
 def push_mention(self, mention: str):
     username = mention[1:]  # skip @
     for player in self.players:
         if player.username == username:
             character = Character(player.character_name, player.id, player.full_name)
             return self.entities.list.append(character)
     return self.entities.list.append(Span(mention))
Esempio n. 3
0
 def push_text_mention(self, user):
     for player in self.players:
         if player.user_id == user.id:
             character = Character(player.character_name, player.id,
                                   player.full_name)
             self.entities.list.append(character)
             return
Esempio n. 4
0
def get_available_spells(character: Character) -> set():
    chr_class = character.get_class()
    available_spells = set()

    if chr_class == 'paladin':
        available_spells = get_available_paladin_abilities(character)  # this function is from commands.py

    return available_spells
Esempio n. 5
0
def handle_monster_death(character: Character, monster: Monster, alive_monsters: dict, guid_name_set: set, monster_GUID: int):
    """
    This function is called when a monster has just died
    :param character: the player's character
    :param monster_GUID: the unique GUID of the monster
    :param monster: the monster that has died
    :param alive_monsters:Dictionary with the alive monsters in the subzone the player is in
    :param guid_name_set: Set which holds the name of each monster_GUID
    """
    print(f'{character.name} has slain {monster.name}!')

    character.award_monster_kill(monster=monster, monster_guid=monster_GUID)
    character.leave_combat()  # will exit the combat loop on next iter

    del alive_monsters[monster_GUID]  # removes the monster from the dictionary
    guid_name_set.remove((monster_GUID, monster.name))  # remove it from the set used for looking up

    handle_loot(character, monster)
Esempio n. 6
0
def get_available_spells(character: Character) -> set():
    chr_class = character.get_class()
    available_spells = set()

    if chr_class == 'paladin':
        available_spells = get_available_paladin_abilities(
            character)  # this function is from commands.py

    return available_spells
Esempio n. 7
0
def handle_loot(character: Character, monster: Monster):
    """ Display the loot dropped from the monster and listen for input if the player wants to take any"""
    print_loot_table(monster.loot)
    while True:
        command = input()

        if command == 'take all':
            # takes everything

            gold = monster.give_loot('gold')
            if gold:  # if it's successful
                character.award_gold(gold)
                print(f'{character.name} has looted {gold} gold.')

            monster_loot = list(
                monster.loot.keys())  # list of strings, the item's names
            for item_name in monster_loot:
                # loop through them and get every one
                item: 'Item' = monster.give_loot(item_name=item_name)

                if item:  # if the loot is successful
                    character.award_item(item=item)
                    print(f'{character.name} has looted {item_name}.')

        elif "take" in command:
            item_name = command[5:]

            if item_name == "gold":
                gold = monster.give_loot("gold")

                if gold:  # if it's successful
                    character.award_gold(gold)
                    print(f'{character.name} has looted {gold} gold.')
            else:  # if we want to take an item
                item = monster.give_loot(item_name=item_name)

                if item:  # if the loot is successful
                    character.award_item(item=item)
                    print(f'{character.name} has looted {item_name}.')
        elif command == "?":
            pac_looting()
        elif command == "exit":  # end the looting process
            print('-' * 40)
            break
        else:
            print("Invalid command.")

        if not monster.loot:  # if the loot is empty, exit the loot window
            print('-' * 40)
            break

        print_loot_table(
            monster.loot
        )  # print the updated table each time we take something
Esempio n. 8
0
def handle_loot(character: Character, monster: Monster):
    """ Display the loot dropped from the monster and listen for input if the player wants to take any"""
    print_loot_table(monster.loot)
    while True:
        command = input()

        if command == 'take all':
            # takes everything

            gold = monster.give_loot('gold')
            if gold:  # if it's successful
                character.award_gold(gold)
                print(f'{character.name} has looted {gold} gold.')

            monster_loot = list(monster.loot.keys())  # list of strings, the item's names
            for item_name in monster_loot:
                # loop through them and get every one
                item: 'Item' = monster.give_loot(item_name=item_name)

                if item:  # if the loot is successful
                    character.award_item(item=item)
                    print(f'{character.name} has looted {item_name}.')

        elif "take" in command:
            item_name = command[5:]

            if item_name == "gold":
                gold = monster.give_loot("gold")

                if gold:  # if it's successful
                    character.award_gold(gold)
                    print(f'{character.name} has looted {gold} gold.')
            else:  # if we want to take an item
                item = monster.give_loot(item_name=item_name)

                if item:  # if the loot is successful
                    character.award_item(item=item)
                    print(f'{character.name} has looted {item_name}.')
        elif command == "?":
            pac_looting()
        elif command == "exit":  # end the looting process
            print('-' * 40)
            break
        else:
            print("Invalid command.")

        if not monster.loot:  # if the loot is empty, exit the loot window
            print('-' * 40)
            break

        print_loot_table(monster.loot)  # print the updated table each time we take something
Esempio n. 9
0
def handle_monster_death(character: Character, monster: Monster,
                         alive_monsters: dict, guid_name_set: set,
                         monster_GUID: int):
    """
    This function is called when a monster has just died
    :param character: the player's character
    :param monster_GUID: the unique GUID of the monster
    :param monster: the monster that has died
    :param alive_monsters:Dictionary with the alive monsters in the subzone the player is in
    :param guid_name_set: Set which holds the name of each monster_GUID
    """
    print(f'{character.name} has slain {monster.name}!')

    character.award_monster_kill(monster=monster, monster_guid=monster_GUID)
    character.leave_combat()  # will exit the combat loop on next iter

    del alive_monsters[monster_GUID]  # removes the monster from the dictionary
    guid_name_set.remove(
        (monster_GUID,
         monster.name))  # remove it from the set used for looking up

    handle_loot(character, monster)
Esempio n. 10
0
def save_character(character: Character):
    """
    Save the character into the database
    """
    character_info: SavedCharacterSchema = session.query(SavedCharacterSchema).filter_by(name=character.name).one_or_none()

    character_level: int = character.level  # type: int
    character_class: str = character.get_class()  # type: str
    character_gold: int = character.inventory['gold']  # type: int
    equipment: {str: int} = character.equipment
    headpiece_id: int = get_item_id_or_none(equipment[CHARACTER_EQUIPMENT_HEADPIECE_KEY])
    shoulderpad_id: int = get_item_id_or_none(equipment[CHARACTER_EQUIPMENT_SHOULDERPAD_KEY])
    necklace_id: int = get_item_id_or_none(equipment[CHARACTER_EQUIPMENT_NECKLACE_KEY])
    chestguard_id: int = get_item_id_or_none(equipment[CHARACTER_EQUIPMENT_CHESTGUARD_KEY])
    bracer_id: int = get_item_id_or_none(equipment[CHARACTER_EQUIPMENT_BRACER_KEY])
    gloves_id: int = get_item_id_or_none(equipment[CHARACTER_EQUIPMENT_GLOVES_KEY])
    belt_id: int = get_item_id_or_none(equipment[CHARACTER_EQUIPMENT_BELT_KEY])
    leggings_id: int = get_item_id_or_none(equipment[CHARACTER_EQUIPMENT_LEGGINGS_KEY])
    boots_id: int = get_item_id_or_none(equipment[CHARACTER_EQUIPMENT_BOOTS_KEY])

    character_values: {str: int or str} = {
        'name': character.name, 'character_class': character_class, 'level': character_level, 'gold': character_gold,
        'headpiece_id': headpiece_id, 'shoulderpad_id': shoulderpad_id, 'necklace_id': necklace_id,
        'chestguard_id': chestguard_id, 'belt_id': belt_id, 'bracer_id': bracer_id, 'gloves_id': gloves_id,
        'leggings_id': leggings_id, 'boots_id': boots_id}

    # if the character exists, update the row, otherwise create a new one
    if character_info:
        session.query(SavedCharacterSchema).filter_by(name=character.name).update(character_values)
    else:
        session.add(SavedCharacterSchema(**character_values))
    session.commit()

    # save the sub-tables
    char_entry = session.query(SavedCharacterSchema).filter_by(name=character.name).first().entry
    save_loaded_scripts(char_entry, character.loaded_scripts)
    save_killed_monsters(char_entry, character.killed_monsters)
    save_completed_quests(char_entry, character.completed_quests)
    save_inventory(char_entry, character.inventory)

    session.commit()
    print("-" * 40)
    print(f'Character {character.name} was saved successfully!')
    print("-" * 40)
Esempio n. 11
0
    def __init__(
        self,
        tier: int,
        scale: int,
        SCREEN_HEIGHT: int,
        SCREEN_WIDTH: int,
        sprite_path: str,
        run_textures: list,
        pattern_texture: dict,
    ):
        """

        :param tier: What tier of the screen the lane should be.
        :param run_textures: A list of textures for running animation (only Q atm)
        """
        self.SCREEN_HEIGHT = SCREEN_HEIGHT
        self.SCREEN_WIDTH = SCREEN_WIDTH
        self.tier = tier

        self.char = Character(
            sprite_path,
            SCREEN_HEIGHT - (SCREEN_HEIGHT // 3) * tier + 20,
            run_textures,
            pattern_texture,
        )
        self.char.center_x = SCREEN_WIDTH // 10
        self.char.scale = scale

        self.floor = arcade.Sprite("../ressources/Floor_Tempo.png")
        self.floor.center_y = SCREEN_HEIGHT - (SCREEN_HEIGHT // 3) * tier + 5
        floor_list = arcade.SpriteList()
        floor_list.append(self.floor)

        self.physics_engine = arcade.PhysicsEnginePlatformer(
            self.char, floor_list)
        self.valid_zone = self.generate_valid_zone()
        self.difficulty = 6
Esempio n. 12
0
def engage_combat(character: Character, monster: Monster, alive_monsters: dict, guid_name_set: set, monster_GUID: int):
    """
    This is where we handle the turn based combat of the game
    available_spells - set of string commands that enable our character to use the spells he has available.

    First we get both parties to enter combat. We start the loop and have the monster attack and
    immediately check if the character is not dead from the blow.
    If not, we take his command and if said command is one that does not end the turn (ie. wants to print some
    information about the fight) we enter an inner loop handling such commands and
    which continues to take commands until it gets one that does end the turn.
    We handle the command (which is most likely a spell or auto attack) and check if the monster is dead.
    :param character: the player
    :param monster: the monster that the player has attacked
    Parameters below are used solely to delete the monster from the dict & set once he's dead
    :param alive_monsters: Dictionary with the alive monsters in the subzone the player is in
    :param guid_name_set: Set which holds the name of each monster_GUID
    :param monster_GUID: The monster GUID
    """
    # Load all of the currently available spells for our character
    available_spells: set() = get_available_spells(character)
    will_end_turn = True  # Dictates if we are going to count the iteration of the loop as a turn

    character.enter_combat()
    monster.enter_combat()
    if monster.gossip:  # if the monster has gossip
        monster.say_gossip()
        sleep(2)

    while character.is_in_combat():
        # We start off the combat with the monster dealing the first blow
        if not will_end_turn:  # skip attack if the turn has not ended
            # skip turn based things
            will_end_turn = True
        else:
            monster.start_turn_update()
            character.start_turn_update()

            if monster.is_alive():
                monster.attack(character)
            else:  # monster has died, most probably from a DoT
                handle_monster_death(character, monster, alive_monsters, guid_name_set, monster_GUID)
                break

        if not character.is_alive():
            monster.leave_combat()
            print(f'{monster.name} has slain character {character.name}')

            prompt_revive(character)
            break

        command = input()
        # check if the command does not end the turn, if it doesn't the same command gets returned
        command = route_in_combat_non_ending_turn_commands(command, character, monster)

        if command == 'attack':
            character.attack(monster)
        elif command in available_spells:
            # try to execute the spell and return if it managed to or not
            successful_cast = character.spell_handler(command, monster)
            if not successful_cast:
                # skip the next attack, don't count this iteration as a turn and load a command again
                will_end_turn = False

        if will_end_turn:
            monster.end_turn_update()
            character.end_turn_update()

        if not monster.is_alive():
            handle_monster_death(character, monster, alive_monsters, guid_name_set, monster_GUID)
            break
Esempio n. 13
0
class Control:
    def __init__(self, screen_width, screen_height):
        self.display = pygame.display.set_mode((screen_width, screen_height))
        self.fpsClock = pygame.time.Clock()
        self.char = Character(
            0, 510, 6, self.load_image("adventurer/adventurer-idle-00.png",
                                       -1))
        self.wall_list = [Wall(0, 500, screen_width, 100)]
        self.background = pygame.Surface(self.display.get_size())
        self.background = pygame.image.load("res/background.png")
        self.background = self.background.convert()
        self.sprites = pygame.sprite.RenderPlain(self.char)

    def check_events(self):
        # pylint: disable=no-member
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                sys.exit()

        keys = pygame.key.get_pressed()

        if (keys[pygame.K_LEFT]):
            self.char.move(-self.char.speed, 0)
            self.check_collisions(-self.char.speed, 0)

        if (keys[pygame.K_RIGHT]):
            self.char.move(self.char.speed, 0)
            self.check_collisions(self.char.speed, 0)

        if (keys[pygame.K_SPACE]):
            self.char.jump()
            self.check_collisions(0, self.char.jump_speed)
        # pylint: enable=no-member

    def check_collisions(self, x, y):

        for wall in self.wall_list:
            if self.char.rect.colliderect(wall.rect):
                if x != 0:
                    if x > 0:
                        self.char.rect.right = wall.rect.left
                    else:
                        self.char.rect.left = wall.rect.right

                if y != 0:
                    self.char.jump_speed = 0
                    if y > 0:
                        self.char.rect.bottom = wall.rect.top
                        self.char.is_jumping = False
                    else:
                        self.char.rect.top = wall.rect.bottom

    def load_image(self, name, colorkey=None):
        fullname = os.path.join("res", name)
        try:
            image = pygame.image.load(fullname)
        except pygame.error:
            print("Cannot load image:", fullname)
            raise SystemExit()
        image = image.convert()
        if colorkey is not None:
            if colorkey == -1:
                colorkey = image.get_at((0, 0))
            image.set_colorkey(colorkey, pygame.RLEACCEL)
        return image, image.get_rect()

    def main_loop(self):

        while 1:

            self.fpsClock.tick(30)

            self.check_events()

            self.char.update()
            self.check_collisions(0, self.char.jump_speed)

            #self.display.fill((0,0,0))
            self.display.blit(self.background, (0, 0))

            self.sprites.draw(self.display)
            #self.display.blit(self.char.image,(self.char.rect.x,self.char.rect.y))

            for wall in self.wall_list:
                wall.draw(self.display, (100, 100, 100))

            pygame.display.update()
Esempio n. 14
0
def engage_combat(character: Character, monster: Monster, alive_monsters: dict,
                  guid_name_set: set, monster_GUID: int):
    """
    This is where we handle the turn based combat of the game
    available_spells - set of string commands that enable our character to use the spells he has available.

    First we get both parties to enter combat. We start the loop and have the monster attack and
    immediately check if the character is not dead from the blow.
    If not, we take his command and if said command is one that does not end the turn (ie. wants to print some
    information about the fight) we enter an inner loop handling such commands and
    which continues to take commands until it gets one that does end the turn.
    We handle the command (which is most likely a spell or auto attack) and check if the monster is dead.
    :param character: the player
    :param monster: the monster that the player has attacked
    Parameters below are used solely to delete the monster from the dict & set once he's dead
    :param alive_monsters: Dictionary with the alive monsters in the subzone the player is in
    :param guid_name_set: Set which holds the name of each monster_GUID
    :param monster_GUID: The monster GUID
    """
    # Load all of the currently available spells for our character
    available_spells: set() = get_available_spells(character)
    will_end_turn = True  # Dictates if we are going to count the iteration of the loop as a turn

    character.enter_combat()
    monster.enter_combat()
    if monster.gossip:  # if the monster has gossip
        monster.say_gossip()
        sleep(2)

    while character.is_in_combat():
        # We start off the combat with the monster dealing the first blow
        if not will_end_turn:  # skip attack if the turn has not ended
            # skip turn based things
            will_end_turn = True
        else:
            monster.start_turn_update()
            character.start_turn_update()

            if monster.is_alive():
                monster.attack(character)
            else:  # monster has died, most probably from a DoT
                handle_monster_death(character, monster, alive_monsters,
                                     guid_name_set, monster_GUID)
                break

        if not character.is_alive():
            monster.leave_combat()
            print(f'{monster.name} has slain character {character.name}')

            prompt_revive(character)
            break

        command = input()
        # check if the command does not end the turn, if it doesn't the same command gets returned
        command = route_in_combat_non_ending_turn_commands(
            command, character, monster)

        if command == 'attack':
            character.attack(monster)
        elif command in available_spells:
            # try to execute the spell and return if it managed to or not
            successful_cast = character.spell_handler(command, monster)
            if not successful_cast:
                # skip the next attack, don't count this iteration as a turn and load a command again
                will_end_turn = False

        if will_end_turn:
            monster.end_turn_update()
            character.end_turn_update()

        if not monster.is_alive():
            handle_monster_death(character, monster, alive_monsters,
                                 guid_name_set, monster_GUID)
            break
Esempio n. 15
0
def save_character(character: Character):
    """
    Save the character into the database
    """
    character_info: SavedCharacterSchema = session.query(
        SavedCharacterSchema).filter_by(name=character.name).one_or_none()

    character_level: int = character.level  # type: int
    character_class: str = character.get_class()  # type: str
    character_gold: int = character.inventory['gold']  # type: int
    equipment: {str: int} = character.equipment
    headpiece_id: int = get_item_id_or_none(
        equipment[CHARACTER_EQUIPMENT_HEADPIECE_KEY])
    shoulderpad_id: int = get_item_id_or_none(
        equipment[CHARACTER_EQUIPMENT_SHOULDERPAD_KEY])
    necklace_id: int = get_item_id_or_none(
        equipment[CHARACTER_EQUIPMENT_NECKLACE_KEY])
    chestguard_id: int = get_item_id_or_none(
        equipment[CHARACTER_EQUIPMENT_CHESTGUARD_KEY])
    bracer_id: int = get_item_id_or_none(
        equipment[CHARACTER_EQUIPMENT_BRACER_KEY])
    gloves_id: int = get_item_id_or_none(
        equipment[CHARACTER_EQUIPMENT_GLOVES_KEY])
    belt_id: int = get_item_id_or_none(equipment[CHARACTER_EQUIPMENT_BELT_KEY])
    leggings_id: int = get_item_id_or_none(
        equipment[CHARACTER_EQUIPMENT_LEGGINGS_KEY])
    boots_id: int = get_item_id_or_none(
        equipment[CHARACTER_EQUIPMENT_BOOTS_KEY])

    character_values: {
        str: int or str
    } = {
        'name': character.name,
        'character_class': character_class,
        'level': character_level,
        'gold': character_gold,
        'headpiece_id': headpiece_id,
        'shoulderpad_id': shoulderpad_id,
        'necklace_id': necklace_id,
        'chestguard_id': chestguard_id,
        'belt_id': belt_id,
        'bracer_id': bracer_id,
        'gloves_id': gloves_id,
        'leggings_id': leggings_id,
        'boots_id': boots_id
    }

    # if the character exists, update the row, otherwise create a new one
    if character_info:
        session.query(SavedCharacterSchema).filter_by(
            name=character.name).update(character_values)
    else:
        session.add(SavedCharacterSchema(**character_values))
    session.commit()

    # save the sub-tables
    char_entry = session.query(SavedCharacterSchema).filter_by(
        name=character.name).first().entry
    save_loaded_scripts(char_entry, character.loaded_scripts)
    save_killed_monsters(char_entry, character.killed_monsters)
    save_completed_quests(char_entry, character.completed_quests)
    save_inventory(char_entry, character.inventory)

    session.commit()
    print("-" * 40)
    print(f'Character {character.name} was saved successfully!')
    print("-" * 40)
Esempio n. 16
0
    def __init__(self, driver):
        State.__init__(self, driver)
        self._engine = TileEngine('dungeon.map', driver, self)
        self._font = pygame.font.Font(None, 20)
        self._name = random.choice(names)
        self._messages = [(0, "Welcome to %s" % self._name)]
        self._deequip = None
        self._visited = None
        mapinfo = self._engine.getMapInfo()
        self._mapinfo = mapinfo
        self.xp = localXP = 3500
        playerStats = {
            'level': localXP / 100,
            'str': 30,
            'dex': 30,
            'int': 30,
        }
        self.gender = 'Male'
        self.race = 'Human'
        self.charClass = 'Guardian'
        armorStats = {
            'name': '+10 Robes of the Guardian',
            'absorb': 20,
            'toDodge': 10
        }
        weaponStats = {
            'name': '+10 Flaming Angelic Sword',
            'damageMin': 25,
            'damageMax': 75,
            'toHit': 10,
        }
        weapon = entities.Weapon('sword.png', self._engine, 0, 0, weaponStats)
        armor = entities.Armor('armor.png', self._engine, 0, 0, armorStats)
        self._player = Character('player.png', self._engine, mapinfo['startx'],
                                 mapinfo['starty'], playerStats, 1)
        self._player.giveItem(weapon)
        self._player.equip(weapon)
        self._player.giveItem(armor)
        self._player.equip(armor)

        self._engine.addSprite(self._player)
        self._engine.centerOn(self._player)

        staffStats = {'name': 'Terrifyingly Powerful Staff of Glok-Yar'}
        self._staff = entities.Staff('staff.png', self._engine,
                                     mapinfo['staffx'], mapinfo['staffy'],
                                     staffStats)
        self._engine.addSprite(self._staff)

        self._entries = []
        counter = 1
        while counter:
            try:
                entranceX = mapinfo['entranceX%d' % counter]
                entranceY = mapinfo['entranceY%d' % counter]
                entrance = entities.Entry('stairs.png', self._engine,
                                          entranceX, entranceY)
                self._entries.append(entrance)
                self._engine.addSprite(entrance)
                counter += 1
            except KeyError:
                counter = 0

        self._turn = 0
        mixer.music.load(localSoundsDir + '23 - Cold_Mountain_Clouds.ogg')
        mixer.music.set_volume(localVol * 4)
        mixer.music.play(-1)
Esempio n. 17
0
class PlayingGame(State):
    def __init__(self, driver):
        State.__init__(self, driver)
        self._engine = TileEngine('dungeon.map', driver, self)
        self._font = pygame.font.Font(None, 20)
        self._name = random.choice(names)
        self._messages = [(0, "Welcome to %s" % self._name)]
        self._deequip = None
        self._visited = None
        mapinfo = self._engine.getMapInfo()
        self._mapinfo = mapinfo
        self.xp = localXP = 3500
        playerStats = {
            'level': localXP / 100,
            'str': 30,
            'dex': 30,
            'int': 30,
        }
        self.gender = 'Male'
        self.race = 'Human'
        self.charClass = 'Guardian'
        armorStats = {
            'name': '+10 Robes of the Guardian',
            'absorb': 20,
            'toDodge': 10
        }
        weaponStats = {
            'name': '+10 Flaming Angelic Sword',
            'damageMin': 25,
            'damageMax': 75,
            'toHit': 10,
        }
        weapon = entities.Weapon('sword.png', self._engine, 0, 0, weaponStats)
        armor = entities.Armor('armor.png', self._engine, 0, 0, armorStats)
        self._player = Character('player.png', self._engine, mapinfo['startx'],
                                 mapinfo['starty'], playerStats, 1)
        self._player.giveItem(weapon)
        self._player.equip(weapon)
        self._player.giveItem(armor)
        self._player.equip(armor)

        self._engine.addSprite(self._player)
        self._engine.centerOn(self._player)

        staffStats = {'name': 'Terrifyingly Powerful Staff of Glok-Yar'}
        self._staff = entities.Staff('staff.png', self._engine,
                                     mapinfo['staffx'], mapinfo['staffy'],
                                     staffStats)
        self._engine.addSprite(self._staff)

        self._entries = []
        counter = 1
        while counter:
            try:
                entranceX = mapinfo['entranceX%d' % counter]
                entranceY = mapinfo['entranceY%d' % counter]
                entrance = entities.Entry('stairs.png', self._engine,
                                          entranceX, entranceY)
                self._entries.append(entrance)
                self._engine.addSprite(entrance)
                counter += 1
            except KeyError:
                counter = 0

        self._turn = 0
        mixer.music.load(localSoundsDir + '23 - Cold_Mountain_Clouds.ogg')
        mixer.music.set_volume(localVol * 4)
        mixer.music.play(-1)

    def event(self, key, pressed):
        soundOpenMenu.set_volume(localVol * .5)
        turned = 1
        if pressed:
            if key == K_KP8 or key == K_UP:
                self._player.move(0, -1)
            elif key == K_KP2 or key == K_DOWN:
                self._player.move(0, 1)
            elif key == K_KP4 or key == K_LEFT:
                self._player.move(-1, 0)
            elif key == K_KP6 or key == K_RIGHT:
                self._player.move(1, 0)
            elif key == K_KP1:
                self._player.move(-1, 1)
            elif key == K_KP7:
                self._player.move(-1, -1)
            elif key == K_KP9:
                self._player.move(1, -1)
            elif key == K_KP3:
                self._player.move(1, 1)
            elif key == K_u:
                self._deequip = inventory.DeEquip(self._driver, self._player,
                                                  self)
                self._visited = self._deequip
                turned = 0
            elif key == K_e:
                self._visited = inventory.Equip(self._driver, self._player,
                                                self)
            elif key == K_d:
                self._visited = inventory.Drop(self._driver, self._player,
                                               self)
            elif key == K_s:
                self._visited = inventory.Sell(self._driver, self._player,
                                               self)
            elif key == K_a:
                self._visited = inventory.Use(self._driver, self._player, self)
            elif key == K_h:
                self._visited = inventory.Help(self._driver, self._player,
                                               self)

            elif key == K_b:
                if self._player.money > 250:
                    self._player.money -= 250
                    self.message("You buy a Healing Potion for 250 Gold")
                    potionStats = {
                        'name': "Healing Potion",
                        'healingMin': 25,
                        'healingMax': 150
                    }
                    potion = entities.Potion('armor.png', self._engine, 0, 0,
                                             potionStats)

                    self._player.giveItem(potion)
                    soundCoins.set_volume(localVol * 1)
                    soundCoins.play()
                else:
                    self.message(
                        "You don't have enough Gold to buy a Healing Potion")

            elif key == K_ESCAPE:
                self._driver.done()

            self._engine.centerOn(self._player)
            if turned:
                self.takeTurn()

    def message(self, message):
        try:
            self._messages.append((self._turn, message))
        except AttributeError:
            pass  # Don't message until self._turn is ready

    def paint(self, screen):
        self._engine.paint(screen)

        self.paintStats(screen, self._player)
        self.paintMessages(screen)

    def paintMessages(self, screen):
        x = 2
        y = 0
        screenSize = self._driver.getScreenSize()
        white = (255, 255, 255)
        right = x + screenSize[0] - 4
        messageImages = []
        for turn, message in self._messages:
            if turn < self._turn - 3: continue
            messageImages.append(
                self._font.render(message, 0, white).convert())
        if messageImages:
            bottom = y + (
                (messageImages[0].get_size()[1] + 2) * len(messageImages))
            pygame.draw.line(screen, white, (x, y), (right, y))
            pygame.draw.line(screen, white, (right, y), (right, bottom))

            pygame.draw.line(screen, white, (right, bottom), (x, bottom))

            pygame.draw.line(screen, white, (x, bottom), (x, y))
            screen.fill((64, 64, 192), (x + 1, y + 1, right - 3, bottom - 1))
            for image in messageImages:
                screen.blit(image, (x + 1, y + 1))
                y += image.get_size()[1] + 2

    def paintStats(self, screen, player):
        statsTuple = (player.str, player.dex, player.int, player.hp,
                      player.maxhp, player.mp, player.maxmp, player.money,
                      player.xp)
        line = ("The Guardian (Level %d):  " % player.level +
                "STR %d DEX %d INT %d  HP %d(%d) MP %d(%d)  Gold %d  XP %d"
                ) % statsTuple

        white = (255, 255, 255)
        stats = self._font.render(line, 0, white).convert()
        screenSize = self._driver.getScreenSize()
        x = 2
        y = screenSize[1] - stats.get_size()[1] - 4
        right = x + screenSize[0] - 4
        bottom = screenSize[1] - 2
        pygame.draw.line(screen, white, (x, y), (right, y))
        pygame.draw.line(screen, white, (right, y), (right, bottom))
        pygame.draw.line(screen, white, (right, bottom), (x, bottom))
        pygame.draw.line(screen, white, (x, bottom), (x, y))
        screen.fill((64, 64, 192), (x + 2, y + 2, right - 4, bottom - 4))
        screen.blit(stats, (x + 1, y + 1))

    def reactivate(self):
        self._visited = None

    def takeTurn(self):
        self._turn += 1
        chance = float(self._mapinfo['spawnChance']) / 100.0
        picked = random.random()
        if picked < chance:
            adv = ai.createAdventurer(self._entries, self._engine)
            message = "You sense an intruder enter the dungeon"
            self.message(message)
            self._engine.addSprite(adv, 1)

            soundEnemySpawn.set_volume(localVol * 1)
            soundEnemySpawn.play()
        self._engine.takeTurn()

    def update(self):
        if (self._visited):
            self._driver.start(self._visited)
Esempio n. 18
0
cls()
print('Conectando ao banco de dados...')

engine = create_engine('sqlite:///data.db')
Base.metadata.bind = engine

DBSession = sessionmaker(bind=engine)
session = DBSession()

if session != None:
    time.sleep(.3)
    print('Acesso ao banco de dados:' + AZUL + ' OK' + RESET)
    time.sleep(.3)
    print('Inicializando tabelas...')
    Item.create_table()
    Character.create_table()
    time.sleep(.3)
    print(AZUL + 'Iniciando programa...' + RESET)
    time.sleep(.5)

    ### MENU PRINCIPAL ###
    while True:
        cls()
        print('\33[34mGERADOR DE ENTIDADES - versao alpha 0.1\33[0m')
        print('  1. Criar nova entidade')
        print('  2. Visualizar entidades')
        print('  3. Editar entidade')
        print('  4. Deletar entidade')
        print('  0. Sair')

        c = None
Esempio n. 19
0
class Game(object):
	"""width and height are the width and height of the starting level"""
	def __init__(self, width, height):
		self.mapt = Map(width, height)

		self.player = Character("Frank", "thief", int(width / 2), int(height / 2))

		self.current_level.set_entity(self.player.x, self.player.y, "guy")



	@property
	def current_level(self):
		return self.mapt.get_level()

	def entity_at(self, x, y):
		return self.current_level.entitylist[y][x]

	def tick(self):
		for entity in self.entitylist:
			entity.tick()

	def move_player(self, direction):	# direction should be one of N, S, E, W, NE, SE, NW, SW as a string
		x = self.player.x
		y = self.player.y
		# horizontal/vertical movement
		if direction.lower() == "n":
			if self.entity_at(x, y - 1).walkable:
				self.player.move(x, y - 1)
				self.current_level.move_entity(x, y, x, y - 1)
		if direction.lower() == "s":
			if self.entity_at(x, y + 1).walkable:
				self.player.move(x, y + 1)
				self.current_level.move_entity(x, y, x, y + 1)
		if direction.lower() == "e":
			if self.entity_at(x + 1, y).walkable:
				self.player.move(x + 1, y)
				self.current_level.move_entity(x, y, x + 1, y)
		if direction.lower() == "w":
			if self.entity_at(x - 1, y).walkable:
				self.player.move(x - 1, y)
				self.current_level.move_entity(x, y, x - 1, y)

		# diagonal movement
		if direction.lower() == "ne":
			if self.entity_at(x + 1, y - 1).walkable:
				self.player.move(x + 1, y - 1)
				self.current_level.move_entity(x, y, x + 1, y - 1)
		if direction.lower() == "se":
			if self.entity_at(x + 1, y + 1).walkable:
				self.player.move(x + 1, y + 1)
				self.current_level.move_entity(x, y, x + 1, y + 1)
		if direction.lower() == "nw":
			if self.entity_at(x - 1, y - 1).walkable:
				self.player.move(x - 1, y - 1)
				self.current_level.move_entity(x, y, x - 1, y - 1)
		if direction.lower() == "sw":
			if self.entity_at(x - 1, y + 1).walkable:
				self.player.move(x - 1, y + 1)
				self.current_level.move_entity(x, y, x - 1, y + 1)
Esempio n. 20
0
	def __init__(self, width, height):
		self.mapt = Map(width, height)

		self.player = Character("Frank", "thief", int(width / 2), int(height / 2))

		self.current_level.set_entity(self.player.x, self.player.y, "guy")
Esempio n. 21
0
def print_class_abilities_in_combat(character: Character):
    if character.get_class() == 'paladin':
        print_paladin_abilities_in_combat(character)