2016-12-03 1 views
-1

오류 메시지 :Python3 컴파일 오류

내가 클래스에서 너무 내 전투 기능을 만들어 파이터 내 인스턴스를 호출하는 방법을 알아내는 힘든 시간을 보내고 있어요
FE.. 
************ MISSING LINE *************** 
file 1 line number: 2 
missing line in file 2, no match for file 1 line: 
'=================== ROUND 1 ===================\n' 
***************************************** 

F.. 
====================================================================== 
ERROR: test_combat_round (__main__.TestRPG) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "test_rpg.py", line 64, in test_combat_round 
    self.assertIsNone(combat_round(self.rich, self.thompson)) 
    File "/Users/ajsmitty12/Desktop/ISTA130/rpg.py", line 124, in combat_round 
    player1.attack(player1, player2) 
AttributeError: 'int' object has no attribute 'attack' 

====================================================================== 
FAIL: test_attack (__main__.TestRPG) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "test_rpg.py", line 42, in test_attack 
    self.assertEqual(out, buf.getvalue()) 
AssertionError: 'Rich attacks Thompson!\n\tHits for 5 hit points!\n\tThompson   h[24 chars]g.\n' != 'Rich attacks Thompson (HP: 10)!\n\tHits for 5 hit  points!\n\tT[33 chars]g.\n' 
- Rich attacks Thompson! 
+ Rich attacks Thompson (HP: 10)! 
?      +++++++++ 
    Hits for 5 hit points! 
    Thompson has 5 hit points remaining. 


====================================================================== 
FAIL: test_main (__main__.TestRPG) 
---------------------------------------------------------------------- 
Traceback (most recent call last): 
    File "test_rpg.py", line 117, in test_main 
    self.assertTrue(compare_files('rpg_main_out_correct.txt', out)) 
AssertionError: False is not true 

---------------------------------------------------------------------- 
Ran 7 tests in 0.006s 

FAILED (failures=2, errors=1) 
Correctness score = 57.14285714285714% 



    Description: 
    -This program will simulate combate for a simple Role Playing Game (RPG). 
    - The game has a single type of character, the Fighter. 
    -Each inidividual Fighter has an integer value caled "hit points" that represents his/her current health (the amount of damage he/she can sustain before death) 
    -It will simulate combat between 2 Fighers. 
    -Combat is divided into rounds: 
    -During each round each combatant will make 1 attempt to stike the other. 
    -We will use random numbers to simulate rolling dice, the higher number attacks first, and the lower number goes 2nd if still alive. 
    -If there is a tie, the players will go at the same time, they will attack eachother at the same moment. 
    -During a simultaneous attack both Fighters will get to attack even if one (or both) if (are) killed during that round. 
    -The progam will use a random number to determine whether an attack attempt is successful or not. 
    -Each successful attack will inflict damage on the opponent. 
    -To simulate damage, we'll reduce the opponent's hit points by another random number 
    -When a Fighters hit points are reduced to 0 (or less than 0) that player is considered to be dead. 
    -Combat round continue until one(or both) combatants are dead. 
    ''' 

, 그 클래스의 외부이다. player1과 player2의 난수를 올바르게 비교하고 있는지 궁금합니다. 그것으로 어지럽게 할 때 나는 사용하려고 시도했다 : player1 = Fighter() player2 = Fighter() 이 때 내 오류 메시지는 Fighter()> Fighter()가 비교할 수 없다고 말했을 것이다. 마지막으로, 왜 내 test_attack이 실패하는지 잘 모르겠습니다.

내 코드 (지금까지) :

import random 
class Fighter: 
    def __init__(self, name): 
     ''' 
    -This is my initializer method, which takes 2 parameters: 
      -Self 
      -Name (a string, the name of a fighter) 
     -This method will set a name attribute to the value of the name parameter 
     -It will also set a hit_points attribute to 10 (all fighters begin life with 10 hit points). 
     ''' 
     self.name = name 
     self.hit_points = 10 

    def __repr__(self): 
     ''' 
     -This method takes 1 parameter, self. 
     -It returns a string showing the name and hit points of the instances in the following format: 
       Bonzo (HP: 9) 
     ''' 
     result = str(self.name) + " (HP: " + str(self.hit_points) + ")" 
     return result 

    def take_damage(self, damage_amount): 
     ''' 
     -This method takes 2 parameters: 
      -self (the Fighter instance that calls the method) 
      -damage_amount (an integer representing the number of hit points of damage that have just been inflicted on this Fighter): 
       -The method should first decrease the hit_points attribute by the damage_amount. 
       -Next, it should check to see if the Fighter has died from the damage: 
        -A hit_points value that is 0 or less indicates death, and will print a message like the following: 
         \tAlas, Bonzo has fallen! 
        -Otherwise, it will print a message like the following (in this example, the player had 5 hit points left over after damage) 
         \tBonzo has 5 hit points remaining. 
       -The method returns nothing. 

     ''' 
     self.hit_points = self.hit_points - damage_amount 
     if self.hit_points <= 0: 
      print('\t' + 'Alas, ' + str(self.name) + ' has fallen!') 
     else: 
      print('\t' + str(self.name) + ' has ' + str(self.hit_points) + ' hit points remaining.') 
    def attack(self, other): 
     ''' 
     -This method takes 2 parameters: 
      -self 
      -other (another Fighter instance being attacked by self) 
     -The method will print the name of the attacker and attacked in the following format: 
      Bonzo attacks Chubs! 
     -Next, determine whether the attack hits by generating a random integer between 1 and 20 
      -Use the randrange function from the random module to get this number. 
      -A number that is 12 or higher indicates a hit: 
       - For an attack that hits, generate a random number between 1 and 6(using random.randrange) to represent the amount of damage inflicted by the attack 
        ***Do NOT use the from random import randrange sytanze (randrange works like range, not like randint (think about the upper bounds you choose)). 
       - Print the amount of damage inflicted like the following: 
        \tHits for 4 hit points! 
       -Invoke the take_damage method on the victim (i.e. on other), passing it the amount of damage inflicted. 
      -For an attack that misses, print the following message: 
       \tMisses! 
     -This method returns nothing. 
     ''' 
     self.other = Fighter(self.name) 
     print(str(self.name) + ' attacks ' + str(other) + '!') 
     attack = random.randrange(1, 20) 
     if attack >= 12: 
      damage_amount = random.randrange(1, 6) 
      print('\t' + 'Hits for ' + str(damage_amount) + ' hit points!') 
      other.take_damage(damage_amount) 
     else: 
      print('\t' + 'Misses!') 

    def is_alive(self): 
     ''' 
     -This method takes 1 parameter, self. 
      -It returns True if self has a positive number of points, False otherwise. 
     ''' 

     if self.hit_points > 0: 
      return True 
     else: 
      return False 
def combat_round(player1, player2): 
    ''' 
    -This function takes 2 parameters: 
     -The 1st is an instance of Fighter. 
     -The 2nd is another instance of Fighter. 
    -It determines which of the 2 fighters attacks 1st for the round by generating a random interger (use randrange) between 1 and 6 for each fighter: 
     -if the numbers are equal: 
      -print the following message: 
       Simultaneous! 
      -Have each figher instance call his attack method on the other figher (the 1st figher in the argument list must attack first to make the test work correctly) 
     -if one number is larger: 
      -the fighter with the larger roll attacks 1st (by calling his attack method and passing it the figher being attacked). 
      -if the 2nd fighter survives the attack (call is_alive), he then attack the 1st. 
    -This function returns nothing. 
    ''' 
    Fighter.name = player1 
    Fighter.name = player2 
    player1 = random.randrange(1, 6) 
    player2 = random.randrange(1, 6) 
    if player1 == player2: 
     print('Simultaneous!') 
     player1.attack(player2) 
    if player1 > player2: 
     player1.attack(player2) 
     if player2.is_alive() == True: 
      player2.attack(player1) 
    if player2 > player1: 
     player2.attack(player1) 
     if player1.is_alive() == True: 
      player1.attack(player2) 
+0

친절하게 질문을 수정하십시오. –

답변

1

당신의 클래스는 괜찮아 보이지만 combat_round 기능은 몇 가지 문제가있다. 당신은 player1 = Fighter() 등으로 궤도에 있었다

..

player1 = Fighter(name = 'Jeff') 
player2 = Fighter(name = 'Bill') 

는하지만 지금 먼저 가서 하나를 선택합니다. 당신은>, <, ==와 비교할 수 있습니다. __eq__()과 같은 특별한 방법을 커스터마이징하지 않고 파이썬은 비교할 속성을 알지 못하기 때문입니다.

player1.speed = random.randrange(1,6) 
player2.speed = random.randrange(1,6) 

지금이 같은 테스트를 작성할 수 있습니다 :과 비교 한 다음 속성을 설정하는 방법에 대한 어떻게 기능 combat_round()경우 전투기의 걸리는 경우,

if player1.speed == player2.speed: 
    print("Simultaneous!") 

을 또한, 당신은 인스턴스화 할 필요가없는 함수 안에서. 그러나 함수가 전투기의 이름 인 문자열을 사용하면 내 예제처럼 할 수 있습니다.