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()
4

2 回答 2

1

This line:

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

Is much more complicated than it needs to be. players.index returns the index of a given object within players, so you're searching for the position of the number you just entered in the list. So players.index(active_player) searches for the number you just entered within players, and if it finds it, it returns the index it is located at within players. Since players contains Player objects (not integers), the lookup will always fail and throw an exception.

I think what you're trying to do is just

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

Using active_player as an index in your list. You should note however that since list indexing begins at zero, you should not consider zero to be your "quit" value or you will not be able to access the first player in your list.

于 2013-07-20T00:35:06.417 回答
0

players.index(active_player) tries to find and return the first location of active_player in players. active_player is a number, not a player, though. You just want

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

(Other bug: You forgot to call int on the player's input for active_player. Also, list indexing starts at 0, so you may want to subtract 1 from active_player when indexing into players.)

于 2013-07-20T00:34:32.123 回答