2

我想知道是否有人可以就如何创建带有选项的径向菜单给我任何建议,例如“攻击”、“谈话”,当您单击游戏中的对象时会自动弹出……有点像使用的径向菜单在众多策略/RPG游戏等中。

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

提前致谢, 伊尔蒙

4

2 回答 2

2

实际上,我最近在我正在编程的一个游戏中使用了它。所以你通常需要做的是检查精灵/对象的点击。

#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,这会创建一个矩形,以便在将文本传送到屏幕时使用。然后将顶部坐标更改为当前顶部坐标。然后你在左边做同样的事情。然而,下一行 'self.top += ...' 是为了调整之前在屏幕上显示的文本,这样你就不会以文本覆盖文本结束。然后你只需将它粘贴到popupSurf。

在每个选项被 blitted 到 popupSurf 之后,您需要将 popupSurf 到您的主表面,该表面是在程序开始时使用“pygame.display.set_mode”创建的。根据您提供的所有信息,假设您希望弹出窗口出现在屏幕中央,因此我将 centerx 和 centery 放在屏幕中央。然后剩下要做的就是将它blit到屏幕上并更新显示。如果您不完全理解,请发表评论。

于 2013-11-29T05:47:20.963 回答
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
于 2013-12-23T05:19:33.753 回答