Domanda

Im trying to set a score in a game Im programming in python/pygame.

My score works when I have something like:

global score 
score = 0

Pseudo:

if player_rect.coliderect(baddie_rect):
      score +=1

Then I display the score to the screen.

But I want to use this score in a function of another class. Where that function is called in the main class.

so

in collision function I would like to increment the score, which is in a player class. but I would like to print the score in the main class. I have something like this using shortened code:

class player:
   .
   .
   .
   global score 
   score = 0
   def __init(self):
       self.score=0
   def get_score(self):
       return self.score
   def set_score(self, score):
       self.score = score
   def collision():
      .
      .
      if player_rect.coliderect(baddie_rect):
           self.score +=1

When I try to get the score when a collision occurs:

class main():
    player = player()
    player.colision()
    print player.get_score()

Nothing happens, the score doesnt increment!

Any suggestions?

È stato utile?

Soluzione

class Player:
   def __init(self):
       self.score=0
   def collision():
      if player_rect.coliderect(baddie_rect):
           self.score +=1


class main():
    player = Player()
    player.collision()
    print(player.score)

There is no need for globals here. In Python, you almost never need getters or setters. Just access or set the instance attribute score directly. If you ever need self.score to perform a more complicated operation, you can make it a property, which will allow you to define getter-/setter-like behavior without changing the syntax.

Altri suggerimenti

Your code, except for the "global" (which is completely unnecesary) seems right. Is true that in Python is preferred properties rather than access methods, but in this case it should not be the error.

Why don't you change the code in collision() to be:

def collision():
    self.score += 1

and then try to see if the error is somewhere else, perhaps in player_rect.coliderect(baddie_rect):?

I'm not saying that the error is THERE, but I hope you get the point to go from simple to complex

I found that the score needs to be a self object initialized at the start of the scoreboard class, not a global variable:

#Scoreboard class
class Scoreboard:
    def __init__(self):
        self.player_score = 0
        
    def update_score(self):
        self.player_score += 1

#Main file
score = Scoreboard()

if player_rect.coliderect(baddie_rect):
  score.update_score()

print(score.player_score)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top