class FightTest(unittest.TestCase):

    def setUp(self):
        self.bron_hero = Hero("Bron", 100, "DragonSlayer")
        self.torug_orc = Orc("Torug", 100, 1.2)
        self.new_fight = Fight(self.bron_hero, self.torug_orc)
        self.axe = Weapon("Axe", 20, 0.2)
        self.sword = Weapon("Sword", 12, 0.7)
        self.bron_hero.equip_weapon(self.sword)
        self.torug_orc.equip_weapon(self.axe)

    def test_init(self):
        self.assertEqual(self.new_fight.orc, self.torug_orc)
        self.assertEqual(self.new_fight.hero, self.bron_hero)

    def test_who_is_first(self):
        first_entity = self.new_fight.who_is_first()
        self.assertIn(first_entity, [self.bron_hero, self.torug_orc])

    def test_fight(self):
        self.new_fight.simulate_battle()
        self.assertFalse(self.torug_orc.is_alive() and self.bron_hero.is_alive())

    def test_fight_with_no_weapons(self):
        self.torug_orc.weapon = None
        self.new_fight.simulate_battle()
        self.assertFalse(self.torug_orc.is_alive())
Example #2
0
class Player:
    def __init__(self, name, race):
        self.race = race
        self.town = Town(race)
        self.gold = 1000
        self.hero = None
        self.name = name

    def hire_hero(self, name):
        self.hero = Hero(name)

    def upgrade_building(self, building):
        """ Accepts the building you want to upgrade """
        if building.price > self.gold:
            raise NoGold

        if not building.upgrade_available():
            raise BuildingAtMaxLevel

        self.gold -= building.price
        building.upgrade()

    def move_army_from_town_to_hero(self, unit_type, unit_count):
        if self.hero.is_in_town == False:
            raise HeroNotInTown

        if self.hero == None:
            raise NoHero

        if self.town.army[unit_type] < unit_count:
            raise NoUnits

        self.town.decrease_army(unit_type, unit_count)
        self.hero.increase_army(unit_type, unit_count)

    def move_army_from_hero_to_town(self, unit_type, unit_count):
        if self.hero == None:
            raise NoHero

        if self.hero.is_in_town == False:
            raise HeroNotInTown

        if self.hero.army[unit_type] < unit_count:
            raise NoUnits

        self.hero.decrease_army(unit_type, unit_count)
        self.town.increase_army(unit_type, unit_count)

    def train_army(self, unit_type, unit_count):
        if self.town.castle.units_available_to_train < unit_count:
            raise NoDailyUnits

        if ALL_RACE_UNITS[self.race][self.town.barracs.\
        army[unit_type]].price * unit_count > self.gold:
            raise NoGold

        self.town.army[unit_type] += unit_count

        self.gold -= ALL_RACE_UNITS[self.race][self.town.\
            barracs.army[unit_type]].price * unit_count
Example #3
0
class TestFight(unittest.TestCase):

    def setUp(self):
        self.my_hero = Hero("Hero",  100, "Hero")
        self.my_orc = Orc("Orc", 100, 1.5)
        self.the_fight = Fight(self.my_hero, self.my_orc)

    def test_init(self):
        self.assertEqual(self.my_hero.name, "Hero")
        self.assertEqual(self.my_hero.health, 100)
        self.assertEqual(self.my_hero.nickname, "Hero")
        self.assertEqual(self.my_orc.name, "Orc")
        self.assertEqual(self.my_orc.health, 100)
        self.assertEqual(self.my_orc.berserk_factor, 1.5)

    def test_attacks_first(self):
        my_arr = []
        for i in range(0, 100):
            if self.the_fight.attacks_first() == True:
                my_arr.append(1)
            my_arr.append(0)
        self.assertIn(1, my_arr)
        self.assertIn(0, my_arr)

    def test_simulate_fight(self):
        proba1 = Weapon("axe", 1, 0.1)
        proba2 = Weapon("sword", 40, 0.9)
        self.my_hero.equip_weapon(proba1)
        self.my_orc.equip_weapon(proba2)
        the_fight = Fight(self.my_hero, self.my_orc)
        self.assertFalse(the_fight.simulate_fight())
Example #4
0
 def test_simulate_fight_hero_win(self):
     orc_l = Orc("Loser", 300, 2)
     hero_w = Hero("Winner", 300, "TheWinner")
     wep = Weapon("Ubiec", 15, 0.5)
     hero_w.equip_weapon(wep)
     hero_fight = Fight(hero_w, orc_l)
     self.assertEqual(hero_fight.simulate_fight(), hero_fight._HERO_WINNER)
Example #5
0
 def setUp(self):
     weapon = Weapon('Dagger', 10, 0.0)
     hero = Hero('Asd', 100, 'Hero')
     hero.equip_weapon(weapon)
     orc = Orc('Dsa', 1, 1.4)
     orc.equip_weapon(weapon)
     self.fight = fight.Fight(hero, orc)
Example #6
0
class TestHero(unittest.TestCase):
    def test_hero_known_as_not_Jenkins(self):
        self.bron_hero = Hero("Bron", 100, "Dragon Slayer")
        self.assertEqual(self.bron_hero.known_as(), "Bron the Dragon Slayer")

    def test_hero_known_as_Jenkins(self):
        self.leeroy = Hero("Leeroy", 100, "Jenkins")
        self.assertEqual(self.leeroy.known_as(), "Leeroy Jenkins")
Example #7
0
 def test_fight1(self):
     new_hero = Hero("Jack", 100, "Ripper")
     new_orc = Orc("Gruumsh", 40, 1.2)
     hero_weapon = Weapon("The Sting", 8, 0.33)
     orc_weapon = Weapon("The Pacifier", 12, 1)
     new_hero.equip_weapon(hero_weapon)
     new_orc.equip_weapon(orc_weapon)
     Fight(new_hero, new_orc)
Example #8
0
 def test_fight_with_one_weapon(self):
     hero = Hero("Bron", 15, "DragonSlayer")
     evil_orc = Orc('karakondjul', 10 , 1.5)
     weapon1 = Weapon("Axe", 5, 0.5)
     hero.equip_weapon(weapon1)
     fight = Fighting(hero,evil_orc)
     winner = fight.simulate_fight()
     self.assertTrue(isinstance(winner,Hero) or isinstance(winner,Orc))
Example #9
0
   def __init__(self):
      #super is a builtin python function that represents the parent class of
      #this object (parent class = Creature here). This makes a monster inside  
      #the parent class of creature, with all the properties of creature. 

      Monster.__init__(self)
      Hero.__init__(self)
      
      self.weapon2 = None
Example #10
0
 def test_fight_equal(self):
     hero_one = Hero("Bron", 100, "DragonSlayer")
     orc_one = Orc("Orcy", 150, 1.5)
     hero_one.weapon = Weapon("Axe", 20, 0.5)
     orc_one.weapon = Weapon("Axe", 20, 0.5)
     self.fight_one.simulate_battle()
     # both has the same weapon, but the orc has berserc_factor,\
     # he should be alive at the end
     self.assertTrue(self.orc_one.is_alive())
Example #11
0
    def test_print_map_after_battle(self):
        hero = Hero("Alan", 1, "Turing")
        hero.weapon = Weapon("Stick", 1, 0.1)
        self.dungeon.map = "ZSNZ"
        self.dungeon.spawn("1", hero)
        self.dungeon.spawn_npcs()

        self.dungeon.move_player("1", "right")
        self.assertEqual(self.dungeon.map, "Z.OZ")
class TestDungeon(unittest.TestCase):

    def setUp(self):

        self.without_weapon = Weapon("With bare hands", 0, 0)
        self.thanes_hummer = Weapon("Thanes hummer", 15, 0.4)
        self.yurnero_blade = Weapon("Yurneros blade", 10, 0.35)
        self.the_hero = Hero("Thanes", 150, 150, "Mountain King")
        self.the_orc = Orc("Yurnero the Blademaster", 150, 150, 1.3)
        self.the_chen = Orc("Chen", 150, 150, 1.3)
        self.small_potion = Potion("Small potion", 15)
        self.midium_potion = Potion("Midium potion", 25)
        self.the_hero.equip_weapon(self.thanes_hummer)
        self.the_orc.equip_weapon(self.yurnero_blade)
        self.map = Dungeon("map.txt")
        self.map.read_map()
        self.map.dict_of_items[self.yurnero_blade] = []
        self.map.dict_of_items[self.thanes_hummer] = []
        self.map.dict_of_items[self.small_potion] = []
        self.map.dict_of_items[self.midium_potion] = []
        self.map.dict_of_herous[self.the_orc] = []
        self.map.dict_of_herous[self.the_hero] = []
        self.map.spawn_player("shosho", self.the_hero)
        #self.map.spawn_player("kosho", self.the_orc)
        #self.map.dict_champion_name[self.the_hero] = "shosho"
        self.map.dict_champion_name[self.the_orc] = "kosho"



    #def test_validate_player(self):
    #    self.assertEqual(self.the_hero, self.map.validate_player_name("hero"))
    def test_spawn_player(self):
        #self.assertFalse(self.map.spawn_player("shosho", self.the_hero))
        self.assertTrue(self.map.spawn_player("kosho", self.the_orc))
        self.assertFalse(self.map.spawn_player("kosho", self.the_chen))

    def test_can_move(self):
        #print("{}\n{}".format(self.map.number_of_rows, self.map.number_of_chars))
        #print((self.map.number_of_rows))
        self.current_user = self.the_orc
        self.map.print_map()

        self.assertFalse(self.map.can_move_up(-1, 0))
        self.assertFalse(self.map.can_move_down(1, 0))
        self.assertTrue(self.map.can_move_right(0, 1))
        self.map.validate_player_name("orc")
        print("{}     {}".format(self.map.current_x, self.map.current_y))
        self.assertFalse(self.map.can_move_up(-1, 0))
        self.assertFalse(self.map.can_move_down(1, 0))
        self.assertTrue(self.map.can_move_right(0, 1))
        self.assertFalse(self.map.can_move_left(0, -1))

    def test_validate_player_name(self):

        self.map.spawn_player("kosho", self.the_orc)
        self.assertEqual(self.map.validate_player_name("kosho"), self.the_orc)
        self.map.print_map()
Example #13
0
class WeaphonTest(unittest.TestCase):

    def setUp(self):
        self.sniper = Weaphon("Gun", 85, 0.10)
        self.hammer = Weaphon("One-Hand", 30, 0)
        self.bron_orc = Orc("Pesho", 100, 1.50)
        self.bron_hero = Hero("Ivan", 100, "Magician")

    def test_weaphon_initialization(self):
        self.assertEquals("Gun", self.sniper.type)
        self.assertEquals(85, self.sniper.damage)
        self.assertEquals(0.10, self.sniper.critical_strike_percent)

    def test_crit_hit_sniper(self):
        temp = False
        for i in range(100):
            if temp:
                break
            else:
                temp = self.sniper.critical_hit()
        self.assertTrue(temp)

    def test_crit_hit_hammer(self):
        temp = False
        for i in range(100):
            if temp:
                break
            else:
                temp = self.hammer.critical_hit()
        self.assertFalse(temp)

    def test_entity_has_weaphon(self):
        self.bron_orc.equip_weapon(self.hammer)
        self.assertTrue(self.bron_orc.has_weaphon())

    def test_entity_do_not_has_wep(self):
        self.assertFalse(self.bron_orc.has_weaphon())

    def test_entity_equip_weaphon_first_time(self):
        self.bron_orc.equip_weapon(self.hammer)
        self.assertEqual("One-Hand", self.bron_orc.weaphon.type)

    def test_equip_weaphon_when_the_entity_allready_has_one(self):
        self.bron_orc.equip_weapon(self.hammer)
        self.bron_orc.equip_weapon(self.sniper)
        self.assertEqual("Gun", self.bron_orc.weaphon.type)

    def test_attack_no_weaphon(self):
        self.assertEqual(0, self.bron_orc.attack())

    def test_atack_hero(self):
        self.bron_hero.equip_weapon(self.hammer)
        self.assertEqual(30, self.bron_hero.attack())

    def test_atack_orc(self):
        self.bron_orc.equip_weapon(self.hammer)
        self.assertEqual(45, self.bron_orc.attack())
Example #14
0
 def test_orc_wins(self):
     hero = Hero("Bron", 50, "DragonSlayer")
     evil_orc = Orc('karakondjul', 100 , 1.5)
     weapon1 = Weapon("Axe", 1, 0.5)
     weapon2 = Weapon("Sword", 34, 0.5)
     hero.equip_weapon(weapon1)
     evil_orc.equip_weapon(weapon2)
     fight = Fighting(hero,evil_orc)
     winner = fight.simulate_fight()
     self.assertTrue(isinstance(winner,Orc))
 def test_fight(self):
     my_Hero = Hero("Ivan", 100, "bad ass")
     my_Orc = Orc("Boko", 100, 1.5)
     my_weapon1 = Weapon("Axe1", 31, 0.2)
     my_weapon2 = Weapon("Axe2", 31, 0.2)
     my_Hero.equip_weapon(my_weapon1)
     my_Orc.equip_weapon(my_weapon2)
     fight1 = Fight(my_Hero, my_Orc)
     fight1.simulate_fight()
     self.assertFalse(my_Orc.is_alive() and my_Hero.is_alive())
Example #16
0
 def test_move_and_fight(self):
     boromir = Hero("Boromir", 100, "OneDoesNotSimply")
     gollum = Orc("Gollum", 100, 1.5)
     axe = Weapon("Mighty Axe", 25, 0.2)
     sword = Weapon("Sword", 25, 0.2)
     boromir.equip_weapon(sword)
     gollum.equip_weapon(axe)
     self.dungeon.spawn("player_1", boromir)
     self.dungeon.spawn("player_2", gollum)
     self.dungeon.spawned["player_2"][1] = 12
     self.dungeon.move("player_1", "right")
     been_fight = self.dungeon.spawned["player_1"][0].is_alive() and self.dungeon.spawned["player_2"][0].is_alive()
     self.assertFalse(been_fight)
Example #17
0
class TestFight(unittest.TestCase):

    def setUp(self):
        self.orc = Orc("Berserk", 1000, 2)
        self.hero = Hero("Bron", 1000, "DragonSlayer")
        self.weapon = Weapon("Mighty Axe", 25, 0.3)
        self.orc.equip_weapon(self.weapon)
        self.hero.equip_weapon(self.weapon)
        self.fight = Fight(self.hero, self.orc)

    def test_simulate_fight(self):
        self.fight.simulate_fight()
        self.assertTrue(not self.orc.is_alive() or not self.hero.is_alive())
Example #18
0
class TestFight(unittest.TestCase):
    def setUp(self):
        self.varyan = Hero("Varyan Wrynn", 100, "King")
        self.garrosh = Orc("Garrosh Hellscream", 100, 7)

        self.weak_weapon = Weapon("Noob Weapon", 10, 0.1)
        self.strong_weapon = Weapon("Woo Weapon", 20, 0.7)

        self.fight = Fight(self.varyan, self.garrosh)

    def test_simulate_fight_win(self):
        self.varyan.equip_weapon(self.strong_weapon)
        self.garrosh.equip_weapon(self.weak_weapon)
        self.assertIsNotNone(self.fight.simulate_fight())
 def compleate_fight(self, player_name, enemy_pos):
     enemy_name = self.get_entity_name(enemy_pos)
     #get player from dict
     player_one = Hero("Bron", 10, "DragonSlayer")
     player_two = Orc("Bron", 10, 1.3)
     for keys in self.heroes_dict:
         if self.heroes_dict[keys] == "%s" % (enemy_name) or self.heroes_dict[keys] == "%s" % (player_name):
             if self.heroes_dict[keys] == "%s" % (player_name):
                 player_one = keys
             if self.heroes_dict[keys] == "%s" % (enemy_name):
                 player_two = keys
     fight = Fight(player_one, player_two)
     fight.simulate_fight()
     return player_one.is_alive()
 def execute_necessary_inits(self):
     thanes_hummer = Weapon("Thanes hummer", 15, 0.4)
     yurnero_blade = Weapon("Yurneros blade", 10, 0.35)
     the_hero = Hero("Thanes", 150, 150, "Mountain King")
     the_orc = Orc("Yurnero the Blademaster", 150, 150, 1.3)
     small_potion = Potion("Small potion", 15)
     midium_potion = Potion("Midium potion", 25)
     the_hero.equip_weapon(thanes_hummer)
     the_orc.equip_weapon(yurnero_blade)
     self.dungeon.dict_of_items[yurnero_blade] = []
     self.dungeon.dict_of_items[thanes_hummer] = []
     self.dungeon.dict_of_items[small_potion] = []
     self.dungeon.dict_of_items[midium_potion] = []
     self.dungeon.dict_of_herous[the_orc] = []
     self.dungeon.dict_of_herous[the_hero] = []
Example #21
0
def main():
    h = Hero("Bron", "Dragonslayer", 100, 100, 2)
    w = Weapon("The Axe of Destiny", 20)
    h.equip(w)
    s = Spell("Fireball", 20, 50, 2)
    h.learn(s) 
    dmap = Dungeon("map.txt")
    dmap.open_map()
    dmap.spawn(h)
    dmap.move_hero("right")
    dmap.move_hero("down")
    dmap.move_hero("down")
    dmap.get_map()
    dmap.hero_attack(by="spell")
    dmap.get_map()
Example #22
0
	def createHero(self):
		name = raw_input("Whats your heros name? ")
		print "***********************"
		print "What kind of hero do you want to be?"
		print "1. Knight 2.Wizard 3.Paladin"
		while True:
			heroKind = raw_input("Choose the number of the kind of hero you want to be: ")
			if heroKind == "1":
				heroClass = "Knight"
				hp = random.randint(100,120)
				mana = random.randint(20,40)
				break
			elif heroKind == "2":
				heroClass = "Wizard"
				hp = random.randint(60,80)
				mana = random.randint(100,120)
				break
			elif heroKind == "3":
				heroClass = "Paladin"
				hp = random.randint(80,100)
				mana = random.randint(40,60)
				break
			else:
				print "It needs to be a number between 1-3!"
				print "1. Knight 2.Wizard 3.Paladin"
		self.player = Hero(heroClass, name, hp, mana)
Example #23
0
	def __init__( self ):

		self.core = Core( 60, 1024, 768, "Ninja" )

		self.intro = Intro()

		self.menu_background = Texture( "menu/background.png" )
		self.menu_title = Menu_title()
		self.menu_play_button = Menu_play_button()
		self.menu_git_button = Menu_link_button( "menu/git.png", "https://github.com/Adriqun" )
		self.menu_google_button = Menu_link_button( "menu/google.png", "https://en.wikipedia.org/wiki/Ninja" )
		self.menu_facebook_button = Menu_link_button( "menu/facebook.png", "nothing", True )
		self.menu_twitter_button = Menu_link_button( "menu/twitter.png", "nothing", True )
		self.menu_music_button = Menu_music_button( "menu/music.png" )
		self.menu_chunk_button = Menu_music_button( "menu/chunk.png", 1 )
		self.menu_exit_log = Menu_exit_log()
		self.menu_author_log = Menu_author_log()
		self.menu_game_log = Menu_link_button( "menu/game.png", "nothing", True )
		self.menu_settings_log = Menu_link_button( "menu/settings.png", "nothing", True )
		self.menu_score_log = Menu_score_log()
		self.menu_music = Menu_music( "menu/Rayman Legends OST - Moving Ground.mp3" )
		
		self.wall = Wall()
		self.hero = Hero()
		self.menu_log = Menu_log()
		self.map = Map()
Example #24
0
 def dataReceived(self, data):
     if not '\n' in data:
         self.buf += data
         return
     full = (self.buf + data).split("\n")
     self.buf = full[-1]
     for line in full[:-1]:
         json_data = json.loads(line)
         if json_data["message_type"] == "hello":
             global game_map
             print "Hello message"
             units = [Unit.from_dict(u) for u in json_data["units"]]
             bullets = [Bullet.from_dict(b) for b in json_data["bullets"]]
             hero = Hero.from_dict(json_data["hero"])
             commander = Commander.from_dict(json_data["commander"])
             game_map = GameMap(json_data["rows"], json_data["cols"],
                                json_data["map"], hero, commander, units, bullets)
         elif json_data["message_type"] == "update":
             # Drop any removed units/bullets, then update values for remaining
             if len(game_map.units) > len(json_data["units"]):
                 game_map.units = game_map.units[:len(json_data["units"])]
             for i in xrange(len(json_data["units"]) - len(game_map.units)):
                 game_map.units.append(Unit(1, 1999, 1999, 0, 0))
             for u_old, u_new in zip(game_map.units, json_data["units"]):
                 u_old.update_from_dict(u_new)
             if len(game_map.bullets) > len(json_data["bullets"]):
                 game_map.bullets = game_map.bullets[:len(json_data["bullets"])]
             for i in xrange(len(json_data["bullets"]) - len(game_map.bullets)):
                 game_map.bullets.append(Bullet(0, 999, 999, 0, 0))
             for b_old, b_new in zip(game_map.bullets, json_data["bullets"]):
                 b_old.update_from_dict(b_new)
             game_map.hero.update_from_dict(json_data["hero"])
             game_map.commander.update_from_dict(json_data["commander"])
Example #25
0
class FightTest(unittest.TestCase):

    def setUp(self):
        self.hero_one = Hero("Bron", 100, "DragonSlayer")
        self.orc_one = Orc("Orcy", 150, 1.5)
        self.fight_one = fight.Fight(self.hero_one, self.orc_one)
        self.axe = Weapon("Axe", 20, 0.2)
        self.sword = Weapon("Sword", 12, 0.7)
        self.hero_one.weapon = self.sword
        self.orc_one.weapon = self.axe

    def test_init(self):
        self.assertEqual(self.fight_one.hero, self.hero_one)
        self.assertEqual(self.fight_one.orc, self.orc_one)

    def test_fight(self):
        self.fight_one.simulate_battle()
        # if one of them died
        self.assertFalse(self.orc_one.is_alive() and self.hero_one.is_alive())

    def test_fight_no_weapon(self):
        self.orc_one.weapon = None
        self.fight_one.simulate_battle()
        # orc has no weapon => orc dies
        self.assertFalse(self.orc_one.is_alive())

    def test_fight_equal(self):
        hero_one = Hero("Bron", 100, "DragonSlayer")
        orc_one = Orc("Orcy", 150, 1.5)
        hero_one.weapon = Weapon("Axe", 20, 0.5)
        orc_one.weapon = Weapon("Axe", 20, 0.5)
        self.fight_one.simulate_battle()
        # both has the same weapon, but the orc has berserc_factor,\
        # he should be alive at the end
        self.assertTrue(self.orc_one.is_alive())
 def setUp(self):
     self.hero = Hero("Bron", 100, "DragonSlayer")
     self.orc = Ork("BronOrk", 100, 1.1)
     self.axe = Weapon("Axe", 12.45, 0.2)
     self.sword = Weapon("Sword of Arthur", 13, 0.5)
     self.battle = Fight(self.hero, self.orc)
     self.dungeon = Dungeon("dungeon.txt")
 def __init__(self):
     
     self.player_score = 0
     self.game_status = True
     
     self.block_list = pygame.sprite.Group()
     self.sprites_list = pygame.sprite.Group()
     
     self.hero = Hero()
     
     
     
     #receive list of blocks per level
     self.level_list = []
     self.level_list.append(level.Level01(self.hero))
     self.level_list.append(level.Level02(self.hero))
     
     self.current_level = 0
     self.current_level = self.level_list[self.current_level]
     
     self.hero.level = self.current_level 
     
     self.hero.x = 340
     self.hero.y = 200 #constants.SCREEN_HEIGHT - self.hero.height
     
     self.sprites_list.add(self.hero)
class HeroTest(unittest.TestCase):

    def setUp(self):
        self.shosh_hero = Hero('Shosh', 100, 'GraveRobber')

    def test_hero_known_as(self):
        self.assertEqual(self.shosh_hero.known_as(), 'Shosh the GraveRobber')
class TestFight(unittest.TestCase):

    def setUp(self):
        self.hero = Hero("Aiden", 500, "Daro Wonderer")
        self.orc = Orc("Thrall", 400, 1.4)
        weapon1 = Weapon("The Ash Bringer", 80, 0.5)
        weapon2 = Weapon('DoomHammer', 80, 0.5)
        self.hero.equip_weapon(weapon1)
        self.orc.equip_weapon(weapon2)

        self.fight = Fight(self.hero, self.orc)

    def test_simulate_fight(self):
        self.fight.simulate_fight()
        self.assertTrue(self.hero.is_alive() or self.orc.is_alive())
        self.assertFalse(self.orc.is_alive() and self.hero.is_alive())
Example #30
0
    def __init__(self, code):
        self.lines = code.splitlines()
        self.line_num = 0

        # Get name from first line (optional)
        try:
            name_line = re.match("Name\s?:\s?(.+)", self.lines[0], re.I)
            name = name_line.groups(0)[0]
            self.lines = self.lines[1:]

        except IndexError:
            name = "Hero"

        # Get class
        try:
            class_line = re.match("Class\s?:\s?(.+)", self.lines[0], re.I)
            hero_class = class_line.groups(0)[0].title()
            self.lines = self.lines[1:]

        except IndexError:
            exit("Error: Missing or invalid class line")

        self.hero = Hero(name, hero_class)
        self.labels = {}

        self.quest = None

        self.input = None
        self.expected = None
        self.output = None
        self.quest_line_num = None

        self.getch = _Getch()
Example #31
0
 def create_hero(self):
     '''Prompt user for Hero information
       return Hero with values from user input.
     '''
     hero_name = input("Hero's name: ")
     hero = Hero(hero_name)
     add_item = None
     while add_item != "4":
        add_item = input("[1] Add ability\n[2] Add weapon\n[3] Add armor\n[4] Done adding items\n\nYour choice: ")
        if add_item == "1":
            ability = self.create_ability()
            hero.add_ability(ability)
        elif add_item == "2":
            weapon = self.create_weapon()
            hero.add_weapon(weapon)
        elif add_item == "3":
            armor = self.create_armor()
            hero.add_armor(armor)
     return hero
def test_hero_add_multi_ability():
    big_strength = Ability("Overwhelming Strength", 300)
    speed = Ability("Lightning Speed", 500)
    Athena = Hero("Athena")
    assert len(Athena.abilities) == 0
    Athena.add_ability(big_strength)
    assert len(Athena.abilities) == 1
    Athena.add_ability(speed)
    assert len(Athena.abilities) == 2
    # Check for correct type
    assert "Ability" in str(Athena.abilities[0])
    assert Athena.abilities[0].name == "Overwhelming Strength"
Example #33
0
def create_hero(max_strength=100, weapons=False, armors=False, health=False):

    heroes = [
        "Athena",
        "Jodie Foster",
        "Christina Aguilera",
        "Gamora",
        "Supergirl",
        "Wonder Woman",
        "Batgirl",
        "Carmen Sandiego",
        "Okoye",
        "America Chavez",
        "Cat Woman",
        "White Canary",
        "Nakia",
        "Mera",
        "Iris West",
        "Quake",
        "Wasp",
        "Storm",
        "Black Widow",
        "San Luis Obispo",
        "Ted Kennedy",
        "San Francisco",
        "Bananas"]
    name = heroes[random.randint(0, len(heroes) - 1)]
    if health:
        power = health
    else:
        power = random.randint(3, 700000)
    hero = Hero(name, power)
    if weapons and armors:
        for weapon in weapons:
            hero.add_ability(weapon)
        for armor in armors:
            hero.add_armor(armor)
    if armors and not weapons:
        for armor in armors:
            hero.add_armor(armor)

    return hero
Example #34
0
def main():
    hero = Hero(10, 5)
    goblin = Goblin(6, 2)
    # hero_health = 10
    # hero_power = 5
    # goblin_health = 6
    # goblin_power = 2

    while goblin.alive() and hero.alive():
        #print("You have %d health and %d power." % (hero.health, hero.power))
        hero.print_status()
        #print("The goblin has %d health and %d power." % (goblin.health, goblin.power))
        goblin.print_status()
        print()
        print("What do you want to do?")
        print("1. fight goblin")
        print("2. do nothing")
        print("3. flee")
        print("> ", )
        user_input = input()
        if user_input == "1":
            # Hero attacks goblin
            # goblin_health -= hero_power
            # print("You do %d damage to the goblin." % hero_power)
            hero.attack(goblin)
            if not goblin.alive():
                print("The goblin is dead.")
        elif user_input == "2":
            pass
        elif user_input == "3":
            print("Goodbye.")
            break
        else:
            print("Invalid input %r" % user_input)

        if goblin.alive():
            # Goblin attacks hero
            # hero_health -= goblin_power
            # print("The goblin does %d damage to you." % goblin_power)
            goblin.attack(hero)
            if not hero.alive():
                print("You are dead.")
    def test_move_hero_with_right_should_move_the_hero(self):
        h = Hero(name="Bron", title="Dragonslayer",
                 health=100, mana=100, mana_regeneration_rate=2)
        a = Dungeon.from_string('''S.##.....T
..##..###.
#.###E###E
#.E...###.
###T#####G''')
        expected = ('''.H##.....T
..##..###.
#.###E###E
#.E...###.
###T#####G''')
        a.spawn(h)

        a.move_hero('right')

        self.assertEqual(expected, a.map)
    def test_to_list(self):
        h = Hero(name="Bron", title="Dragonslayer",
                 health=100, mana=100, mana_regeneration_rate=2)
        a = Dungeon.from_string('''S.##.....T
#T##..###.
#.###E###E
#.E...###.
###T#####G''')
        a.spawn(h)
        expected = ([['H', '.', '#', '#', '.', '.', '.', '.', '.', 'T'],
                    ['#', 'T', '#', '#', '.', '.', '#', '#', '#', '.'],
                    ['#', '.', '#', '#', '#', 'E', '#', '#', '#', 'E'],
                    ['#', '.', 'E', '.', '.', '.', '#', '#', '#', '.'],
                    ['#', '#', '#', 'T', '#', '#', '#', '#', '#', 'G']])

        a.get_current_position()

        self.assertEqual(expected, a.list_map)
Example #37
0
    def create_layer(self):

        layer = Square((255, 255, 255, 1), 0, 0, 640)
        hero = Hero()
        print(hero.sprite)
        if hero.sprite is not None:
            hero.change_to("R")
        else:
            hero.change_to("A")
        layer.add(hero.sprite)
        ctrl = WarCtrl(hero)
        self.add(layer)
        self.add(ctrl)
Example #38
0
 def test_mana_after_consuming_mana_potion(self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     s1 = Spell("invisibility", 20, 50, 2)
     h.learn(s1)
     h.attack()
     mp = ManaPotion("Natural mana potion", 20)
     mp.consume(h)
     expected_result = 70
     self.assertEqual(h.mana, expected_result)
    def test_with_weapon_and_spell_should_attack_by_higher_damage(self):
        h = Hero(name="Bron",
                 title="Dragonslayer",
                 health=100,
                 mana=100,
                 mana_regeneration_rate=2)
        h.learn(Spell(name="Fireball", damage=20, mana_cost=50, cast_range=2))
        h.equip(Weapon(name="The Axe of Destiny", damage=30))
        e = Enemy()

        Fight(h, e)

        self.assertEqual(h.attacking, PLAYER_ATTACK_BY_WEAPON_STRING)
Example #40
0
def main():
    player = Hero("austin")
    store = Store()
    battle = Battle()
    playing = True
    win = None
    rounds = 0

    enemies = [Goblin, Zombie, Wizard, Necromancer, Archer, Shadow]
    while playing:
        player.status()
        displayTown()
        choice = int(input("make your selection "))
        if choice == 1:
            enemy = enemies[random.randint(0, 5)]()
            win = battle.do_battle(player, enemy)
            if not win:
                playing = False
        if choice == 2:
            player.collectbounty()
            store.restock()
            if rounds > 10:
                store.restock(2)
            store.go_shopping(player)
        if choice == 3:
            player.useinventory()
        if choice == 4:
            print("Welcome to University!")
            print("select a new class")
            for key in class_map:
                print(f" {key}")
            new_class = input("select a class ")
            player = player.changeClass(new_class)
        if choice == 5:
            playing = False
    print("thanks for fighting")
Example #41
0
 def _init_heroes(self, count: int) -> Group:
     """ Создаёт группу из героев, добавляет на карту, в список спрайтов
     если count=0, спросит количество героев """
     if not count:
         count = 1
     heroes = Group()
     attrs = [
         dict(name="hero1", image="hero1.png", xy=(12, 8), game=self),
         dict(name="hero2", image="hero2.png", xy=(11, 8), game=self),
         dict(name="hero3", image="hero3.png", xy=(11, 9), game=self),
         dict(name="hero4", image="hero4.png", xy=(12, 9), game=self),
     ][:count]
     for attr in attrs:
         hero = Hero(**attr)  # создадим героя
         heroes.add(hero)  # добавим героя в спрайты героев
         self.characters.add(hero)  # добавим героя в спрайты персонажей
         cell = self.map.get_cell(attr["xy"])  # добавим героя на карту
         cell.characters.append(hero)
     return heroes
Example #42
0
    def create_hero(self):
        hero_name = input("Hero's name: ")
        hero = Hero(hero_name)
        add_item = None
        while add_item != "4":
            add_item = input(
                "[1] Add ability\n[2] Add weapon\n[3] Add armor\n[4] Done adding items\n\nYour choice: "
            )
            if add_item == "1":
                ability = self.create_ability()
                hero.add_ability(ability)

            elif add_item == "2":
                weapon = self.create_weapon()
                hero.add_weapon(weapon)

            elif add_item == "3":
                armor = self.create_armor()
                hero.add_armor(armor)

        return hero
Example #43
0
    def __init__(self):
        self.tmx_file = path.join(level_dir)
        self.tile_renderer = tilerenderer.Renderer(self.tmx_file)
        self.map_surface = self.tile_renderer.make_map()
        self.map_rect = self.map_surface.get_rect()

        self.tile_width = 32

        self.tile_number_x = int(self.map_rect.width // self.tile_width)
        self.tile_number_y = int(self.map_rect.height // self.tile_width)

        self.valid_movement_tiles = {}

        self.hero_group = pg.sprite.Group()
        hero = Hero()
        self.hero_group.add(hero)

        self.enemy_group = pg.sprite.Group()
        enemy = Enemy(6 * 32, 6 * 32)
        self.enemy_group.add(enemy)
        enemy = Enemy(96, 96)
        self.enemy_group.add(enemy)

        self.movement_system = MovementSystem()
        self.ui_system = UISystem(self)

        self.selected_hero = None

        self.states = {
            "0": "selection",
            "1": "movement_selection",
            "2": "action",
            "3": "attack_selection",
            "4": "attack"
        }

        self.state = self.states["0"]

        self.take_input = True

        self.attacker = None
        self.defender = None
        self.damage = []
Example #44
0
 def create_hero(self):
     '''Prompt user for Hero information
       return Hero with values from user input.
     '''
     hero_name = input("Hero's name: ")
     hero = Hero(hero_name)
     add_item = None
     while add_item != "4":
         add_item = input(
             "[1] Add ability\n[2] Add weapon\n[3] Add armor\n[4] Done adding items\n\nYour choice: "
         )
         if add_item == "1":
             hero.add_ability(self.create_ability())
             #HINT: First create the ability, then add it to the hero
         elif add_item == "2":
             hero.add_weapon(self.create_weapon())
             #HINT: First create the weapon, then add it to the hero
         elif add_item == "3":
             hero.add_armor(self.create_armor())
             #HINT: First create the armor, then add it to the hero
     return hero
Example #45
0
 def test_mana_after_consuming_mana_potion_with_more_mana_than_max_mana(
         self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     s1 = Spell("invisibility", 20, 20, 2)
     h.learn(s1)
     h.attack()
     mp = ManaPotion("Potion of supreme healing", 50)
     mp.consume(h)
     expected_result = 100
     self.assertEqual(h.mana, expected_result)
    def create_hero(self):
        hero_name = input("Hero's name: ")
        hero = Hero(hero_name)
        add_item = None
        while add_item != "4":
            add_item = input(
                "[1] Add ability\n[2] Add weapon\n[3] Add armor\n[4] Done adding items\n\nYour choice: "
            )
            if add_item == "1":
                # HINT: First create the ability, then add it to the hero
                ability = self.create_ability()
                hero.create_ability()

            elif add_item == "2":
                # HINT: First create the weapon, then add it to the hero
                weapon = self.create_weapon()
                hero.create_weapon()
            elif add_item == "3":
                # HINT: First create the armor, then add it to the hero
                armor = self.create_armor()
                hero.create_armor()
        return hero
Example #47
0
def play_game():
    battle_map = Dungeon(map_file="level1.txt",
                         treasure_file="treasures_file.json",
                         enemy_file="enemies.json")
    hero_name = input('ENTER YOUR BATTLE NAME: ')
    hero_title = input('ENTER YOUR TITLE: ')
    hero = Hero(name=hero_name,
                title=hero_title,
                health=100,
                mana=50,
                mana_regeneration_rate=5)
    name = hero.known_as()
    print(
        'Welcome {} to level1. Wish you luck, you will need it!'.format(name))
    start_weapon = Weapon(name='Pruchka', damage=25)
    start_spell = Spell(name='Vqtur', damage=30, mana_cost=35, cast_range=2)
    hero.equip(start_weapon)
    hero.learn(start_spell)
    battle_map.spawn(hero)
    battle_map.print_map()
    print(colored('TUTORIAL', 'cyan', attrs=['bold']))
    commands()
    print(colored('To see the commands use "help"', 'cyan', attrs=['bold']))
    game_cycle_level(battle_map, hero)

    if hero.is_alive() is False:
        return 0
    start_level2 = input('Do you want to play on level2? [y/n] ').lower()

    if start_level2[0] == 'y':
        battle_map = Dungeon(map_file="level2.txt",
                             treasure_file="treasures_file.json",
                             enemy_file="enemies.json")
        battle_map.spawn(hero)
        battle_map.print_map()
        game_cycle_level(battle_map, hero)
        print('GOOD JOB! YOU BEAT THE WHOLE GAME!')
    else:
        print('Ha,ha,ha. You are a coward')
Example #48
0
def build_hero(num_of_weapons=0, num_of_armor=0, num_of_abilities=0):
    heroes = [
        "Athena",
        "Jodie Foster",
        "Christina Aguilera",
        "Gamora",
        "Supergirl",
        "Wonder Woman",
        "Batgirl",
        "Carmen Sandiego",
        "Okoye",
        "America Chavez",
        "Cat Woman",
        "White Canary",
        "Nakia",
        "Mera",
        "Iris West",
        "Quake",
        "Wasp",
        "Storm",
        "Black Widow",
        "San Luis Obispo",
        "Ted Kennedy",
        "San Francisco",
        "Bananas",
    ]

    weapons = []
    armors = []

    for _ in range(num_of_weapons):
        weapons.append(create_weapon())

    for _ in range(num_of_armor):
        armors.append(create_armor())

    for _ in range(num_of_abilities):
        weapons.append(create_ability())

    name = random.choice(heroes)
    hero = Hero(name)

    for item in weapons:
        hero.add_ability(item)

    for armor in armors:
        hero.add_armor(armor)

    return hero
Example #49
0
  def __renderScreen(self):
    """ 
    Display the Game's Main Menu, until a option is selected 
    This is going to need to change
    the menu needs to be one just for the main screen 
    """
    if self.GameMenu.active == True:
      self.GameMenu.run()
    
    if self.GameMenu.selection == 0:
      if self.RunWorld == False:
        collisionlist = []

        self.mainCharacter = Hero("Hero", collisionlist)
        self.World = WorldScene(self.screen)
        self.World.addCharacter(self.mainCharacter)
        self.World.setHero(self.mainCharacter)
        self.World.setMap("BIG")
        self.RunWorld = True
      else:
        self.World.update()
def run_game():
    pygame.init()
    game_settings = Settings()
    screen = pygame.display.set_mode(game_settings.screen_size)
    pygame.display.set_caption("Ataque Monstruoso")
    hero = Hero(screen)

    pygame.mixer.music.load('sounds/music.wav')
    pygame.mixer.music.play(-1)

    play_button = Play_button(screen, 'Pressiona para começar')

    count = 0
    count_update = "Monatros mortos: %d" % count
    scoreboard = Scoreboard(screen, count_update)

    enemies = Group()
    bullets = Group()
    enemies.add(Enemy(screen, game_settings))

    tick = 0
Example #51
0
def run_game():
    pygame.init()
    # create a settings object
    game_settings = Settings()
    screen = pygame.display.set_mode(game_settings.screen_size)
    pygame.display.set_caption("Zombie Cats IN SPACE")
    background = Background(game_settings)
    # create a hero object from our hero class
    the_hero = Hero(screen)
    # make the main game loop... it will run forever
    # the_enemy = Enemy('images/cat.png', screen, game_settings, 3)
    bullets = Group()
    enemies = Group()
    game_start_time = time.time()
    tick = 0

    while 1:
        tick += 1
        # screen.fill(background)
        game_settings.timer = (time.time() - game_start_time)
        if tick % 100 == 0:
            game_settings.enemy_count += 1
            # print game_settings.enemy_count
            if game_settings.enemy_count == 1:
                game_settings.enemy_count = 0
                enemies.add(
                    Enemy('images/long_cat_left.png', screen, game_settings,
                          3))

        enemy_hit = groupcollide(enemies, bullets, False, True)
        for enemy in enemy_hit:
            # print enemies
            enemy.hit(1)
            if enemy.health <= 0:
                enemies.remove(enemy)
        # if enemy_hit:
        # 	os.system("say --r=400 'meow' &")
        check_events(screen, the_hero, game_settings, bullets, enemies)
        update_screen(screen, the_hero, game_settings, bullets, enemies,
                      background)
Example #52
0
def create_hero():
    print('Now enter name and title for your hero:')
    print('Example: Bron, Dragonslayer\n')
    name = input('Name: ')
    title = input('Title: ')
    new_screen()
    h = Hero(name=name,
             title=title,
             health=100,
             mana=100,
             mana_regeneration_rate=2)
    h.equip(Weapon(name='knife', damage=10))
    print('Information for hero:\n')
    h.print_hero()
    wait_for_continue_command()
    return h
    def create_hero(self):
        """Prompt for Hero information."""

        hero_name = input("Hero name?: ")
        hero = Hero(hero_name)

        equip_menu = None
        while equip_menu != "4":
            equip_menu = input("\n[1] Add ability\n"
                               "[2] Add weapon\n"
                               "[3] Add armor\n"
                               "[4] Done adding equips\n\n"
                               "Your choice: ")
            print()

            if equip_menu == "1":
                hero.add_ability(self.create_ability())
            elif equip_menu == "2":
                hero.add_weapon(self.create_weapon())
            elif equip_menu == "3":
                hero.add_armor(self.create_armor())

        return hero
 def create_hero(self):
     '''input from user and prompt return.
     '''
     hero_name = input("Hero's name: ")
     hero = Hero(hero_name)
     add_item = None
     while add_item != "4":
         add_item = input(
             "[1] Add ability\n[2] Add weapon\n[3] Add armor\n[4] Done adding items\n\nYour choice: "
         )
         if add_item == "1":
             # add an ability to the hero
             self.create_ability()
             hero.add_ability(self.create_ability)
         elif add_item == "2":
             # add a weapon to the hero
             self.create_weapon()
             hero.add_ability(self.create_weapon)
         elif add_item == "3":
             # add an armor to the hero
             self.create_armor()
             hero.add_ability(self.create_armor)
     return hero
Example #55
0
 def test_hero_move_with_aw_and_equiped_weapon_should_return_true(self):
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     w = Weapon('nojka', 25)
     h.equip(w)
     h.x = 2
     h.y = 3
     enemy = Enemy(health=100, mana=40, damage=60)
     enemy.x = 3
     enemy.y = 3
     fight = Fight(enemy)
     status, error = fight.hero_move(h, 'aw')
     self.assertTrue(status)
Example #56
0
def parse_card(str):
    """
    从字符串中解析卡牌属性,创建卡牌对象
    :param str: 
    :return: 
    """
    member = str.split(',')
    try:
        if member[8] == 'Follower':
            return Card(int(member[0]), member[1], member[2], member[3],
                        int(member[4]), int(member[5]), int(member[6]),
                        member[7], member[8], member[9], member[10],
                        member[11])
        if member[8] == 'Hero':
            return Hero(member)
        else:
            return Card(int(member[0]), member[1],
                        member[2], member[3], member[4], member[5],
                        int(member[6]), member[7], member[8], member[9],
                        member[10], member[11])
    except Exception as e:
        print(e)
Example #57
0
    def __init__(self, screen: pygame.Surface) -> None:
        self.screen = screen

        # true while running
        self.running = False

        # load data from pytmx
        tmx_data = load_pygame(self.map_path)

        # setup level geometry with simple pygame rects, loaded from pytmx
        self.walls = []
        for obj in tmx_data.objects:
            self.walls.append(pygame.Rect(obj.x, obj.y, obj.width, obj.height))

        # create new data source for pyscroll
        map_data = pyscroll.data.TiledMapData(tmx_data)

        # create new renderer (camera)
        self.map_layer = pyscroll.BufferedRenderer(map_data,
                                                   screen.get_size(),
                                                   clamp_camera=False,
                                                   tall_sprites=1)
        self.map_layer.zoom = 2

        # pyscroll supports layered rendering.  our map has 3 'under' layers
        # layers begin with 0, so the layers are 0, 1, and 2.
        # since we want the sprite to be on top of layer 1, we set the default
        # layer for sprites as 2
        self.group = PyscrollGroup(map_layer=self.map_layer, default_layer=2)

        self.hero = Hero()

        # put the hero in the center of the map
        self.hero.position = self.map_layer.map_rect.center
        self.hero._position[0] += 200
        self.hero._position[1] += 400

        # add our hero to the group
        self.group.add(self.hero)
Example #58
0
def loadHeroes(fileName):
    # List to store lines of input file
    heroes = []

    while True:
        # Ensure file name is valid; if not, request a valid one
        try:
            # Open file
            with open(fileName,"r") as file:
                # Iterate through file and append each line to the list
                for line in file:
                    hero = Hero(line.strip())

                    heroes.append(hero)
            break
        except:
            fileDirec = input("Please input the correct path for the heroes.txt file: ")
            chdir(fileDirec)
            continue


    # return the hero list
    return heroes
Example #59
0
def _parse_input_data(input_data):
    games = 0
    wins = 0
    picks = []
    bans = []
    for hero in input_data:
        games += hero['games']
        h = Hero(hero)
        if hero['games'] > 0:
            wins += hero['win']
            picks.append(h)
        if hero['against_games'] > 0:
            bans.append(h)
    if games:
        win_percentage = (wins / games) * 100
    else:
        win_percentage = 0
    return {
        'avg_win': win_percentage,
        'sample': games,
        'picks': picks,
        'bans': bans
    }
Example #60
0
def load_user_hero(user_id):
    
    try:
        # abre el archivo y lo lee si lo encuentra
        fd = os.open(folder + '/' + user_id.__str__(), os.O_RDONLY)
        h = os.read(fd,4096)
        os.close(fd)

        # decodifica el contenido y lo almacena en users
        t = pickle.loads(h)
        attrs = []
        for i in t.keys():
            attrs.append(t[i])

        o = Hero.__new__(Hero)
        o.__dict__.update(t)

        users[user_id] = o
        print('User hero loaded')
    
    except Exception as e:
        print(e.__str__() + '   <----UserNotLoaded')
        return