본문 바로가기

Python_Matter/Solve

Python Learn the basics Quiz 82

반응형

Q>

..Sir Ronald’s opponent - Umbert, has proved to be a very skillful warrior.

(.. Ronald의 상대 인 Umbert는 매우 숙련 된 전사로 판명났습니다.)

In addition, he was a good fifteen years younger, which gave him a certain advantage.

(또한, 그는 15 년 더 젊어서 그에게 약간의 이점을주었습니다.)

But Sir Ronald was also very strong - he had the experience of participation in many battles and in several major wars behind his back.

(그러나 로날드 경 또한 매우 강했습니다. 그는 여러 차례의 전투에 참여한 경험과 등 뒤에서 몇 차례의 중요한 전쟁 경험을 가지고있었습니다.)

And besides that, in his youth he was known as the best duelist in this land.

(게다가 그 어린 시절에 그는이 땅에서 최고의 결투 사라고 알려졌습니다.)
Realizing that the forces are equal, each of them had followed the only course possible - to call for help.

(힘이 동등하다는 것을 깨달을 때, 그들 각각은 가능한 유일한 길을 따랐습니다. 도움을 요청하십시오.)

Umbert sent for the reinforcement his coachman on a horse, and Sir Ronald used a family horn that sounded more than once in hot battles.

(움베르테 (Umbert)는 말을 타고 코치맨 (coachman)을 보강하기 위해 보냈고, 로날드 경 (Sir Ronald)은 격렬한 전투에서 두 번 이상 소리를 낸 가족 경적을 사용했습니다.)

The knight's castle was close enough for the call to arms was heard back there.

(나이트의 성은 팔에 대한 부름을 듣기에 충분할 정도로 가까이에있었습니다.)

Nobody quite knew where the Umbert's accomplices were located, and this made it difficult to come up with a strategy for the battle ahead. 

(Umbert의 공범자가 어디에 있는지는 아무도 모릅니다. 이로 인해 앞으로의 전투 전략을 세우는 것이 어려워졌습니다. )
Fortunately, the reinforcements for both sides arrived almost simultaneously.

(다행히 양측의 증원군이 거의 동시에 도착했습니다.)

Now it was more than a question of the girl's honor.

(이제 그 소녀의 영예에 대한 질문 이상의 것이 었습니다.)

There was no peaceful solutions to this matter. One of the two armies must be destroyed.

(이 문제에 대한 평화적 해결 방법은 없었습니다. 두 군대 중 하나가 파괴되어야합니다.)

In the previous mission - Warriors - you've learned how to make a duel between 2 warriors happen.

(이전의 임무에서 - Warriors - 당신은 2 명의 전사 사이에서 결투를하는 법을 배웠습니다.)

Great job!

(잘 했어!)

But let's move to something that feels a little more epic - the armies! In this mission your task is to add new classes and functions to the existing ones.

(그러나 좀 더 서사적 인 느낌을주는 군대로 이동합시다! 이 임무에서 당신은 기존 수업에 새로운 수업과 기능을 추가해야합니다.)

The new class should be the Army and have the method add_units() - for adding the chosen amount of units to the army.

(새로운 클래스는 군대가되어야하며, 선택된 유닛을 군대에 추가하는 add_units () 메소드가 있어야합니다.)

Also you need to create a Battle() class with a fight() function, which will determine the strongest army.

(또한 가장 강한 군대를 결정할 fight () 함수로 Battle () 클래스를 만들어야합니다. )
The battles occur according to the following principles:

(전투는 다음 원칙에 따라 진행됩니다. )
at first, there is a duel between the first warrior of the first army and the first warrior of the second army.

(처음에는 첫 번째 군대의 첫 번째 전사와 두 번째 군대의 첫 번째 전사 사이에 결투가있었습니다.)

As soon as one of them dies - the next warrior from the army that lost the fighter enters the duel, and the surviving warrior continues to fight with his current health.

(그 중 하나가 죽 자마자 전투기를 잃은 군대의 다음 전사가 결투에 진입하고 살아남은 전사는 현재의 건강 상태로 계속 싸웁니다.)

This continues until all the soldiers of one of the armies die. In this case, the battle() function should return True, if the first army won, or False, if the second one was stronger.

(이것은 한 군대의 모든 병사가 죽을 때까지 계속됩니다. 이 경우 battle () 함수는 첫 번째 군대가 승리하면 True를, 두 번째 군대가 강하면 False를 반환해야합니다.)

Note that army 1 have the advantage to start every fight!

(군대 1에는 모든 싸움을 시작할 수있는 이점이 있습니다!)

 

Example:

chuck = Warrior()
bruce = Warrior()
carl = Knight()
dave = Warrior()
mark = Warrior()

fight(chuck, bruce) == True
fight(dave, carl) == False
chuck.is_alive == True
bruce.is_alive == False
carl.is_alive == True
dave.is_alive == False
fight(carl, mark) == False
carl.is_alive == False

my_army = Army()
my_army.add_units(Knight, 3)
    
enemy_army = Army()
enemy_army.add_units(Warrior, 3)

army_3 = Army()
army_3.add_units(Warrior, 20)
army_3.add_units(Knight, 5)
    
army_4 = Army()
army_4.add_units(Warrior, 30)

battle = Battle()

battle.fight(my_army, enemy_army) == True
battle.fight(army_3, army_4) == False

 

Input: The warriors and armies.

         (전사와 군대)

 

Output: The result of the battle (True or False).

           (전투의 결과 (참 또는 거짓).)

 

How it is used: For computer games development.

                     (컴퓨터 게임 개발 용.)

 

Precondition: 2 types of units

                  (2 가지 유형의 단위)

 

A>

# Taken from mission The Warriors

class Warrior(object):
    def __init__(self):
        self.health = 50
        self.attack = 5

    '''
    @property : get method / 접근지정자
    health > 0 인지 확인 / True or False
    '''
    @property
    def is_alive(self):
        return self.health > 0

class Knight(Warrior):
    def __init__(self):
        self.health = 50
        self.attack = 7

    '''
    health > 0 인지 확인 / True or False
    '''
    @property
    def is_alive(self):
        return self.health > 0

class Army(object):
    def __init__(self):
        self.soldiers = []
    '''
    soldiers 객체를 amry에 추가 작업
    '''
    def add_units(self,soldierToAdd,soldierToAdd_amount):
        if soldierToAdd == Warrior:
           for soldierToAdd_i in range(soldierToAdd_amount):
                self.soldiers.append(Warrior())
        elif soldierToAdd == Knight:
            for soldierToAdd_i in range(soldierToAdd_amount):
                self.soldiers.append(Knight())

    def __len__(self):
        return len(self.soldiers)

class Battle(object):
    def __init__(object):
        pass
    '''
    army1 승리 True army2 승리 False
    assert를 사용해 클래스 진위여부 확인(조건이 True가 아니면 AssertError를 발생)
    '''
    def fight(self, army1, army2):
        assert type(army1) == Army
        assert type(army2) == Army
        while len(army1) > 0 and len(army2) > 0:
            is_soldier1_won = fight(army1.soldiers[0], army2.soldiers[0])
            if is_soldier1_won:
                army2.soldiers.pop(0)
            else:
                army1.soldiers.pop(0)
        if len(army1) > 0:
            return True
        else:
            return False


'''
army1 승리 True army2 승리 False
assert를 사용해 클래스 진위여부 확인(조건이 True가 아니면 AssertError를 발생)
'''
def fight(soldier1, soldier2):
    assert type(soldier1) in {Warrior, Knight}
    assert type(soldier2) in {Warrior, Knight}
    warriorNextToAttack = "soldier1"
    roundIndex = 0

    while True:
        roundIndex += 1
        if warriorNextToAttack == "soldier1":
            damageDealt = soldier1.attack
            soldier2.health -= damageDealt
            warriorNextToAttack = "soldier2"
            if not soldier2.is_alive: return True
        else:
            damageDealt = soldier2.attack
            soldier1.health -= damageDealt
            warriorNextToAttack = "soldier1"
            if not soldier1.is_alive: return False

if __name__ == '__main__':
    # These "asserts" using only for self-checking and not necessary for auto-testing

    chuck = Warrior()
    bruce = Warrior()
    carl = Knight()
    dave = Warrior()
    mark = Warrior()

    assert fight(chuck, bruce) == True
    assert fight(dave, carl) == False
    assert chuck.is_alive == True
    assert bruce.is_alive == False
    assert carl.is_alive == True
    assert dave.is_alive == False
    assert fight(carl, mark) == False
    assert carl.is_alive == False

    print("Coding complete? Let's try tests!")

if __name__ == '__main__':
    # These "asserts" using only for self-checking and not necessary for auto-testing

    # fight tests
    chuck = Warrior()
    bruce = Warrior()
    carl = Knight()
    dave = Warrior()
    mark = Warrior()

    assert fight(chuck, bruce) == True
    assert fight(dave, carl) == False
    assert chuck.is_alive == True
    assert bruce.is_alive == False
    assert carl.is_alive == True
    assert dave.is_alive == False
    assert fight(carl, mark) == False
    assert carl.is_alive == False

    # battle tests
    my_army = Army()
    my_army.add_units(Knight, 3)

    enemy_army = Army()
    enemy_army.add_units(Warrior, 3)

    army_3 = Army()
    army_3.add_units(Warrior, 20)
    army_3.add_units(Knight, 5)

    army_4 = Army()
    army_4.add_units(Warrior, 30)

    battle = Battle()

    assert battle.fight(my_army, enemy_army) == True
    assert battle.fight(army_3, army_4) == False
    print("Coding complete? Let's try tests!")

 

O>

Coding complete? Let's try tests!
Coding complete? Let's try tests!

Process finished with exit code 0

 

S>

https://py.checkio.org

반응형

'Python_Matter > Solve' 카테고리의 다른 글

Python Learn the basics Quiz 84  (0) 2019.06.21
Python Learn the basics Quiz 83  (0) 2019.06.21
Python Learn the basics Quiz 81  (0) 2019.06.20
Python Learn the basics Quiz 80  (0) 2019.06.20
Python Learn the basics Quiz 79  (0) 2019.06.20