Reputation: 3
I tried to create a simple snake type game but put Pacman instead of the snake to make the game simple. I created it in pygame.
My score is not displaying on my game window if I increase it from the class, and the score is not increasing more than one. Please help.
I tried increasing the score in my main game loop and it works just fine, but if I increase the score from the check collisions class, the score increases to 1 and always stays at 1 no matter how much I increase, when Pacman eats a fruit he needs to get +1 score.
class player(object):
def randomize(self,win,score):
self.fx = random.randint(0,1250)
self.fy = random.randint(0,550)
score += 1
print("score is",score)
def check_collisions(score,win):
pacdraw = pygame.Rect(pac.x+10, pac.y+10, 75, 75)
pygame.draw.rect(win,(100,100,100),pacdraw,-1)
fruit = pygame.Rect(pac.fx+10,pac.fy+10, 40, 30)
pygame.draw.rect(win,(100,100,100),fruit,-1)
collide = pacdraw.colliderect(fruit)
if collide:
pac.randomize(win,score)
# score = 0
scorefont = pygame.font.Font("freesansbold.ttf", 32)
def display_score(score,win):
display = scorefont.render(f'score: {score}', True, (225, 225, 225))
win.blit(display, (10, 10))
def Redrawgamewindow():
win.blit(bg, (-300,-200))
win.blit(cherry, (pac.fx, pac.fy))
check_collisions(score,win)
display_score(score,win)
pac.draw(win)```
Upvotes: 0
Views: 107
Reputation: 48
You are using class, so you don't have to pass arguments to the function manually
You can use
def __init__(self, win):
self.score = 0
self.win = win
and you can access the 'score' by 'self'
def randomize(self):
self.fx = random.randint(0,1250)
self.fy = random.randint(0,550)
self.score += 1
print("score is", self.score)
so that 'score' is stored on the Player class, not passing to the function
so if
player = Player(win)
then you can access to player's score variable as below
def display_score(score, win):
display = scorefont.render(f'score: {player.score}', True, (225, 225, 225))
win.blit(display, (10, 10))
Upvotes: 1
Reputation: 167
In the check_collisions
you try to update the score, but numbers are passed by value and not by reference
Try to return the score and assign when you call this function on mainloop
Upvotes: 0