pygame中按钮如何出现在屏幕上

时间:2019-10-30 11:53:28

标签: python pygame

我正在学习pygame,但是遇到了bug。我已经编写了按钮代码,并添加了更新屏幕功能,还编写了可以在您按下该按钮时启动游戏的功能。问题是您可以单击按钮应在的位置,游戏将开始,但按钮不会出现。 以下是按钮类中发生的功能:

def prep_msg(self, msg): #takes place in __init__
    self.msg_image = self.font.render(msg, True, self.text_color, 
        self.button_color)
    self.msg_image_rect = self.msg_image.get_rect()
    self.msg_image_rect.center = self.rect.center

def draw_button(self):
    self.screen.fill(self.button_color, self.rect)
    self.screen.blit(self.msg_image, self.msg_image_rect)

这是更新屏幕功能:

...
if stats.game_active == False: #responsible for whether the game works or not (False = doesn't works)
    play_button.draw_button()

what happens when the game is started     pygame.display.flip()

整个代码:

def update_screen(custom_settings, screen, spaceship, 
    aliens, bullets, rockets, stars, background, play_button, stats):
    screen.fill(custom_settings.bg_color)
    screen.blit(background.image, background.rect)
    for bullet in bullets.sprites(): #returns list of sprites in the group
        bullet.draw_bullet() 
    for rocket in rockets.sprites():
        rocket.draw_rocket()
    stars.draw(screen)
    aliens.draw(screen)
    spaceship.blitme()
    if stats.game_active == False:
        play_button.draw_button()
    pygame.display.flip()

def __init__(self, custom_settings): #initialize the statistics
    self.custom_settings = custom_settings
    self.reset_stats()
    self.game_active = False

class Button():

def __init__(self, custom_settings, screen, msg):
    self.screen = screen
    self.screen_rect = screen.get_rect()

    self.width, self.height = 200, 50
    self.button_color = (0, 255, 0)
    self.text_color = (255,255,255)
    self.font = pygame.font.SysFont(None, 48) #type of font, the size of font

    self.rect = pygame.Rect(0,0, self.width, self.height)
    self.rect.center = self.screen_rect.center

    self.prep_msg(msg) #button's message creates just once

这是主循环:

while True:
    gf.check_events(custom_settings, screen, spaceship, bullets, 
        rockets, play_button, stats)
    if stats.game_active:
        spaceship.update()
        bullets.update()
        rockets.update()
        gf.update_ammunition(bullets, rockets, aliens, custom_settings, screen, spaceship)
        gf.update_aliens(custom_settings, aliens, screen, spaceship, stats, bullets)
        gf.create_fleet(custom_settings, screen, spaceship, aliens)
        gf.check_collisions(custom_settings, screen, spaceship, aliens, bullets, rockets)
        #gf.starsky(custom_settings, screen, spaceship, stars)
        gf.update_screen(custom_settings, screen, spaceship, aliens, bullets, rockets, 
            stars, background, play_button, stats)
        clock.tick(FPS)
        print(clock.get_fps())

0 个答案:

没有答案