I wish to add points to the player's object with the following statement.
players[players.index(active_player)].points += moves[active_move]
The overall code for setting the objects up is really simple but I get a value error that says the player i entered is not in the list. The supplemental code is as follows:
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()
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.
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
.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.