简体   繁体   中英

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

I'm making my own game with Python2.7 through the pygame libraby. It's a 1v1 combat game where players use the same keyboard.

The game works in a main loop that is repeated 60times per second, every time the loop is executed, it calculates lots of things eg the position, problem is that I have 2 players, so I have to write the lines two times.

Example here:

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

and:

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

See the differences p1 and p2, they are variables that belongs to Player 1 and Player 2 respectively.

I just want to find a solution to not write every time the same lines just for p2. I was thinking about the for function so I can even add players easly but I don't know how to do it in this case...

Can someone help me ? :) Please

Create a class player. Then add the attributes of each player to the class. Instantiate your class with player 1 and 2.

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

playerOne = Player()
playerTwo = Player()

direction = playerOne.direction

If you haven't used classes yet, I wouldn't recommend using them though. Inheritance can get pretty nasty...

Hope that helped, Narusan

EDIT: If you haven't used classes in Python yet, I recommend catching up there first and then continuing your game development. I have programmed several games in pygame as well, and classes come in very hand. In fact, it is almost impossible to create pygame games without using proper classes (or endless if-clauses and for-loops that will make everything super slow).

Wish you all the best of luck

How about storing your variables(for example p1direction and p2direction) in a vector(player_directions) indexed by the player number and using a loop access it, for example:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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