鼠标"点击"时的Pygame动作.rect?

tij*_*jko 3 python pygame rect mouseevent

我一直在编写一个测试函数来学习pygame.rect上的鼠标"click"动作将如何产生响应.

至今:

def test():
    pygame.init()
    screen = pygame.display.set_mode((770,430))
    pygame.mouse.set_visible(1)
    background = pygame.Surface(screen.get_size())
    background = background.convert()
    background.fill((250,250,250))
    screen.blit(background, (0,0))
    pygame.display.flip()

    ## set-up screen in these lines above ##

    button = pygame.image.load('Pictures/cards/stand.png').convert_alpha()
    screen.blit(button,(300,200))
    pygame.display.flip()

    ## does button need to be 'pygame.sprite.Sprite for this? ##
    ## I use 'get_rect() ##
    button = button.get_rect()

    ## loop to check for mouse action and its position ##
    while True:
        for event in pygame.event.get():
            if event.type == pygame.mouse.get_pressed():
                ## if mouse is pressed get position of cursor ##
                pos = pygame.mouse.get_pos()
                ## check if cursor is on button ##
                if button.collidepoint(pos):
                    ## exit ##
                    return
Run Code Online (Sandbox Code Playgroud)

我在google上遇到了人们正在使用的页面,或者建议他们使用pygame.sprite.Sprite类来处理图像,我认为这是我的问题所在.我检查了pygames文档,方法之间没有太大的凝聚力,imho.我显然遗漏了一些简单的东西,但是,我认为get_rect可以让pygames中的图像能够检查按下时鼠标位置是否超过它?

编辑:我想我需要调用pygame.sprite.Sprite方法使图像/ rects交互?

tij*_*jko 13

好吧,如果有人感兴趣或有类似的问题,这就是我需要改变的.

先关闭,删除:

button = button.get_rect()
Run Code Online (Sandbox Code Playgroud)

然后:

screen.blit(button, (300, 200))
Run Code Online (Sandbox Code Playgroud)

应该:

b = screen.blit(button, (300, 200))
Run Code Online (Sandbox Code Playgroud)

这将创建Rect按钮位于屏幕上的区域.

到:

if event.type == pygame.mouse.get_pressed()
Run Code Online (Sandbox Code Playgroud)

我改为:

if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
Run Code Online (Sandbox Code Playgroud)

pygame.mouse.get_pressed()得到所有三种小鼠按钮(MOUSEBUTTONDOWN,MOUSEBUTTONUP,或MOUSEMOTION)的状态.我还需要添加event.button == 1以指定这是按下的"鼠标左键"按钮.

最后:

`if button.collidepoint(pos):` 
Run Code Online (Sandbox Code Playgroud)

至:

`if b.collidepoint(pos):`
Run Code Online (Sandbox Code Playgroud)

使用Rectb的碰撞点方法