I am making a memory game for an assignment. When clicking on two tiles that are not the same, only the first tile shows but the second tile does not show and immediately both the tiles are flipped. Is there a way to slow it down so that both tiles are shown before they are flipped again? I have tried using pygame.time.delay() and time.sleep() but nothing seems to work.
class Game:
def handle_mouse_up(self, position):
# handles the events that take place when the mouse button is clicked
# - self is the Game
# - position is the position where the mouse button is clicked
if len(self.flipped) < 2:
for row in self.board:
for tile in row:
if tile.select(position) and not tile.covered:
self.flipped.append(tile)
if len(self.flipped) == 2:
self.check_matching()
def check_matching(self):
# checks whether both the tiles which are flipped are matching or not
# - self is the Game
if self.flipped[0].same_tiles(self.flipped[1]):
self.flipped[0].show_tile()
self.flipped[1].show_tile()
self.flipped.clear()
else:
self.flipped[0].hide_tile()
self.flipped[1].hide_tile()
self.flipped.clear()
class Tile:
def show_tile(self):
# shows the tile which is clicked
# - self is the Tile
self.covered = False
def hide_tile(self):
# hides the tile which is not clicked
# - self is the Tile
self.covered = True
def select(self, mouse_position):
# checks whether a tile has been clicked on or not
# - self is the Tile
# - mouse_position is the position where the mouse is clicked
mouse_click = False
if self.rect.collidepoint(mouse_position):
if self.covered:
mouse_click = True
self.show_tile()
else:
mouse_click = False
return mouse_click
def same_tiles(self, other_tile):
# checks whether both the tiles are same
# - self is the Tile
# - other_tile is the second tile which is flipped
return self.image == other_tile.image
Change the method hide tiles. Don't hide the tiles, but compute the time when the tile has to be hidden. Use pygame.time.get_ticks()
to return the number of milliseconds since pygame.init()
was called. Calculate the point in time after that the image has to be hidden. Add a method that evaluates if the time has exceeded and the tile has to be hidden
class Tile:
def __init__(self):
self.hide_time = None
# [...]
def hide_tile(self):
self.hide_time = pygame.time.get_ticks() + 1000 # 1000 milliseconds == 1 second
def hide_timed(self):
if self.hide_time != None and self.hide_time < pygame.time.get_ticks()
self.covered = True
self.hide_time = None
Add a method to Game
that evaluate whether the tiles need to be hidden:
class Game:
# [...]
def hide_timed(self):
for row in self.board:
for tile in row:
tile.hide_timed()
Call hide_timed
in the application loop in every frame.