代码之家  ›  专栏  ›  技术社区  ›  tijko

鼠标“点击”时的Pygame操作。rect?

  •  6
  • tijko  · 技术社区  · 14 年前

    我一直在编写一个测试函数,以了解鼠标在pygame.rect上的“点击”操作将如何产生响应。

    到目前为止:

    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
    

    我在谷歌上看到过一些页面,人们正在使用或建议使用 pygame.sprite.Sprite 我想这就是我的问题所在。我已经检查了pygames文档,方法之间没有太多的衔接,imho。我显然错过了一些简单的事情,但是,我想 get_rect 会让pygames中的图像在按下时能够检查鼠标位置是否在其上方吗?

    编辑: 我想我需要打电话给 pygame.sprite.sprite游戏 如何使图像/矩形交互?

    2 回复  |  直到 12 年前
        1
  •  18
  •   tijko    12 年前

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

    首先,删除:

    button = button.get_rect()
    

    然后:

    screen.blit(button, (300, 200))
    

    应为:

    b = screen.blit(button, (300, 200))
    

    这是为了创建 Rect 按钮在屏幕上所处的区域。

    发送到:

    if event.type == pygame.mouse.get_pressed()
    

    我改为:

    if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
    

    这个 pygame.mouse.get_pressed() 获取所有三个鼠标按钮(MOUSEBUTTONDOWN、MOUSEBUTTONUP或MOUSEMOTION)的状态。我还需要添加 event.button == 1 指定这是正在按下的“鼠标左键”。

    最后:

    `if button.collidepoint(pos):` 
    

    收件人:

    `if b.collidepoint(pos):`
    

    使用 Rect公司 b碰撞点法

        2
  •  2
  •   ivan133    12 年前

    我认为rect方法调用collapsepoint,而不是collapse* r *点。 这是 link 到文档!

    推荐文章