如何在Pygame中制作弹出式放射状菜单?

时间:2013-11-28 11:05:17

标签: python menu popup pygame radial

我想知道是否有人可以就如何创建带有选项的径向菜单给出任何建议,例如:当你点击游戏中的一个物体时,“攻击”,“说话”会自动弹出......有点像许多策略/ RPG游戏中使用的径向菜单等。

我对Python / Pygame很陌生,所以请尽可能完整地解释。

提前致谢, Ilmiont

2 个答案:

答案 0 :(得分:2)

我最近在我正在编程的一个游戏中使用过它。 所以你需要做的就是检查sprite / object的点击。

#example
def make_popup(self):
    popupSurf = pygame.Surface(width, height)
    options = ['Attack',
               'Talk']
    for i in range(len(options)):
        textSurf = BASICFONT.render(options[i], 1, BLUE)
        textRect = textSurf.get_rect()
        textRect.top = self.top
        textRect.left = self.left
        self.top += pygame.font.Font.get_linesize(BASICFONT)
        popupSurf.blit(textSurf, textRect)
    popupRect = popupSurf.get_rect()
    popupRect.centerx = SCREENWIDTH/2
    popupRect.centery = SCREENHEIGHT/2
    DISPLAYSURFACE.blit(popupSurf, popupRect)
    pygame.display.update()

现在好了解释一下以及它是如何工作的。

popupSurf = pygame.Surface这一行创建了popupSurf作为绘制内容的表面。

选项非常自我解释。然后我们有一个for循环,它将采用所有选项并单独显示每个选项。接下来是textSurf = BASICFONT ... BASICFONT是你在开始时创建的字体,我个人最喜欢使用SysFont,因为它很容易与py2exe一起使用。

然后是textRect,这会创建一个矩形,在将文本blit到屏幕时使用。然后将顶部坐标更改为当前顶部坐标。然后你在左边做同样的事情。然而,下一行'self.top + = ...'是为了调整先前blit到屏幕的文本,所以你最终不会在文本上面添加文本。 然后你只需将它blit到popupSurf。

在弹出每个选项到popupSurf后,你需要将popupSurf blit到你的主表面,这是在程序开头使用'pygame.display.set_mode'创建的。从您给出的所有信息中,假设您希望弹出窗口显示在屏幕的中央,这样我就可以使用centerx和centery并将它们置于屏幕中心。然后剩下要做的就是将它blit到屏幕并更新显示。如果您不完全理解,请发表评论。

答案 1 :(得分:1)

要做到这一点,只需让while循环不断检查鼠标的位置,然后检查要点击的鼠标。单击鼠标后,检查选择了哪个选项,如果选项None退出弹出菜单。

#example
def doPopup(self):
    #popup loop
    while True:
        #draw the popup
        make_popup(self)
        #check for keyboard or mouse events
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == MOUSEMOTION:
                #update mouse position
                self.mousex, self.mousey = event.pos
            #check for left click
            elif event.type == MOUSEBUTTONDOWN and event.button == 1:
                OPTION = option_selected(self)
                if OPTION != None:
                    return OPTION'
                else:
                    return None
        FPSCLOCK.tick(FPS)

def option_selected(self):
    popupSurf = pygame.Surface(width, height)
    options = ['Attack',
               'Talk']
    #draw up the surf, but don't blit it to the screen
    for i in range(len(options)):
        textSurf = BASICFONT.render(options[i], 1, BLUE)
        textRect = textSurf.get_rect()
        textRect.top = self.top
        textRect.left = self.left
        self.top += pygame.font.Font.get_linesize(BASICFONT)
        popupSurf.blit(textSurf, textRect)
        if textSurf.collidepoint(self.mousex, self.mousey):
            return options[i]
    popupRect = popupSurf.get_rect()
    popupRect.centerx = SCREENWIDTH/2
    popupRect.centery = SCREENHEIGHT/2