0

So I just wanna get some words written in the centre of the rectangles like 'Play Game' or something like that and I'm not exactly sure what to really do.

def drawText(text, x, y, fSize):
    screen_text = pygame.font.SysFont("Calibri", fSize, True).render(text, True, (0, 0, 0))
    rect = screen_text.get_rect()
    rect.center = ((screen_side_length // 2) + x), ((screen_side_length // 2) + y)
    screen.blit(screen_text, rect)

def main_menu():
    user_choice = None
    while user_choice == None:
        screen.fill((255, 255, 255))
        drawText('main menu', 0, 0, 20)

        x, y = pygame.mouse.get_pos()

        button_1 = pygame.Rect(50, 100, 200, 50)
        button_2 = pygame.Rect(50, 200, 200, 50)

        pygame.draw.rect(screen, (255, 0, 0), button_1)
        pygame.draw.rect(screen, (255, 0, 0), button_2)
        
        click = False
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1:
                    click = True
                
        pygame.display.update()
        clock.tick(15)
    return user_choice

KingBo
  • 1

1 Answers1

0

You have to set the center of the text rectangle:

font = pygame.font.SysFont("Calibri", fSize, True) 

def drawTextCenter(text, centerx, centery, fSize):
    font.render(text, True, (0, 0, 0)) 
    rect = screen_text.get_rect(center = (centerx, centery))
    screen.blit(screen_text, rect)

Pass the center of the rectangle to the drawTextCenter function:

button_1 = pygame.Rect(50, 100, 200, 50)
drawTextCenter('main menu', button_1.centerx, button_1.centery, 20)

Do not create the pygame.font.Font object in every frame. Create the font once at the begin of the program. Creating a font object is very time consuming because the font file has to be read and interpreted.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174