Pygame实现记忆拼图游戏14

发布于:2025-03-22 ⋅ 阅读:(20) ⋅ 点赞:(0)

《Pygame实现记忆拼图游戏13》中实现鼠标点击图案后会显示图案的功能,接下来实现的是比较两个图案是否相同的功能,如果相同,则会一直显示这两个图案,否则在显示了这两个不同的图案之后,会遮盖这两个图案,如图1所示。

图1 比较两个选中的图案

实现以上功能的步骤是:首先判断用户是第一次选中图案还是第二次选中图案,如果是第一次选中,则记录该图案;如果用户是第二次选中图案,接下来则获取这两次选择图案的形状和颜色,并进行比较(选中这两个图案,此时图案就会显示);如果两次选择的形状和颜色不同,最后遮盖这两个图案,等待用户继续选择。

1 判断用户是第一次选中图案还是第二次选中图案

在main()函数中,接着《Pygame实现记忆拼图游戏13》中提到的代码,判断用户是第一次选中图案还是第二次选中图案,如图2所示。

图2 判断用户是第一次选中图案还是第二次选中图案的代码

其中,第40行代码中判断第一次选择的标志firstSelection是否是None,如果是则说明是第一次选择,此时通过第41行代码记录第一次选中图案的列数boxx和行数boxy。第一次选择的标志firstSelection在while True循环之外定义,初始值是None。

2 获取两次选择图案的形状和颜色

如果用户是第二次选择图案,则获取两次选择图案的形状和颜色,代码如图3所示。

图3 获取两次选择图案的形状和颜色的代码

其中,第42行代码中的else与图2中的if匹配,表示用户是第二次选择图案;第43-44行代码通过自定义函数getShapeAndColor()获取第一次选择图案的形状和颜色;第45-48行代码获取第二次选择图案的形状和颜色。

相关链接1 自定义函数getShapeAndColor()的相关资料,请参考

《Pygame实现记忆拼图游戏6》

3 遮盖选中的图案

接下来比较两个图案的形状和颜色,如果不相同,则将这两个图案遮盖(因为选中后这两个图案就显示了),如果相同,则不进行任何处理(因为选中后这两个图案就显示了)。代码如图4所示。

题4 遮盖选中图案的代码

其中,第48行代码比较两个图案的形状和颜色;如果不相同,第50行代码首先监听1秒钟;第51-53行代码通过自定义函数coverBoxesAnimation()遮盖选中的两个颜色;第54-55行代码将这两个图案的状态恢复为“遮盖”;第56行代码将第一次选择的标志firstSelection恢复为None。

相关链接2 自定义函数coverBoxesAnimation()的相关资料,请参考

《Pygame实现记忆拼图游戏9》

4 完整代码

添加上述功能后的完整代码如下所示。

import pygame
import os
from pygame.locals import *
import random

def main():
    global DISPLAYSURF
    global FPSCLOCK
    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT))
    pygame.display.set_caption('Memory Puzzle')
    
    mainBoard = getRandomizedBoard()
    revealedBoxes = generateRevealedBoxesData(False)
    startGameAnimation(mainBoard)
    mousex = 0 
    mousey = 0
    firstSelection = None
    while True:
        mouseClicked = False
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                os.sys.exit()
            elif event.type == MOUSEMOTION:
                mousex, mousey = event.pos
            elif event.type == MOUSEBUTTONUP:
                mousex, mousey = event.pos
                mouseClicked = True

        boxx, boxy = getBoxAtPixel(mousex, mousey)
        DISPLAYSURF.fill(BGCOLOR)
        drawBoard(mainBoard, revealedBoxes)
        if boxx != None and boxy != None:
            if not revealedBoxes[boxx][boxy]:
                drawHighlightBox(boxx, boxy)
            if not revealedBoxes[boxx][boxy] and mouseClicked:
                revealBoxesAnimation(mainBoard, [(boxx, boxy)])
                revealedBoxes[boxx][boxy] = True
                if firstSelection == None: 
                    firstSelection = (boxx, boxy)
                else: 
                    icon1shape, icon1color = getShapeAndColor(mainBoard,\
                                                        firstSelection[0], \
                                                        firstSelection[1])
                    icon2shape, icon2color = getShapeAndColor(mainBoard, \
                                                              boxx, \
                                                              boxy)
                    if icon1shape != icon2shape or icon1color != icon2color:
                        pygame.time.wait(1000)
                        coverBoxesAnimation(mainBoard, \
                                     [(firstSelection[0], firstSelection[1]), \
                                      (boxx, boxy)])
                        revealedBoxes[firstSelection[0]][firstSelection[1]] = False
                        revealedBoxes[boxx][boxy] = False
                    firstSelection = None
        pygame.display.update()

def getBoxAtPixel(x, y):
    for boxx in range(BOARDWIDTH):
        for boxy in range(BOARDHEIGHT):
            left, top = leftTopCoordsOfBox(boxx, boxy)
            boxRect = pygame.Rect(left, top, BOXSIZE, BOXSIZE)
            if boxRect.collidepoint(x, y):
                return (boxx, boxy)
    return (None, None)

def drawHighlightBox(boxx, boxy):
    left, top = leftTopCoordsOfBox(boxx, boxy)
    pygame.draw.rect(DISPLAYSURF, HIGHLIGHTCOLOR, \
                     (left - 5, top - 5, BOXSIZE + 10, BOXSIZE + 10), 4)
    
def getRandomizedBoard():
    icons = []
    for color in ALLCOLORS:
        for shape in ALLSHAPES:
            icons.append( (shape, color) )
            
    random.shuffle(icons) 
    numIconsUsed = int(BOARDWIDTH * BOARDHEIGHT / 2) 
    icons = icons[:numIconsUsed] * 2 
    random.shuffle(icons)

    board = []
    for x in range(BOARDWIDTH):
        column = []
        for y in range(BOARDHEIGHT):
            column.append(icons[0])
            del icons[0] 
        board.append(column)
    return board

def startGameAnimation(board):
    coveredBoxes = generateRevealedBoxesData(False)
    drawBoard(board, coveredBoxes)

    boxes = []
    for x in range(BOARDWIDTH):
        for y in range(BOARDHEIGHT):
            boxes.append( (x, y) )
    random.shuffle(boxes)
    boxGroups = splitIntoGroupsOf(8, boxes)
    for boxGroup in boxGroups:
        revealBoxesAnimation(board, boxGroup)
        coverBoxesAnimation(board, boxGroup)
                                    
def revealBoxesAnimation(board, boxesToReveal):
    for coverage in range(BOXSIZE, (-REVEALSPEED) - 1, -REVEALSPEED):
        drawBoxCovers(board, boxesToReveal, coverage)

def coverBoxesAnimation(board, boxesToCover):
    for coverage in range(0, BOXSIZE + REVEALSPEED, REVEALSPEED):
        drawBoxCovers(board, boxesToCover, coverage)
        
def drawBoxCovers(board, boxes, coverage):
    for box in boxes:
        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(shape, color, box[0], box[1])
        if coverage > 0: 
            pygame.draw.rect(DISPLAYSURF, BOXCOLOR, \
                             (left, top, coverage, BOXSIZE))
    pygame.display.update()
    FPSCLOCK.tick(FPS)
    
def splitIntoGroupsOf(groupSize, theList):
    result = []
    for i in range(0, len(theList), groupSize):
        result.append(theList[i:i + groupSize])
    return result

def leftTopCoordsOfBox(boxx, boxy):
    left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN
    top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN
    return (left, top)

def drawBoard(board, revealed):
    for boxx in range(BOARDWIDTH):
        for boxy in range(BOARDHEIGHT):
            left, top = leftTopCoordsOfBox(boxx, boxy)
            if not revealed[boxx][boxy]:
                pygame.draw.rect(DISPLAYSURF, BOXCOLOR, \
                                 (left, top, BOXSIZE, BOXSIZE))
            else:
                shape, color = getShapeAndColor(board, boxx, boxy)
                drawIcon(shape, color, boxx, boxy)
                
def generateRevealedBoxesData(val):
    revealedBoxes = []
    for i in range(BOARDWIDTH):
        revealedBoxes.append([val] * BOARDHEIGHT)
    return revealedBoxes

def getShapeAndColor(board, boxx, boxy):
    return board[boxx][boxy][0], board[boxx][boxy][1]
def drawIcon(shape, color, boxx, boxy):
    quarter = int(BOXSIZE * 0.25) 
    half =    int(BOXSIZE * 0.5)  

    left, top = leftTopCoordsOfBox(boxx, boxy) 
    if shape == DONUT:
        pygame.draw.circle(DISPLAYSURF, color, \
                           (left + half, top + half), half - 5)
        pygame.draw.circle(DISPLAYSURF, BGCOLOR, \
                           (left + half, top + half), quarter - 5)
    elif shape == SQUARE:
        pygame.draw.rect(DISPLAYSURF, color, \
            (left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half))
    elif shape == DIAMOND:
        pygame.draw.polygon(DISPLAYSURF, color, \
                            ((left + half, top), \
                             (left + BOXSIZE - 1, top + half), \
                             (left + half, top + BOXSIZE - 1), \
                             (left, top + half)))
    elif shape == LINES:
        for i in range(0, BOXSIZE, 4):
            pygame.draw.line(DISPLAYSURF, color,\
                             (left, top + i), (left + i, top))
            pygame.draw.line(DISPLAYSURF, color, \
                             (left + i, top + BOXSIZE - 1), \
                             (left + BOXSIZE - 1, top + i))
    elif shape == OVAL:
        pygame.draw.ellipse(DISPLAYSURF, color, \
                            (left, top + quarter, BOXSIZE, half))
pygame.init()
WINDOWWIDTH = 640 
WINDOWHEIGHT = 480

BOARDWIDTH = 10 
BOARDHEIGHT = 7
assert (BOARDWIDTH * BOARDHEIGHT) % 2 == 0, \
           'Board needs to have an even number of boxes for pairs of matches.'

BOXSIZE = 40
GAPSIZE = 10
REVEALSPEED = 8
FPS = 30
XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2)
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2)

GRAY     = (100, 100, 100)
NAVYBLUE = ( 60,  60, 100)
WHITE    = (255, 255, 255)
RED      = (255,   0,   0)
GREEN    = (  0, 255,   0)
BLUE     = (  0,   0, 255)
YELLOW   = (255, 255,   0)
ORANGE   = (255, 128,   0)
PURPLE   = (255,   0, 255)
CYAN     = (  0, 255, 255)

DONUT = 'donut'
SQUARE = 'square'
DIAMOND = 'diamond'
LINES = 'lines'
OVAL = 'oval'

BGCOLOR = NAVYBLUE
BOXCOLOR = WHITE
HIGHLIGHTCOLOR = BLUE

ALLCOLORS = (RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN)
ALLSHAPES = (DONUT, SQUARE, DIAMOND, LINES, OVAL)
assert len(ALLCOLORS) * len(ALLSHAPES) * 2 >= BOARDWIDTH * BOARDHEIGHT, \
                "Board is too big for the number of shapes/colors defined."

if __name__ == '__main__':
    main()