After a user loses in my game, I want to display a game-over screen that has a restart button/restart image that restarts the game when the user clicks on it with his/her mouse.
I don't know how to implement this mouse click functionality in my code.
For my game, I have a Game()
class, with the methods, processEvents()
, runLogic()
and displayFrame()
. I run these methods in the while
loop of main()
.
# loop inside of main()
# pygame, display surface - called screen, already initialized
while not gameExit:
gameExit = game.processEvents()
game.runLogic()
game.displayFrame(screen, background)
In the __init__()
method of the Game()
class, I have an attribute self.gameOver = False
. When self.gameOver
is becomes True
, the runLogic()
function does not run, but instead displayFrame()
calls a function, gameOver(display)
that displays the game-over screen.
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()
The gameOver(display)
function displays a restart button.
def gameOver(display):
# loadImage returns (image, image.get_rect())
restartImage = utility.loadImage("restart.png")
display.blit(restartImage[0], (320, 250))
I want to make it such that when the user clicks this restartImage
, the game restarts.
I know that I'll have to handle mouseclick in the processEvents()
function.
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
Ideally, I will have a function isButtonClicked
that goes something like this
def isButtonClicked(mousepos, button):
return button.collidepoint(mousepos)
And in the processEvents
function, I just do
if self.isButtonClicked(pos, restartImage[1]):
# restart the game
self.__init__()
HOWEVER, I cannot directly pass in restartImage
as it has been created in gameOver(display)
. So, I'm not sure how to structure my code so that processEvents
can handle a mouseclick to the image/button I created in another function.
Any help will be greatly appreciated. Sorry if my explanation is a bit convoluted. I felt it was necessary to explain my code structure, as my question is more about how to logically write my code than what methods to use.