在用户输入游戏后,我希望显示一个游戏结束屏幕,其中包含重启按钮/重启图像,当用户用鼠标点击游戏时重启游戏。
我不知道如何在我的代码中实现此鼠标单击功能。
对于我的游戏,我有一个Game()
课程,其中包含processEvents()
,runLogic()
和displayFrame()
等方法。我在while
的{{1}}循环中运行这些方法。
main()
在# loop inside of main()
# pygame, display surface - called screen, already initialized
while not gameExit:
gameExit = game.processEvents()
game.runLogic()
game.displayFrame(screen, background)
类的__init__()
方法中,我有一个属性Game()
。当self.gameOver = False
变为self.gameOver
时,True
函数不会运行,而是runLogic()
会调用显示游戏结束屏幕的函数displayFrame()
。< / p>
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(display)
我想这样做,当用户点击此def gameOver(display):
# loadImage returns (image, image.get_rect())
restartImage = utility.loadImage("restart.png")
display.blit(restartImage[0], (320, 250))
时,游戏会重新启动。
我知道我必须在restartImage
函数中处理鼠标点击。
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
isButtonClicked
在def isButtonClicked(mousepos, button):
return button.collidepoint(mousepos)
函数中,我只是做
processEvents
但是,我无法直接传递if self.isButtonClicked(pos, restartImage[1]):
# restart the game
self.__init__()
,因为它是在restartImage
中创建的。所以,我不确定如何构造我的代码,以便gameOver(display)
可以处理鼠标点击我在另一个函数中创建的图像/按钮。
任何帮助将不胜感激。对不起,如果我的解释有点复杂。我觉得有必要解释我的代码结构,因为我的问题更多的是关于如何逻辑编写我的代码而不是使用什么方法。