Insert score in a button game function

2019-03-02 10:40发布

I have this code for a button that is pressable:

def button(msg,xloc,yloc,xlong,ylong,b1,b2,action=None):

    hover = pygame.mouse.get_pos() 
    click = pygame.mouse.get_pressed()

    if xloc < hover [0] < xloc+xlong and yloc< hover [1] < yloc+ylong:
        pygame.draw.rect(display, b1, (xloc ,yloc ,xlong,ylong))
        if click [0]==1 and action != None:
            action()

    else:
        pygame.draw.rect(gameDisplay, inactiveButton, (xloc ,yloc ,xlong,ylong))
    label = pygame.font.SysFont("arial",16)
    textSurf, textBox = textMsg(msg, label)
    textBox.center = ((xloc +(300)),((yloc +(150))
    gameDisplay.blit(textSurf,textBox)

and the code for the scoring is:

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

    if event.type == pygame.MOUSEBUTTONDOWN:
        score+=1
        print (score)

I would like have a score that – upon pressing the correct button in the choices in order to answer in a quiz game – will be displayed and incremented by 1. How can I do that?

1条回答
The star\"
2楼-- · 2019-03-02 11:38

Here's the simplest way to implement a button that I know. Create a rect for the button and draw it with pygame.draw.rect (or blit an image). For the collision detection, check if the event.pos of a pygame.MOUSEBUTTONDOWN event collides with the rect and then just increment the score variable.

import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))

GRAY = pg.Color('gray15')
BLUE = pg.Color('dodgerblue1')


def main():
    clock = pg.time.Clock()
    font = pg.font.Font(None, 30)
    button_rect = pg.Rect(200, 200, 50, 30)

    score = 0
    done = False

    while not done:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                done = True
            if event.type == pg.MOUSEBUTTONDOWN:
                if event.button == 1:
                    if button_rect.collidepoint(event.pos):
                        print('Button pressed.')
                        score += 1

        screen.fill(GRAY)
        pg.draw.rect(screen, BLUE, button_rect)
        txt = font.render(str(score), True, BLUE)
        screen.blit(txt, (260, 206))

        pg.display.flip()
        clock.tick(30)


if __name__ == '__main__':
    main()
    pg.quit()

Addendum: Actually, I would implement a button with the help of classes, sprites and sprite groups. If you don't know how classes and sprites work, I'd recommend to check out Program Arcade Games (chapter 12 and 13).

import pygame as pg


pg.init()
GRAY= pg.Color('gray12')
BLUE = pg.Color('dodgerblue1')
FONT = pg.font.Font(None, 30)


# The Button is a pygame sprite, that means we can add the
# instances to a sprite group and then update and render them
# by calling `sprite_group.update()` and `sprite_group.draw(screen)`.
class Button(pg.sprite.Sprite):

    def __init__(self, pos, callback):
        pg.sprite.Sprite.__init__(self)
        self.image = pg.Surface((50, 30))
        self.image.fill(BLUE)
        self.rect = self.image.get_rect(topleft=pos)
        self.callback = callback

    def handle_event(self, event):
        """Handle events that get passed from the event loop."""
        if event.type == pg.MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                print('Button pressed.')
                # Call the function that we passed during the
                # instantiation. (In this case just `increase_x`.)
                self.callback()


class Game:

    def __init__(self):
        self.screen = pg.display.set_mode((800, 600))
        self.clock = pg.time.Clock()

        self.x = 0
        self.button = Button((200, 200), callback=self.increase_x)
        self.buttons = pg.sprite.Group(self.button)
        self.done = False

    # A callback function that we pass to the button instance.
    # It gets called if a collision in the handle_event method
    # is detected.
    def increase_x(self):
        """Increase self.x if button is pressed."""
        self.x += 1

    def run(self):
        while not self.done:
            self.handle_events()
            self.run_logic()
            self.draw()
            self.clock.tick(30)

    def handle_events(self):
        for event in pg.event.get():
            if event.type == pg.QUIT:
                self.done = True

            for button in self.buttons:
                button.handle_event(event)

    def run_logic(self):
        self.buttons.update()

    def draw(self):
        self.screen.fill(GRAY)
        self.buttons.draw(self.screen)
        txt = FONT.render(str(self.x), True, BLUE)
        self.screen.blit(txt, (260, 206))

        pg.display.flip()


if __name__ == "__main__":
    Game().run()
    pg.quit()
查看更多
登录 后发表回答