2013-07-20 66 views
0

我希望用下面的语句给玩家的对象添加点数。访问对象属性时遇到的问题

players[players.index(active_player)].points += moves[active_move] 

设置的对象了整体的代码是非常简单的,但我得到的是说我输入的玩家不在列表中的值错误。补充代码如下:

class Player(object): 
     def __init__(self, name): 
      self.name = name 
      self.points = 0 

def setup(players): 
    numplayers = int(raw_input("Enter number of players: ")) 
    for i in range(numplayers): 
     name = raw_input("Enter player name: ") 
     player = Player(name) 
     players.append(player) 

def display_moves(moves): 
    for item in moves: 
     print item, moves[item] 

def main(): 
    players = [] 
    moves = {'Ronaldo Chop': 10, 'Elastico Chop': 30, 'Airborne Rainbow': 50, 'Fancy Fake Ball Roll': 50, 'Stop Ball and Turn': 20} 
    setup(players) 
    display_moves(moves) 
    flag = False 
    while not flag: 
     active_player = raw_input("Enter a player (0 to exit):") 
     if active_player == 0: 
      break 
     active_move = raw_input("Enter a move: ") 
     players[players.index(active_player)].points += moves[active_move] 

main() 
+0

为什么在最后的while循环中使用'flag'?如果你想要一个无限循环,只需使用'while True:'。 – Bakuriu

回答

0

players.index(active_player)试图寻找并在players返回active_player第一位置。尽管如此,active_player是一个数字,而不是一个玩家。你只是想

players[active_player].points += moves[active_move] 

(其他错误:你忘了玩家的输入呼吁intactive_player另外,列表索引从0开始,所以你可能要进行索引players时从active_player减去1。)

1

这条线:

players[players.index(active_player)].points += moves[active_move] 

复杂得多比它需要。 players.index返回players中给定对象的索引,因此您正在搜索刚刚在列表中输入的数字的位置。因此,players.index(active_player)会搜索您刚才在玩家中输入的号码,如果找到它,它会返回它位于players内的索引。由于players包含Player对象(不是整数),查找将始终失败并引发异常。

我认为你正在试图做的是刚刚

players[active_player].points += moves[active_move] 

使用active_player在你的列表中的索引。 但是您应该注意,由于列表索引从零开始,因此不应将零视为“退出”值,否则将无法访问列表中的第一个播放器。