python连连看_python tkinter实现连连看游戏
需要自己添加图片素材呦
运行效果:
完整代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-10-02 15:19:24
# @Author : Salamander(1906747819@qq.com)
# @Link : http://51lucy.com
import os, random
import tkinter as tk
import tkinter.messagebox
from PIL import Image, ImageTk
class MainWindow():
__gameTitle = "连连看游戏"
__windowWidth = 700
__windowHeigth = 500
__icons = []
__gameSize = 10 # 游戏尺寸
__iconKind = __gameSize * __gameSize / 4 # 小图片种类数量
__iconWidth = 40
__iconHeight = 40
__map = [] # 游戏地图
__delta = 25
__isFirst = True
__isGameStart = False
__formerPoint = None
EMPTY = -1
NONE_LINK = 0
STRAIGHT_LINK = 1
ONE_CORNER_LINK = 2
TWO_CORNER_LINK = 3
def __init__(self):
self.root = tk.Tk()
self.root.title(self.__gameTitle)
self.centerWindow(self.__windowWidth, self.__windowHeigth)
self.root.minsize(460, 460)
self.__addComponets()
self.extractSmallIconList()
self.root.mainloop()
def __addComponets(self):
self.menubar = tk.Menu(self.root, bg="lightgrey", fg="black")
self.file_menu = tk.Menu(self.menubar, tearoff=0, bg="lightgrey", fg="black")
self.file_menu.add_command(label="新游戏", command=self.file_new, accelerator="Ctrl+N")
self.menubar.add_cascade(label="游戏", menu=self.file_menu)
self.root.configure(menu=self.menubar)
self.canvas = tk.Canvas(self.root, bg = "white", width = 450, height = 450)
self.canvas.pack(side=tk.TOP, pady = 5)
self.canvas.bind("", self.clickCanvas)
def centerWindow(self, width, height):
screenwidth = self.root.winfo_screenwidth()
screenheight = self.root.winfo_screenheight()
size = "%dx%d+%d+%d" % (width, height, (screenwidth - width)/2, (screenheight - height)/2)
self.root.geometry(size)
def file_new(self, event=None):
self.iniMap()
self.drawMap()
self.__isGameStart = True
def clickCanvas(self, event):
if self.__isGameStart:
point = self.getInnerPoint(Point(event.x, event.y))
# 有效点击坐标
if point.isUserful() and not self.isEmptyInMap(point):
if self.__isFirst:
self.drawSelectedArea(point)
self.__isFirst= False
self.__formerPoint = point
else:
if self.__formerPoint.isEqual(point):
self.__isFirst = True
self.canvas.delete("rectRedOne")
else:
linkType = self.getLinkType(self.__formerPoint, point)
if linkType["type"] != self.NONE_LINK:
# TODO Animation
self.ClearLinkedBlocks(self.__formerPoint, point)
self.canvas.delete("rectRedOne")
self.__isFirst = True
if self.isGameEnd():
tk.messagebox.showinfo("You Win!", "Tip")
self.__isGameStart = False
else:
self.__formerPoint = point
self.canvas.delete("rectRedOne")
self.drawSelectedArea(point)
# 判断游戏是否结束
def isGameEnd(self):
for y in range(0, self.__gameSize):
for x in range(0, self.__gameSize):
if self.__map[y][x] != self.EMPTY:
return False
return True
"""
提取小头像数组
"""
def extractSmallIconList(self):
imageSouce = Image.open(r"imagesNARUTO.png")
for index in range(0, int(self.__iconKind)):
region = imageSouce.crop((self.__iconWidth * index, 0,
self.__iconWidth * index + self.__iconWidth - 1, self.__iconHeight - 1))
self.__icons.append(ImageTk.PhotoImage(region))
"""
初始化地图 存值为0-24
"""
def iniMap(self):
self.__map = [] # 重置地图
tmpRecords = []
records = []
for i in range(0, int(self.__iconKind)):
for j in range(0, 4):
tmpRecords.append(i)
total = self.__gameSize * self.__gameSize
for x in range(0, total):
index = random.randint(0, total - x - 1)
records.append(tmpRecords[index])
del tmpRecords[index]
# 一维数组转为二维,y为高维度
for y in range(0, self.__gameSize):
for x in range(0, self.__gameSize):
if x == 0:
self.__map.append([])
self.__map[y].append(records[x + y * self.__gameSize])
"""
根据地图绘制图像
"""
def drawMap(self):
self.canvas.delete("all")
for y in range(0, self.__gameSize):
for x in range(0, self.__gameSize):
point = self.getOuterLeftTopPoint(Point(x, y))
im = self.canvas.create_image((point.x, point.y),
image=self.__icons[self.__map[y][x]], anchor="nw", tags = "im%d%d" % (x, y))
"""
获取内部坐标对应矩形左上角顶点坐标
"""
def getOuterLeftTopPoint(self, point):
return Point(self.getX(point.x), self.getY(point.y))
"""
获取内部坐标对应矩形中心坐标
"""
def getOuterCenterPoint(self, point):
return Point(self.getX(point.x) + int(self.__iconWidth / 2),
self.getY(point.y) + int(self.__iconHeight / 2))
def getX(self, x):
return x * self.__iconWidth + self.__delta
def getY(self, y):
return y * self.__iconHeight + self.__delta
"""
获取内部坐标
"""
def getInnerPoint(self, point):
x = -1
y = -1
for i in range(0, self.__gameSize):
x1 = self.getX(i)
x2 = self.getX(i + 1)
if point.x >= x1 and point.x < x2:
x = i
for j in range(0, self.__gameSize):
j1 = self.getY(j)
j2 = self.getY(j + 1)
if point.y >= j1 and point.y < j2:
y = j
return Point(x, y)
"""
选择的区域变红,point为内部坐标
"""
def drawSelectedArea(self, point):
pointLT = self.getOuterLeftTopPoint(point)
pointRB = self.getOuterLeftTopPoint(Point(point.x + 1, point.y + 1))
self.canvas.create_rectangle(pointLT.x, pointLT.y,
pointRB.x - 1, pointRB.y - 1, outline = "red", tags = "rectRedOne")
"""
消除连通的两个块
"""
def ClearLinkedBlocks(self, p1, p2):
self.__map[p1.y][p1.x] = self.EMPTY
self.__map[p2.y][p2.x] = self.EMPTY
self.canvas.delete("im%d%d" % (p1.x, p1.y))
self.canvas.delete("im%d%d" % (p2.x, p2.y))
"""
地图上该点是否为空
"""
def isEmptyInMap(self, point):
if self.__map[point.y][point.x] == self.EMPTY:
return True
else:
return False
"""
获取两个点连通类型
"""
def getLinkType(self, p1, p2):
# 首先判断两个方块中图片是否相同
if self.__map[p1.y][p1.x] != self.__map[p2.y][p2.x]:
return { "type": self.NONE_LINK }
if self.isStraightLink(p1, p2):
return {
"type": self.STRAIGHT_LINK
}
res = self.isOneCornerLink(p1, p2)
if res:
return {
"type": self.ONE_CORNER_LINK,
"p1": res
}
res = self.isTwoCornerLink(p1, p2)
if res:
return {
"type": self.TWO_CORNER_LINK,
"p1": res["p1"],
"p2": res["p2"]
}
return {
"type": self.NONE_LINK
}
"""
直连
"""
def isStraightLink(self, p1, p2):
start = -1
end = -1
# 水平
if p1.y == p2.y:
# 大小判断
if p2.x < p1.x:
start = p2.x
end = p1.x
else:
start = p1.x
end = p2.x
for x in range(start + 1, end):
if self.__map[p1.y][x] != self.EMPTY:
return False
return True
elif p1.x == p2.x:
if p1.y > p2.y:
start = p2.y
end = p1.y
else:
start = p1.y
end = p2.y
for y in range(start + 1, end):
if self.__map[y][p1.x] != self.EMPTY:
return False
return True
return False
def isOneCornerLink(self, p1, p2):
pointCorner = Point(p1.x, p2.y)
if self.isStraightLink(p1, pointCorner) and self.isStraightLink(pointCorner, p2) and self.isEmptyInMap(pointCorner):
return pointCorner
pointCorner = Point(p2.x, p1.y)
if self.isStraightLink(p1, pointCorner) and self.isStraightLink(pointCorner, p2) and self.isEmptyInMap(pointCorner):
return pointCorner
def isTwoCornerLink(self, p1, p2):
for y in range(-1, self.__gameSize + 1):
pointCorner1 = Point(p1.x, y)
pointCorner2 = Point(p2.x, y)
if y == p1.y or y == p2.y:
continue
if y == -1 or y == self.__gameSize:
if self.isStraightLink(p1, pointCorner1) and self.isStraightLink(pointCorner2, p2):
return {"p1": pointCorner1, "p2": pointCorner2}
else:
if self.isStraightLink(p1, pointCorner1) and self.isStraightLink(pointCorner1, pointCorner2) and self.isStraightLink(pointCorner2, p2) and self.isEmptyInMap(pointCorner1) and self.isEmptyInMap(pointCorner2):
return {"p1": pointCorner1, "p2": pointCorner2}
# 横向判断
for x in range(-1, self.__gameSize + 1):
pointCorner1 = Point(x, p1.y)
pointCorner2 = Point(x, p2.y)
if x == p1.x or x == p2.x:
continue
if x == -1 or x == self.__gameSize:
if self.isStraightLink(p1, pointCorner1) and self.isStraightLink(pointCorner2, p2):
return {"p1": pointCorner1, "p2": pointCorner2}
else:
if self.isStraightLink(p1, pointCorner1) and self.isStraightLink(pointCorner1, pointCorner2) and self.isStraightLink(pointCorner2, p2) and self.isEmptyInMap(pointCorner1) and self.isEmptyInMap(pointCorner2):
return {"p1": pointCorner1, "p2": pointCorner2}
class Point():
def __init__(self, x, y):
self.x = x
self.y = y
def isUserful(self):
if self.x >= 0 and self.y >= 0:
return True
else:
return False
"""
判断两个点是否相同
"""
def isEqual(self, point):
if self.x == point.x and self.y == point.y:
return True
else:
return False
"""
克隆一份对象
"""
def clone(self):
return Point(self.x, self.y)
"""
改为另一个对象
"""
def changeTo(self, point):
self.x = point.x
self.y = point.y
MainWindow()
以上就是python tkinter实现连连看游戏的详细内容,更多关于python tkinter连连看的资料请关注云海天教程其它相关文章!
原文链接:https://github.com/salamander-mh/PyMatch
python连连看_python tkinter实现连连看游戏相关推荐
- python剪刀石头布_Python Tkinter教程系列01:剪刀石头布游戏
编写剪刀石头布游戏 让我们使用Python 3和Tkinter开发相同的游戏.我们可以将游戏命名为Rock-Paper-Scissors-Lizard-Spock. 规则和玩法Rock crushes ...
- 编写五子棋的完整python代码_python制作简单五子棋游戏
本文实例为大家分享了python五子棋游戏的具体代码,供大家参考,具体内容如下 #五子棋 '" 矩阵做棋盘 16*16 "+" 打印棋盘 for for 游戏是否结束 开 ...
- 单词九连猜python编程_python实现猜单词游戏
本文实例为大家分享了python实现猜单词游戏的具体代码,供大家参考,具体内容如下 0.效果 1.代码 # 猜单词游戏 import random #添加 WORDS = ("python& ...
- 石头剪刀布python代码_Python之石头剪刀布小游戏(史上最详细步骤)
嗨,各位好呀,我是真小凡. 相信你如果是一个刚学习Python的小白,一定会很想做一个自己的Python小游戏(我就是这样子的),那么今天我们就一起实操一下! 首先要清楚,做一个项目必须的流程是什么 ...
- python 回车键_python tkinter 绑定回车键
# _*_ coding:utf-8_*_ from Tkinter import * def submit(ev = None): p.set(u.get()) root = Tk() root.t ...
- python 下棋_Python开发象棋小游戏(总体思路分析)
先来个温馨提示:不会象棋,或者不是很懂象棋规则的朋友,可以先去下载个象棋小游戏,了解一下规则,毕竟后面这些规则都是我们写的啦,但也不能乱写呀,嘎嘎嘎~~~ 切入正题,在开始之前呢,我们要先缕清思路,下 ...
- python剪刀石头布小游戏源码下载_Python Tkinter实现剪刀石头布小游戏
Python Tkinter实现剪刀石头布小游戏 发布时间:2020-10-26 14:56:52 来源:亿速云 阅读:67 作者:Leah 本篇文章给大家分享的是有关Python Tkinter实现 ...
- Python Tkinter——数字拼图游戏详解版
Python Tkinter 实践系列--数字拼图游戏详解版 import random #Python中的random是一个标准库用于生成随机数.随机整数.还有随机从数据集取数据. import t ...
- Python Tkinter——数字拼图游戏
Python Tkinter 实践系列--数字拼图游戏 tkinter模块,掌握窗口创建.消息循环等tkinter的基本架构 读取并显示图片,处理键盘事件 导入random库,导入python中的tk ...
最新文章
- 我不懂,数学家为啥老跟驴过不去?
- 还在封装各种 Util 工具类?这个神级框架帮你解决所有问题!
- 【安全漏洞】CVE-2020-26567 DSR-250N 远程拒绝服务漏洞分析
- 【Python基础】Pandas笔记---概述与数据结构
- STM32的I/O口的八种工作模式
- 光纤交换机是什么,光纤交换机的作用是什么?
- mysql所支持的比较运算符_mysql比较运算符有哪些?Mysql比较运算符详解
- 小议传统分层与新式分层,抑或与DDD分层
- java box unboxing
- 从 Oracle 到 PostgreSQL :从 Uptime 到数据库实例运行时间
- linux screen 命令是 ssh 的有效补充
- Android读取电话薄中的电话号码
- 浅析数据中心交换机芯片,中国自主可控国产化交换机已是历史必然
- 多媒体技术及应用:概述、多媒体技术的特征、多媒体硬件系统、多媒体存储技术
- oracle添加字段sql并添加注释
- linux内核网桥源码,Linux-kernel网桥代码分析(二)
- c语言致命错误无法打开网页,电脑中IE浏览器显示异常或无法打开网页崩溃的解决方法...
- Sugar BI数据可视化图表标注
- Programming in lua 中文版
- Spring MVC拦截器(一)---定义,配置及单个拦截器执行流程
热门文章
- 被误读的博弈:谁才是大厂解除屏蔽的最终受益者?
- php mysql全能权威指南 pdf_《PHP+MySQL全能权威指南(配光盘)》怎么样_目录_pdf在线阅读 - 课课家教育...
- php transport,PHPMailer - PHP email transport class
- ISCC2021 美人计
- BUUCTF--[VN2020 公开赛]拉胯的三条命令
- python 类的绑定方法和非绑定方法
- Python中str、list、numpy分片操作
- catboost原理以及Python代码
- pythonslice_shift_Pandas 解决dataframe的一列进行向下顺移问题
- arm ffmpeg报错:Invalid data found when processing input(没解决)(在ubuntu上能正常运行)(重新交叉编译后问题解决)