본문 바로가기

Python_Matter/Solve

Python Learn the basics Quiz 84

반응형

Q>

The flocks of crows circled over the battlefield.

(까마귀 무리가 전장을 돌았습니다.

Many brave warriors have fallen in this battle, many have continued to fight. 

(많은 용감한 전사들이이 전투에 빠졌고 많은 사람들이 계속 싸웠습니다. )
"If this goes on, we’ll simply kill each other, and there will be no winners - we’ll all lose." - reflected Sir Ronald, watching a bleak picture in front of him. 

("이것이 계속된다면, 우리는 단순히 서로를 죽일 것이며, 승자도 없을 것입니다. 우리 모두 잃을 것입니다." - 로널드 경이 그를 앞에서 황량한 모습으로 보았습니다. )
"I have to make an important decision.

("나는 중요한 결정을 내려야한다.)

I know what it’ll cost, but now that’s the only thing that can save us all..." 

(비용이 들겠는지 압니다 만, 이제 그것이 우리 모두를 구할 수있는 유일한 방법입니다 ... " )
A long time ago, when he was often in search of trouble and adventure, he went to hunt a witch who had a huge bounty on her head.

(오래 전에, 그는 종종 문제와 모험을 찾아 나서고, 머리에 거대한 현상금을 가진 마녀를 사냥하러 갔다.)

The bloody creature was able to save her life by persuading the knight to take a gift from her - a vial of vampire blood.

(피 묻은 동물은 나이트에게 그녀의 선물 인 뱀파이어 약병을 선물하도록 설득하여 자신의 목숨을 구할 수있었습니다.)

This blood poured into the dying man’s mouth could bring him back to life in vampire form.

(이 피는 죽어가는 남자의 입에 쏟아져 그를 뱀파이어 형태로 다시 살릴 수 있습니다. )
Is it really the day when he has to use it?.. 

(정말로 사용해야하는 날인가요? .. )
It seemed to be the only way to win this battle. 

(이 전투에서이기는 유일한 방법 인 것 같았습니다. )
Sir Ronald began to lean over the barely living bodies of his knights, who were lying beside him. To each of them he said: 

(Ronald 경은 기사 옆에 누워있는 간신히 살아있는 몸 위에 몸을 기울이기 시작했습니다. 그들 각자에게 그는 말했다 : )
- "Drink. You’ll be given a new life..."

(- 마셔. 너는 새로운 삶을 살게 될거야. ")

So we have 3 types of units: the Warrior, Knight and Defender. Let's make the battles even more epic and add another type - the Vampire!

(그래서 우리는 3 종류의 유닛을 가지고 있습니다 : 전사, 기사, 수비수. 전투를 더욱 서사시하게 만들고 다른 유형 인 뱀파이어를 추가합시다! )
Vampire should be the subclass of the Warrior class and have the additional vampirism parameter, which helps him to heal himself.

(뱀파이어는 전사 클래스의 하위 클래스 여야하며 뱀파이어 매개 변수가 추가로 있어야 자신을 치료할 수 있습니다.)

When the Vampire hits the other unit, he restores his health by +50% of the dealt damage (enemy defense makes the dealt damage value lower).

(뱀파이어가 다른 유닛을 공격하면 그는 처치 한 피해의 + 50 %만큼 자신의 건강을 회복합니다 (적 방어는 피해 수치가 낮아집니다). )
The basic parameters of the Vampire:

(뱀파이어의 기본 매개 변수 :)

health = 40
attack = 4
vampirism = 50%

 

Example:

chuck = Warrior()
bruce = Warrior()
carl = Knight()
dave = Warrior()
mark = Warrior()
bob = Defender()
mike = Knight()
rog = Warrior()
lancelot = Defender()
eric = Vampire()
adam = Vampire()
richard = Defender()
ogre = 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
fight(bob, mike) == False
fight(lancelot, rog) == True
fight(eric, richard) == False
fight(ogre, adam) == True

my_army = Army()
my_army.add_units(Defender, 2)
my_army.add_units(Vampire, 2)
my_army.add_units(Warrior, 1)
    
enemy_army = Army()
enemy_army.add_units(Warrior, 2)
enemy_army.add_units(Defender, 2)
enemy_army.add_units(Vampire, 3)

army_3 = Army()
army_3.add_units(Warrior, 1)
army_3.add_units(Defender, 4)

army_4 = Army()
army_4.add_units(Vampire, 3)
army_4.add_units(Warrior, 2)

battle = Battle()

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

 

Input: The warriors and armies.

        (전사와 군대.)

 

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

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

 

How it is used: For the computer games development.

                     (컴퓨터 게임 개발 용.)

 

Precondition: 4 types of units

                  (4 가지 유형의 단위)

 

A>

import itertools

'''
itertools : 반복자 구하는 모듈
'''

class Warrior:
    def __init__(self):
        self._health = 50
        self._attack = 5

    @property
    def is_alive(self):
        return self._health > 0

    @property
    def health(self):
        return self._health

    '''
    setter : 변경(set)
    health 속성의 값을 변경
    _ : single underscore / 내부적으로 사용하는 변수
    '''
    @health.setter
    def health(self, health):
        self._health = health

    @property
    def attack(self):
        return self._attack
    '''
    setter : 변경(set)
    attack 속성의 값을 변경
    _ : single underscore / 내부적으로 사용하는 변수
    '''
    @attack.setter
    def attack(self, attack_power):
        self._attack = attack_power

    def attack_enemy(self, enemy: object) -> None:
        dmg = self._attack
        return enemy.take_damage(dmg)

    def take_damage(self, dmg: int) -> int:
        self._health -= dmg
        return dmg

'''
super : 자식 클래스에서 부모 클래스의 내용을 사용
'''
class Knight(Warrior):
    def __init__(self):
        super(Knight, self).__init__()
        self._attack += 2

class Defender(Warrior):
    def __init__(self):
        super(Defender, self).__init__()
        self._health += 10
        self._attack -= 2
        self._defense = 2

    def take_damage(self, dmg: int) -> int:
        final_dmg = dmg - self._defense
        if final_dmg > 0:
            self._health -= final_dmg
        return final_dmg

class Vampire(Warrior):
    def __init__(self):
        super(Vampire, self).__init__()
        self._health -= 10
        self._attack -= 1
        self._vampirism = 0.5

    def attack_enemy(self, enemy: object):
        dmg_done = super(Vampire, self).attack_enemy(enemy)
        self._health += dmg_done * self._vampirism
        return dmg_done


def fight(unit_1, unit_2):
    for i in itertools.count():
        if not i % 2:
            '''
            unit_1 공격
            '''
            unit_1.attack_enemy(unit_2)

            if not unit_2.is_alive:
                return True
        else:
            '''
            unit_2 공격
            '''
            unit_2.attack_enemy(unit_1)
            if not unit_1.is_alive:
                return False

class Army(object):
    def __init__(self):
        self._units = []
        self._index = 0

    @property
    def is_alive(self):
        return self._index < len(self._units)

    def add_units(self, unit_type, number):
        self._units.extend((unit_type() for i in range(number)))

    def get_unit(self):
        return self._units[self._index]

    def unit_is_death(self):
        self._index += 1

'''
@staticmethod
정적 메소드 / 인스턴스에서도 접근이 가능
'''
class Battle(object):

    @staticmethod
    def fight(army_1, army_2):
        while army_1.is_alive and army_2.is_alive:
            if fight(army_1.get_unit(), army_2.get_unit()):
                army_2.unit_is_death()
            else:
                army_1.unit_is_death()
        return army_1.is_alive

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()
    bob = Defender()
    mike = Knight()
    rog = Warrior()
    lancelot = Defender()
    eric = Vampire()
    adam = Vampire()
    richard = Defender()
    ogre = 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
    assert fight(bob, mike) == False
    assert fight(lancelot, rog) == True
    assert fight(eric, richard) == False
    assert fight(ogre, adam) == True

    # battle tests
    my_army = Army()
    my_army.add_units(Defender, 2)
    my_army.add_units(Vampire, 2)
    my_army.add_units(Warrior, 1)

    enemy_army = Army()
    enemy_army.add_units(Warrior, 2)
    enemy_army.add_units(Defender, 2)
    enemy_army.add_units(Vampire, 3)

    army_3 = Army()
    army_3.add_units(Warrior, 1)
    army_3.add_units(Defender, 4)

    army_4 = Army()
    army_4.add_units(Vampire, 3)
    army_4.add_units(Warrior, 2)

    battle = Battle()

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

 

O>

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 86  (0) 2019.06.21
Python Learn the basics Quiz 85  (0) 2019.06.21
Python Learn the basics Quiz 83  (0) 2019.06.21
Python Learn the basics Quiz 82  (0) 2019.06.21
Python Learn the basics Quiz 81  (0) 2019.06.20