Pygame游戏菜单查找矩形位置

时间:2018-05-04 17:24:58

标签: python pygame

class menu:
    hover = False
    def __init__(self, text, pos):
        self.text = text
        self.pos = pos
        self.set_rect()
        self.draw()

    def draw(self):
        self.set_render()
        screen.blit(self.render, self.rect)

    def set_render(self):
        self.render = subFont.render(self.text, True, self.get_color())

    def get_color(self):
        if self.hover:
            return (BLACK)
        else:
            return (GREEN)

    def set_rect(self):
        self.set_render()
        self.rect = self.render.get_rect()
        self.rect.topleft = self.pos



select = [menu("Computer Virus", (100, 200)),
          menu("Computer Crime", (100, 300)),
          menu("QUIT", (100, 400))]

running = True
while running:
    for evnt in event.get():  
        if evnt.type == QUIT:
            running = False
    screen.fill(WHITE)    
    title()
    for menu in select:
        if menu.rect.collidepoint(mouse.get_pos()):
            menu.hover = True               
        else:
            menu.hover = False
        menu.draw()
    pointer()
    display.update()

这是我的游戏菜单,其中悬停将允许您更改颜色 我打算这样做,当你点击其中一个选项,它会带你到其他地方。如何找到rect的位置以及鼠标与哪个文本碰撞?

1 个答案:

答案 0 :(得分:1)

此代码可以满足您的需求:

class menu:
    hover = False

    def __init__(self, text, pos, callback):
        self.text = text
        self.pos = pos
        self.callback = callback # so we now what function to call
        self.set_rect()
        self.draw()
    # the rest of your code

def quit_loop():
    global running
    running = False
select = [menu("Computer Virus", (100, 200), lambda: print("Computer Virus")), # Add a callback
          menu("Computer Crime", (100, 300), lambda: print("Computer Crime")),
          menu("QUIT", (100, 400), quit_loop)]

running = True
while running:
    for evnt in event.get():
        if evnt.type == QUIT:
            running = False
        if evnt.type == MOUSEBUTTONDOWN: # if a mousebutton got pressed
            if evnt.button == 1: # if the first button got pressed
                for menu in select:
                    if menu.rect.collidepoint(evnt.pos): # does this one collide
                        menu.callback() # call the callback