繁体   English   中英

Python2.7如何在循环中使用多重变量?

[英]Python2.7 how do I use multiples variables in a loop?

我正在通过pygame libraby用Python2.7制作自己的游戏。 这是一款1v1格斗游戏,玩家使用相同的键盘。

游戏在一个主循环中运行,该循环每秒重复执行60次,每次执行循环时,它都会计算很多事情,例如位置,问题是我有2个玩家,因此我必须写两次行。

这里的例子:

如果p1direction =='right'并且p1XS <p1Attributes [1]:p1XS + = p1Attributes [0]

和:

如果p2direction =='正确'并且p2XS <p2Attributes [1]:p2XS + = p2Attributes [0]

看到差异p1和p2,它们是分别属于玩家1和玩家2的变量。

我只想找到一个解决方案,以免每次只为p2写相同的行。 我在考虑for函数,因此我什至可以轻松添加播放器,但在这种情况下我不知道该怎么做...

有人能帮我吗 ? :) 请

创建一个班级播放器。 然后将每个玩家的属性添加到类中。 使用玩家1和2实例化您的课程。

class Player():
    direction = "right"
    etc.
    def shoot(self):
        if self.direction == "right"
             shoot_right()

playerOne = Player()
playerTwo = Player()

direction = playerOne.direction

如果您还没有使用过类,那么我不建议您使用它们。 继承会变得很讨厌...

希望能有所帮助,Narusan

编辑:如果您还没有在Python中使用过类,我建议先赶上那里,然后再继续您的游戏开发。 我也已经在pygame中编写了几款游戏,而且课堂也很方便。 实际上,如果不使用适当的类(或无尽的if子句和for循环,会使一切变得非常缓慢),创建pygame游戏几乎是不可能的。

祝你好运

如何将变量(例如p1direction和p2direction)存储在由玩家编号索引的向量(player_directions)中,并使用循环访问它,例如:

number_of_players  = 2
playersXS = function_that_fills_playersXS() # return a vector containing your p1XS and p2XS  variables in a vector

for player_number in xrange(number_of_players):
    if player_directions[player_number]=='right' and playersXS[player_number]< Attributes[player_number][1]:
        playersXS[player_number]+=Attributes[player_number][0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM