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

2024-05-10 20:27:18 发布

您现在位置:Python中文网/ 问答频道 /正文

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

游戏在一个每秒重复60次的主循环中运行,每次循环执行时,它都会计算很多东西,例如位置,问题是我有两个玩家,所以我必须写两行。你知道吗

Example here:

if p1direction == 'right' and p1XS < p1Attributes[1]: p1XS += p1Attributes[0]

and:

if p2direction == 'right' and p2XS < p2Attributes[1]: p2XS += p2Attributes[0]

请看区别p1和p2,它们分别属于播放器1和播放器2。你知道吗

我只是想找到一个解决办法,不写每次相同的行只为p2。我在考虑for函数,这样我甚至可以很容易地添加玩家,但我不知道如何在这种情况下做到这一点。。。你知道吗

有人能帮我吗?:)拜托


Tags: andright游戏if玩家键盘播放器pygame
2条回答

创建一个类播放器。 然后将每个玩家的属性添加到类中。 用player1和player2实例化你的类。你知道吗

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

playerOne = Player()
playerTwo = Player()

direction = playerOne.direction

如果您还没有使用类,我不建议您使用它们。继承权会变得很糟糕。。。你知道吗

希望有帮助, 纳鲁桑

编辑: 如果您还没有在Python中使用类,我建议您先在那里学习,然后继续您的游戏开发。我在pygame中也编写了几个游戏,而且课程非常紧随其后。事实上,如果不使用适当的类(或者无限的if子句和for循环,这将使一切变得非常缓慢),几乎不可能创建pygame游戏。你知道吗

祝你好运

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

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]

相关问题 更多 >