1

我一直在使用 python 3.2 开发纸牌游戏,但不确定如何实例化单独的玩家。游戏可以有 2 到 8 名玩家。我在想我可以使用蛮力并有类似的东西:

   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...

看起来很脏。有没有更清洁的方法来解决这个问题?

谢谢你。

4

1 回答 1

1

使用列表和 for 循环:

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

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

现在你有一个玩家列表,你可以随心所欲。

于 2012-06-10T06:39:48.700 回答