Evan
Evan

Reputation: 528

How to instantiate an unknown number of instances in python3.2

I have been working on a card game in python 3.2 and am not sure about how to instantiate separate players. The game can have anywhere from 2 players to 8 players. I was thinking I could use brute force and have something like:

   players = int(input('how many players?: ))
   if players ==2:
       p1 = Player()
       p2 = Player()
   elif players ==3:
       p1 = Player()
       p2 = Player()
       p3 = Player()
   elif players ==4:
       p1 = Player()
       p2 = Player()
       p3 = Player()
       p4 = Player()

etc...

that seems dirty. Is there a cleaner way of getting around this?

Thank you.

Upvotes: 1

Views: 159

Answers (1)

lxop
lxop

Reputation: 8595

Use a list and a for loop:

players = int (input ('how many players?: '))
if not 2 <= players <= 8:
  <raise an exception or something>

p = []
for _ in range (players):
  p.append (Player())

Now you have a list of players that you can do what you like with.

Upvotes: 1

Related Questions