示例#1
34
 def setup(self):
     self.dungeon = Dungeon("map.txt")
     self.hero = Hero("Geralt", "white wolf", 150, 150, 5)
     self.hero.equip(Weapon("Sword", 30))
     self.hero.learn(Spell("wolf's attack", 20, 20, 2))
     self.dungeon.spawn(self.hero)
     self.command = None
示例#2
0
def load_weapons(handle=None):
    import os
    import json
    import re
    from pathlib import Path
    data_folder = os.path.dirname(__file__)
    data_folder = Path(data_folder or Path.cwd())
    weapons_json_file = data_folder / r"Base_WeaponsList.json"
    with open(weapons_json_file, "r") as dataFile:
        data = dataFile.read()
    obj = json.loads(data)

    for k, v in obj.items():
        # newname = v["name"].replace(" ", "_").lower()
        pattern = re.compile(r"\b" + v["regExpSearch"], re.IGNORECASE)
        # print(f"{handle} -- {v['name']} -- {v['regExpSearch']}")
        if re.search(pattern, handle):
            # print(handle)
            my_weapon = Weapon(name=handle)
            for i in v.keys():
                if i == "damage":
                    setattr(my_weapon, i, [v[i]])
                # print(f"{i} = {getattr(my_weapon, i)}")
                else:
                    setattr(my_weapon, i, v[i])
            return my_weapon
    return Weapon("body odor")
示例#3
0
    def __init__(self, id, color, speed, pos):
        self.id = id
        self.alive = True
        self.color = color
        self.speed = speed
        self.acceleration = [0, 0]
        self.position = pos
        self.rotation = 0.0
        self.publisher = rospy.Publisher(self.id, Marker, queue_size=10)
        self.render()

        self.weapons = []
        i = 0
        while i < HANDS_COUNT + 1:
            me = self.id + "_weapon" + str(i)

            position = (HAND_LENGTH[0], 0, 0)
            parent = self.id + "_weapon" + str(i - 1)

            if i == 0:
                parent = self.id
                position = (0.4, 0, 0)

            weapon = Weapon(me, Marker.CYLINDER, parent, position, HAND_LENGTH,
                            [1, 1, 1], 120)
            self.weapons.append(weapon)
            i += 1

        position = (1, 0, 0)
        parent = self.id + "_weapon" + str(i - 1)
        weapon = Weapon(self.id + "_damage", Marker.SPHERE, parent, position,
                        [0.5, 0.5, 0.5], [1, 0, 0], 0)
        self.weapons.append(weapon)
        self.damage = weapon
示例#4
0
    def run(self):
        race = self.get_title()
        raceName[race][0]()
        print('Хотите продолжить этой расой?\n')
        print('1. Да')
        print('2. Нет')
        x = proverka('Введите число: ', 1, 2)
        if x == 1:
            self.menu.forsed_command = True
            name = input(
                'Введите имя персонажа: '
            )  # вместо ифов использовать массив как роказывал дмитриф

            char = Char(name, race)
            os.system('cls' if os.name == 'nt' else 'clear')
            print('\nВыбеерите начальное снаряжение: ')
            print('1. Меч(1-4)')
            print('2. Кремневый пистолет(2-3)')
            print('3. Лук(0-6)\n')
            x = proverka('Введите число: ', 1, 3)
            if x == 1:
                Sword = Weapon('Меч', 10, [1, 4], 70)
                char.addWeapon(Sword)
            if x == 2:
                FlintlockPistol = Weapon('Кремневый пистолет', 10, [2, 3], 70)
                char.addWeapon(FlintlockPistol)
            if x == 3:
                Bow = Weapon('Лук', 10, [0, 6], 70)
                char.addWeapon(Bow)
            CharRegystry().addChar(char)
            CharRegystry().raceCorrect(race)
 def setUp(self):
     sword = Weapon('Spartan Sword', 1, 20)
     bow = Weapon('Long Bow', 5, 60)
     
     self.leonidas = Character('King Leonidas', 10, sword, 200)
     self.legolas = Character('Elf Legolas', 5, bow, 100, 4)
     self.hulk = Character('Incredible Hulk', 100, None, 800, 2)
示例#6
0
 def __init__(self):
     self.hitpoints = randint(100, 125)
     self.locationx = 0
     self.locationy = 0
     self.inventory = []
     self.inventory.append(Weapon(0))
     for x in range(9):
         self.inventory.append(Weapon(randint(1, 3)))
         self.inventory[x + 1].add_observer(self)
     self.weapon_held = 0
示例#7
0
    def setUp(self):
        sword = Weapon('Spartan Sword', 1, 20)
        bow = Weapon('Long Bow', 5, 60)

        self.leonidas = Character('King Leonidas', 10, sword, 200)
        self.legolas = Character('Elf Legolas', 5, bow, 100, 4)
        self.hulk = Character('Incredible Hulk', 100, None, 800, 2)

        self.arena = Battleground('Thunderdome', 20, 20)
        self.battle = Battle(self.arena)
示例#8
0
    def cycle_weapon(self):

        if self.current_weapon.weapon_type == Weapon.PISTOL:
            self.current_weapon = Weapon(Weapon.SHOTGUN)

        elif self.current_weapon.weapon_type == Weapon.SHOTGUN:
            self.current_weapon = Weapon(Weapon.AUTOMATIC)

        elif self.current_weapon.weapon_type == Weapon.AUTOMATIC:
            self.current_weapon = Weapon(Weapon.PISTOL)
示例#9
0
 def __init__(self):
     self.hp = random.randint(100, 125)
     #modified the attack rating to make destroying monsters more enjoyable
     self.attack = random.randint(30, 45)
     self.weapons = []
     for i in range(4):
         if i == 0:
             self.weapons.append(Weapon(False))
     #randomly assign other weapon types to 9 remaining open slots using weapon class
         else:
             self.weapons.append(Weapon())
示例#10
0
 def test_fight_simulation(self):
     hero = Hero("Natsu", 10000, "DragonSlayer")
     orc = Orc("BadOrc", 100, 2)
     fight = Fight(hero, orc)
     dragonpower = Weapon("Dragonpower", 200, 0.8)
     axe = Weapon("Axe", 120, 0.4)
     fight.hero.weapon = dragonpower
     fight.orc.weapon = axe
     fight.simulate_fight()
     self.assertEqual(fight.orc.battlehp, 0)
     self.assertTrue(fight.hero.battlehp > 0)
示例#11
0
def test_hero_multi_weapon_attack():
    strength = Weapon("Overwhelming Strength", 200)
    sword_of_truth = Weapon("Sword of Truth", 700)
    Athena = Hero("Athena")
    Athena.add_ability(strength)
    Athena.add_ability(sword_of_truth)
    assert len(Athena.abilities) == 2

    test_runs = 100
    for _ in range(0, test_runs):
        attack = Athena.attack()
        assert attack <= 900 and attack >= 0
 def test_start_fight(self):
     f = Fight()
     h = Hero("Geralt", "White wolf", 100, 100, 5)
     h.equip(Weapon("Axe", 40))
     h.learn(Spell("Storm", 30, 50, 3))
     e = Enemy(100, 200, 30)
     e.equip(Weapon("Sword", 40))
     e.learn(Spell("Fire", 30, 20, 3))
     d = 2
     h = f.start_fight(h, e, d)
     print('=======================')
     print(h.known_as(), h.get_health())
示例#13
0
    def __init__(self,
                 db,
                 ctx: Ctx,
                 foe_name=None,
                 foe_candidate="Random",
                 challenge_level=".25",
                 damage_generator="Random",
                 hit_point_generator="Max"):
        gender_candidate = 'U'
        self.character_id = -1
        self.ctx = ctx
        self.name = foe_name
        ability_array_str = 'Common'
        if foe_candidate == "Random":
            foe_candidate = self.find_random(db=db,
                                             challenge_level=challenge_level)
        level = 1  # Player level will always be 1 for Foes
        Character.__init__(self,
                           db=db,
                           ctx=ctx,
                           gender_candidate=gender_candidate,
                           ability_array_str=ability_array_str,
                           damage_generator=damage_generator,
                           hit_point_generator=hit_point_generator,
                           level=level)
        self.get_foe(db=db, foe_candidate=foe_candidate)
        self.stats.character_id = self.character_id
        self.stats.character_class = self.race  # this looks funky, but characterStats presentation for the foe race
        self.stats.character_race = self.foe_type  # is easier to compare using the class as "skeleton" and race as
        # Undead.  Leaving that like that for it.  In all programmatic work the foe race and foe_type will be used.

        if self.melee_weapon is not None:
            self.melee_weapon_obj = Weapon(db=db,
                                           ctx=ctx,
                                           name=self.get_melee_weapon())
            self.melee_weapon_obj.set_weapon_proficient()
        if self.ranged_weapon is not None:
            self.ranged_weapon_obj = Weapon(db=db,
                                            ctx=ctx,
                                            name=self.get_ranged_weapon())
            self.melee_weapon_obj.set_weapon_proficient()

        self.set_damage_adjs(db=db)

        self.class_eval.append({
            "pythonClass": "Foe",
            "foe_candidate": foe_candidate,
            "challenge_level": challenge_level,
            "damage_generator": damage_generator,
            "hit_point_generator": hit_point_generator,
            "level": level
        })
        self.logger.info(msg="user_audit", json_dict=self.__dict__, ctx=ctx)
    def default_weapons(self):
        '''Skapar objekt av klassen Weapon'''

        knife = Weapon("Knife", 11)
        self.all_weapons.append(knife)

        gun = Weapon("Gun", 12)
        self.all_weapons.append(gun)

        screwdriver = Weapon("Screwdriver", 7)
        self.all_weapons.append(screwdriver)

        broomstick = Weapon("Broomstick", 9)
        self.all_weapons.append(broomstick)
示例#15
0
    def treasure_found(self):
        treasure = random.choice(["weapon", "spell", "mana", "health"])
        print('You win {}!'.format(treasure))
        if treasure == "health":
            self.hero.take_healing(random.randint(10, 50))
            return self.hero.health

        if treasure == "mana":
            self.hero.take_mana(random.randint(10, 50))
            return self.hero.mana

        if treasure == "spell":
            random_key = str(random.randint(1, 7))
            spells = self.read_json("items/spells.json")
            spell_dic = spells.get(random_key)
            spell = Spell(**spell_dic)
            self.hero.learn(spell)
            return spell.name

        if treasure == "weapon":
            random_key = str(random.randint(1, 4))
            weapons = self.read_json("items/weapons.json")
            weapon_dic = weapons.get(random_key)
            weapon = Weapon(**weapon_dic)
            self.hero.equip(weapon)
            return weapon.name
示例#16
0
 def buying_menu(self, hero):
     print("Lets see what I have...")
     available_weapons = weapon_pile().get_weapon_pile()
     counter = 1
     for aw in available_weapons:
         print(
             str(counter) + ". " + aw.name + " -- " + str(aw.low_damage) +
             "-" + str(aw.high_damage) + " -- $" +
             str(random.randrange(30, 200)))
         counter += 1
     weapon_choice = input("Which one would you like to buy: ")
     if int(weapon_choice) >= 1 and int(weapon_choice) <= len(
             available_weapons):
         buying_weapon = Weapon(available_weapons[int(weapon_choice) -
                                                  1].name)
         if hero.char.money > buying_weapon.money:
             hero.GetWeapon().upgrade_weapon(buying_weapon.name)
             hero.char.decrease_money(buying_weapon.money)
             print(hero.char.name + " now has " + str(hero.char.money) +
                   " gold.")
         else:
             print(
                 "The shopkeep grimmaces and says, \"Sorry, you don't have enough money!\""
             )
         print("You leave the shop")
示例#17
0
    def add_item(self, obj_type, item_id, index, modifier_id=None):
        # TODO refactor obj_type checks, code duplication
        self.filled_cells.add(index)
        if obj_type == "w":
            stats = WEAPONS[item_id]
            path, name, description, damage, speed, attack_range, weight, value, rarity = stats
            if path not in self.seen_images:
                image = self.img_loader.load_image(path)
            else:
                image = self.seen_images[path]
            self.f_inv[index] = Weapon(image, name, description, damage, speed,
                                       attack_range, weight, value, rarity,
                                       modifier_id)

        elif obj_type == "i":
            stats = ITEMS[item_id]

            path, name, description, duration, health, max_health, damage, speed, weight, value, rarity = stats
            if path not in self.seen_images:
                image = self.img_loader.load_image(path)
            else:
                image = self.seen_images[path]  # TODO
            self.f_inv[index] = Item(image, name, description, duration,
                                     health, max_health, damage, speed, weight,
                                     value, rarity)
示例#18
0
文件: Game.py 项目: Ockerse/CIS343
 def __init__(self):
     self.player = Player()
     self.neighborhood = Neighborhood()
     self.home = Home()
     self.weapon = Weapon()
     self.totalMonsters = 0
     self.isPlaying = True
示例#19
0
def main():
    hero_name = input("Enter hero's name: ")
    hero_title = input("Enter hero's title: ")
    hero = Hero(hero_name, hero_title, 150, 150, 5)
    hero.equip(Weapon("Sword", 30))
    hero.learn(Spell("KillALL", 35, 30, 3))
    dungeon = Dungeon("map.txt", "basic_loot_list_example.json")
    dungeon.spawn(hero)


    dict_commands = {"mu": "up", "md": "down", "ml": "left", "mr": "right", "au": "up", "ad": "down", "al": "left", "ar": "right", "h": "help"}
    dict_commands_move = {"mu": "up", "md": "down", "ml": "left", "mr": "right"}
    dict_commands_attack = {"au": "up", "ad": "down", "al": "left", "ar": "right"}

    index_of_hero = [1, 1]

    print_commands()

    while not dungeon.end_of_game:
        dungeon.print_map()
        print()
        player_input = ""
        while player_input not in dict_commands.keys():

            player_input = str(input(">>> "))
        if player_input == "h":
            print_commands()
        if player_input in dict_commands_move.keys():
            dungeon.move_hero(dict_commands_move[player_input])
        if player_input in dict_commands_attack.keys():
            dungeon.hero_atack(dict_commands_attack[player_input])
        if dungeon.end_of_game:
            break
 def test_has_weapon(self):
     my_weapon = Weapon("axe", 30, 0.5)
     my_entity = Entity("Furious", 100)
     my_entity.equip_weapon(my_weapon)
     self.assertTrue(my_entity.has_weapon())
     my_entity = Entity("Furious", 100)
     self.assertFalse(my_entity.has_weapon())
示例#21
0
 def __init__(self, name, power_level, health):
     self.name = input("What would you like your robot's name to to be?")
     self.power_level = input("What would you like " + self.name +
                              "'s power level to be?")
     self.health = input("What would you like " + self.name +
                         "'s max health to be?")
     self.weapon: Weapon()
示例#22
0
 def setUp(self):
     self.hero = Hero("Gosho", 30, "Goshko")
     self.orc = Orc("Pesho", 100, 1.3)
     self.fight = Fight(self.hero, self.orc)
     self.weapon = Weapon("qax", 40, 0.3)
     self.hero.weapon = self.weapon
     self.orc.weapon = self.weapon
示例#23
0
    def __init__(self,
                 start_pos,
                 img="images/Characters/"
                 "warrior",
                 stats=[3, 1, 1, 35]):
        super().__init__(start_pos, img)
        # CONSTRUCTOR PARAMETERS #
        # stats: a list of initial stats in the order [MELEE, RANGE, MAGIC, MAX_HP]

        self.class_name = "WARRIOR"
        self.rage_timer = 0  # counts upward to self.max_rage_timer
        self.max_rage_time = 5.25
        self.stats["MELEE"] = stats[0]
        self.stats["RANGE"] = stats[1]
        self.stats["MAGIC"] = stats[2]
        self.stats["CUR_HP"] = stats[3]
        self.stats["MAX_HP"] = stats[3]
        self.stats["ABILITY"] = self.max_rage_time
        self.frames["rage"] = pygame.image.load(img + "/rage.png")
        rect = self.frames["rage"].get_rect()
        width = int(rect.w * (self.playerHeight / rect.h))
        height = self.playerHeight
        self.frames["rage"] = pygame.transform.scale(self.frames["rage"],
                                                     (width, height))
        self.frames["rage"] = self.frames["rage"].convert_alpha()

        self.weapons["axe"] = Weapon("images/Weapons/silverhalberd.png",
                                     (40, 40))
        self.cur_weapon = self.weapons["axe"]
        self.cur_weapon.rect = self.rect.copy()
        self.num_ability_uses = 3
        self.rage_active = False
        self.weapon_rotated = self.cur_weapon.image
示例#24
0
def test_hero_weapon_attack_mean_value():
    kkrunch = Hero("Kaptain Krunch")
    strength = random.randint(10, 30000)
    min_attack = strength // 2
    big_strength = Weapon("Sword of Whimsy", strength)
    kkrunch.add_ability(big_strength)
    calculated_mean = (strength - min_attack) // 2 + min_attack
    accepted_window = 400
    iterations = 6000

    sum_of_sqr = 0
    total_attack = 0

    for _ in range(iterations):
        attack_value = kkrunch.attack()
        assert attack_value >= min_attack and attack_value <= strength
        total_attack += attack_value
        deviation = attack_value - calculated_mean
        sum_of_sqr += deviation * deviation

    actual_mean = total_attack / iterations
    print("Max Allowed Damage: {}".format(strength))
    print("Attacks Tested: {}".format(iterations))
    print("Mean -- calculated: {} | actual: {}".format(calculated_mean,
                                                       actual_mean))
    print("Acceptable Min: {} | Acceptable Max: {}".format(
        actual_mean - accepted_window, actual_mean + accepted_window))
    print("Tested Result: {}".format(actual_mean))
    assert actual_mean <= calculated_mean + accepted_window
    assert actual_mean >= calculated_mean - accepted_window
示例#25
0
    def __init__(self,
                 start_pos,
                 img="images/Characters/wizard",
                 stats=[1, 1, 3, 17]):
        super().__init__(start_pos, img)

        self.class_name = "WIZARD"
        self.TimeStop_timer = 5.25
        self.stats["MELEE"] = stats[0]
        self.stats["RANGE"] = stats[1]
        self.stats["MAGIC"] = stats[2]
        self.stats["CUR_HP"] = stats[3]
        self.stats["MAX_HP"] = stats[3]
        self.stats["ABILITY"] = self.TimeStop_timer
        self.weapons["staff"] = Weapon("images/Weapons/earthstaff.png",
                                       (40, 40))
        self.cur_weapon = self.weapons["staff"]
        self.cur_weapon.rect = self.rect.copy()
        self.num_ability_uses = 1
        self.DelayTimer = 60
        self.useAbility = False
        self.weapon_rotated = self.cur_weapon.image
        self.base_attack_cooldown = 0.5
        self.last_base_attack = 0
        self.weapon_rotated = self.cur_weapon.image
示例#26
0
    def mainPane(self):
        locations = ["Tavern", "Shop", "Forest", "Inn", "Castle"]
        character_approval = False
        while character_approval != True:
            hero = Hero(Weapon().generate_weapon())
            print("Your character is " + hero.char.name +
                  "\nEquipped with a " + hero.get_weapon().name +
                  " that does " + str(hero.get_weapon().low_damage) + "-" +
                  str(hero.get_weapon().high_damage) + " damage.")
            char_generation = input("Do you approve of this character: ")
            if "Y" in char_generation.upper():
                character_approval = True

        while True:
            print("\nLocations: ")
            counter = 1
            for i in locations:
                print(str(counter) + ". " + i)
                counter += 1
            location_choice = input("Where would you like to go: ")
            if int(location_choice) is 1:
                Tavern(hero)
            if int(location_choice) is 2:
                Shop(hero)
            if int(location_choice) is 3:
                forest = Forest()
                forest.entry(hero)
            if int(location_choice) is 4:
                hotel = Inn(hero)
            if int(location_choice) is 5:
                Castle(hero)
            input()
示例#27
0
 def startGame(self, type):
     self.objectHandler.clearObjects()
     self.objectHandler.addObject(
         Player('00', int(self.window.width / 2),
                int(self.window.height / 2), 60, 80, type))
     self.objectHandler.addObject(
         Weapon('01', self.objectHandler.getObjectByID('00')))
     self.objectHandler.addObject(
         UIBar('03', self.objectHandler.getObjectByID('00'), UI.HEALTH, 50,
               self.window.height - 50, self.window.width / 6,
               self.window.height / 25))
     if self.objectHandler.getObjectByID('00').type == PlayerType.WIZARD:
         self.objectHandler.addObject(
             UIBar('04', self.objectHandler.getObjectByID('00'), UI.MAGIC,
                   (self.window.width / 2) - ((self.window.width / 6) / 2),
                   self.window.height - 50, self.window.width / 6,
                   self.window.height / 25))
     elif self.objectHandler.getObjectByID('00').type == PlayerType.ROGUE:
         self.objectHandler.addObject(
             UIBar('04', self.objectHandler.getObjectByID('00'), UI.MAGIC,
                   (self.window.width / 2) - ((self.window.width / 6) / 2),
                   self.window.height - 50, self.window.width / 6,
                   self.window.height / 25))
         self.objectHandler.addObject(
             UIBar('05', self.objectHandler.getObjectByID('00'), UI.STAMINA,
                   (self.window.width - (self.window.width / 6) - 50),
                   self.window.height - 50, self.window.width / 6,
                   self.window.height / 25))
     self.state = GameState.GAME
示例#28
0
 def test_damage_setter(self):
     weapon = Weapon("Оружие", 50)
     self.assertEqual(weapon.damage, 50)
     weapon.damage = -20
     self.assertEqual(weapon.damage, 50)
     weapon.damage = 30
     self.assertEqual(weapon.damage, 30)
    def update(self):
       if not obj_user_car.Collisonwall():
            if self.keyboard.up:
                #self.user_car.vel.add(Vector((0.05, -0.05)))
                self.user_car.rotator(False)
                #self.user_car.rotating = True

            elif self.keyboard.down:
                #self.user_car.vel.add(Vector((0.05, 0.05)))
                self.user_car.rotator(True)
                #self.user_car.rotating = True

            elif  self.keyboard.left:
                self.user_car.vel.add(Vector((-0.05, 0)))
            elif self.keyboard.right:#if the right is pressed then add the nitro animation
                if self.user_car.vel.length() > 10:
                    pass
                else:
                    self.user_car.vel.add(Vector((0.05, 0)))
            elif self.keyboard.space:

                url = 'https://i.imgur.com/RVi7F76.png'
                missile = Weapon(Vector((obj_user_car.pos.x + car_width, obj_user_car.pos.y)), Vector(((random.randrange(2,5)),0)), url, 4, 4)
                weapCollision.addWeapon(missile)
                obj_Int.missileCollision(missile)

                #obj_missile = Weapon(Vector((obj_user_car.pos.x + IMG_usr_DIMS[0], obj_user_car.pos.y)),Vector((random.randrange(1, 5), 0)), missile_url, 4, 4)
                #weapCollision.addWeapon(obj_missile)
            else:
                #self.user_car.vel=Vector((1,0))#if nothing is done then keep moving forward
                pass
示例#30
0
def test_hero_weapon_ability_attack():
    quickness = Ability("Quickness", 1300)
    sword_of_truth = Weapon("Sword of Truth", 700)
    Athena = Hero("Athena")
    Athena.add_ability(quickness)
    Athena.add_ability(sword_of_truth)
    assert len(Athena.abilities) == 2
    attack_avg(Athena, 0, 2000)