簡體   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