** MemoryPuzzle 记忆拼图 **
经过前几篇的基本学习,今天就开始实战,在实战中学习,既会有成就感,还能巩固一下前面的知识
想想还有点小激动,毕竟是第一个游戏,虽然很简单,已经够我玩一下午了 ** (●'◡'●) **
(有兴趣的童鞋可以自己再加上音效,加上计时器)
** 游戏实现的思路(基本步骤)**
1,绘制一个640*480的窗口
2,在里面绘制10*7个box(方块)
3,方块的大小为 40*40,方块间的间隔为10
4,计算方块与窗口间的边距,用来确定绘制Box的具体像素坐标
5,定义一个数据结构用来存放Board中每一个Box的状态(形状,颜色)
6,根据以上条件,绘制好游戏基本的元素(Board和Box)
7,在每一个Box上面绘制一层白色的覆盖Cover
8,再定义一个数据结构用来存每一个Box对应的False/True(覆盖/揭开)状态
9,获得鼠标点击事件,鼠标点击的像素坐标
10,根据像素坐标转化成Box的坐标
11,根据Box的坐标获得其状态(形状,颜色)
12,点击后就将他揭开(状态设为True)
如果该Box是第一个点击的Box,就赋值给firstSelection
如果是第二个点击的Box,将他与第一个Box对比,如果如果形状或颜色不匹配就将其状态设为False(覆盖),匹配就检查游戏是否获胜;不管匹配不匹配,都重新设置firstSelection为None
13,游戏基本就OK了,再定义几个动画,增加游戏体验:
覆盖Box的动画
揭开Box的动画
开场动画
游戏获胜动画
(●'◡'●)
** 不多说了直接上代码 (代码量也不多300多行,基本每一行我都做了详细的注释)**
# -*- coding: UTF-8 -*-
'''
Created on 2016年11月22日
@author: 小峰峰
'''
import random, pygame, sys
from pygame.locals import *
FPS = 30 #设置帧率
WINDOWWIDTH = 640# 设置窗口的宽度
WINDOWHEIGHT = 480# 设置窗口的高度
REVEALSPEED = 8# 设置box滑动的和显示的速度
BOXSIZE = 40# 设置box的大小
GAPSIZE = 10# 设置box间的间隔
BOARDWIDTH = 10# 设置横向box的数量
BOARDHEIGHT = 7# 设置纵向box的数量
# 断言:总的box数必须能被2整除,因为要两两配对
assert (BOARDWIDTH * BOARDHEIGHT) % 2 == 0, '总的box数必须是偶数'
XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2)# 计算距离x轴边缘的距离
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2)# 计算距离y轴边缘的距离
# R G B
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)
BGCOLOR = NAVYBLUE# 设置背景色
LIGHTBGCOLOR = GRAY# 设置亮背景色
BOXCOLOR = WHITE# 设置box的颜色
HIGHLIGHTCOLOR = BLUE# 设置高亮颜色
#定义形状
DONUT = 'donut'# 甜甜圈
SQUARE = 'square'# 方形
DIAMOND = 'diamond'# 钻石
LINES = 'lines'# 多条线
OVAL = 'oval'# 椭圆
ALLCOLORS = (RED, GREEN, BLUE, YELLOW , RED , GREEN, BLUE,)
ALLSHAPES = (DONUT, SQUARE, DONUT, SQUARE, OVAL)
# 断言:颜色和形状的数量的乘积的两倍必须大于所有的box的数量,这样才能保证在每一对都不重复的情况下也能填满所有的box
assert len(ALLCOLORS) * len(ALLSHAPES) * 2 >= BOARDWIDTH * BOARDHEIGHT, "颜色和形状数量的乘积的两倍必须大于所有的box的数量"
def main():
global FPSCLOCK, DISPLAYSURF# 定义全局变量
mousex = 0 # 用来表示鼠标的x坐标
mousey = 0 # 用来表示鼠标的y坐标
pygame.init()# 初始化pygame
FPSCLOCK = pygame.time.Clock()# 获得pygame时钟
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))# 设置窗口大小
pygame.display.set_caption('Memory Game')# 设置标题
mainBoard = getRandomizedBoard()# 随机获得board的状态
revealedBoxes = generateRevealedBoxesData(False)# 生成一个数据结构,用来存放已经找到匹配的box
firstSelection = None # 用来记录第一个被点击的box的坐标(x, y)
DISPLAYSURF.fill(BGCOLOR)# 设置背景
startGameAnimation(mainBoard)# 开始游戏的入场动画
while True: # 游戏主循环
mouseClicked = False# 鼠标点击状态
# 事件处理
for event in pygame.event.get():
# 按下ESC键或者点击关闭,就退出程序
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
# 鼠标移动时记录鼠标位置
elif event.type == MOUSEMOTION:
mousex, mousey = event.pos
# 鼠标点击时记录点击位置,并把点击状态设置为True
elif event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
mouseClicked = True
#通过鼠标的x,y值获得对应的box的x,y(也就是鼠标所指的box)
boxx, boxy = getBoxAtPixel(mousex, mousey)
if boxx != None and boxy != None:
# 鼠停标在一个box的上面,并且已经点击了该box
if not revealedBoxes[boxx][boxy] and mouseClicked:
revealBoxesAnimation(mainBoard, [(boxx, boxy)])# 动画
revealedBoxes[boxx][boxy] = True # 相当于将这个box存入revealed中
if firstSelection == None: # 如果第一个被点击的box为空,就把当前的box设为第一个点击的box
firstSelection = (boxx, boxy)
else:
# 如果当前的box是第二次被点击的box
# 检查他与第一次被点击的box是否匹配
icon1shape, icon1color = getShapeAndColor(mainBoard, firstSelection[0], firstSelection[1])# 获得第一次被点击的box的形状和颜色
icon2shape, icon2color = getShapeAndColor(mainBoard, boxx, boxy)# 获得当前被点击的box的形状和颜色
if icon1shape != icon2shape or icon1color != icon2color:# 如果形状或颜色不匹配
pygame.time.wait(300) # 等待300毫秒
coverBoxesAnimation(mainBoard, [(firstSelection[0], firstSelection[1]), (boxx, boxy)])# 把这两个box都覆盖回去
revealedBoxes[firstSelection[0]][firstSelection [1]] = False# 相当于把第一个box从revealed里拿出
revealedBoxes[boxx][boxy] = False# 相当于把当前的box从revealed里拿出
elif hasWon(revealedBoxes): # 判断是否获胜
gameWonAnimation(mainBoard)
#不管匹配不匹配,都重新设置第一个被点击的box为None
firstSelection = None
# 更新屏幕
pygame.display.update()
# 设置帧率
FPSCLOCK.tick(FPS)
# 生成一个10*7的数组,用来存放box的状态
def generateRevealedBoxesData(val):
revealedBoxes = []
for i in range(BOARDWIDTH):
revealedBoxes.append([val] * BOARDHEIGHT)
return revealedBoxes
# 随机生成 board 内的游戏数据
def getRandomizedBoard():
# 全排列举所有的颜色和形状的组合,存在icons中
icons = []
for color in ALLCOLORS:
for shape in ALLSHAPES:
icons.append( (shape, color) )
random.shuffle(icons) # 随机打乱icons里的元素的顺序
numIconsUsed = int(BOARDWIDTH * BOARDHEIGHT / 2) # 计算需要多少种的元素(也就是 board 里所有 box 的一半)
icons = icons[:numIconsUsed] * 2 # 将上面得到的元素复制一份(得到的结果就可以两两配对)
random.shuffle(icons)# 再次打乱 icons 里的元素的顺序
# 创建用来存放 board 数据的结构,将上面处理好的 icons 分组放入 board 中
board = []
for x in range(BOARDWIDTH):
column = []
for y in range(BOARDHEIGHT):
column.append(icons[0])
del icons[0] # 删除已经复制的元素
board.append(column)
return board
# 根据groupSize大小分组
def splitIntoGroupsOf(groupSize, theList):
#将一个list分成以groupSize为大小的多个组
result = []
for i in range(0, len(theList), groupSize):
result.append(theList[i:i + groupSize])
return result
# 计算出box的左上角的像素坐标
def leftTopCoordsOfBox(boxx, boxy):
# 将数字坐标转化成像素坐标
left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN
top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN
return (left, top)
# 根据鼠标的像素坐标获得box的坐标(也就是获得鼠标所指的box)
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)
# 绘制图标,将颜色和形状绘制在相应的box中
def drawIcon(shape, color, boxx, boxy):
quarter = int(BOXSIZE * 0.25) # 1/4的box大小
half = int(BOXSIZE * 0.5) # 1/2的box大小
left, top = leftTopCoordsOfBox(boxx, boxy) # 获得box的左上角的像素坐标
# 绘制图形
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))
# 根据box坐标获得box的形状和颜色
def getShapeAndColor(board, boxx, boxy):
# 形状值对应的存在board[x][y][0]中
# 颜色值对应的存在board[x][y][1]中
return board[boxx][boxy][0], board[boxx][boxy][1]
# 绘制box上的coverage
def drawBoxCovers(board, boxes, coverage):
# 绘制覆盖/揭开的box
for box in boxes:# 获得每一个box
left, top = leftTopCoordsOfBox(box[0], box[1])# 计算每一个box的左上角像素坐标
pygame.draw.rect(DISPLAYSURF, WHITE, (left, top, BOXSIZE, BOXSIZE))# 将这个box绘制成白色
shape, color = getShapeAndColor(board, box[0], box[1])# 获得这个box里存放的形状和颜色
drawIcon(shape, color, box[0], box[1])# 绘制对应的图标
if coverage > 0: # 当该box有覆盖时就绘制一层白色的覆盖
pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, coverage, BOXSIZE))
# 更新屏幕
pygame.display.update()
# 设置帧率
FPSCLOCK.tick(FPS)
# 显示揭开的动画
def revealBoxesAnimation(board, boxesToReveal):
# Do the "box reveal" animation.
for coverage in range(BOXSIZE, (-REVEALSPEED) - 1, - REVEALSPEED):
drawBoxCovers(board, boxesToReveal, coverage)
# 显示覆盖的动画
def coverBoxesAnimation(board, boxesToCover):
# Do the "box cover" animation.
for coverage in range(0, BOXSIZE + REVEALSPEED, REVEALSPEED):
drawBoxCovers(board, boxesToCover, coverage)
# 绘制Board
def drawBoard(board, revealed):
# 根据所有的box的状态(覆盖/揭开)绘制对应的box
for boxx in range(BOARDWIDTH):
for boxy in range(BOARDHEIGHT):
left, top = leftTopCoordsOfBox(boxx, boxy)
if not revealed[boxx][boxy]:
# 绘制一个被覆盖的box
pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, BOXSIZE, BOXSIZE))
else:
# 绘制一个揭开的图标
shape, color = getShapeAndColor(board, boxx, boxy)
drawIcon(shape, color, boxx, boxy)
# 游戏的开场动画
def startGameAnimation(board):
# 一次随机获得8个box显示
coveredBoxes = generateRevealedBoxesData(False)
boxes = []
for x in range(BOARDWIDTH):
for y in range(BOARDHEIGHT):
boxes.append( (x, y) )
random.shuffle(boxes)
# 将上面的结果以8个为一组的分组
boxGroups = splitIntoGroupsOf(8, boxes)
drawBoard(board, coveredBoxes)
# 对每一组的元素都进行,先揭开再覆盖的动画
for boxGroup in boxGroups:
revealBoxesAnimation(board, boxGroup)
coverBoxesAnimation(board, boxGroup)
# 游戏获胜的动画
def gameWonAnimation(board):
coveredBoxes = generateRevealedBoxesData(True)
color1 = LIGHTBGCOLOR
color2 = BGCOLOR
# 闪动背景颜色
for i in range(9):
color1, color2 = color2, color1 # 交换颜色
DISPLAYSURF.fill(color1)
# 显示所有的box
drawBoard(board, coveredBoxes)
pygame.display.update()
pygame.time.wait(300)
# 判断游戏是否获胜
def hasWon(revealedBoxes):
# 当所有的box都被揭开时,游戏才获胜,否则返回False
for i in revealedBoxes:
if False in i:
return False
return True
if __name__ == '__main__':
main()
ps:说明一下为了减小游戏的难度,这里的颜色集我只用了{ RED, GREEN, BLUE, YELLOW } 这四个,形状集也只用了 { DONUT, SQUARE, OVAL } 这三个。
** 运行结果:**
** 游戏获胜 **