在上一节中,我们给图形盖上了盖子,这一节,我们要实现点击鼠标,打开盖子的任务,分以下几个步骤完成:
- 检测鼠标是否按下
- 判断鼠标按下的位置是否有图形
- 判断这个图形位置是否有盖子
- 如果有盖子,打开盖子
- 修改盖子状态
(1) 检测鼠标是否按下
通过获取pygame event,并检测类型是否为MOUSEBUTTONUP,代码如下:
mouseClicked = False
...
...
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
mouseClicked = True
(2)判断鼠标按下的位置是否有图形
这里我们用一个函数完成, 方法是为每一个盒子都创建一个boxrect, 然后逐一去和鼠标按下位置进行碰撞检测, 如果有碰撞, 则返回这个盒子的行列位置, 否则返回None
def getBoxAtPixel(x, y):
for boxx in range(BOARD_WIDTH):
for boxy in range(BOARD_HEIGHT):
left, top = leftTopCoordsOfBox(boxx, boxy)
boxRect = pygame.Rect(left, top, BOXSIZE, BOXSIZE)
if boxRect.collidepoint(x, y):
return (boxx, boxy)
return (None, None)
(3)判断这个图形位置是否有盖子
因为之前创建的revealedBoxes二维数组记录了盖子信息,所以可以通过判断revealedBoxes[boxx][boxy]的真假来完成
if not revealedBoxes[boxx][boxy] ...
(4) 如果有盖子, 打开盖子,并修改盖子信息 打开盖子涉及重新绘制图形, 我们用函数来完成
def revealBoxesAction(displaysurf, board, box, fpsclock):
left, top = leftTopCoordsOfBox(box[0], box[1])
pygame.draw.rect(displaysurf, BGCOLOR, (left, top, BOXSIZE, BOXSIZE))
shape, color = getShapeAndColor(board, box[0], box[1])
drawIcon(displaysurf,shape, color, box[0], box[1])
pygame.display.update()
fpsclock.tick(FPS)
修改盖子信息
revealedBoxes[boxx][boxy] = True
(5)完整代码
def main():
pygame.init()
fpsclock = pygame.time.Clock()
displaysurf = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Memory Game")
displaysurf.fill(BGCOLOR)
board = getRandomizedBoard()
revealedBoxes = generateRevealedBoxesData(False)
while True:
mouseClicked = False
displaysurf.fill(BGCOLOR)
drawBoard(displaysurf, board, revealedBoxes)
for event in pygame.event.get():
if __name__ == '__main__':
if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
mouseClicked = True
if mouseClicked:
boxx, boxy = getBoxAtPixel(mousex, mousey)
if boxx != None and boxy != None:
if not revealedBoxes[boxx][boxy] and mouseClicked:
revealBoxesAction(displaysurf, board, (boxx, boxy), fpsclock)
revealedBoxes[boxx][boxy] = True
pygame.display.update()
fpsclock.tick(FPS)
运行程序, 当点击盒子时, 会翻开盖子.