How draw button in window in pygame

Viewed 111

I have this code in my program, if I click on the choosen area that the server start new game. How to do it that in this place will be button or a square with text 'new game'?

with socket.create_connection((SERVER, PORT)) as sock:
    with context.wrap_socket(sock, server_hostname="localhost") as client:
        session_id = None
        while True:
            #command = str(input("Podaj komendę"))
            #command = translate_pos_to_number(pos[0] // 200, pos[1] // 200)
            czy_wyjsc = True
            while czy_wyjsc:
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        running = False
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        if pygame.mouse.get_pressed()[0]:  # [0] Jeśli lewy przycisk myszki jest kliknięty
                            pos = pygame.mouse.get_pos()
                            print(pos[0] // 200, pos[1] // 200)
                            czy_wyjsc = False
                            break
                surface.fill((20, 189, 172))

                grid.draw(surface)

                pygame.display.flip()

            if (pos[0] // 200 == 1, pos[1] // 200 == 3):
                command = "start"
                if command == "start":
                    login = np.random.randint(100, 999)
                    msg_start = f'To:SER\r\nLogin:{login}\r\nContent-length:5\r\nMessage:START\r\n\r\n'
                    client.sendall(msg_start.encode())
1 Answers


To create a button in pygame, you first need to add a font to your python program and then, create a label to show some text in that button:

font = pygame.font.SysFont("monospace", 30)
label = font.render("SomeText", 1, [COLOR])

After that, you need to create a rectangle on your screen:

pygame.draw.rect(YOUR_SCREEN, YOUR_COLOR ,(X_POS,Y_POS,X_SIZE,Y_SIZE),1)
YOUR_SCREEN.blit(label,(X_POS,Y_POS))

And after that, you only need to add the collision in your pygame events:

for events in pygame.event.get():
        if events.type == pygame.QUIT:
            pygame.quit()
        if events.type == pygame.MOUSEBUTTONDOWN:
                if pygame.Rect(X_POS,Y_POS,X_SIZE,Y_SIZE).collidepoint(pygame.mouse.get_pos()):
                    Your_Function() #Your_Function is the function you want to execute when clicking the button.

I hope I helped you ! (and if you have any questions, feel free to ask)

Related