Пример #1
0
    def move(self, player_name, direction):
        # If wrong direction is given, do nothing
        directions = ["left", "right", "up", "down"]
        if direction not in directions:
            return "Wrong direction given."

        # Read map from file
        output = ""
        f = open(self.filepath, "r+")
        output += f.read()
        f.close()

        # converts output to list of lists of single-character strings (easier to work with)
        getGPS = output = [list(x) for x in output.split("\n")]
        # current coordinates
        location = self.get_coordinates(getGPS, player_name)
        # destination coordinates
        destination = self.modify_indexes(self.get_coordinates(getGPS, player_name), direction)

        # if coordinate tuple exceeds the map boundaries - terminate
        if destination[0] < 0 or destination[1] < 0 or destination[0] > len(output) or destination[1] > len(output[0]):
            return "Out of Bounds."

        # What is the ASCI character in the given map location
        target = output[destination[0]][destination[1]]
        # Gets indicator of player who wants to execute a move on the board
        indicator = self.get_player_indicator(self.spawnlist[player_name])
        # enemy is opposite indicator
        enemy = "OH".replace(indicator, "")
        if target == "#":
            return "You will hit the wall."
        elif target == ".":
            # swap the "." and current moving player indicator in map
            output[location[0]][location[1]], output[destination[0]][destination[1]] = (
                output[destination[0]][destination[1]],
                output[location[0]][location[1]],
            )
        elif target == enemy:
            # tokill is opposite object of currently-moving player
            enemyElem = {i: self.spawnlist[i] for i in self.spawnlist if i != player_name}
            ToKill = self.get_value_from_single_element_dict(enemyElem)
            # creates fight and simulates it, leaving only winning player on map
            # if winner attacked, its indicator overwrites the fallen enemy's one
            # if winner was attacked, the fallen enemy one's is changed wiht "." on map
            bitka = Fight(self.spawnlist[player_name], ToKill)
            battle_result = bitka.simulate_fight()
            output[location[0]][location[1]] = "."
            output[destination[0]][destination[1]] = self.get_player_indicator(battle_result)
            for item in self.spawnlist:
                if self.spawnlist[item] == battle_result:
                    print("{} wins!".format(item))

        # saves information to the dungeon map text file
        f = open(self.filepath, "w+")
        for i in range(0, len(output)):
            if i != (len(output) - 1):
                f.write("".join(output[i]) + "\n")
            else:
                f.write("".join(output[i]))
        f.close()
Пример #2
0
 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())
Пример #3
0
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())
Пример #4
0
    def hero_attack(self, by=""):
        if by == 'weapon' and self.hero.weapon is None:
            raise Exception("Hero cannot attack by weapon")

        if by == 'spell' and self.hero.spell is None:
            raise Exception("Hero cannot attack by spell")

        if by == 'spell' and self.hero.spell is not None:
            for i in range(self.__coords[1]+1, self.__coords[1]+1+self.hero.spell.cast_range**2):
                try:
                    print(self.map[self.__coords[0]][i], self.__coords[1], self.__coords[1]+1+self.hero.spell.cast_range**2)
                    if self.map[self.__coords[0]][i] == Dungeon.WALKABLE_PATH:
                        continue

                    elif self.map[self.__coords[0]][i] == Dungeon.ENEMY:
                        print("A fight is started between our {} and {}".format(repr(self.hero), repr(self.enemy)))
                        f = Fight(self.hero, self.enemy)
                        f.fight(self.hero.weapon_to_fight())
                        break
                    print("Nothing in casting range {}".format(self.hero.spell.cast_range))
                    return False
                except IndexError:
                    break

        if by == 'weapon' and self.hero.weapon is not None:
            print("A fight is started between our {} and {}".format(repr(self.hero), repr(self.enemy)))
            Fight(self.hero, self.enemy).fight(self.hero.weapon_to_fight())
            return True
Пример #5
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)
 def move(self, player_name, direction):
     player = self.players[player_name]
     old_player_pos = list(player[1])
     is_move_correct, new_player_pos = self._check_move_possible(
         old_player_pos, direction)
     self.players[player_name][1] = new_player_pos
     if is_move_correct:
         old_row = old_player_pos[1]
         old_col = old_player_pos[0]
         self.map_grid[old_row][old_col] = '.'
         del self.occupied_cells[tuple(old_player_pos)]
         new_row = new_player_pos[1]
         new_col = new_player_pos[0]
         if self.map_grid[new_row][new_col] != '.':
             attacker = player[0]
             defender = self.occupied_cells[tuple(new_player_pos)]
             fight = Fight(attacker, defender)
             fight.simulate_fight()
             if not fight.attacker.is_alive():
                 self._update_map()
                 return True
         self.occupied_cells[tuple(new_player_pos)] = player[0]
         self.map_grid[new_row][new_col] = Dungeon._get_entity_symbol(
             player[0])
         self._update_map()
     return is_move_correct
Пример #7
0
 def test_simulate_fight_orc_win(self):
     orc_w = Orc("Winner", 300, 2)
     hero_l = Hero("Loser", 300, "TheLoser")
     wep = Weapon("Ubiec", 15, 0.5)
     orc_w.equip_weapon(wep)
     orc_fight = Fight(hero_l, orc_w)
     self.assertEqual(orc_fight.simulate_fight(), orc_fight._ORC_WINNER)
Пример #8
0
    def battle(self, name, dest, otpt, chr_loc):
        """Invoked when an Entity's destination map block
        is occupied by the opposite entity type

        Args:
            name - Name of the Entity that walks over. Type(String)
            dest - Coordinates of move direction. Type(Tuple)
            otpt - Converted map. Type(List of Lists of Strings)
            chr_loc - Current coordinates of entity. Type(Tuple)"""
        to_fight = None
        for each in self.ingame:
            if self.ingame[each].location == dest:
                to_fight = self.ingame[each]

        battle = Fight(self.ingame[name], to_fight)
        battle_result = battle.simulate_fight()
        otpt[chr_loc[0]][chr_loc[1]] = "."
        otpt[dest[0]][dest[1]] = self.get_entity_indicator(battle_result)
        if self.ingame[name] == battle_result:
            self.ingame[name].location = dest
        else:
            self.map = self.map.replace("H", ".")
        for item in self.ingame:
            if self.ingame[item] == battle_result:
                self.map = self.revert_map_to_string_state(otpt)
                return "{} wins!".format(item)
Пример #9
0
class TestFightingSkills(unittest.TestCase):
    def setUp(self):
        self.orc = Orc("Gerasim", 100, 1.7)
        self.hero = Hero("Spiridon", 100, "Lich King")
        self.bitka = Fight(self.orc, self.hero)
        self.orc.weapon = Weapon("Wirt's Leg", 30, 0.9)
        self.hero.weapon = Weapon("WarGlaive", 30, 0.5)

    def test_init_fighters(self):
        self.assertEqual(self.orc.name, "Gerasim")
        self.assertEqual(self.orc.health, 100)
        self.assertEqual(self.orc.berserk_factor, 1.7)
        self.assertEqual(self.hero.name, "Spiridon")
        self.assertEqual(self.hero.health, 100)
        self.assertEqual(self.hero.nickname, "Lich King")

    def test_simulate_fight(self):
        result = self.bitka.simulate_fight()
        self.assertIn(result, [self.orc, self.hero])

    def test_simulate_fight_with_no_weapon(self):
        self.orc.weapon = None
        result = self.bitka.simulate_fight()
        self.assertEqual(self.hero, result)

    def test_simulate_fight_with_unarmed_characters(self):
        self.orc.weapon = None
        self.hero.weapon = None
        result = self.bitka.simulate_fight()
        self.assertEqual(result, "No winner")
Пример #10
0
class FightTest(unittest.TestCase):

    def setUp(self):
        self.hero = Hero("Arthas", 660, "Lich King")
        self.orc = Orc("Thrall", 700, 1.7)
        self.heroWeapon = Weapon("Frostmourne", 35, 0.7)
        self.orcWeapon = Weapon("Doomhammer", 40, 0.6)
        self.hero.weapon = self.heroWeapon
        self.orc.weapon = self.orcWeapon
        self.fight = Fight(self.hero, self.orc)

    def test_init(self):
        self.assertEqual(self.fight.hero, self.hero)
        self.assertEqual(self.fight.orc, self.orc)

    def test_coin_toss_for_first_attacker(self):
        self.assertIn(self.fight.coin_toss(),
                      [(self.orc, self.hero), (self.hero, self.orc)])

    def test_simulate_fight_with_no_weapons(self):
        self.fight.hero.weapon = None
        self.fight.orc.weapon = None
        result = self.fight.simulate_fight()
        self.assertEqual(result, "No winner")

    def test_simulate_fight_with_only_one_weapon(self):
        self.fight.hero.weapon = None
        result = self.fight.simulate_fight()
        self.assertEqual(result, self.fight.orc)

    def test_simulate_fight_with_both_armed_chars(self):
        result = self.fight.simulate_fight()
        self.assertIn(result, [self.fight.orc, self.hero])
Пример #11
0
class FightTest(unittest.TestCase):

    def setUp(self):
        self.orc = Orc("PeshoOrc", 100, 1.2)
        self.hero = Hero("PeshoHero", 100, "peshooo")
        self.weapon1 = Weapon("axe", 50, 0.5)
        self.weapon2 = Weapon("axe2", 70, 0.3)
        self.fighting = Fight(self.hero, self.orc)
        self.orc.weapon = self.weapon1

    def test_init(self):
        self.assertEqual(self.fighting.Orc,self.orc)
        self.assertEqual(self.fighting.Hero,self.hero)

    def test_coin(self):
        arr = []
        flag = [False, False]
        for i in range(1, 100):
            arr.append(self.fighting.coin())

        for i in arr:
            if i:
                flag[0] = True
            else:
                flag[1] = True
        self.assertEqual(flag, [True, True])

    def test_simulate_fight(self):
        self.assertEqual("PeshoOrc", self.fighting.simulate_fight())
Пример #12
0
    def move(self, name, direction):
        self.map = [x for x in self.map]
        if direction == "right":
            step = 1
        elif direction == "left":
            step = - 1
        elif direction == "down":
            step = self._ROW_LENGTH
        elif direction == "up":
            step = - self._ROW_LENGTH

        for i in range(len(self.heroes)):
            if self.heroes[i][0] == name:
                if self.map[i + step] == '.':
                    self.map[i + step] = "H" if isinstance(self.heroes[i][1], Hero) else "O"
                    self.map[i] = '.'
                    self.heroes.insert(i + step, self.heroes[i])
                    self.heroes.pop(i)
                    self.map = "".join(self.map)
                    return True
                elif self.map[i + step] == "H" or self.map[i + step] == "O":
                    self.fight = Fight(self.heroes[i][1], self.heroes[i + step][1])
                    self.fight.simulate_fight()
                    if self.heroes[i][1].is_alive():
                        self.map[i + step] = "H" if isinstance(self.heroes[i][1], Hero) else "O"
                        self.map[i] = '.'
                        self.heroes.insert(i + step, self.heroes[i])
                        self.heroes.pop(i)
                    else:
                        self.map[i] = '.'
                        self.heroes.pop(i)
                    self.map = "".join(self.map)

                    return True

                elif self.map[i + step] == '\n':
                    if self.map[i + step + 1] == '.':
                        self.map[i + step + 1] = "H" if isinstance(self.heroes[i][1], Hero) else "O"
                        self.map[i] = '.'
                        self.heroes.insert(i + step + 1, self.heroes[i])
                        self.heroes.pop(i)
                        self.map = "".join(self.map)
                        return True
                    elif self.map[i + step + 1] == "H" or self.map[i + step + 1] == "O":
                        self.fight = Fight(self.heroes[i][1], self.heroes[i + step + 1][1])
                        self.fight.simulate_fight()
                        if self.heroes[i][1].is_alive():
                            self.map[i + step + 1] = "H" if isinstance(self.heroes[i][1], Hero) else "O"
                            self.map[i] = '.'
                            self.heroes.insert(i + step + 1, self.heroes[i])
                            self.heroes.pop(i)
                        else:
                            self.map[i] = '.'
                            self.heroes.pop(i)
                        self.map = "".join(self.map)
                        return True
        self.map = "".join(self.map)
        return False
 def setUp(self):
     self.hero = Hero('Stoyan', 200, 'DeathBringer')
     self.hero.equip_weapon(Weapon('Sword', 20, 0.5))
     self.orc = Orc('Beginner Orc', 100, 1.5)
     self.orc.equip_weapon(Weapon('Stick', 10, 0.1))
     self.legendary_orc = Orc('Broksiguar', 200, 2)
     self.legendary_orc.equip_weapon(Weapon('Frostmourne', 80, 0.9))
     self.fight_hero_vs_orc = Fight(self.hero, self.orc)
     self.fight_hero_vs_legendary_orc = Fight(self.hero, self.legendary_orc)
Пример #14
0
 def duel_accept(self, other):
     if other["duel_invite"] == None or len([x for x in other["duel_invite"] if x[0] == self.id]) == 0:
         raise MyException(u"Игрок отменил свой вызов")
     if other["zone"] != self["zone"]:
         raise MyException(u"Игрок находится в другой локации")
     if other["loc"] != "default":
         raise MyException(u"Игрок пока не может начать дуэль")
     other["duel_invite"] = [di for di in other["duel_invite"] if di[0] != self.id]
     Fight.create([other], [self], _type="training")
Пример #15
0
 def start_fight(self):
     arena = Fight(self.hero_player, self.orc_player)
     arena.simulate_fight(self.orc_player, self.hero_player)
     if not arena.simulate_fight(self.orc_player, self.hero_player):
         return False
     elif self.orc_player.is_alive() and not self.hero_player.is_alive():
         print(self.orc_player_name, "won!")
     elif self.hero_player.is_alive() and not self.orc_player.is_alive():
         print(self.hero_player_name, "won!")
Пример #16
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())
Пример #17
0
    def test_fight(self):

        hero = Hero("LevskiHooligan", 650, "ChupimSkuli")
        orc = Orc("CskaSkinhead", 100, 3)
        fight = Fight(hero, orc)
        beer_bottle = Weapon("BeerBottle", 150, 0.8)
        metal_pipe = Weapon("MetalPipe", 180, 0.9)
        fight.hero.weapon = metal_pipe
        fight.orc.weapon = beer_bottle
        fight.simulate_fight()

        self.assertEqual(fight.orc.fight_health, 0)
        self.assertTrue(fight.hero.fight_health > 0)
Пример #18
0
    def move(self, player_name, direction):
        if player_name in self.players:
            player = self.players[player_name]
            # go_to -> (coord_x1, coord_y1)
            go_to = self.go_to_field(player[1], player[2], direction)
            if go_to:
                if self.dungeon[go_to[1]][go_to[0]] == '#':
                    print('Obstacle in that direction.')
                    return False
                elif self.dungeon[go_to[1]][go_to[0]] == '.':
                    self.dungeon[go_to[1]][go_to[0]] = self.dungeon[
                        player[2]][player[1]]
                    self.dungeon[player[2]][player[1]] = '.'
                    self.players[player_name] = (player[0], go_to[0], go_to[1])
                elif self.dungeon[go_to[1]][go_to[0]] == 'W':
                    weapon = self.get_weapon(go_to[0], go_to[1])
                    player[0].equip_weapon(weapon)
                    self.dungeon[go_to[1]][go_to[0]] = self.dungeon[
                        player[2]][player[1]]
                    self.dungeon[player[2]][player[1]] = '.'
                    self.players[player_name] = (player[0], go_to[0], go_to[1])
                    print('{} weapon equipped!'.format(weapon.type))
                else:  # in that case we meet enemy
                    # recognise hero and orc
                    if isinstance(player[0], Hero):
                        hero = (player_name, player[0])
                        orc = self.entity_at_field(go_to[0], go_to[1])
                    else:
                        hero = self.entity_at_field(go_to[0], go_to[1])
                        orc = (player_name, player[0])

                    # get the winner
                    fight = Fight(hero[1], orc[1])
                    fight.simulate_fight()
                    if fight.hero.health != 0:
                        print('{} wins!!!'.format(hero[0]))
                        self.dungeon[go_to[1]][go_to[0]] = 'H'
                        self.players.pop(orc[0])
                        self.players[hero[0]] = (hero[1], go_to[0], go_to[1])
                    else:
                        print('{} wins!!!'.format(orc[0]))
                        self.dungeon[go_to[1]][go_to[0]] = 'O'
                        self.players.pop(hero[0])
                        self.players[orc[0]] = (orc[1], go_to[0], go_to[1])
                    self.dungeon[player[2]][player[1]] = '.'
            else:
                print('Movement out of bounds.')
                return False
        else:
            message = 'There is no such player in the game.'
            raise ValueError(message)
Пример #19
0
    def move(self, player_id, direction):
        if player_id in self.players:
            pos = self.players[player_id][1]
            new_pos = ()

            oponent = 'O' if type(self.players[player_id][0]) is Hero else 'H'

            if direction == 'right' and pos[1] + 1 < len(self.map[pos[0]]):
                new_pos = (pos[0], pos[1] + 1)

            elif direction == 'left' and pos[1] - 1 >= 0:
                new_pos = (pos[0], pos[1] - 1)

            elif direction == 'up' and pos[0] - 1 >= 0:
                new_pos = (pos[0] - 1, pos[1])

            elif direction == 'down' and pos[0] + 1 < len(self.map):
                new_pos = (pos[0] + 1, pos[1])

            else:
                return False

            if self.map[new_pos[0]][new_pos[1]] == '.':
                self.map[new_pos[0]][new_pos[1]] = self.map[pos[0]][pos[1]]
                self.map[pos[0]][pos[1]] = '.'
                self.players[player_id][1] = new_pos
                return True

            elif self.map[new_pos[0]][new_pos[1]] == oponent:
                for oponent_name in self.players:

                    if self.players[oponent_name][1] == new_pos:
                        fight = Fight(self.players[player_id][0], self.players[oponent_name][0])

                        if not fight is None:
                            fight_outcome = fight.simulate_fight()
                            print(fight_outcome[0])

                            if fight_outcome[1] == 'H':
                                self.players.pop(oponent_name)
                                self.players[player_id][1] = new_pos
                                self.map[new_pos[0]][new_pos[1]] = self.map[pos[0]][pos[1]]
                                self.map[pos[0]][pos[1]] = '.'

                            elif fight_outcome[1] == 'O':
                                self.players.pop(player_id)
                                self.map[pos[0]][pos[1]] = '.'

                            return fight_outcome[1]
            else:
                return False
Пример #20
0
	def attack(self, req, replysock):
		# assume we're attacking the first enemy
		loc = self.places[req.location]
		user = self.users[req.user]
		if len(loc.enemies) == 0:
			replysock.send('/attack No enemies to attack')
		else:
			enemy = loc.enemies[0]
			fight = Fight(user, enemy, self.event_pub, ['player-' + user.name])
			winner = fight.fight()
			if winner != enemy:
				loc.enemies.remove(enemy)
				loc.dead.append(enemy)
			replysock.send('/attack {0} wins'.format(winner.name))
Пример #21
0
    def enemy_case(self, p_next, player_name):
        if type(self.return_self(player_name)) == Hero:
            second = self.return_self(player_name)
            first = self.return_enemy(p_next)
        else:
            second = self.return_enemy(p_next)
            first = self.return_self(player_name)

        print('Wild {} appeared!'.format(self.return_enemy(p_next)))
        print('FIGHT!')
        fight = Fight(first, second)
        winner = fight.simulate_fight()
        print('{} WINS!'.format(winner))
        return winner
 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 initiate_fight(self, player_name, position):
     player_obj = self.__players[player_name]["object"]
     for enemy_player in self.__players:
         if self.__players[enemy_player]["position"] == position:
             new_fight = Fight(player_obj, self.__players[enemy_player]["object"])
             winner = new_fight.simulate_fight()
             if winner == player_obj:
                 loser = enemy_player
             else:
                 loser = player_name
                 player_name = enemy_player
             break
     if loser:
         del self.__players[loser]
     return player_name
Пример #24
0
 def setUp(self):
     self.orc = Orc("PeshoOrc", 100, 1.2)
     self.hero = Hero("PeshoHero", 100, "peshooo")
     self.weapon1 = Weapon("axe", 50, 0.5)
     self.weapon2 = Weapon("axe2", 70, 0.3)
     self.fighting = Fight(self.hero, self.orc)
     self.orc.weapon = self.weapon1
 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")
Пример #26
0
    def fight_for_territory(self, position, new_position):
        initial_enemy_health = 100
        if self.map[new_position.x][new_position.y] == 'P':
            enemy = Python(initial_enemy_health)
        elif self.map[new_position.x][new_position.y] == 'A':
            enemy = Anaconda(initial_enemy_health)
        if not enemy:
            return False

        fight_to_the_death = Fight(self.hero, enemy)
        fight_to_the_death.simulate_fight()
        if self.hero.is_alive():
            self.change_position(position, new_position)
            if isinstance(enemy, Anaconda):
                self.hero.add_boss_benefits()
            return True
Пример #27
0
 def test_fight(self):
     self.bron_orc.equip_weapon(self.hammer)
     self.bron_hero.equip_weapon(self.sniper)
     self.fight1 = Fight(self.bron_hero, self.bron_orc)
     print
     self.assertEqual(1, self.fight1.simulate_fight())
     print("__________________________________________________________")
Пример #28
0
 def fight_time(self):
     if self.cords[self.spawned[0]] == self.cords[self.spawned[1]]:
         print('')
         print("Its time for fight. Lets Bet!")
         print('')
         self.its_show_time = Fight(self.player1, self.player2)
         self.its_show_time.simulate_fight()
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())
Пример #30
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())
Пример #31
0
 def test_enemy_with_same_x_as_hero_and_y_in_range_to_attack_choose_normal_attack_reduces_hero_health_5(
         self):
     # test with weapon and spell and enemy dmg > spell dmg > weapon dmg
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     enemy = Enemy(health=100, mana=40, damage=60)
     enemy.x = 3
     enemy.y = 2
     weapon = Weapon(name='Pruchka', damage=50)
     s = Spell('fireball', damage=45, mana_cost=15, cast_range=3)
     enemy.learn(s)
     enemy.equip(weapon)
     fight = Fight(enemy)
     h.x = 3
     h.y = 3
     fight.enemy_move(h)
     self.assertEqual(h.health, 40)
Пример #32
0
 def test_enemy_with_bigger_weapon_dmg_and_not_enough_range_should_change_x_to_hero_2(
         self):
     # hero is on the left side of enemy and in the same y level
     h = Hero(name="Bron",
              title="Dragonslayer",
              health=100,
              mana=100,
              mana_regeneration_rate=2)
     enemy = Enemy(health=100, mana=40, damage=20)
     enemy.x = 5
     enemy.y = 3
     weapon = Weapon(name='Pruchka', damage=50)
     s = Spell('fireball', damage=45, mana_cost=15, cast_range=1)
     enemy.learn(s)
     enemy.equip(weapon)
     fight = Fight(enemy)
     h.x = 3
     h.y = 3
     fight.enemy_move(h)
     self.assertEqual(enemy.x, 4)
Пример #33
0
    def enter_tile(self, tile):
        #TODO: Add Method for Player Entry
        tile.show_tile_prompt()
        player_input = input("Your Choice:").lower()
        if player_input == "f":
            if Fight.fight(self.player, tile.enemy):
                self.show_world_prompt(tile)
            else:
                return False

        if player_input == "c":
            self.enter_city()
 def handle_encounters(self, row, col):
     for respawn_tuple in self.save_respawn_points:
         self.dungeon[respawn_tuple[0]][respawn_tuple[1]] = 'S'
     if self.dungeon[row][col] == 'E':
         self.set_enemy(Enemy(health=100, mana=100, damage=20))
         if self.hero is not None and self.enemy is not None:
             f = Fight(self.hero, self.enemy)
             f.fight()
             if not self.hero.is_alive():
                 self.spawn(self.hero)
     elif self.dungeon[row][col] == 'T':
         self.get_treasure()
     elif self.dungeon[row][col] == 'G':
         print('Level complete!')
         exit()
     elif self.dungeon[row][col] == 'S':
         self.save_respawn_points.append((row, col))
     elif self.dungeon[row][col] == '.':
         pass
     else:
         print('WTF have you encountered?')
    def test_with_weapon_should_attack_by_weapon(self):
        h = Hero(name="Bron",
                 title="Dragonslayer",
                 health=100,
                 mana=100,
                 mana_regeneration_rate=2)
        h.equip(Weapon(name="The Axe of Destiny", damage=20))
        e = Enemy()

        Fight(h, e)

        self.assertEqual(h.attacking, PLAYER_ATTACK_BY_WEAPON_STRING)
Пример #36
0
    def _move_into(self, x, y):
        symbol = self.map[x][y]
        if symbol == 'T':
            self.collector.treasures[(x, y)].apply_on_hero(self.hero)
        elif symbol == 'E':
            Fight(self.hero, self.collector.enemies[(x, y)]).start_fight()

        if self._is_game_over():
            print("Game over!")
            sys.exit(0)
        elif symbol == 'G':
            self._go_on_next_level()
Пример #37
0
class TestFight(unittest.TestCase):

        def setUp(self):
            self.sten = Hero("Bron", 100, "DragonSlayer")
            self.sho = Orc("Vilasteros", 100, 1.34)
            self.bow = Weapon("Mighty Bow", 13, 0.17)
            self.axe = Weapon("Thunder Axe", 19, 0.25)
            self.sho.equip_weapon(self.bow)
            self.sten.equip_weapon(self.axe)
            self.battle = Fight(self.sten, self.sho)

        def test_init(self):
            self.assertEqual(self.battle.hero, self.sten)
            self.assertEqual(self.battle.orc, self.sho)

        def test_player_order(self):
            pass

        def test_simulate_fight(self):
            self.battle.simulate_fight()
            self.assertTrue(self.sten.is_alive() ^ self.sho.is_alive())

        def test_fight_with_no_weapons_orc(self):
            self.sho.equipped_weapon = None
            self.battle.simulate_fight()
            self.assertTrue(self.sten.is_alive())

        def test_fight_with_no_weapons_hero(self):
            self.sten.equipped_weapon = None
            self.battle.simulate_fight()
            self.assertTrue(self.sho.is_alive())
    def test_init_fiht(self):
        h = Hero(name="Bron",
                 title="Dragonslayer",
                 health=100,
                 mana=100,
                 mana_regeneration_rate=2)
        e = Enemy()

        f = Fight(h, e)

        self.assertIsNotNone(f)
        self.assertIsNotNone(f.hero)
        self.assertIsNotNone(f.enemy)
Пример #39
0
class fightTest(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_fight(self):
        self.bron_orc.equip_weapon(self.hammer)
        self.bron_hero.equip_weapon(self.sniper)
        self.fight1 = Fight(self.bron_hero, self.bron_orc)
        print
        self.assertEqual(1, self.fight1.simulate_fight())
        print("__________________________________________________________")

    def test_fight2(self):
        self.bron_orc.equip_weapon(self.sniper)
        self.bron_hero.equip_weapon(self.hammer)
        self.fight1 = Fight(self.bron_hero, self.bron_orc)
        self.assertEqual(2, self.fight1.simulate_fight())
    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)
Пример #41
0
    def move(self, player_name, direction):
        pyrva = self.players[player_name].i_coord
        vtora = self.players[player_name].j_coord
        self.direction = direction
        i = 0
        j = 0

        if direction == "right":
            i = 0
            j = 1
        elif direction == "left":
            i = 0
            j = -1
        elif direction == "down":
            i = 1
            j = 0
        elif direction == "up":
            i = -1
            j = 0

        if type(self.players[player_name]) == Hero and self.map_array[
                pyrva + i][vtora + j] == 'O':
            fight = Fight(self.players[player_name],
                          self.that_enemy(pyrva + i, vtora + j))
            fight.simulate_fight()

        elif type(self.players[player_name]) == Orc and self.map_array[
                pyrva + i][vtora + j] == 'H':
            fight = Fight(self.players[player_name],
                          self.that_enemy(pyrva + i, vtora + j))
            fight.simulate_fight()

        if self.map_array[pyrva + i][vtora + j] == '.':
            if type(self.players[player_name]) == Hero:
                self.map_array[pyrva + i][vtora + j] = 'H'
                self.map_array[pyrva][vtora] = '.'
                if direction == "left" or direction == "right":
                    self.players[player_name].j_coord += j
                else:
                    self.players[player_name].i_coord += i
            elif type(self.players[player_name]) == Orc:
                self.map_array[pyrva + i][vtora + j] = 'O'
                self.map_array[pyrva][vtora] = '.'
                if direction == "left" or direction == "right":
                    self.players[player_name].j_coord += j
                else:
                    self.players[player_name].i_coord += i
            else:
                return False
Пример #42
0
    def move(self, player_name, direction):
        if direction == "left":
            move_by = -1
        elif direction == "right":
            move_by = 1
        elif direction == "up":
            move_by = -11
        else:
            move_by = 11

        dungeon = open(self.file_path, "r")
        dungeon_map = dungeon.read()
        dungeon.close()
        dungeon_map = list(dungeon_map)
        new_place = self.spawned[player_name][1] + move_by
        out_of_map = new_place < 0 or new_place > len(dungeon_map) - 1
        if out_of_map or dungeon_map[new_place] in ["H", "O", "#", "\n"]:
            return False
        else:
            a = dungeon_map[new_place]
            dungeon_map[new_place] = dungeon_map[self.spawned[player_name][1]]
            dungeon_map[self.spawned[player_name][1]] = a
            self.spawned[player_name][1] += move_by
            dungeon_map = "".join(dungeon_map)
            dungeon = open(self.file_path, "w")
            dungeon.write(dungeon_map)
            dungeon.close()
            for player, info in self.spawned.items():
                into_right = self.spawned[player_name][1] == info[1] + 1
                into_left = self.spawned[player_name][1] == info[1] - 1
                into_up = self.spawned[player_name][1] == info[1] - 11
                into_down = self.spawned[player_name][1] == info[1] + 11
                into_enemy = into_right or into_left or into_up or into_down
                enemies = type(info[0]) != type(self.spawned[player_name][0])
                if into_enemy and enemies:
                    fight = Fight(info[0], self.spawned[player_name][0])
                    fight.simulate_fight()

            return True
    def test_with_spell_and_weapon_with_distance_and_no_mana_should_move(self):
        h = Hero(name="Bron",
                 title="Dragonslayer",
                 health=100,
                 mana=100,
                 mana_regeneration_rate=2)
        h.learn(Spell(name="Fireball", damage=30, mana_cost=50, cast_range=2))
        h.equip(Weapon(name="The Axe of Destiny", damage=40))
        e = Enemy()
        h.mana = 0

        f = Fight(h, e, distance=2)

        self.assertEqual(f.distance, 0)
Пример #44
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())
Пример #45
0
class TestFight(unittest.TestCase):
    def setUp(self):
        self.bron_hero = Hero("Bron", 100, "DragonSlayer")
        self.axe = Weapon("Mighty Axe", 25, 0.2)
        self.sword = Weapon("Mighty Sword", 12, 0.7)
        self.bron_orc = Orc("Bron", 100, 1.3)
        self.my_fight = Fight(self.bron_hero, self.bron_orc)
        self.bron_hero.weapon = self.sword
        self.bron_orc.weapon = self.axe

    def test_fight_init(self):
        self.assertEqual(self.my_fight.hero, self.bron_hero)
        self.assertEqual(self.my_fight.orc, self.bron_orc)

    def test_who_is_first(self):
        flag_hero = False
        flag_orc = False
        for i in range(0, 10):
            self.my_fight.who_is_first()
            if self.my_fight.who_is_first() == self.bron_hero:
                flag_hero = True
            else:
                flag_orc = True
        self.assertTrue(flag_hero and flag_orc)

    def test_simulate_fight(self):
        self.my_fight.simulate_fight()
        self.assertFalse(self.bron_orc.is_alive()
                         and self.bron_hero.is_alive())

    def test_simulate_fight_hero_wtih_wep_vs_hero_without_wep(self):
        self.hero_without_wep = Hero("Toni", 100, "Monster")
        self.fight = Fight(self.bron_hero, self.hero_without_wep)
        self.fight.simulate_fight()
        self.assertFalse(self.hero_without_wep.is_alive())

    def test_simulate_fight_hero_vs_equal_orc(self):
        self.equal_orc = Orc("Toni", 100, 1.5)
        self.equal_orc.weapon = self.sword
        self.fight = Fight(self.bron_hero, self.equal_orc)
        self.fight.simulate_fight()
        self.assertFalse(self.bron_hero.is_alive())
Пример #46
0
class FightTests(unittest.TestCase):
    def setUp(self):
        self.hero = Hero("Don Quixote", 9.99, "The Common Sense")
        self.orc = Orc("Oplik", 10, 0.3)
        self.fight = Fight(self.hero, self.orc)
        self.spoon = Weapon("Rounded Spoon", 2, 0.7)
        self.knife = Weapon("Rusty Knife", 6, 0.3)
        self.orc.weapon = self.knife
        self.hero.weapon = self.spoon

    def test_fight_init(self):
        self.assertEqual(self.hero, self.fight.hero)
        self.assertEqual(self.orc, self.fight.orc)

    def test_set_hero_value_error(self):
        with self.assertRaises(ValueError):
            Fight("pancake", self.orc)

    def test_set_orc_value_erroe(self):
        with self.assertRaises(ValueError):
            Fight(self.hero, "pancake")

    def test_get_player_sequence(self):
        h = False
        o = False
        for i in range(0, 1000):
            h = h or (self.fight.get_player_sequence()
                      == (self.hero, self.orc))
            o = o or (self.fight.get_player_sequence()
                      == (self.orc, self.hero))
        self.assertTrue(h)
        self.assertTrue(o)

    def test_simulate_fight(self):
        self.fight.simulate_fight()
        self.assertFalse(self.fight.orc.is_alive()
                         and self.fight.hero.is_alive())

    def test_simulate_fight_no_weapon_orc(self):
        self.fight.orc.weapon = None
        self.fight.simulate_fight()
        self.assertFalse(self.fight.orc.is_alive())

    def test_simulate_fight_no_weapon_hero(self):
        self.fight.hero.weapon = None
        self.fight.simulate_fight()
        self.assertFalse(self.fight.hero.is_alive())
Пример #47
0
def Monastery():
    window.clear()
    window.print_double_line()
    window.smooth_print("\n".join(dialogs["monastery"]["intro"]))
    window.print_double_line()
    window.user_input(dialogs["pause"])

    window.print_double_line()
    window.smooth_print("\n".join(dialogs["monastery"]["first_battle"]))
    window.print_double_line()

    for i in range(5):
        window.smooth_print(
            f"\n Paintings remaining before next event: \033[1;33;40m{player.next_event - player.room}\033[1;37;40m\n")
        window.user_input(dialogs["pause"])

        enemy = choose_opponent()
        fight = Fight(window, player, enemy)
        fight.fight()
        player.room += 1

        if i != 4:
            window.print_double_line()
            window.smooth_print("\n".join(dialogs["monastery"]["interlude1"]))
            window.print_double_line()

    EncounterAcolyte()
    player.room += 1
    player.next_event = 11

    for i in range(5):
        window.smooth_print(
            f"\n Paintings remaining before meeting the Master: \033[1;33;40m{player.next_event - player.room}\033[1;37;40m\n")
        window.user_input(dialogs["pause"])

        enemy = choose_opponent()
        fight = Fight(window, player, enemy)
        fight.fight()
        player.room += 1

        if i != 4:
            window.print_double_line()
            window.smooth_print("\n".join(dialogs["monastery"]["interlude2"]))
            window.print_double_line()

    Bossfight()
    ending()
Пример #48
0
class TestFight(unittest.TestCase):

    def setUp(self):
        self.hero = Hero("Bron", 100, "DragonSlayer")
        self.orc = Orc("Shapeshifter", 100, 1.5)
        sword = Weapon("Sword", 10, 0.2)
        axe = Weapon("Axe", 10, 0.2)
        self.hero.equip_weapon(sword)
        self.orc.equip_weapon(axe)
        self.battle = Fight(self.hero, self.orc)

    def test_fight_init(self):
        self.assertEqual(self.battle.hero.name, "Bron")
        self.assertEqual(self.battle.hero.health, 100)
        self.assertEqual(self.battle.hero.nickname, "DragonSlayer")
        self.assertEqual(self.battle.orc.name, "Shapeshifter")
        self.assertEqual(self.battle.orc.health, 100)
        self.assertEqual(self.battle.orc.berserk, 1.5)

    def test_flip_coin(self):
        flip_chances = set()
        for i in range(1000):
            flip_chances.add(self.battle.flip_coin())

        self.assertIn(True, flip_chances)
        self.assertIn(False, flip_chances)

    def test_simulate_fight_hero_first(self):
        entity_wins = set()
        for i in range(1000):
            self.battle.hero.health = 100
            self.battle.orc.health = 100
            entity_wins.add(self.battle.simulate_fight())

        self.assertIn("Hero wins.", entity_wins)
        self.assertIn("Orc wins.", entity_wins)
Пример #49
0
class FightTests(unittest.TestCase):
    def setUp(self):
        self.orc_goshe = Orc("Georgi", 100, 1.2)
        self.hero_slayer = Hero("DragonSlayer", 100, "Killer")
        self.axe = Weapon("Axe", 10, 0.2)
        self.sword = Weapon("Sword", 12, 0.5)
        self.orc_goshe.weapon = self.axe
        self.hero_slayer.weapon = self.sword
        self.battle_one = Fight(self.orc_goshe, self.hero_slayer)

    def test_fight_init(self):
        self.assertEqual(self.battle_one.orc, self.orc_goshe)
        self.assertEqual(self.battle_one.hero, self.hero_slayer)


#как да тествам кой е attacker???!!!!

    def test_who_is_attacked_and_attacker(self):
        result_array = []
        attacker, attacked = self.battle_one._set_turn()
        result_array.append(attacked)
        result_array.append(attacker)
        self.assertIn(self.orc_goshe, result_array)
        self.assertIn(self.hero_slayer, result_array)

    def test_simulate_battle_fight_without_weapon(self):
        self.orc_goshe.weapon = None
        self.battle_one.simulate_fight()
        self.assertFalse(self.orc_goshe.is_alive())

    def test_simulate_battle_fight(self):
        self.battle_one.simulate_fight()
        result_array = []
        result_array.append(self.orc_goshe.is_alive())
        result_array.append(self.hero_slayer.is_alive())
        self.assertIn(False, result_array)
Пример #50
0
class TestFight(unittest.TestCase):

    def setUp(self):
        self.hero = Hero('Stoyan', 200, 'DeathBringer')
        self.hero.equip_weapon(Weapon('Sword', 20, 0.5))
        self.orc = Orc('Beginner Orc', 100, 1.5)
        self.orc.equip_weapon(Weapon('Stick', 10, 0.1))
        self.legendary_orc = Orc('Broksiguar', 200, 2)
        self.legendary_orc.equip_weapon(Weapon('Frostmourne', 80, 0.9))
        self.fight_hero_vs_orc = Fight(self.hero, self.orc)
        self.fight_hero_vs_legendary_orc = Fight(self.hero, self.legendary_orc)

    def test_fight_init(self):
        self.assertEqual(self.fight_hero_vs_orc.hero, self.hero)
        self.assertEqual(self.fight_hero_vs_orc.orc, self.orc)

    def test_simulate_hero_win(self):
        self.fight_hero_vs_orc.simulate_fight()
        self.assertEqual(self.fight_hero_vs_orc.orc.current_health, 0)

    def test_simulate_orc_win(self):
        self.fight_hero_vs_legendary_orc.simulate_fight()
        self.assertEqual(
            self.fight_hero_vs_legendary_orc.hero.current_health, 0)
Пример #51
0
def simulate_fight():
    # Two users login, one of them fails and retries
    print
    print("############################################")
    print("############## SIMULATE FIGHT ##############")
    print("############################################")

    # Login both users
    username_one = "user1"
    password_one = "user1"
    username_two = "user2"
    password_two = "user2"
    user_one = User(username_one, password_one)
    if not user_one.valid:
        print("User1 did not authenticate!!")
        exit()
    else:
        print("User1 authenticated!")
    user_two = User(username_two, password_two)
    if not user_two.valid:
        print("User2 did not authenticate!!")
        exit()
    else:
        print("User2 authenticated!")

    # Get their squads
    squad_one = create_squad(
        user_one.username, "7911ceb9f0f546c2b49bff6a8bd7044d")
    squad_two = create_squad(
        user_two.username, "b3f175ec05564cdbbb8545bf6f26b469")

    print("User1 will use Squad <" + str(squad_one.uid)+">")
    print("User2 will use Squad <" + str(squad_two.uid)+">")
    # Create Fight

    test_fight = Fight(squad_one, squad_two)

    # Attack
    b_hpt_prev_health = squad_two.hierophant.get_stat_health()
    a_cpt_dmg = squad_one.captain.get_stat_fight()
    print("Squad B Hierophant health pre-fight: " + str(b_hpt_prev_health))
    print("Squad A Captain attacks with " + str(a_cpt_dmg) + " damage")
    test_fight.a_attack(squad_one.captain.uid, squad_two.hierophant.uid)
    
    # End fight and save squads
    test_fight.end_game()

    # Get Squad b again an check Hierophant health
    del squad_two
    squad_two = create_squad(
        user_two.username, "b3f175ec05564cdbbb8545bf6f26b469")
    
    b_hpt_post_health = squad_two.hierophant.get_stat_health()
    
    print("Squad B Hierophant health post-fight: " + str(b_hpt_post_health))
Пример #52
0
    def can_move(self, x, y, player_name):
        if x >= 0 and \
           x < len(self.current_map) and \
           y >= 0 and \
           y < len(self.current_map[0]):
            if self.current_map[x][y] != "#" and self.current_map[x][y] == ".":
                return True
            elif self.current_map[x][y] != self.players[player_name]['sign']:
                print('Battle begins! Someone will DIE now')
                for player in self.players:
                    if self.players[player]['type'] == 'Hero':
                        hero = self.players[player]['class']
                    elif self.players[player]['type'] == 'Orc':
                        orc = self.players[player]['class']
                # print(players[0], players[1])
                Fight(hero, orc).simulate_fight()

            return False
        return False
Пример #53
0
    def attack_from_distance(self, direction):
        direction = self.directions[direction]
        land_hit_pos_x = self._hero_pos[
            0] + direction[0] * self._hero.spell.cast_range
        land_hit_pos_y = self._hero_pos[
            1] + direction[1] * self._hero.spell.cast_range

        start_pos_x = self._hero_pos[0]
        start_pos_y = self._hero_pos[1]

        range_ = max(abs(land_hit_pos_x - start_pos_x),
                     abs(land_hit_pos_y - start_pos_y))
        for i in range(range_):
            start_pos_x, start_pos_y = (start_pos_x + direction[0],
                                        start_pos_y + direction[1])
            if start_pos_x < 0 or\
                start_pos_y < 0 or\
                start_pos_x >= len(self._map) or\
                start_pos_y >= len(self._map[start_pos_x]):
                break
        # while(abs(start_pos_x) <= abs(land_hit_pos_x) and
        #         abs(start_pos_y) <= abs(land_hit_pos_y) and
        #         start_pos_x >= 0 and
        #         start_pos_y >= 0 and
        #         start_pos_x < len(self._map) and
        #         start_pos_y < len(self._map[start_pos_x])):
            elif type(self._map[start_pos_x][start_pos_y]) is str and\
                    self._map[start_pos_x][start_pos_y] == '#':
                raise Exception("Hero cant attack through walls")
            elif isinstance(self._map[start_pos_x][start_pos_y], Enemy):
                if self._hero.can_cast():
                    Fight(dungeon=self,
                          enemy_pos=(start_pos_x, start_pos_y)).fight()
                    self._map[self._hero_pos[0]][self._hero_pos[1]] = 'H'
                else:
                    raise Exception(
                        'Hero doesnt have enough mana to attack from distance')
                return True

        print('There is no enemy in this direction')
        return False
Пример #54
0
    def unpause(self):
        if self.next_was == 0:  #previous state was Move-menu
            self.next_was = None
            self.cur_troops = self.next.troops
        elif self.next_was == 1:  #prev state was Fight
            self.next_was = None
            if self.next.hq_conquered:
                self.to_winlose(win=True)
                return
            self.map.redraw()
        elif self.next_was == 3:  #win/lose screen
            State.unpause(self)
            self.to_start_menu()
            return
        elif self.next_was == 4:  #prev state was AirstrikeMenu
            self.next_was = None
            self.airstriking = True
            self.cur_troops = self.next.troops

        State.unpause(self)

        if self.player.ai:
            return

        self.map.changed = 1
        self.conti.update()
        if self.airstriking and self.cur_troops:  #airstrike
            self.pause()
            self.next = Fight(self)
            self.quit()
        elif self.airstriking and not self.cur_troops:
            self.airstriking = False
        elif self.cur_troops:
            self.move_troops()
        else:
            if self.from_reg:
                self.map.select(self.from_reg.id)
            self.from_reg = None
            self.dest_reg = None
        self.msgline.set_msg("")
        self.msgline.draw(self.bg)
Пример #55
0
class TestFight(unittest.TestCase):

    def setUp(self):
        self.orc = Orc("Bron", 300, 1.3)
        self.hero = Hero("Brom", 300, "DragonSlayer")
        self.fight_sim = Fight(self.hero, self.orc)

    def test_hero_in_fight(self):
        self.assertEqual("Brom", self.fight_sim.hero.name)
        self.assertEqual(300, self.fight_sim.hero.health)
        self.assertEqual("DragonSlayer", self.fight_sim.hero.nickname)

    def test_orc_in_fight(self):
        self.assertEqual("Bron", self.fight_sim.orc.name)
        self.assertEqual(300, self.fight_sim.orc.health)
        self.assertEqual(1.3, self.fight_sim.orc.berserk_factor)

    def test_flip_coin(self):
        coins = []
        for i in range(100):
            coins.append(self.fight_sim._flip_coin())
        self.assertIn(self.fight_sim._HERO_TURN, coins)
        self.assertIn(self.fight_sim._ORC_TURN, coins)

    def test_simulate_fight_orc_win(self):
        orc_w = Orc("Winner", 300, 2)
        hero_l = Hero("Loser", 300, "TheLoser")
        wep = Weapon("Ubiec", 15, 0.5)
        orc_w.equip_weapon(wep)
        orc_fight = Fight(hero_l, orc_w)
        self.assertEqual(orc_fight.simulate_fight(), orc_fight._ORC_WINNER)

    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)
Пример #56
0
 def update_screen(self, starter=''):
     if self.state == 0:
         self.screen.blit(self.images['white_bg'], (0, 0))
         pygame.display.flip()
         textSurface = self.myfont.render("Choisissez un starter !", False,
                                          (0, 0, 255), (255, 255, 255))
         self.screen.blit(textSurface, (400, 114))
         starter_1 = pygame.transform.scale(self.images['Salamèche'],
                                            (112, 112))
         starter_1_rect = starter_1.get_rect()
         starter_1_rect.left = 469
         starter_1_rect.top = 214
         self.screen.blit(starter_1, (469, 214))
         starter_2 = pygame.transform.scale(self.images['Bulbizarre'],
                                            (112, 112))
         starter_2_rect = starter_2.get_rect()
         starter_2_rect.left = 669
         starter_2_rect.top = 214
         self.screen.blit(starter_2, (669, 214))
         starter_3 = pygame.transform.scale(self.images['Carapuce'],
                                            (112, 112))
         starter_3_rect = starter_3.get_rect()
         starter_3_rect.left = 269
         starter_3_rect.top = 214
         self.screen.blit(starter_3, (269, 214))
         pygame.display.flip()
         self.state = 1
         return {
             'Salamèche': starter_1_rect,
             'Bulbizarre': starter_2_rect,
             'Carapuce': starter_3_rect
         }
     elif self.state == 1:
         self.screen.blit(self.images['white_bg'], (0, 0))
         pygame.display.flip()
         self.screen.blit(self.images['fight_bg'], (0, 0))
         pygame.display.flip()
         self.fight = Fight(starter, Rattata(), self)
         return
Пример #57
0
    def fight(self):
        # list of Fight objects
        fights = []
        # only fight if there's a unit here
        if not self.unit_in_loc:
            return fights
        # dictionary of PlayerColor to list of locations
        fighting_locations = {}
        fighting_locations = self.add_fighting_neighbor(
            fighting_locations, Direction.EAST)
        fighting_locations = self.add_fighting_neighbor(
            fighting_locations, Direction.WEST)
        fighting_locations = self.add_fighting_neighbor(
            fighting_locations, Direction.SOUTH)
        fighting_locations = self.add_fighting_neighbor(
            fighting_locations, Direction.NORTH)
        if self.unit_in_loc:
            fighting_locations = util.add_loc_to_fight_queue(
                fighting_locations, self.unit_in_loc.owner, self)

        while len(fighting_locations.keys()) > 1:
            # Dictionary of PlayerColor to Location
            round_fighters = {}
            for color in fighting_locations.keys():
                round_fighters[color] = fighting_locations[color].pop()
            while len(round_fighters) > 1:
                fight_results = unit.resolve_fight_round(round_fighters)
                for color in fight_results:
                    if fight_results[color]:
                        round_fighters[color].unit_in_loc = None
                        dead_loc = round_fighters.pop(color)
                        fights.append(Fight((dead_loc.x, dead_loc.y)))
                        if len(fighting_locations[color]) == 0:
                            # If this was the last unit for this player, remove that player from the fight.
                            fighting_locations.pop(color)
                    else:
                        fighting_locations[color].append(round_fighters[color])
        return fights
Пример #58
0
all_players = []

for x in range(0, num_players / 3):
    red_clan_member = ClanMember("player_red_" + str(x), clan_red)
    green_clan_member = ClanMember("player_green_" + str(x), clan_green)
    blue_clan_member = ClanMember("player_blue_" + str(x), clan_blue)

    all_players.append(red_clan_member)
    all_players.append(green_clan_member)
    all_players.append(blue_clan_member)

print clan_red
print clan_green
print clan_blue

f = Fight()
df = DominationFight()

print "round,red_count,green_count,blue_count"
for round_count in range(0, 10000):
    for x in range(0, num_players):
        player_a = random.choice(all_players)
        player_b = random.choice(all_players)

        #if round_count % 300:
        f.fight(player_a, player_b)
        #else:
        #  df.fight(player_a, player_b)

    if round_count % 300 == 0:
        print str(round_count) + "," + str(clan_red.size()) + "," + str(
Пример #59
0
class Dungeon:
    def __init__(self, file_path):
        self.get_map(file_path)

    def set_enemies(self):
        self.enemies = []
        self.enemies.append(Enemy(health=100, mana=100, damage=20))
        self.enemies.append(Enemy(health=80, mana=80, damage=10))
        self.enemies.append(Enemy(health=150, mana=150, damage=25))
        self.enemies.append(Enemy(health=120, mana=120, damage=15))
        self.enemies.append(Enemy(health=50, mana=70, damage=45))

    def set_treasure(self):
        self.treasure = []
        spell = []
        spell.append(Spell(name="djsn", damage=20, mana_cost=20, cast_range=1))
        spell.append(Spell(name="dksm", damage=10, mana_cost=10, cast_range=3))
        spell.append(Spell(name="sajj", damage=25, mana_cost=25, cast_range=1))
        spell.append(Spell(name="sajk", damage=15, mana_cost=15, cast_range=2))
        spell.append(Spell(name="sakm", damage=45, mana_cost=45, cast_range=1))
        weapon = []
        weapon.append(Weapon(name="snsankansn", damage=20))
        weapon.append(Weapon(name="nsknaknska", damage=10))
        weapon.append(Weapon(name="sanjnkjsna", damage=25))
        weapon.append(Weapon(name="lakklaksla", damage=15))
        weapon.append(Weapon(name="klaskamkml", damage=45))
        self.treasure.append(spell)
        self.treasure.append(weapon)

    def get_map(self, file_path):
        self.dungeon = []
        f = open(file_path, "r")
        for line in f:
            temp = []
            for el in line:
                temp.append(el)
            self.dungeon.append(temp)

    def print_map(self):
        for row in self.dungeon:
            for el in row:
                print(el, end="")

    def spawn(self, hero):
        self.hero = hero
        for y in range(len(self.dungeon)):
            for x in range(len(self.dungeon[y])):
                if self.dungeon[y][x] == "S":
                    self.dungeon[y][x] = "H"
                    return True
        return False

    def get_hero_location(self):
        for y in range(len(self.dungeon)):
            for x in range(len(self.dungeon[y])):
                if self.dungeon[y][x] == "H":
                    return (x, y)
        return False

    def move_up(self):
        location = self.get_hero_location()
        if location[1] < 0:
            return False
        elif self.dungeon[location[0]][location[1] + 1] == "#":
            return False
        elif self.dungeon[location[0]][location[1] + 1] == "T":
            self.pick_treasure()
        elif self.dungeon[location[0]][location[1] + 1] == ".":
            self.dungeon[location[0]][location[1]] = "."
            self.dungeon[location[0]][location[1] + 1] = "H"
        elif self.dungeon[location[0]][location[1] + 1] == "E":
            self.fight = Fight(self.hero, self.enemies[randint(0, 4)])
            self.fight.start(self)
            if self.fight.start(self):
                self.dungeon[location[0]][location[1] + 1] = "H"
            else:
                self.spawn(hero)

    def move_down(self):
        location = self.get_hero_location()
        if location[1] >= len(self.dungeon):
            return False
        elif self.dungeon[location[0]][location[1] - 1] == "#":
            return False
        elif self.dungeon[location[0]][location[1] - 1] == "T":
            self.pick_treasure()
        elif self.dungeon[location[0]][location[1] - 1] == ".":
            self.dungeon[location[0]][location[1]] = "."
            self.dungeon[location[0]][location[1] - 1] = "H"
        elif self.dungeon[location[0]][location[1] - 1] == "E":
            self.fight = Fight(self.hero, self.enemies[randint(0, 4)])
            if self.fight.start(self):
                self.dungeon[location[0]][location[1] - 1] = "H"
            else:
                self.spawn(hero)

    def move_left(self):
        location = self.get_hero_location()
        if location[0] < 0:
            return False
        elif self.dungeon[location[0] - 1][location[1]] == "#":
            return False
        elif self.dungeon[location[0] - 1][location[1]] == "T":
            self.pick_treasure()
        elif self.dungeon[location[0] - 1][location[1]] == ".":
            self.dungeon[location[0]][location[1]] = "."
            self.dungeon[location[0] - 1][location[1]] = "H"
        elif self.dungeon[location[0] - 1][location[1]] == "E":
            self.fight = Fight(self.hero, self.enemies[randint(0, 4)])
            self.fight.start(self)
            if self.fight.start(self):
                self.dungeon[location[0] - 1][location[1]] = "H"
            else:
                self.spawn(hero)

    def move_right(self):
        location = self.get_hero_location()
        if location[0] >= len(self.dungeon[0]) - 1:
            return False
        elif self.dungeon[location[0] + 1][location[1]] == "#":
            return False
        elif self.dungeon[location[0] + 1][location[1]] == "T":
            self.pick_treasure()
        elif self.dungeon[location[0] + 1][location[1]] == ".":
            self.dungeon[location[0]][location[1]] = "."
            self.dungeon[location[0] + 1][location[1]] = "H"
        elif self.dungeon[location[0] + 1][location[1]] == "E":
            self.fight = Fight(self.hero, self.enemies[randint(0, 4)])
            if self.fight.start(self):
                self.dungeon[location[0] + 1][location[1]] = "H"
            else:
                self.spawn(hero)

    def move_hero(self, direction):
        if direction == "up":
            self.move_up()
        elif direction == "down":
            self.move_down()
        elif direction == "left":
            self.move_left()
        elif direction == "right":
            self.move_right()

    def pick_treasure(self):
        index = randint(0, 1)
        if index:
            self.hero.equip(self.pick_treasures[1][randint(0, 4)])
        else:
            self.hero.learn(self.pick_treasures[0][randint(0, 4)])
Пример #60
0
class EntityTest(unittest.TestCase):
    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 test_hero_init(self):
        self.assertEqual("Bron", self.hero.name)
        self.assertEqual(100, self.hero.health)
        self.assertEqual("DragonSlayer", self.hero.nickname)

    def test_known_as(self):
        self.assertEqual(self.hero.known_as(), "Bron the DragonSlayer")

    def test_get_health(self):
        self.assertEqual(100, self.hero.get_health())
        self.assertEqual(100, self.orc.get_health())

    def test_is_alive(self):
        self.assertTrue(self.hero.is_alive())
        self.hero.health = 0
        self.orc.health = -1
        self.assertFalse(self.orc.is_alive())
        self.assertFalse(self.hero.is_alive())

    def test_take_damage(self):
        self.assertTrue(self.hero.take_damage(30.0))
        result = self.hero.get_health()
        self.assertEqual(70.0, result)
        self.assertFalse(self.hero.take_damage(70))

    def test_take_more_damage_that_he_can(self):
        self.assertFalse(self.hero.take_damage(101))

    def test_take_healing(self):
        self.assertTrue(self.hero.take_healing(10))
        self.hero.health = 10
        self.assertTrue(self.hero.take_healing(10.0))
        self.hero.health = 0
        self.assertFalse(self.hero.take_healing(10.0))

    def test_orc_init(self):
        self.assertEqual("BronOrk", self.orc.name)
        self.assertEqual(100, self.orc.health)

    def test_ork_berseker(self):
        self.orc._Ork__set_berserk_factor(3)
        self.assertEqual(2, self.orc.berserk_factor)
        self.orc._Ork__set_berserk_factor(0.5)
        self.assertEqual(1, self.orc.berserk_factor)

    def test_has_weapon(self):
        self.assertFalse(self.orc.has_weapon())
        self.orc.equip_weapon(self.axe)
        self.assertTrue(self.orc.has_weapon())

    def test_equip_weapon(self):
        new_weapon = Weapon("Bazuka", 15, 3)
        self.orc.equip_weapon(new_weapon)
        self.assertEqual(new_weapon, self.orc.weapon)

    def test_attack(self):
        self.assertFalse(self.orc.has_weapon())
        self.assertEqual(0, self.orc.attack())
        self.orc.equip_weapon(self.axe)
        self.assertEqual(self.axe.damage, self.orc.attack())

    def test_fight_init(self):
        self.assertEqual(self.battle.hero, self.hero)
        self.assertEqual(self.battle.orc, self.orc)

    def test_simulate_fight(self):
        self.orc.weapon = self.axe
        self.hero.weapon = self.sword
        self.battle.simulate_fight()

    def test_spawn(self):
        self.assertTrue(self.dungeon.spawn('Bron', self.hero))
        self.assertTrue(self.dungeon.spawn('BronOrk', self.orc))
        # self.dungeon.print_map()

    def test_move(self):
        self.dungeon.spawn('Bron', self.hero)
        self.dungeon.spawn('Undead', self.orc)
        self.assertFalse(self.dungeon.move('Bron', 'left'))
        self.assertFalse(self.dungeon.move('Bron', 'up'))
        self.assertTrue(self.dungeon.move('Bron', 'right'))
        self.assertFalse(self.dungeon.move('Undead', 'down'))
        self.assertTrue(self.dungeon.move('Undead', 'up'))
        self.dungeon.print_map()