new with pygame. My button doesnt work. why? [duplicate]

坚强是说给别人听的谎言 提交于 2021-02-05 12:23:26

问题


Ignore AmountOfPlayers() function. Im new with pygame and my button doesn't do anything. why? How can I improve my code with pygame?

while True:
    pygame.init()
    size=(1440,810)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("POCKER SFAHOT")
    welcomeimage = 'welcome.png'
    imgwelcome = pygame.image.load(welcomeimage)
    screen.blit(imgwelcome, (0,0))
    pygame.display.flip()
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse = pygame.mouse.get_pos()
            if (300 <= mouse[0] <= 1150) and (600 <= mouse[1] <= 470):
                AmountOfPlayers()
    pygame.event.get()

回答1:


The condition 600 <= mouse[1] <= 470 is always False, because 600 is never less than 470. It has to be 470 <= mouse[1] <= 600:

if (300 <= mouse[0] <= 1150) and (600 <= mouse[1] <= 470):

if (300 <= mouse[0] <= 1150) and (470 <= mouse[1] <= 600):

However, I recommend using pygame.Rect and collidepoint(). See the example:

import pygame

pygame.init()
size=(1440,810)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("POCKER SFAHOT")
welcomeimage = 'welcome.png'
imgwelcome = pygame.image.load(welcomeimage).convert_alpha()

welcome = True
run = True

while run:
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

        if event.type == pygame.MOUSEBUTTONDOWN:
            rect = pygame.Rect(300, 370, 850, 130)
            if welcome and rect.collidepoint(event.pos):
                welcome = False
                
    if welcome:
        screen.blit(imgwelcome, (0,0))
    else:
        screen.fill(0)
        AmountOfPlayers()
    
    pygame.display.flip()

pygame.quit()
exit()



回答2:


You need to initialize pygame only once, but call pygame.init() in the event loop. Move all initialization before while True: loop and leave only the code that handles events in the loop.



来源:https://stackoverflow.com/questions/64992901/new-with-pygame-my-button-doesnt-work-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!