Pygame Score per Click

68 Views Asked by At

I would like to create a program that whenever I pressed a mouse button, its score will be incrementing by 1.

here is my code so far:

import pygame

pygame.init()

white = (255,255,255)
display = pygame.display.set_mode((800, 400))

def count():

    exit = True

while exit:

    mouseClick = pygame.mouse.get_pressed()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

        if event.type == pygame.MOUSEBUTTONDOWN:
            global score
            score = 0
            if mouseClick[0] == 1:
                score1=score+1
                print (score1)
            else:
                print (score)

    display.fill(white)
    pygame.display.update()
count()
1

There are 1 best solutions below

5
On

The problem lies in the way you handle score:

if event.type == pygame.MOUSEBUTTONDOWN:
    global score
    score = 0
    if mouseClick[0] == 1:
        score1=score+1
        print (score1)
    else:
        print (score)

At every iteration, if a click is detected, you reset score. So it's just always equal to 0.

Just get rid of that score = 0 (and of that global score as well), and put it right before your main loop:

score = 0
while exit:
    ...

Now, when you want to increment score, you don't need a second variable. Instead, just write:

score += 1

Which is equivalent to:

score = score + 1

On the other hand, your code always redefines a new variable score1, and assign it to score + 1, which is equal to 1. So what you just have is a score variable always equal to 0, and a score1 variable always equal to 1.

A logical way to handle all of this would be:

score = 0
while exit:    
    ...
        if event.type == pygame.MOUSEBUTTONDOWN:
            if mouseClick[0] == 1:
                score += 1