Python 2.7 如何在Pygame中实现按钮点击功能?

Python 2.7 如何在Pygame中实现按钮点击功能?,python-2.7,pygame,Python 2.7,Pygame,当用户在我的游戏中失败后,我想在屏幕上显示一个游戏,该屏幕上有一个重新启动按钮/重新启动图像,当用户用鼠标单击游戏时,该图像将重新启动游戏 我不知道如何在我的代码中实现这个鼠标点击功能 对于我的游戏,我有一个game()类,包含方法processEvents(),runLogic()和displayFrame()。我在main()的while循环中运行这些方法 在Game()类的\uuuu init\uuuu()方法中,我有一个属性self.gameOver=False。当self.gameOv

当用户在我的游戏中失败后,我想在屏幕上显示一个游戏,该屏幕上有一个重新启动按钮/重新启动图像,当用户用鼠标单击游戏时,该图像将重新启动游戏

我不知道如何在我的代码中实现这个鼠标点击功能

对于我的游戏,我有一个
game()
类,包含方法
processEvents()
runLogic()
displayFrame()
。我在
main()
while
循环中运行这些方法

Game()
类的
\uuuu init\uuuu()
方法中,我有一个属性
self.gameOver=False
。当
self.gameOver
变为
True
时,
runLogic()
函数不运行,而是
displayFrame()
调用一个函数,
gameOver(display)
,在屏幕上显示游戏

def displayFrame(self, display, background):

    if self.gameOver:
        gameOver(display)

    if not self.gameOver:
        display.blit(background, (0, 0))
        self.allsprites.update()
        self.allsprites.draw(display)

    pygame.display.flip()
gameOver(显示)
功能显示一个重启按钮

def gameOver(display):
    # loadImage returns (image, image.get_rect())
    restartImage = utility.loadImage("restart.png")
    display.blit(restartImage[0], (320, 250))
我希望这样,当用户单击此
重新启动图像时,游戏将重新启动

我知道我必须在
processEvents()
函数中处理mouseclick

def processEvents(self):
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            # need to use collidepointrect function
            # don't know how to implement!
    return False
理想情况下,我将有一个类似这样的函数

def isButtonClicked(mousepos, button):
    return button.collidepoint(mousepos)
processEvents
函数中,我只需要

if self.isButtonClicked(pos, restartImage[1]):
    # restart the game 
    self.__init__()
但是,我不能直接传入
重新启动图像
,因为它是在
gameOver(display)
中创建的。因此,我不确定如何构造代码,以便
processEvents
可以处理鼠标单击我在另一个函数中创建的图像/按钮

def processEvents(self):
    for event in pygame.event.get():
        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            # need to use collidepointrect function
            # don't know how to implement!
    return False

任何帮助都将不胜感激。对不起,如果我的解释有点复杂的话。我觉得有必要解释我的代码结构,因为我的问题更多的是关于如何逻辑地编写代码,而不是使用什么方法。

不要运行
self.\uu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu()
-创建函数
reset\u
以及何时重新启动游戏。
gameOver
很奇怪,它在一秒钟内执行了数千次,而你加载了无数次图像。你不能只加载一次图像吗?也许你应该把类
Game()
分成两个类
Game
GameOver
,它们有自己的函数
processEvents
runLogic
displayFrame
,这样它们就可以更好地控制函数中的元素了——就像这样。或者,当游戏结束时,您应该替换变量
game
中的类,以使用不同的
processEvents
runLogic
displayFrame
。不要运行
self.\uuu init\uuuuuuuuuuuuuuu()
-创建函数
reset\u data()
,该函数在开始时设置所有值,并在
中使用它
以及何时重新启动游戏。
gameOver
很奇怪,它在一秒钟内执行了数千次,而你加载了无数次图像。你不能只加载一次图像吗?也许你应该把类
Game()
分成两个类
Game
GameOver
,它们有自己的函数
processEvents
runLogic
displayFrame
,这样它们就可以更好地控制函数中的元素了——就像这样。或者,您应该在变量
game
中替换类,以便在游戏结束时使用不同的
processEvents
runLogic
displayFrame