2014-07-12 27 views
0

我有这个hw在这里,我目前坚持。我的教授给我们提供的类异常,但我不知道有没有人能告诉我它是如何工作的,由于某种原因,当我运行这个程序,我得到这个:提升类例外通岩石剪刀游戏

Traceback (most recent call last): 
    File "C:\Python34\lab3.1.py", line 32, in <module> 
    rps_game_winner(game_2) 
    File "C:\Python34\lab3.1.py", line 5, in rps_game_winner 
    raise WrongNumberOfPlayersError('Wrong number of players!') 
WrongNumberOfPlayersError: Wrong number of players! 

所以想知道,如果有人能告诉我是什么做错了,或者我可以做些什么来使这个计划更好。 TY给大家

class WrongNumberOfPlayersError(Exception): pass 
class NoSuchStrategyError(Exception): pass 

def rps_game_winner(game): 
    if len(game) != 2: 
     raise WrongNumberOfPlayersError('Wrong number of players!') 
     return print ("A WrongNumberOfPlayers error has occurred. \n\n") 

    # Write the code for the NoSuchStratgyError 
    stop_words = ['R', 'P', 'S'] 
    if stop_words not in game[0]: 
     raise NoSuchStrategyError('No such strategy!') 

    # Write the code to determine the winner 
    # Write the code to return a List with the winner's name and strategy 
    if ("R" in game[0]) and ("S" in game[1]): 
     return print (game[0], "wins since Rock beat Scissor\n\n") 
    elif ("P" in game[0]) and ("R" in game[1]): 
     return print (game[0], "wins since Paper beat Rock\n\n") 
    elif ("S" in game[0]) and ("P" in game[1]): 
     return print (game[0], "wins since Scissor beat Paper\n\n") 
    elif ("S" in game[1]) and ("P" in game[0]): 
     return print (game[1], "wins since Scissor beat Paper\n\n") 
    elif ("P" in game[1]) and ("R" in game[0]): 
     return print (game[1], "wins since Paper beat Scissor\n\n") 
    elif ("R" in game[1]) and ("S" in game[0]): 
     return print (game[1], "wins since Rock beat Scissor\n\n") 

game = [["Armando", "P"], ["Dave", "S"]]# ["Dave", "S"] wins 
game_2 = [['Joe','R']] # wrong number of players 
game_3 = [['Joe','R'],['Walter','Q']] # no such strategy as 'Q' 
rps_game_winner(game)# returns the list ["Dave", "S"] wins since Scissors beat Paper 
rps_game_winner(game_2)# raises exception wrong number of players 
rps_game_winner(game_3)# raises exception no such strategy as 'Q' 
+0

看起来就是这样的结果。请记住,你在这里定义EXCEPTIONS,然后故意抛出它们。你应该得到一个带有回溯的错误消息 –

+0

你应该阅读[关于错误的教程](https://docs.python.org/2.7/tutorial/errors.html)。如果你觉得有些混乱,你也应该问问你的教授。这就是他们在那里的原因。 – jonrsharpe

回答

1

我认为你无法理解一个例外(或者更确切地说,一个Exception!)是什么。为了理解代码可能失败的原因,您可以定义它们。例如:

class WrongNumberOfPlayersError(Exception): 
    pass 

这是一个Exception(字面意思,因为它从Exception继承所以它可以做任何事情的Exception能做到),您已经定义要知道,当你有错号码的玩家!因此

players = [("Player 1", "S"), ("Player 2", "P"), ("Player 3", "R")] 
rps_game_winner(players) 
# this should raise an exception, since there are the WRONG NUMBER OF PLAYERS! 

您与try/except块(在某些语言中称为try/catch)这样处理这些:

while True: 
    players = get_players() # imagine a function that created this list, 
          # now you're looping over making a new one each 
          # time it's wrong 
    try: 
     rps_game_winner(players) 
    except WrongNumberOfPlayersError as e: 
     # handle the exception somehow. You only make it into this block if 
     # there are the wrong number of players, and it's already looping forever 
     # so probably just... 
     pass 
    else: # if there are no exceptions 
     break # get out of the infinite loop!! 

在你rps_game_winner功能,您有以下逻辑:

if len(game) != 2: 
    raise WrongNumberOfPlayersError("Wrong number of players!") 
    return print ("A WrongNumberOfPlayers error has occurred. \n\n") 

这这就是为什么我认为你的理解有点有缺陷。一旦你raise那个异常,该函数就退出。它从来没有读取return行(这可能是最好的,因为你不能return打印功能,它只是None由于在讨论范围以外的原因。在Python 2中,我相信这会导致你的代码失败完全运行)

这个函数就像一个为你工作的小型机器(本例中的“工作”是某种计算或运行算法等)。机器完成工作后,该工作结果即为return。但是如果出现问题,它应该告诉你“嘿,这不是我工作的结果,这是坏事”,所以它不是一个例外。基本上:如果出现问题,您可以选择raise,如果一切正常,您可以选择return

请注意,还有更多的事情比这个错误(例如,你永远不会抛出NoSuchStrategyError当前的代码),但该问题的基础是在误解例外是什么。

下面是一个过度抽象的代码,应该完成你想要的东西。请记住,我故意混淆了一些代码,因此它无法用作复制/粘贴。特别是,我很自豪地实现了赢/输/抽奖:)

R = 0b001 
P = 0b010 
S = 0b100 

class WrongNumberOfPlayersError(Exception): pass 
class NoSuchStrategyError(Exception): pass 

class RPSGame(object): 
    def __init__(self, *players): 
     try: 
      self.p1, self.p2 = players 
      # assume constructed as game('p1','p2') 
     except Exception: 
      try: self.p1, self.p2 = players[0] 
      # assume constructed as game(['p1','p2']) 
      except Exception: 
       raise WrongNumberOfPlayersError("Only two players per game") 
       # no more assumptions, raise that exception 
    def start(self): 
     print("{0.name} plays {0.human_choice} || {1.name} plays {1.human_choice}".format(
      self.p1, self.p2)) 
     def winner(p1, p2): 
      global R, P, S 
      wintable = {R: {R^S: 2, R^P: 1}, 
         P: {P^R: 2, P^S: 1}, 
         S: {S^P: 2, S^R: 1}} 
      resulttable = ["Draw","Lose","Win"] 
      return resulttable[wintable[p1.choice].get(p1^p2,0)] + " for {}".format(p1) 
     return winner(self.p1, self.p2) 

class Player(object): 
    rhyme_to_reason = {R:"Rock", P:"Paper", S:"Scissors"} 
    def __init__(self, name, choice): 
     self.name = name 
     try: choiceU = choice.upper() 
     except AttributeError: 
      # choice is R, P, S not "R", "P", "S" 
      choiceU = choice 
     if choiceU not in ("R","P","S",R,P,S): 
      raise NoSuchStrategyError("Must use strategy R, P, or S") 
     choicetable = {"R":R,"P":P,"S":S} 
     self.choice = choicetable.get(choiceU,choiceU) 
     self.human_choice = Player.rhyme_to_reason[self.choice] 
    def __xor__(self, other): 
     if not isinstance(other, Player): 
      raise NotImplementedError("Cannot xor Players with non-Players") 
     return self.choice^other.choice 
    def __hash__(self): 
     return hash((self.name, self.choice)) 
    def __str__(self): 
     return self.name 

if __name__ == "__main__": 
    import random, itertools 
    num_players = input("How many players are there? ") 
    players = [Player(input("Player name: "), input("Choice: ") or random.choice([R,P,S])) for _ in range(int(num_players))] 
    scoreboard = {player: 0 for player in players} 
    for pairing in itertools.combinations(players, 2): 
     game = RPSGame(pairing) 
     result = game.start() 
     if result.startswith("W"): 
      scoreboard[pairing[0]] += 1 
     elif result.startswith("L"): 
      scoreboard[pairing[1]] += 1 
     else: 
      pass 
     print(result) 
    for player, wins in scoreboard.items(): 
     print("{:.<20}{}".format(player,wins))