Example #1
0
    def __init__(self):

        self.heroRace = Race()
        self.heroClass = ""

        #Получаем Данные от пользователя
        self.getName()
        self.getClass()
        self.getRace()

        super().__init__(self.name, self.heroRace.stats, Elements(), 0)

        ## Инвентарь героя
        self.inventory = Inventory()
        ## Обмундирование героя
        self.equipment = Equipment()
        ## Карман с Лечебками героя
        self.potionsPocket = PotionsPocket()
Example #2
0
def newGame():
    game_name=input('请输入关卡名称:')
    boss_name=input('请输入boss名称:')
    boss_level=int(input('请输入boss等级'))
    boss_Pattack=int(input('请输入boss攻击力:'))
    boss_Pdefense=int(input('请输入boss防御力:'))
    boss_Mattack=int(input('请输入boss法强:'))
    boss_Mdefense=int(input('请输入boss魔抗:'))
    boss_speed=int(input('请输入boss速度:'))
    Ep.printEquipment()
    str=input('请输入本关卡可能掉落的装备序号,使用空格隔开,回车确认:')
    getEquipmentNum=list(str.split())
    n=0
    for n in range(len(getEquipmentNum)):
        getEquipmentNum[n]=int(getEquipmentNum[n])
    game=Game(game_name,boss_name,boss_level,boss_Pattack,boss_Pdefense,boss_Mattack,boss_Mdefense,boss_speed,getEquipmentNum)
    games.append(game)
    print('添加成功')
Example #3
0
    def pick_up(self):
        #add to the player's inventory and remove from the map
        if len(GameGlobals.inventory) >= 26:
            GameGlobals.messageBox.print('Your inventory is full, cannot pick up ' + self.owner.name + '.')
        else:
            GameGlobals.inventory.append(self.owner)
            GameGlobals.levelobjects.remove(self.owner)
            GameGlobals.messageBox.print('You picked up a ' + self.owner.name + '!')

            #special case: automatically equip, if the corresponding equipment slot is unused
            equipment = self.owner.equipment
            if equipment and Equipment.get_equipped_in_slot(equipment.slot) is None:
                equipment.equip()
Example #4
0
def sentGoogleSheetImformation(stockSymbol, name):

    result = Equipment.infoDataFormate(stockSymbol)

    result['name'] = name

    url = "https://script.google.com/macros/s/AKfycbyDg_HBWWJWrAspnyrrDkUNkNO6HPfgSq_7CHNlOTy9/exec"
    data = {
        "sheetUrl": "https://docs.google.com/spreadsheets/d/1wGARftMGTwvy6x4RbNUjcfUJIG6NIpZXRXqRYd3QuoQ/edit#gid=1755276593",
        "sheetTag": stockSymbol,
        "action": "write",
        "data": str(result).replace("\'", "\"")
    }
    r = requests.get(url, params=data)
    pass
Example #5
0
    def find_current_item(self, item):
        common_item_types = Storage.ItemStorage.get_common_item_keys()
        temp_modlist = [
            Crafting.CraftMod("None"),
            Crafting.CraftMod("None"),
            Crafting.CraftMod("None")
        ]

        if item == "Item name":
            current_item = Equipment.EquipmentCommon(
                random.choice(common_item_types), "Common", "Item name",
                temp_modlist)
        else:
            current_item = Storage.item_storage.item_dict[item]
            print(current_item.stat_bonuses)
        return current_item
Example #6
0
 def __init__(self, idChar, name, race, mystery, blood_thirst,
              greed_lvl, gold, relations, location):
     self.idChar = idChar                            # Integer
     self.name = name                                # String
     self.race = race                                # String
     self.attributes = race.attribute_set            # AttributeSet
     self.competences = race.competence_set          # CompetenceSet
     self.mystery = mystery                          # Integer [0,10]
     self.blood_thirst = blood_thirst                # Integer [0,10]
     self.greed_lvl = greed_lvl                      # Integer [0,10]
     self.gold = gold                                # Integer
     self.estate = []                            # List of Building
     self.equipment = Equipment()                    # Equipment
     self.bagpack = BagPack()                        # BagPack
     self.relations = relations                      # Dictionnary
     self.RACE_RELATIONS = race.relations            # Dictionnary
     self.location = location                        # String (by now)
Example #7
0
    def update_new_item_stats(self, e):
        temp_mod_list = []
        for mod in self.mod_boxes:
            name = mod.GetValue()
            new_mod = Crafting.CraftMod(name)
            temp_mod_list.append(new_mod)

        temp_item_name = self.item_type.GetValue()
        temp_type = self.item_key_combobox.GetValue()
        temp_rarity = self.item_rarity_value.GetValue()

        new_item = Equipment.EquipmentCommon(temp_type,
                                             temp_rarity,
                                             name=temp_item_name,
                                             mod_list=temp_mod_list)
        self.current_item = new_item
        self.show_current_item_stats(e)
Example #8
0
	def __init__(self):

		self.heroRace = Race()
		self.heroClass = ""

		#Получаем Данные от пользователя
		self.getName()
		self.getClass()
		self.getRace()

		super().__init__(self.name,self.heroRace.stats,Elements(),0)

		## Инвентарь героя
		self.inventory = Inventory()
		## Обмундирование героя
		self.equipment = Equipment()
		## Карман с Лечебками героя
		self.potionsPocket = PotionsPocket()
Example #9
0
def admin_menu():
    while True:
        print('''
        1 添加装备
        2 查看装备信息
        3 删除装备信息
        4 添加游戏关卡
        5 查看游戏关卡
        6 删除游戏关卡
        7 查看玩家信息
        ''')
        admin_choice = input('请输入您的选择:')
        if admin_choice == 'back':
            return
        if admin_choice == '1':
            Ep.newEquipment()
            pass
        if admin_choice == '2':
            Ep.printEquipment()
        if admin_choice == '3':
            while True:
                n = input('请输入您要删除的装备的序号或输入 back 返回')
                if n == 'back':
                    break
                n = int(n)
                Ep.deletEquipment(n)
        if admin_choice == '4':
            GL.newGame()
            pass
        if admin_choice == '5':
            GL.printGames()
            pass
        if admin_choice == '6':
            while True:
                n = input('请输入您要删除的游戏关卡的序号或输入 back 返回')
                if n == 'back':
                    break
                n = int(n)
                GL.deleteGame(n)
        if admin_choice == '7':
            n = 0
            for person in Ps.persons:
                print('序号:', n)
                person.printPerson()
                print('\n')
                n = n + 1
            del n
    pass
Example #10
0
 def main():
     employee = Employee.Employee("Steve Jobs", 1)
     employee.setTitle("CEO")
     location = Location.Location()
     purchase = Purchase.Purchase(time.time(), "Walmart", time.time())
     equipment = Equipment.Equipment(purchase, 1234, "Computer", "FFD123",
                                     "1134D")
     location.addEmployee(employee)
     employee.setLocation(location)
     location.addEquipment(equipment)
     equipment.setAssignee(employee)
     employee.addEquipment(equipment)
     coordinates = Coordinate.Coordinate()
     coordinates.setAddress("One Redmond Way, Redmond, WA")
     coordinates.setCellPhone("(206) 246-1342")
     coordinates.setWorkPhone("(425) 422-1356")
     employee.setCoordinates(coordinates)
     equipment.setLocation(location)
     location.setMaintenanceEmployee(employee)
     employee.setSupervisor(employee)
     location.prettyPrint()
Example #11
0
    def load_common_items():
        common_item_source = csv.DictReader(open(BaseStats.COMMON_ITEMS_STORAGE), escapechar='\\')
        for row in common_item_source:
            if row["Key"] in item_storage.item_dict.keys():
                print(f"There are duplicate {row['Key']}")
                continue
            else:
                new_item = Equip.EquipmentCommon(row["Key"], row["Rarity"], row["Name"])
                new_item.mod_list = []
                mod_list_keys = json.loads(row["ModList"])
                for m in mod_list_keys:
                    if m == "None":
                        new_item.mod_list.append(Craft.CraftMod("None"))
                    for key, value in item_storage.mod_dict.items():
                        if key == m:
                            new_item.mod_list.append(value)
                new_item.get_nonunique_item_stats()


            new_item.type = row["Type"]
            new_item.slot = row["Slot"]
            item_storage.item_dict[row["Name"]] = new_item
Example #12
0
class Character:

    """
        A class for Characters.
        =======================
        Attributes :
        ------------
            - id: Integer
            - name: String
            - race: String
            - attributes set: Instance of AttributeSet - copy from race
            - competences set: Instance of CompetenceSet - copy from race
            - mystery Value: Integer [0,10]
            - blood thirst Value: Integer [0,10]
            - level of greed: Integer [0,10]
            - gold: Integer
            - estate: List of buildings
            - equipment: Dictionnary of Item {Location: Item}
            - other objets: List of Item {Item: number}
            - Bonus: Dictionnary of Integer
            - relations: Dictionnary of Integer
            - RACE_RELATIONS: Dictionnary of Integer - copy from race
            - Location: Instance of Location
    """

    def __init__(self, idChar, name, race, mystery, blood_thirst,
                 greed_lvl, gold, relations, location):
        self.idChar = idChar                            # Integer
        self.name = name                                # String
        self.race = race                                # String
        self.attributes = race.attribute_set            # AttributeSet
        self.competences = race.competence_set          # CompetenceSet
        self.mystery = mystery                          # Integer [0,10]
        self.blood_thirst = blood_thirst                # Integer [0,10]
        self.greed_lvl = greed_lvl                      # Integer [0,10]
        self.gold = gold                                # Integer
        self.estate = []                            # List of Building
        self.equipment = Equipment()                    # Equipment
        self.bagpack = BagPack()                        # BagPack
        self.relations = relations                      # Dictionnary
        self.RACE_RELATIONS = race.relations            # Dictionnary
        self.location = location                        # String (by now)

    #############################################
    # Definitions des relations entre personnages
    #############################################

    def getInfluence(self):
        """
            Compute the influence value.
            ----------------------------
            The formula is: ...

            OUTPUT: Integer
        """
        at_blth = (self.attributes.attractivity + self.blood_thirst)/4
        if at_blth == 0:
            return 0
        else:
            bonus_myst = self.mystery*(4/10)
            return(int((at_blth + (bonus_myst)/2)))

    def getObedience(self, character):
        """
            Compute the obedience value of a character.
            -------------------------------------------
            The formula is: ...

            OUTPUT: Integer
        """
        influence = character.getInfluence()
        if self.RACE_RELATIONS[character.race] <= -5:
            return(int(self.RACE_RELATIONS[character.race] + influence))
        elif (self.RACE_RELATIONS[character.race] > -5
              and self.RACE_RELATIONS[character.race] <= 0):
            return(int(self.RACE_RELATIONS[character.race] + influence/1.3))
        elif (self.RACE_RELATIONS[character.race] > 0
              and self.RACE_RELATIONS[character.race] <= 5):
            return(int(self.RACE_RELATIONS[character.race] + influence/2))
        else:
            return(int(self.RACE_RELATIONS[character.race] + influence/3))

    def getLoyalty(self, character):
        """
            Compute the loyalty value of a character.
            -----------------------------------------
            The formula is: ...

            OUTPUT : Integer
        """
        return(self.getObedience(character) + (self.greed_lvl - 5))

    def getStress(self):
        """
            Compute the stress value in the current location.
            -------------------------------------------------
            The formula is: ...

            OUTPUT : Integer
        """
        return(self.RACE_RELATIONS[self.location.people.name]/2)

    ##########################
    # Fonctions de deplacement
    ##########################

    def moveTo(self, location):
        """
            Move to new Location.
            ---------------------

            OUTPUT: None
        """
        self.location = location

    ###########################
    # Fonctions pour les objets
    ###########################

    def takeItem(self, item, number=1):
        """
            Add an item to BagPack
            ----------------------

            OUTPUT: None
        """
        self.bagpack.addItem(item, number)

    def putItem(self, item, number=1):
        """
            Remove an item from bagpack
            ---------------------------

            OUTPUT: None
        """
        self.bagpack.removeItem(item, number)

    def equipWeapon(self, weapon, hand="right_hand"):
        """
            Equip a weapon.
            ---------------
            Add a weapon from bagpack to equipment and apply enchantments
            on the character.

            OUTPUT: None
        """
        if weapon in self.bagpack.weapons:
            self.equipment.addWeapon(weapon, hand)
            self.putItem(weapon)
            weapon.equipEffect(self)
        else:
            print("Vous ne possedez pas cet objet")

    def unequipWeapon(self, hand="all"):
        """
            Unequip a weapon.
            -----------------
            Add a weapon from equipment to bagpack and disapply enchantments.

            OUTPUT: None
        """
        weapons = {'right_hand': self.equipment.right_hand,
                   'left_hand': self.equipment.left_hand}
        if hand == 'all':
            for w in weapons:
                self.takeItem(weapons[w])
                weapons[w].unequipEffect(self)
                self.equipment.removeArmor(w)
        else:
            try:
                self.takeItem(weapons[hand])
                weapons[hand].unequipEffect(self)
                self.equipment.removeWeapon(hand)
            except KeyError:
                print("Emplacement invalide")
            except AttributeError:
                print("Il n'y a rien a cet emplacement")

    def equipArmor(self, armor):
        """
            Equip an armor.
            ---------------
            Add an armor from bagpack to equipment and apply enchantments
            on the character.

            OUTPUT: None
        """
        if armor in self.bagpack.armors:
            self.equipment.addArmor(armor)
            self.putItem(armor)
            armor.equipEffect(self)
        else:
            print("Vous ne possedez pas cet objet")

    def unequipArmor(self, location="all"):
        """
            Unequip an armor.
            -----------------
            Add an armor from equipment to bagpack and disapply enchantments.

            OUTPUT: None
        """
        armors = {"head": self.equipment.head,
                  "shoulders": self.equipment.shoulders,
                  "arms": self.equipment.arms,
                  "trunk": self.equipment.trunk,
                  "legs": self.equipment.legs,
                  "feet": self.equipment.feet}
        if location == 'all':
            for armor in armors:
                self.takeItem(armors[armor])
                armors[armor].unequipEffect(self)
                self.equipment.removeArmor(armor)
        else:
            try:
                self.takeItem(armors[location])
                armors[location].unequipEffect(self)
                self.equipment.removeArmor(location)
            except KeyError:
                print("Emplacement invalide")
            except AttributeError:
                print("Il n'y a rien a cet emplacement")

    def equipJewelry(self, jewelry, finger='right1'):
        """
            Equip a jewelry.
            ---------------
            Add a jewelry from bagpack to equipment and apply enchantments
            on the character.

            OUTPUT: None
        """
        if jewelry in self.bagpack.jewelries:
            self.equipment.addJewelry(jewelry, finger)
            self.putItem(jewelry)
            jewelry.equipEffect(self)
        else:
            print("Vous ne possedez pas cet objet")

    def unequipJewelry(self, location="all"):
        """
            Unequip a jewelry.
            -----------------
            Add a jewelry from equipment to bagpack and disapply enchantments.

            OUTPUT: None
        """
        jewelries = {"right1": self.equipment.right1,
                     "right2": self.equipment.right2,
                     "left1": self.equipment.left1,
                     "left2": self.equipment.left2,
                     "neck": self.equipment.neck,
                     "wrist": self.equipment.wrist}
        if location == 'all':
            for j in jewelries:
                self.takeItem(jewelries[j])
                jewelries[j].unequipEffect(self)
                self.equipment.removeJewelry(j)
        else:
            try:
                self.takeItem(jewelries[location])
                jewelries[location].unequipEffect(self)
                self.equipment.removeJewelry(location)
            except KeyError:
                print("Emplacement invalide")
            except AttributeError:
                print("Il n'y a rien a cet emplacement")

    #####################
    # Fonctions de quetes
    #####################

    def questRequest(self, quest, team):
        """
            The character make a quest request to a team.
            ---------------------------------------------
            Add the quest to the list of waiting quests

            OUTPUT: None
        """
        print("{} vous propose une quete a l'equipe {}"
              .format(self.name, team.name))
        team.waiting_Quest += [quest]

    ##########################
    # Fonctions d'organisation
    ##########################

    def createTeam(self, name, description):
        """
            Create a new Team
            -----------------
            Upgrade the character to TeamChief and create a new team
            which the caracter is the chief

            OUTPUT: None
        """
        chief = TeamChief(self.idChar, self.name, self.race, self.HP,
                          self.attributes, self.competences, self.mystery,
                          self.blood_thirst, self.greed_lvl,
                          self.gold, self.relations)
        del self
        return(Team(name, chief, [chief], 0, description))
Example #13
0
import pygame
import config
import Player
import Terrain
import Equipment
import showcoords

pygame.init()
window = pygame.display.set_mode((config.screen_width, config.screen_height))
pygame.display.set_caption("Minecraft2D")

terrain = Terrain.Terrain()
player = Player.Player(terrain)
equipment = Equipment.Equipment()


def update(ev):
    player.update(ev, terrain, equipment)
    equipment.update(ev)


def draw():
    window.fill((0, 0, 0))
    terrain.draw(window, player)
    player.draw(window)
    equipment.draw(window)
    showcoords.draw(window, player)


terrain.create_terrain()
Example #14
0
        earth.update(2)
        earth.update(4)
        earth.update(6)

        a1 = eve.reproduce(adam)
        a2 = eve.reproduce(adam)
        a3 = eve.reproduce(adam)

        b1 = ana.reproduce(joseph)
        b2 = ana.reproduce(joseph)
        b3 = ana.reproduce(joseph)

        earth.update(10)

        c1 = Equipment.Spear()
        c1r = Equipment.Shield()
        c2 = Equipment.Sword()
        c3 = Equipment.Sword()
        c4 = Equipment.Sword()

        adam.equip(c1)
        adam.equip(c1r)

        war = adam.declareWar(joseph.family)
        if war.victor.leader is joseph:
            JOSEPH_WIN += 1
        if war.victor.leader is adam:
            ADAM_WIN += 1

print('Adam Wins: ' + str(ADAM_WIN))
Example #15
0
 def load_unique_items():
     unique_key_source = csv.DictReader(open(BaseStats.ITEM_UNIQUE_KEYS))
     for row in unique_key_source:
         new_item = Equip.EquipmentUnique(row["Key"], row["Key"])
         item_storage.item_dict[row["Key"]] = new_item
Example #16
0
    def gameInit(self):
        self.sounds = Sound.Sound()
        self.building = Building.Building(self.screen, self.screenSize)
        if self.rainEffect:
            self.weather = []
            for columnNumber in range(1,
                                      self.building.leftWallX // Weather.SIZE):
                self.weather.append(
                    Weather.Column(columnNumber * Weather.SIZE, self.screen,
                                   self.building.floorY))
            for columnNumber in range(self.building.leftWallX // Weather.SIZE,
                                      self.building.rightWallX //
                                      Weather.SIZE):
                self.weather.append(
                    Weather.Column(columnNumber * Weather.SIZE, self.screen,
                                   self.building.leftWallX))
            for columnNumber in range(self.building.rightWallX // Weather.SIZE,
                                      self.screenWidth // Weather.SIZE):
                self.weather.append(
                    Weather.Column(columnNumber * Weather.SIZE, self.screen,
                                   self.building.floorY))
        self.sky = Weather.Sky(self.screen, self.screenWidth,
                               self.screenHeight, self.building.leftWallX,
                               self.building.rightWallX,
                               self.building.ceilingY, self.sounds)

        # RANDOMLY SPAWNED
        self.hero = Character.Player(self.screen, self.building,
                                     self.screenWidth, self.screenHeight)

        self.cultist = Trash.Cultist(self.screen, self.building)
        self.enemiesToSpawn.append(self.cultist)
        self.cultist2 = Trash.Cultist(self.screen, self.building)
        self.enemiesToSpawn.append(self.cultist2)

        self.angel = Trash.Angel(self.screen, self.building)
        #self.enemies.append(self.angel)
        #self.angel.spawn()
        self.enemiesToSpawn.append(self.angel)

        self.skeleton = Trash.Skeleton(self.screen, self.building)
        self.enemiesToSpawn.append(self.skeleton)
        self.skeleton2 = Trash.Skeleton(self.screen, self.building)
        self.enemiesToSpawn.append(self.skeleton2)

        self.bomb = Equipment.Bomb(self.screen, self.building)
        self.equipmentToSpawn.append(self.bomb)
        self.bomb2 = Equipment.Bomb(self.screen, self.building)
        self.equipmentToSpawn.append(self.bomb2)
        self.garlic = Equipment.Garlic(self.screen, self.building)
        self.equipmentToSpawn.append(self.garlic)
        self.garlic2 = Equipment.Garlic(self.screen, self.building)
        self.equipmentToSpawn.append(self.garlic2)
        self.flute = Equipment.Flute(self.screen, self.building)
        self.equipmentToSpawn.append(self.flute)
        self.flute2 = Equipment.Flute(self.screen, self.building)
        self.equipmentToSpawn.append(self.flute2)
        self.rune = Equipment.Rune(self.screen, self.building)
        self.equipmentToSpawn.append(self.rune)
        self.rune2 = Equipment.Rune(self.screen, self.building)
        self.equipmentToSpawn.append(self.rune2)
        self.rune3 = Equipment.Rune(self.screen, self.building)
        self.equipmentToSpawn.append(self.rune3)
        self.sword = Equipment.Sword(self.screen, self.building)
        self.equipmentToSpawn.append(self.sword)
        self.whip = Equipment.Whip(self.screen, self.building)
        self.equipmentToSpawn.append(self.whip)
        self.shield = Equipment.Shield(self.screen, self.building)
        self.equipmentToSpawn.append(self.shield)
Example #17
0
 def use_item(self, player):
     player.set_armor(Equipment.GoldArmor())
Example #18
0
 def use_item(self, player):
     player.set_weapon(Equipment.BrokenSword())
Example #19
0
 def use_item(self, player):
     player.set_weapon(Equipment.EmeraldSickle())
Example #20
0
 def use_item(self, player):
     player.set_weapon(Equipment.WaterSword())
Example #21
0
class Hero(Entity):
    def __init__(self):

        self.heroRace = Race()
        self.heroClass = ""

        #Получаем Данные от пользователя
        self.getName()
        self.getClass()
        self.getRace()

        super().__init__(self.name, self.heroRace.stats, Elements(), 0)

        ## Инвентарь героя
        self.inventory = Inventory()
        ## Обмундирование героя
        self.equipment = Equipment()
        ## Карман с Лечебками героя
        self.potionsPocket = PotionsPocket()

    ## Получает имя Персонажа
    def getName(
            self):  #TODO! Не получать пустую строку , и чтобы ввод был норм.
        while True:
            self.name = input("Input you name:")
            if self.name:
                # Если что-то было введено - прекратить цикл
                break

    ## Получает Рассу
    def getRace(self):
        #Получаем Расу
        self.heroRace = utils.getChoice(
            "Choose your Race:",
            races)  #TODOlater Сделать вывод по горизонтали

    ## Получает Класс
    def getClass(
        self
    ):  #TODO Сдлеать сразу содание класса, при выборе одного из классов(вызывается создание класса) http://stackoverflow.com/questions/8141165/how-to-dynamically-select-a-method-call-in-python
        self.heroClass = utils.getChoice("Choose Your Class:",
                                         ["Warrior", "Ranger", "Mage"])

        ## Выводит полный перечень Того что есть у Персонажа:

    ## Уровень Опыт Класс Рассу
    ## Статистики (stats, hp, mp, money)
    ## Урон
    ## Вещи в inventory (инвентаре)
    ## Вещи в equipment (обмундировании)
    ## Лечебки в potionsPocket
    ## Резисты Персонажа
    ## Квесты в QuestJournal
    ## Заклинания в SpellBook

    def showStats(self):
        #TODO showStats() в hero делать с переносом на новую строку при выводе каждого объекта. При этом с использованием \n и дальше на новой строке код
        #        -Level exp
        #		 +Race Class
        # 		 +Stats
        #        +Damage
        #        +inventory
        #        +equipment
        #        +potionsPocket
        #        +resists
        #        -questJournal
        #        -spellbook
        #
        pass

    ## восстанавливает hp и mp
    def heal(self):
        self.stats.hp = self.stats.maxHp
        self.stats.mp = self.stats.maxMp

    ## Кастует Заклинание
    def castSpell(
            self, spell
    ):  #TODOlater Сделать когда будет готов класс Spell и SpellBook
        pass

        #TODO Переименовать на action? или еще что-то
    def castSpellChoice(self, hero, enemies):
        pass

    def usePotionChoice(self, hero, enemies):
        choosedPotion = utils.getChoice("What potion to use?",
                                        self.potionsPocket.items(),
                                        cancel=True)
        if choosedPotion:
            # Если было выбрано одно из зелий
            self.use(choosedPotion)
        else:
            #TODO! Выбрали отмену
            return False

        #вызывает simpleAttack для выбранного монстра
    def attackChoice(self, hero, enemies):
        if len(enemies) > 1:
            choosedEnemy = utils.getChoice("Choose your target:",
                                           enemies,
                                           cancel=True)
            if choosedEnemy == 0:
                #TODO! Выбрана отмена
                return False
        else:
            # Если один противник - его бьёт автоматически
            choosedEnemy = enemies[0]
        self.simpleAttack(choosedEnemy)

    def doTurn(self, hero, enemies):
        availableBattleChoices = self.getAvailableBattleChoices()
        selectedBattleChoice = utils.getChoice(
            "What would you do?", list(availableBattleChoices.keys()))
        availableBattleChoices[selectedBattleChoice](hero, enemies)

        ## Возвращает Словарь с возможными вариантами хода и методом за них отвечающим
    def getAvailableBattleChoices(self):
        battleChoices = {}
        # Simple attack is always available
        battleChoices["Attack with \"{0}\"".format(
            self.equipment.weapon())] = self.attackChoice
        #if not self.spellBook.isEmpty():
        #   battleChoices["Cast Spell"] = self.castSpellChoice
        if not self.potionsPocket.isEmpty():
            battleChoices["Use Potion"] = self.usePotionChoice
        return battleChoices

        ## Одевает item в equipment и убирает из inventory
    def equip(self, item):
        if self.equipment.equipment[
                item.piece] != "empty":  #if there is an item
            self.unequip(self.equipment.equipment[item.piece])
        #now the slot is empty
        self.equipment.equipment[item.piece] = item
        #Если вещь в инвентаре - убрать её оттуда
        self.inventory.removeItem(item)
        #give items Stats bonus and damage/defence
        self.stats.addStats(item.bonusStats)
        if item.isWeapon():
            self.stats.damage.addDamage(item.damage)
        if item.isArmor():
            self.defence += item.defence

    #Think Нужен ли equipList() - который будет просто вызывать equip для каждой вещи

    ## Снимает item из equipment и кладёт в inventory
    def unequip(self, item):
        #remove Stats that this item added
        self.stats.removeStats(self.equipment.equipment[item.piece].bonusStats)
        if item.isWeapon():
            self.stats.damage.removeDamage(item.damage)
        if item.isArmor():
            self.defence -= item.defence
            #add it to inventory
        self.inventory.addItem(self.equipment.equipment[item.piece])
        #make this slot empty
        self.equipment.equipment[item.piece] = "empty"

    ## Использует вещь на героя (например Зелье)
    def use(self, item):
        item.use(self)

    ## Возвращает true Если герой может использовать это (Spell, weapon, armor и т.п.)
    def canUse(self, object):
        return object.canUse(hero)

    def __str__(self):
        #return '"{0}" Health: {1}/{2} Mana: {3}/{4} {5} Defence: {6}'.format(self.name,self.hp,self.maxHp,self.mp,self.maxMp,self.stats.damage,self.defence)
        return '"{0}"  Health: {1.hp}/{1.maxHp}  Mana: {1.mp}/{1.maxMp}  {1.damage}  Defence: {2}'.format(
            self.name, self.stats, self.defence)
Example #22
0
class Hero(Entity):

	def __init__(self):

		self.heroRace = Race()
		self.heroClass = ""

		#Получаем Данные от пользователя
		self.getName()
		self.getClass()
		self.getRace()

		super().__init__(self.name,self.heroRace.stats,Elements(),0)

		## Инвентарь героя
		self.inventory = Inventory()
		## Обмундирование героя
		self.equipment = Equipment()
		## Карман с Лечебками героя
		self.potionsPocket = PotionsPocket()

	## Получает имя Персонажа
	def getName(self): #TODO! Не получать пустую строку , и чтобы ввод был норм.
		while True:
			self.name = input("Input you name:")
			if self.name:
				# Если что-то было введено - прекратить цикл
				break
	## Получает Рассу
	def getRace(self):
		#Получаем Расу
		self.heroRace = utils.getChoice("Choose your Race:",races) #TODOlater Сделать вывод по горизонтали

	## Получает Класс
	def getClass(self): #TODO Сдлеать сразу содание класса, при выборе одного из классов(вызывается создание класса) http://stackoverflow.com/questions/8141165/how-to-dynamically-select-a-method-call-in-python
		self.heroClass = utils.getChoice("Choose Your Class:",[
			"Warrior",
			"Ranger",
			"Mage"
		])


		## Выводит полный перечень Того что есть у Персонажа:
	## Уровень Опыт Класс Рассу
	## Статистики (stats, hp, mp, money)
	## Урон
	## Вещи в inventory (инвентаре)
	## Вещи в equipment (обмундировании)
	## Лечебки в potionsPocket
	## Резисты Персонажа
	## Квесты в QuestJournal
	## Заклинания в SpellBook

	def showStats(self):
	#TODO showStats() в hero делать с переносом на новую строку при выводе каждого объекта. При этом с использованием \n и дальше на новой строке код
	#        -Level exp
	#		 +Race Class
	# 		 +Stats
	#        +Damage
	#        +inventory
	#        +equipment
	#        +potionsPocket
	#        +resists
	#        -questJournal
	#        -spellbook
	#
		pass

	## восстанавливает hp и mp
	def heal(self):
		self.stats.hp = self.stats.maxHp
		self.stats.mp = self.stats.maxMp

	## Кастует Заклинание
	def castSpell(self, spell): #TODOlater Сделать когда будет готов класс Spell и SpellBook
		pass

		#TODO Переименовать на action? или еще что-то
	def castSpellChoice(self, hero, enemies):
		pass

	def usePotionChoice(self, hero, enemies):
		choosedPotion = utils.getChoice("What potion to use?", self.potionsPocket.items(), cancel=True)
		if choosedPotion:
			# Если было выбрано одно из зелий
			self.use(choosedPotion)
		else:
			#TODO! Выбрали отмену
			return False

		#вызывает simpleAttack для выбранного монстра
	def attackChoice(self, hero, enemies):
		if len(enemies) > 1:
			choosedEnemy = utils.getChoice("Choose your target:", enemies, cancel=True)
			if choosedEnemy == 0:
				#TODO! Выбрана отмена
				return False
		else:
		# Если один противник - его бьёт автоматически
			choosedEnemy = enemies[0]
		self.simpleAttack(choosedEnemy)

	def doTurn(self, hero, enemies):
		availableBattleChoices = self.getAvailableBattleChoices()
		selectedBattleChoice = utils.getChoice("What would you do?", list(availableBattleChoices.keys()))
		availableBattleChoices[selectedBattleChoice](hero, enemies)


		## Возвращает Словарь с возможными вариантами хода и методом за них отвечающим
	def getAvailableBattleChoices(self):
		battleChoices = {}
		# Simple attack is always available
		battleChoices["Attack with \"{0}\"".format(self.equipment.weapon())] = self.attackChoice
		#if not self.spellBook.isEmpty():
		#   battleChoices["Cast Spell"] = self.castSpellChoice
		if not self.potionsPocket.isEmpty():
			battleChoices["Use Potion"] = self.usePotionChoice
		return battleChoices

		## Одевает item в equipment и убирает из inventory
	def equip(self, item):
		if self.equipment.equipment[item.piece] != "empty":#if there is an item
			self.unequip(self.equipment.equipment[item.piece])
		#now the slot is empty
		self.equipment.equipment[item.piece]=item
		#Если вещь в инвентаре - убрать её оттуда
		self.inventory.removeItem(item)
		#give items Stats bonus and damage/defence
		self.stats.addStats(item.bonusStats)
		if item.isWeapon():
			self.stats.damage.addDamage(item.damage)
		if item.isArmor():
			self.defence+=item.defence

	#Think Нужен ли equipList() - который будет просто вызывать equip для каждой вещи

	## Снимает item из equipment и кладёт в inventory
	def unequip(self, item):
		#remove Stats that this item added
		self.stats.removeStats(self.equipment.equipment[item.piece].bonusStats)
		if item.isWeapon():
			self.stats.damage.removeDamage(item.damage)
		if item.isArmor():
			self.defence-=item.defence
			#add it to inventory
		self.inventory.addItem(self.equipment.equipment[item.piece])
		#make this slot empty
		self.equipment.equipment[item.piece] = "empty"


	## Использует вещь на героя (например Зелье)
	def use(self, item):
		item.use(self)

	## Возвращает true Если герой может использовать это (Spell, weapon, armor и т.п.)
	def canUse(self, object):
		return object.canUse(hero)

	def __str__(self):
		#return '"{0}" Health: {1}/{2} Mana: {3}/{4} {5} Defence: {6}'.format(self.name,self.hp,self.maxHp,self.mp,self.maxMp,self.stats.damage,self.defence)
		return '"{0}"  Health: {1.hp}/{1.maxHp}  Mana: {1.mp}/{1.maxMp}  {1.damage}  Defence: {2}'.format(self.name, self.stats, self.defence)