Reputation: 17
I'm trying to create a program that will keep track of your party and their health in a tabletop RPG. The best way I can think of so far is to have two separate lists, one with the party members and one with their health, so that when you display the party, it will run a code that looks something like this:
for Member in Party:
print(str(Member) + ":", str(Health), "HP")
Is there a way to pull the corresponding HP for each member from the different lists?
Upvotes: 1
Views: 1004
Reputation: 493
If it is important that you have two different lists, and those lists are both in the same order (first element of party member list corresponds with first element of hp list) then you can zip the two lists and iterate over them both simultaneously.
If you want to modify the elements of the list, however, then you can enumerate them, allowing you to keep track of the index as you loop over the two lists, and then modify the lists by index in the loop.
for i, (member, hp) in enumerate(zip(members, hitpoints)):
print(member, hp)
if member == 'Bob':
hitpoints[i] -= 10
However, I would recommend making a dict, a different data structure than using two lists, but much more elegant to use.
>>> members = ['A', 'B', 'C']
>>> hp = [5, 10, 7]
>>> member_hp = dict(zip(members, hp))
>>> member_hp['A']
5
>>> member_hp['A'] -= 3
>>> member_hp['A']
2
>>> member_hp['D'] = 20 # adds new member D with hp of 20
For slightly (and I mean only very slightly) more advanced usage, you can use the json module to read and write this data to a text file, to persist across multiple sessions.
Upvotes: 1
Reputation: 9997
I would use a combination of both recommendations in the comments section. Using OOP seems to be optimal here, so, below is a short possible example
class Party(dict):
def add_member(self,member):
self[member.name] = member.hp
def party_hp(self):
total_hp = 0
for name,hp in self.items():
total_hp += hp
return total_hp
class Member():
def __init__(self, name, hp):
self.name = name
self.hp = hp
player1 = Member("player1",10)
player2 = Member("player2",10)
player3 = Member("player3",10)
player4 = Member("player4",10)
test_party = Party()
test_party.add_member(player1)
test_party.add_member(player2)
test_party.add_member(player3)
test_party.add_member(player4)
print(test_party.party_hp())
>>>> 40
Note that this is just to show how OOP can be a real viable solution. Basically, in my example you have a Party
class that hold a dictionary of members. Calling party_hp
on it will return you the total hp of the party.
The exact implementation can be totally different. You could for example accept a list of users to shorten the number of code lines needed when adding members to a Party
. Again, this is a skeleton of what you could use.
Upvotes: 0