0

I just started to learn about classes last week in my game dev. class. I am trying to create something that will allow me to create instances of something while in a for loop. For example, I am trying to create 5 instances of Player in a loop and use an ID number that will increase with each time the loop loops. I've gotten this far.

class Player(object):
    def __init__(self, nm, am, wp, ht, ide):
        self.name = nm
        self.ammo = am
        self.weapon = wp
        self.health = ht
        self.id = ide

    def __str__(self):
        values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "ID #: " + str(self.id)
        return values

def main():
    Players = 0
    while Players < 5:
        play1 = Player("Joe", 5, "Machine gun", 22, 1)
        print (play1)
        Players = Players + 1

I've managed to create 5 instances of Joe which is fine, but how would I increase the ID #?

Justin Farr
  • 183
  • 3
  • 5
  • 16

3 Answers3

0
    class Player(object):
    def __init__(self, nm, am, wp, ht, ide):
        self.name = nm
        self.ammo = am
        self.weapon = wp
        self.health = ht
        self.id = ide

    def __str__(self):
        values = "Hi my name is " + self.name + "\n" + "Ammo: " + str(self.ammo) + "\n" + "Weapon: " + self.weapon + "\n" + "Health: " + str(self.health) + "\n" + "ID #: " + str(self.id)
        return values

def main():
    Players = 0
    while Players < 5:
        play1 = Player("Joe", 5, "Machine gun", 22, Players)
        print (play1)
        Players = Players + 1

Use The Var Players And Put It Into The Class

perfectvid2012
  • 25
  • 1
  • 1
  • 5
  • I used this one as it seemed to work best for me for whatever reason, but now as I am trying to also create a class and 5 instances of `Enemy` on top of the `Players` it doesn't seem to work. What could I do to fix this? – Justin Farr Feb 28 '15 at 18:45
  • Do you know what I could do, @perfectvid2012 ? – Justin Farr Feb 28 '15 at 19:25
0

I would put your players in an array so they can be used outside of the scope of the loop.

def main():
Players = 0
list_of_players = []
for i in range(5):
    list_of_players.append(Player("Joe", 5, "Machine gun", 22, i+1))
    print list_of_players[i]
preezzzy
  • 598
  • 5
  • 23
0

You can use a list:

players = []
while len(players) < 5:
    players.append(Player("Joe", 5, "Machine gun", 22, len(players) + 1))
cdonts
  • 9,304
  • 4
  • 46
  • 72