# coding:utf-8
import pygame, sys, random, time, easygui
from pygame.locals import *
# 初始化pygame环境
pygame.init()
# 创建窗口
canvas = pygame.display.set_mode((1000, 600))
# 加载图片
bg = pygame.image.load("imgs/bg.jpg")
win = pygame.image.load("imgs/win.png")
# 设置标题
pygame.display.set_caption("连连看")
# 图片位置数组
p = [[60, 120], [170, 120], [280, 120], [390, 120], [500, 120], [610, 120], [720, 120], [830, 120],[60, 230], [170, 230], [280, 230], [390, 230], [500, 230], [610, 230], [720, 230], [830, 230],[60, 340], [170, 340], [280, 340], [390, 340], [500, 340], [610, 340], [720, 340], [830, 340],[60, 450], [170, 450], [280, 450], [390, 450], [500, 450], [610, 450], [720, 450], [830, 450]]# 定义变量存储点击的卡片信息
first_num = 0
first_x = 0
first_y = 0# 创建handleEvent方法
def handleEvent():# 全局变量global first_num, first_x, first_yfor event in pygame.event.get():if event.type == pygame.QUIT or event.type == KEYDOWN and event.key == K_ESCAPE:sys.exit()pygame.quit()# 判断点击鼠标左键if event.type == MOUSEBUTTONDOWN and event.button == 1:# 获取鼠标坐标mouse_x = event.pos[0]mouse_y = event.pos[1]# 调用Click方法获取点击到的卡片信息if Click(mouse_x, mouse_y):sec_num = Click(mouse_x, mouse_y)[0]sec_x = Click(mouse_x, mouse_y)[1]sec_y = Click(mouse_x, mouse_y)[2]# 创建列表存储点击标号相同卡片的下标dellist = []# 给第一次点击的卡片信息赋值if first_num == 0:first_num = sec_numfirst_x = sec_xfirst_y = sec_yelse:# 第二次点击卡片标号相同判断坐标if sec_num == first_num :if not(first_x == sec_x and first_y == sec_y) :# 获取标号相同的卡片在cards列表中的下标for i in range(len(cards)):if cards[i].num == sec_num:dellist.append(i)# 删除卡片for j in range(2):if j == 0:cards.pop(dellist[j])else:cards.pop(dellist[j] - 1)first_num = 0first_x = 0first_y = 0# 第二次点击卡片标号不同时给点击卡片信息重新赋值else:first_num = sec_numfirst_x = sec_xfirst_y = sec_y# 创建Card类
class Card ():def __init__(self, num , x, y):self.num = numself.img = pygame.image.load('imgs/' + str(num) + '.png')self.x = xself.y = ydef paint(self):canvas.blit(self.img, (self.x, self.y))# 创建cards列表存储所有卡片
cards = []
for i in range(0, 32):n = int(i % 16 + 1)m = int(random.randint(0, (31 - i)))x = p[m][0]y = p[m][1]cards.append(Card(n , x, y))p.pop(m)# 添加点击事件获取点击到的卡片信息
def Click(mouse_x, mouse_y):x1 = mouse_xy1 = mouse_y# 获取所有卡片信息for i in range(0, len(cards)):imgx = cards[i].ximgy = cards[i].y# 判断鼠标点击位置是否在卡片上if imgx + 100 > x1 and x1 > imgx and imgy + 100 > y1 and y1 > imgy:img = cards[i].numreturn img , imgx, imgyreturn False#获取开始时间
start_time = time.time()
while True:# 画出游戏背景#canvas.blit(bg, (0, 0))#添加游戏结束背景if len(cards) == 0:canvas.blit(win,(0,0))else:canvas.blit(bg,(0,0))# 画出所有图片for i in range(0, len(cards)):cards[i].paint()#获取游戏时间if len(cards) != 0:end_time = time.time()timing = int(end_time - start_time)#easygui.msgbox('耗时:' + str(timing))Time = pygame.font.SysFont('华文琥珀',40)TextTime = Time.render('time:' + str(timing),True,(255,255,255))canvas.blit(TextTime,(720,40))# 更新屏幕内容pygame.display.update()# 调用handleEvent方法handleEvent()