예제 #1
0
class FightTests(unittest.TestCase):
    def setUp(self):
        self.weapon = Weapon(name="The Axe of Destiny", damage=20)
        self.spell = Spell(name="Fireball",
                           damage=30,
                           mana_cost=50,
                           cast_range=2)
        self.hero = Hero(name="Bron",
                         title="Dragonslayer",
                         health=100,
                         mana=100,
                         mana_regeneration_rate=2)
        self.enemy_to_die = Enemy(health=100, mana=100, damage=20)
        self.enemy_to_win = Enemy(health=100, mana=100, damage=50)
        self.hero.equip(self.weapon)
        self.hero.learn(self.spell)
        self.first_fight = Fight(self.hero, self.enemy_to_die)
        self.second_fight = Fight(self.hero, self.enemy_to_win)

    def test_init_for_type_error_for_hero(self):
        with self.assertRaises(TypeError):
            Fight(self.weapon, self.enemy_to_win)

    def test_init_for_type_error_for_enemy(self):
        with self.assertRaises(TypeError):
            Fight(self.hero, self.spell)

    def test_fight_method_where_hero_wins(self):
        self.assertTrue(self.first_fight.fight())

    def test_fight_method_where_enemy_wins(self):
        self.assertFalse(self.second_fight.fight())
예제 #2
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
예제 #3
0
 def run(self):
     fight = Fight(self._team1.dna, self._team2.dna, self._pokemons, self._moves, self._types)
     (victory1, victory2) = fight.fight()
     if victory1:
         self._team1.win()
     if victory2:
         self._team2.win()
예제 #4
0
def EncounterAcolyte():
    window.print_double_line()
    window.smooth_print("\n".join(dialogs["monastery"]["acolyte"]["text1"]))
    window.print_double_line()

    plural_draw_pile = "s" if len(player.draw_pile) > 1 else ""

    window.smooth_print(
        f" Your current health is \033[1;33;40m{player.HP}\033[1;37;40m/\033[1;33;40m{player.maxHP}\033[1;37;40m.")
    window.smooth_print("[1] \033[1;32;40mBreathe\033[1;37;40m (Heal 5 HP)")
    window.smooth_print(
        "[2] \033[1;31;40mDraw\033[1;37;40m (Challenge the Acolyte)")
    window.smooth_print(
        f"[3] \033[1;36;40mReflect\033[1;37;40m (Shuffle your discard pile back into your draw pile without adding a \033[1;31;40mFlaw\033[1;37;40m, and forget up to 3 cards in your deck. You currently have \033[1;33;40m{len(player.draw_pile)} \033[1;37;40mcard{plural_draw_pile} remaining in your draw pile.)")
    window.print_double_line()
    eventchoice = window.user_input(
        " Please enter the number corresponding to your choice to proceed:\n")
    if eventchoice == "1":
        window.print_double_line()
        window.smooth_print(
            "\n".join(dialogs["monastery"]["acolyte"]["breathe"]))
        window.print_double_line()
        player.HP += 5
        window.smooth_print(
            f" You have gained 5 health points. Your current health is \033[1;33;40m{player.HP}\033[1;37;40m/\033[1;33;40m{player.maxHP}\033[1;37;40m.")
        window.user_input(dialogs["pause"])
    elif eventchoice == "2":
        fight = Fight(window, player, acolyteE)
        fight.fight()
    elif eventchoice == "3":
        player.draw_pile.extend(player.discard_pile)
        player.discard_pile = []

        forget_cards()
    else:
        window.print_double_line()
        window.smooth_print(
            "\n".join(dialogs["monastery"]["acolyte"]["hesitation"]))
        window.print_double_line()
        player.HP += 5
        window.smooth_print(
            f" You have gained 5 health points. Your current health is \033[1;33;40m{player.HP}\033[1;37;40m/\033[1;33;40m{player.maxHP}\033[1;37;40m.")
        window.user_input(dialogs["pause"])

    window.print_double_line()
    window.smooth_print("\n".join(dialogs["monastery"]["acolyte"]["ending"]))
    window.print_double_line()
예제 #5
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()
예제 #6
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?')
예제 #8
0
 def start_a_fight(self, enemy_x, enemy_y, first_attack):
     weapons = self.weapons + [None]
     spells = self.spells + [None]
     weapon = choice(weapons)
     spell = choice(spells)
     self.enemy = choice(self.enemies)
     self.enemy.x = enemy_x
     self.enemy.y = enemy_y
     self.enemy.learn(spell)
     self.enemy.equip(weapon)
     fight = Fight(self.enemy)
     return fight.fight(self.hero, first_attack)
예제 #9
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))
예제 #10
0
 def __fight(self, by, dist_to_enemy):
     enemy = self.__choose_enemy()
     print(f"A fight is started between our {self.__hero} and {enemy}")
     fight = Fight(self.__hero, enemy)
     result = fight.fight(by, dist_to_enemy)
     if result:
         self.__enemies = self.__enemies[1:]
         print("Enemy is dead!")
     else:
         self.__place(self.__hero.checkpoint_position[0],
                      self.__hero.checkpoint_position[1], self.__hero_x,
                      self.__hero_y)
         self.__hero.regenerate()
         print("Hero is dead!")
     return result
예제 #11
0
def Bossfight():
    window.print_double_line()
    window.smooth_print("\n".join(dialogs["monastery"]["boss1"]))
    window.print_double_line()
    window.user_input(dialogs["pause"])
    window.print_double_line()
    window.smooth_print("\n".join(dialogs["monastery"]["boss2"]))
    window.print_double_line()
    window.user_input(" Press enter to open your sketchbook and FIGHT.\n")

    dialogs["fight"]["win"] = "\033[1;34;40m\n \"Excellent work, disciple! However, I am only getting started...\"\033[1;37;40m\n"
    dialogs["fight"]["abandon"] = "\033[1;34;40m \"Hmm, this is concerning. Perhaps you just weren't warmed up yet.\""
    fight = Fight(window, player, master1E)
    fight.fight()

    dialogs["fight"]["win"] = "\033[1;34;40m\n \"How splendid! It seems you are ready for your true ultimate trial.\"\033[1;37;40m\n"
    dialogs["fight"]["abandon"] = "\033[1;34;40m \"What is this? Gather your equipment, and prove that you are worthy of my teachings!\""
    fight = Fight(window, player, master2E)
    fight.fight()

    dialogs["fight"]["win"] = "\033[1;34;40m\n \"Absolutely outstanding! Please follow me inside the monastery, and we shall discuss about your performance.\"\033[1;37;40m\n"
    dialogs["fight"]["abandon"] = "\033[1;34;40m \"This final trial was intended to be difficult. I am disappointed, but not surprised. Follow me inside the monastery, and we shall discuss of your performance.\""
    fight = Fight(window, player, master3E)
    fight.fight()
예제 #12
0
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(
            clan_green.size()) + "," + str(clan_blue.size())

    # defections
#  defector = random.choice(all_players)
#  defector_new_clan = random.choice(clans)
#  defector_new_clan.add_member(defector)

#print clan_red
#print clan_green
#print clan_blue
class FightTests(unittest.TestCase):
    def setUp(self):
        self.spell = Spell(name="Fireball",
                           damage=5,
                           mana_cost=20,
                           cast_range=1)
        self.weapon = Weapon(name="The Axe of Destiny", damage=10)
        self.hero = Hero(name="Bron",
                         title="Dragonslayer",
                         health=100,
                         mana=100,
                         mana_regeneration_rate=2)
        self.map = [['.', '.', '#', '#', '.', 'S', '.', '.', '.', 'T'],
                    ['#', 'T', '#', '#', '.', '.', '#', '#', '#', '.'],
                    ['#', '.', '#', '#', '#', 'E', '#', '#', '#', 'E'],
                    ['#', '.', 'E', '.', '.', '.', '#', '#', '#', '.'],
                    ['#', '#', '#', 'T', '#', 'T', '#', '#', '#', 'G']]

        self.enemies = {
            "2,5": {
                "damage": 10,
                "health": 40,
                "mana": 20,
                "weapon": None,
                "spell": self.spell.to_json()
            },
            "2,9": {
                "damage": 10,
                "health": 40,
                "mana": 20,
                "weapon": self.weapon.to_json(),
                "spell": None
            },
            "3,2": {
                "damage": 10,
                "health": 40,
                "mana": 20,
                "weapon": None,
                "spell": None
            }
        }

        self.treasures = {
            "1,1": {
                "class": "Potion",
                "type": "mana",
                "amount": 50
            },
            "0,9": {
                "class": "Potion",
                "type": "health",
                "amount": 50
            },
            "4,3": {
                "class": "Weapon",
                "name": "The Axe of Destiny",
                "damage": 10
            },
            "4,5": {
                'class': "Spell",
                'name': 'Fireball',
                'damage': 5,
                'mana_cost': 20,
                'cast_range': 1
            }
        }

        self.json_data = {
            "map": self.map,
            "enemies": self.enemies,
            "treasures": self.treasures
        }

        self.dungeon = Dungeon(self.json_data)
        self.dungeon.spawn(self.hero)

        self.fight = Fight(dungeon=self.dungeon, enemy_pos=(2, 5))

    def test_init_initializing_correctly(self):
        self.assertEqual(self.fight.dungeon, self.dungeon)
        self.assertEqual(self.fight.enemy,
                         Enemy.from_json(self.enemies['2,5']))
        self.assertEqual(self.fight.enemy_pos, (2, 5))

    def test_init_raises_Assertion_error_when_there_is_no_enemy_on_the_given_pos(
            self):
        with self.assertRaises(AssertionError):
            Fight(dungeon=self.dungeon, enemy_pos=(0, 1))

    def test__range_between(self):
        self.assertEqual(self.fight._range_between(), 2)

    def test__direction_to_enemy_without_arguments(self):
        with self.subTest('Hero is up from enemy'):
            self.assertEqual(self.fight._direction_to_enemy(), (1, 0))

        with self.subTest('Hero is down from enemy'):
            self.fight.dungeon._hero_pos = (3, 5)

            self.assertEqual(self.fight._direction_to_enemy(), (-1, 0))

    def test__direction_to_enemy_with_argument(self):
        self.fight.enemy_pos = (3, 2)
        with self.subTest('Hero is left from enemy'):
            self.fight.dungeon._hero_pos = (3, 1)
            self.assertEqual(self.fight._direction_to_enemy(False), (0, 1))

        with self.subTest('Hero is right from enemy'):
            self.fight.dungeon._hero_pos = (3, 5)

            self.assertEqual(self.fight._direction_to_enemy(False), (0, -3))

    def test_hero_move_moves_hero_on_the_map_towards_enemy(self):
        self.fight.hero_move()

        self.assertEqual(self.fight.dungeon._map[1][5], self.hero)

    def test_enemy_move_moves_enemy_on_the_map_towards_hero(self):
        self.fight.enemy_move()

        self.assertEqual(self.fight.dungeon._map[1][5], self.fight.enemy)
        self.assertEqual(self.fight.enemy_pos, (1, 5))

    def test_player_makes_move_one_of_the_players_move_when_hero_has_to_move(
            self):
        self.fight.player_makes_move(self.dungeon._hero)

        self.assertEqual(self.fight.dungeon._map[1][5], self.hero)

    def test_player_makes_move_one_of_the_players_move_when_enemy_has_to_move(
            self):
        self.fight.player_makes_move(self.fight.enemy)

        self.assertEqual(self.fight.dungeon._map[1][5], self.fight.enemy)

    def test_player_makes_move_hero_attacks(self):
        self.fight.dungeon._hero.learn(self.spell)
        self.fight.enemy_move()
        self.fight.player_makes_move(self.fight.dungeon._hero)

        self.assertEqual(self.fight.enemy.get_health(), 35)

    def test_player_makes_move_enemy_attacks(self):
        self.fight.hero_move()
        self.fight.player_makes_move(self.fight.enemy)

        self.assertEqual(self.fight.dungeon._hero.get_health(), 85)

    def test_fight(self):
        spell = Spell(name="Fireball", damage=20, mana_cost=4, cast_range=1)
        self.fight.dungeon._hero.learn(spell)
        print()
        self.fight.dungeon.print_map()
        self.fight.fight()

        self.assertEqual(self.fight.dungeon._hero.get_health(), 85)
        self.assertEqual(self.fight.dungeon._hero_pos, (1, 5))
        self.assertFalse(self.fight.enemy.is_alive())

    def test_fight_hero_is_dead(self):
        self.hero._health = 10
        with self.assertRaises(HeroIsDeadError):
            self.fight.fight()
예제 #14
0
class Game():
    '''
    Class name: Game 
    Class Purpose: To play a game of "The Search for Horcruxes"
    '''
    def __init__(self):
        '''
        Purpose: To initialize the game to be able to play
        Parameters: None
        Returns: None
        '''

        self.character = Character()
        self._state = GameState.NOTYET
        self._eventType = None
        self._action = None
        self.fight = None
        self._wins = 0
        self._losses = 0
        self._totalMovesMade = 0
        self._averageMoveCount = 0
        self._stepsLeft = 10
        self._horcruxesLeft = 3
        self._enemiesLeft = 2
        self._userInput = ""
        self._againMessage = ""
        self._lastResult = ""
        self._displayMessage = ""
        self._continueMessage = ""
        self._horcruxesCaptured = []

    def __repr__(self):
        """Provide a string representation of the instance"""
        return "Game(Character='{}', State='{}', Wins='{}', Losses='{}')".format(
            self.character.characterName, self._state, self._wins,
            self._losses)

    @property
    def state(self):
        """Getter to get state of game"""
        return self._state

    @state.setter
    def state(self, newState):
        """Setter to set state of game"""
        self._state = newState

    @property
    def wins(self):
        """Get the current win count"""
        return self._wins

    @property
    def losses(self):
        """Get the current loss count"""
        return self._losses

    @property
    def moveCount(self):
        """Get the average move count
           to win or lose"""
        return self._averageMoveCount

    @property
    def horcruxCount(self):
        """Getter to get the horcrux found number"""
        return self._horcruxesLeft

    @horcruxCount.setter
    def horcruxCount(self, newCount):
        """Setter to change the horcrux count"""
        self._horcruxesLeft = newCount

    @property
    def enemiesLeft(self):
        """Getter to determine if enemy limit has been reached"""
        return self._enemiesLeft

    @enemiesLeft.setter
    def enemiesLeft(self, newCount):
        """Setter to set new enemy count"""
        self._enemiesLeft = newCount

    def setResultMessage(self, resultMessage):
        """Setter to set the result of the game"""
        self._lastResult = resultMessage

    def setUserInput(self, inputMessage):
        """Setter for the function input"""
        self._userInput = inputMessage

    def setContinueInput(self, inputMessage):
        """Setter to determine if user wants to continue"""
        self._continueMessage = inputMessage

    def getDisplayMessage(self):
        """Returns the current display message for 
           game"""
        return self._displayMessage

    def getEventType(self):
        """Returns the curret event type for the game"""
        return self._eventType

    def getStepsLeft(self):
        """Returns the number of steps left"""
        return self._stepsLeft

    def _generateGameSituation(self, displayInstance):
        """Function that generates a situation for the user to be in"""
        threadSemaphore.lock()
        situationChoice = random.choice(
            [obstacles, downgrades, horcruxes, enhancements])
        possibleChoices = [message for message in situationChoice['data']]
        message = random.choice(possibleChoices)

        while self._displayMessage == message:
            message = random.choice(possibleChoices)

        # set event type and display message to access in display
        # decrease the number of steps the user has
        self._eventType = situationChoice['type']
        self._displayMessage = message[0]
        self._action = message[1]
        self._stepsLeft = self._stepsLeft - 1
        self._updateOnAction(message)
        threadSemaphore.unlock()

    def _updateOnAction(self, message):
        """If a situation has an action associated, take that action"""
        def takeAction(positive):
            """Take action appropriate for category"""
            keyAction = list(self._action.keys())[0]
            valAction = list(self._action.values())[0]
            addVal = valAction if positive else -valAction
            if keyAction == 'health':
                self.character.characterHealth = self.character.characterHealth + addVal
            elif keyAction == 'power':
                self.character.characterPower = self.character.characterPower + addVal
            elif keyAction == 'smarts':
                self.character.characterSmarts = self.character.characterSmarts + addVal

        if self._eventType == 'enhancements':
            takeAction(True)
        elif self._eventType == 'downgrades':
            takeAction(False)
        elif self._eventType == 'horcruxes':
            horcruxes['data'].remove(message)
            self._horcruxesCaptured.append(message)

    def _fightEnemy(self, displayInstance, enemyName, enemyStats,
                    characterPlaying):
        '''
        Purpose: To handle fighting an enemy
        Parameters:
            - displayInstance (Display): The display instance for communication of messages
            - enemyName (str): The name of the enemy
            - enemyStats (dict): The stats of the enemy
            - characterPlaying (Character): The character that was chosen
        Returns: None
        '''

        self.fight = Fight(enemyName, enemyStats, characterPlaying)
        self.fight.fight(displayInstance)
        if self.fight.fightResult == 'win':
            self._enemiesLeft -= 1

    def _noFightSelected(self):
        """For when the user selects he does not wish to fight"""
        self.character.characterHealth -= 20
        self.character.characterPower -= 1

    def _horcruxChange(self):
        """To handle a horcrux event
           decrease horcrux count and remove horcrux"""
        self._horcruxesLeft -= 1

    def _handleGameSituation(self, displayInstance):
        """Function that determines how to handle the
           given game situation"""
        threadSemaphore.lock()
        if self._eventType == 'obstacles' and self._userInput == '1':
            self._fightEnemy(displayInstance, self._action,
                             enemies[self._action], self.character)
        elif self._eventType == 'obstacles' and self._userInput == '2':
            self._noFightSelected()
        threadSemaphore.unlock()

        # wait for continue message to be set in display
        while not displayInstance.continueSet:
            if self._stepsLeft == 0: break
        displayInstance.continueSet = False

        # determine if game should be ended
        self._endGame()

    def _endGame(self):
        """Function to end the game and send
           signal to display to do so"""
        threadSemaphore.lock()
        if self._continueMessage == 'n' or \
           self._horcruxesLeft == 0 or \
           self._enemiesLeft == 0 or \
           self.character.characterHealth <= 0 or \
           self._stepsLeft == 0:
            self._state = GameState.RESULT
        self._displayMessage = ""
        self._continueMessage = ""
        threadSemaphore.unlock()

    def _reinitializeBeginning(self):
        """Function to reinitialize character back to normal"""
        self.character.characterHealth = 75
        self.character.characterPower = 5
        self.character.characterSmarts = 5
        self.character.characterName = ""
        self._displayMessage = ""
        self._continueMessage = ""
        self._eventType = ""
        self._userInput = ""
        self._action = ""
        self.fight = None
        self._stepsLeft = 10
        self._horcruxesLeft = 3
        self._enemiesLeft = 2
        self._againMessage = ""
        self._lastResult = ""
        self.state = GameState.NOTYET

        # this has to be reinitialized because deleting components of
        # horxcruxes during program so two aren't used
        for horcrux in self._horcruxesCaptured:
            horcruxes['data'].append(horcrux)

    def _newGameStats(self):
        """Function to update game statistics"""
        if self._lastResult == "win":
            self._wins += 1
        else:
            self._losses += 1
        self._totalMovesMade += (10 - self._stepsLeft)
        self._averageMoveCount = self._totalMovesMade / (self._wins +
                                                         self._losses)

    def _playAgain(self):
        """Function to determine if should play again"""
        threadSemaphore.lock()
        if self._againMessage == 'y':
            self._reinitializeBeginning()
        else:
            self._state = GameState.END
        threadSemaphore.unlock()

    def playGame(self, displayInstance):
        """Run the game until the end has reached"""
        while self._state != GameState.END:
            if self._state == GameState.PLAYING:
                # send a message to display
                self._generateGameSituation(displayInstance)
                # sleep briefly to allow other thread to take control of semaphore
                time.sleep(.1)
                # receive user input from display
                self._handleGameSituation(displayInstance)
            elif self._state == GameState.RESULT:
                time.sleep(.1)
                threadSemaphore.lock()
                self._newGameStats()
                self._state = GameState.AGAIN
                threadSemaphore.unlock()
            elif self._state == GameState.AGAIN:

                # wait until again message received
                while self._againMessage == "":
                    {}

                # see if should play again
                self._playAgain()
                time.sleep(.5)
            time.sleep(.1)
예제 #15
0
#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,[clan_red,clan_blue,clan_green])
    #else:
    #  df.fight(player_a, player_b)

    if(clan_blue.size() == num_players):
      print "Clan blue won.";
      print str(round_count) + "," + str(clan_red.size()) + "," + str(clan_green.size()) + "," + str(clan_blue.size())
      raw_input("Press Enter to continue...")
    if(clan_red.size() == num_players):
      print "Clan red won.";
      print str(round_count) + "," + str(clan_red.size()) + "," + str(clan_green.size()) + "," + str(clan_blue.size())
      raw_input("Press Enter to continue...")
    if(clan_green.size() == num_players):
      print "Clan green won.";
      print str(round_count) + "," + str(clan_red.size()) + "," + str(clan_green.size()) + "," + str(clan_blue.size())
      raw_input("Press Enter to continue...")
예제 #16
0
from enemy import Enemy
from fight import Fight
from random import randint

kd = [17, 18]  # коофициент доспеха
hp = [randint(50, 51), randint(50, 51)]  # Количество здоровья
strength = [6, 6]  # сила
dexterity = [3, 1]  # ловкость
att = [[3, 10], [4, 6]]  # количество кубов, наминал
add_damage = [6, 6]  # + к урону
add_hit = [1, 1]  # + к попаданию

gork = Enemy('Горк', kd[0], hp[0], strength[0], dexterity[0], att[0],
             add_damage[0], add_hit[0])
mork = Enemy('Морк', kd[1], hp[1], strength[1], dexterity[1], att[1],
             add_damage[1], add_hit[1])

fight = Fight(gork, mork)

fight.fight()
    def hero_attack(self, by):
        if by == 'spell':
            self.find_closest_enemy_in_range(self.hero.spell.get_cast_range())
            fight_range = self.hero.spell.get_cast_range()
            if self.enemy_positon is None:
                print(f"Nothing in casting range {fight_range}")
            else:
                self.temp_enemy = self.enemy
                print(
                    f"A fight is started between our {str(self.hero)} and Enemy with damage{str(self.enemy)}"
                )
                while not (self.enemy_positon[0] == self.hero_position[0]
                           and self.enemy_positon[1] == self.hero_position[1]):

                    self.temp_enemy.take_damage(self.hero.attack(by='spell'))
                    print(
                        f"Hero casts a {self.hero.spell.get_name()}, hits enemy for {self.hero.attack(by='spell')} dmg. Enemy health is {self.temp_enemy.get_health()}"
                    )
                    if self.enemy.is_alive() is False:
                        break
                    if self.enemy_positon[0] < self.hero_position[0] and\
                        self.dungeon[
                            self.enemy_positon[0] + 1][
                            self.enemy_positon[1]] != '#':
                        self.enemy_positon[0] += 1
                        print(
                            "Enemy moves one square down in order to get to the hero. This is his move."
                        )
                        continue

                    if self.enemy_positon[0] > self.hero_position[0] and\
                        self.dungeon[
                            self.enemy_positon[0] - 1][
                            self.enemy_positon[1]] != '#':
                        self.enemy_positon[0] -= 1
                        print(
                            "Enemy moves one square up in order to get to the hero. This is his move."
                        )
                        continue

                    if self.enemy_positon[1] < self.hero_position[1] and\
                        self.dungeon[
                            self.enemy_positon[0]][
                            self.enemy_positon[1] + 1] != '#':
                        self.enemy_positon[1] += 1
                        print(
                            "Enemy moves one square to the right in order to get to the hero. This is his move."
                        )
                        continue

                    if self.enemy_positon[1] > self.hero_position[1] and\
                        self.dungeon[
                            self.enemy_positon[0]][
                            self.enemy_positon[1] - 1] != '#':
                        self.enemy_positon[1] -= 1
                        print(
                            "Enemy moves one square to the left in order to get to the hero. This is his move."
                        )
                        continue
                self.set_enemy(Enemy(health=100, mana=100, damage=20))
                f = Fight(self.hero, self.enemy)
                if not f.fight():
                    self.spawn(self.hero)

        elif by == 'weapon':
            print("Enemy is not close enough!")

        else:
            raise ValueError("There only weapon and spell!")