资讯专栏INFORMATION COLUMN

Just for fun——用Python的Tkinter写个连连看

崔晓明 / 1427人阅读

摘要:很早之前用也是写过一个,但是写的不好,这次用写,看看自己有木有提升。

UI

代码

</>复制代码

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # @Date : 2017-10-02 15:19:24
  4. # @Author : Salamander (*********@qq.com)
  5. # @Link : http://51lucy.com
  6. import os, random
  7. import tkinter as tk
  8. import tkinter.messagebox
  9. from PIL import Image, ImageTk
  10. class MainWindow():
  11. __gameTitle = "连连看游戏"
  12. __windowWidth = 700
  13. __windowHeigth = 500
  14. __icons = []
  15. __gameSize = 10 # 游戏尺寸
  16. __iconKind = __gameSize * __gameSize / 4 # 小图片种类数量
  17. __iconWidth = 40
  18. __iconHeight = 40
  19. __map = [] # 游戏地图
  20. __delta = 25
  21. __isFirst = True
  22. __isGameStart = False
  23. __formerPoint = None
  24. EMPTY = -1
  25. NONE_LINK = 0
  26. STRAIGHT_LINK = 1
  27. ONE_CORNER_LINK = 2
  28. TWO_CORNER_LINK = 3
  29. def __init__(self):
  30. self.root = tk.Tk()
  31. self.root.title(self.__gameTitle)
  32. self.centerWindow(self.__windowWidth, self.__windowHeigth)
  33. self.root.minsize(460, 460)
  34. self.__addComponets()
  35. self.extractSmallIconList()
  36. self.root.mainloop()
  37. def __addComponets(self):
  38. self.menubar = tk.Menu(self.root, bg="lightgrey", fg="black")
  39. self.file_menu = tk.Menu(self.menubar, tearoff=0, bg="lightgrey", fg="black")
  40. self.file_menu.add_command(label="新游戏", command=self.file_new, accelerator="Ctrl+N")
  41. self.menubar.add_cascade(label="游戏", menu=self.file_menu)
  42. self.root.configure(menu=self.menubar)
  43. self.canvas = tk.Canvas(self.root, bg = "white", width = 450, height = 450)
  44. self.canvas.pack(side=tk.TOP, pady = 5)
  45. self.canvas.bind("", self.clickCanvas)
  46. def centerWindow(self, width, height):
  47. screenwidth = self.root.winfo_screenwidth()
  48. screenheight = self.root.winfo_screenheight()
  49. size = "%dx%d+%d+%d" % (width, height, (screenwidth - width)/2, (screenheight - height)/2)
  50. self.root.geometry(size)
  51. def file_new(self, event=None):
  52. self.iniMap()
  53. self.drawMap()
  54. self.__isGameStart = True
  55. def clickCanvas(self, event):
  56. if self.__isGameStart:
  57. point = self.getInnerPoint(Point(event.x, event.y))
  58. # 有效点击坐标
  59. if point.isUserful() and not self.isEmptyInMap(point):
  60. if self.__isFirst:
  61. self.drawSelectedArea(point)
  62. self.__isFirst= False
  63. self.__formerPoint = point
  64. else:
  65. if self.__formerPoint.isEqual(point):
  66. self.__isFirst = True
  67. self.canvas.delete("rectRedOne")
  68. else:
  69. linkType = self.getLinkType(self.__formerPoint, point)
  70. if linkType["type"] != self.NONE_LINK:
  71. # TODO Animation
  72. self.ClearLinkedBlocks(self.__formerPoint, point)
  73. self.canvas.delete("rectRedOne")
  74. self.__isFirst = True
  75. if self.isGameEnd():
  76. tk.messagebox.showinfo("You Win!", "Tip")
  77. self.__isGameStart = False
  78. else:
  79. self.__formerPoint = point
  80. self.canvas.delete("rectRedOne")
  81. self.drawSelectedArea(point)
  82. # 判断游戏是否结束
  83. def isGameEnd(self):
  84. for y in range(0, self.__gameSize):
  85. for x in range(0, self.__gameSize):
  86. if self.__map[y][x] != self.EMPTY:
  87. return False
  88. return True
  89. """
  90. 提取小头像数组
  91. """
  92. def extractSmallIconList(self):
  93. imageSouce = Image.open(r"imagesNARUTO.png")
  94. for index in range(0, int(self.__iconKind)):
  95. region = imageSouce.crop((self.__iconWidth * index, 0,
  96. self.__iconWidth * index + self.__iconWidth - 1, self.__iconHeight - 1))
  97. self.__icons.append(ImageTk.PhotoImage(region))
  98. """
  99. 初始化地图 存值为0-24
  100. """
  101. def iniMap(self):
  102. self.__map = [] # 重置地图
  103. tmpRecords = []
  104. records = []
  105. for i in range(0, int(self.__iconKind)):
  106. for j in range(0, 4):
  107. tmpRecords.append(i)
  108. total = self.__gameSize * self.__gameSize
  109. for x in range(0, total):
  110. index = random.randint(0, total - x - 1)
  111. records.append(tmpRecords[index])
  112. del tmpRecords[index]
  113. # 一维数组转为二维,y为高维度
  114. for y in range(0, self.__gameSize):
  115. for x in range(0, self.__gameSize):
  116. if x == 0:
  117. self.__map.append([])
  118. self.__map[y].append(records[x + y * self.__gameSize])
  119. """
  120. 根据地图绘制图像
  121. """
  122. def drawMap(self):
  123. self.canvas.delete("all")
  124. for y in range(0, self.__gameSize):
  125. for x in range(0, self.__gameSize):
  126. point = self.getOuterLeftTopPoint(Point(x, y))
  127. im = self.canvas.create_image((point.x, point.y),
  128. image=self.__icons[self.__map[y][x]], anchor="nw", tags = "im%d%d" % (x, y))
  129. """
  130. 获取内部坐标对应矩形左上角顶点坐标
  131. """
  132. def getOuterLeftTopPoint(self, point):
  133. return Point(self.getX(point.x), self.getY(point.y))
  134. """
  135. 获取内部坐标对应矩形中心坐标
  136. """
  137. def getOuterCenterPoint(self, point):
  138. return Point(self.getX(point.x) + int(self.__iconWidth / 2),
  139. self.getY(point.y) + int(self.__iconHeight / 2))
  140. def getX(self, x):
  141. return x * self.__iconWidth + self.__delta
  142. def getY(self, y):
  143. return y * self.__iconHeight + self.__delta
  144. """
  145. 获取内部坐标
  146. """
  147. def getInnerPoint(self, point):
  148. x = -1
  149. y = -1
  150. for i in range(0, self.__gameSize):
  151. x1 = self.getX(i)
  152. x2 = self.getX(i + 1)
  153. if point.x >= x1 and point.x < x2:
  154. x = i
  155. for j in range(0, self.__gameSize):
  156. j1 = self.getY(j)
  157. j2 = self.getY(j + 1)
  158. if point.y >= j1 and point.y < j2:
  159. y = j
  160. return Point(x, y)
  161. """
  162. 选择的区域变红,point为内部坐标
  163. """
  164. def drawSelectedArea(self, point):
  165. pointLT = self.getOuterLeftTopPoint(point)
  166. pointRB = self.getOuterLeftTopPoint(Point(point.x + 1, point.y + 1))
  167. self.canvas.create_rectangle(pointLT.x, pointLT.y,
  168. pointRB.x - 1, pointRB.y - 1, outline = "red", tags = "rectRedOne")
  169. """
  170. 消除连通的两个块
  171. """
  172. def ClearLinkedBlocks(self, p1, p2):
  173. self.__map[p1.y][p1.x] = self.EMPTY
  174. self.__map[p2.y][p2.x] = self.EMPTY
  175. self.canvas.delete("im%d%d" % (p1.x, p1.y))
  176. self.canvas.delete("im%d%d" % (p2.x, p2.y))
  177. """
  178. 地图上该点是否为空
  179. """
  180. def isEmptyInMap(self, point):
  181. if self.__map[point.y][point.x] == self.EMPTY:
  182. return True
  183. else:
  184. return False
  185. """
  186. 获取两个点连通类型
  187. """
  188. def getLinkType(self, p1, p2):
  189. # 首先判断两个方块中图片是否相同
  190. if self.__map[p1.y][p1.x] != self.__map[p2.y][p2.x]:
  191. return { "type": self.NONE_LINK }
  192. if self.isStraightLink(p1, p2):
  193. return {
  194. "type": self.STRAIGHT_LINK
  195. }
  196. res = self.isOneCornerLink(p1, p2)
  197. if res:
  198. return {
  199. "type": self.ONE_CORNER_LINK,
  200. "p1": res
  201. }
  202. res = self.isTwoCornerLink(p1, p2)
  203. if res:
  204. return {
  205. "type": self.TWO_CORNER_LINK,
  206. "p1": res["p1"],
  207. "p2": res["p2"]
  208. }
  209. return {
  210. "type": self.NONE_LINK
  211. }
  212. """
  213. 直连
  214. """
  215. def isStraightLink(self, p1, p2):
  216. start = -1
  217. end = -1
  218. # 水平
  219. if p1.y == p2.y:
  220. # 大小判断
  221. if p2.x < p1.x:
  222. start = p2.x
  223. end = p1.x
  224. else:
  225. start = p1.x
  226. end = p2.x
  227. for x in range(start + 1, end):
  228. if self.__map[p1.y][x] != self.EMPTY:
  229. return False
  230. return True
  231. elif p1.x == p2.x:
  232. if p1.y > p2.y:
  233. start = p2.y
  234. end = p1.y
  235. else:
  236. start = p1.y
  237. end = p2.y
  238. for y in range(start + 1, end):
  239. if self.__map[y][p1.x] != self.EMPTY:
  240. return False
  241. return True
  242. return False
  243. def isOneCornerLink(self, p1, p2):
  244. pointCorner = Point(p1.x, p2.y)
  245. if self.isStraightLink(p1, pointCorner) and self.isStraightLink(pointCorner, p2) and self.isEmptyInMap(pointCorner):
  246. return pointCorner
  247. pointCorner = Point(p2.x, p1.y)
  248. if self.isStraightLink(p1, pointCorner) and self.isStraightLink(pointCorner, p2) and self.isEmptyInMap(pointCorner):
  249. return pointCorner
  250. def isTwoCornerLink(self, p1, p2):
  251. for y in range(-1, self.__gameSize + 1):
  252. pointCorner1 = Point(p1.x, y)
  253. pointCorner2 = Point(p2.x, y)
  254. if y == p1.y or y == p2.y:
  255. continue
  256. if y == -1 or y == self.__gameSize:
  257. if self.isStraightLink(p1, pointCorner1) and self.isStraightLink(pointCorner2, p2):
  258. return {"p1": pointCorner1, "p2": pointCorner2}
  259. else:
  260. if self.isStraightLink(p1, pointCorner1) and self.isStraightLink(pointCorner1, pointCorner2) and self.isStraightLink(pointCorner2, p2) and self.isEmptyInMap(pointCorner1) and self.isEmptyInMap(pointCorner2):
  261. return {"p1": pointCorner1, "p2": pointCorner2}
  262. # 横向判断
  263. for x in range(-1, self.__gameSize + 1):
  264. pointCorner1 = Point(x, p1.y)
  265. pointCorner2 = Point(x, p2.y)
  266. if x == p1.x or x == p2.x:
  267. continue
  268. if x == -1 or x == self.__gameSize:
  269. if self.isStraightLink(p1, pointCorner1) and self.isStraightLink(pointCorner2, p2):
  270. return {"p1": pointCorner1, "p2": pointCorner2}
  271. else:
  272. if self.isStraightLink(p1, pointCorner1) and self.isStraightLink(pointCorner1, pointCorner2) and self.isStraightLink(pointCorner2, p2) and self.isEmptyInMap(pointCorner1) and self.isEmptyInMap(pointCorner2):
  273. return {"p1": pointCorner1, "p2": pointCorner2}
  274. class Point():
  275. def __init__(self, x, y):
  276. self.x = x
  277. self.y = y
  278. def isUserful(self):
  279. if self.x >= 0 and self.y >= 0:
  280. return True
  281. else:
  282. return False
  283. """
  284. 判断两个点是否相同
  285. """
  286. def isEqual(self, point):
  287. if self.x == point.x and self.y == point.y:
  288. return True
  289. else:
  290. return False
  291. """
  292. 克隆一份对象
  293. """
  294. def clone(self):
  295. return Point(self.x, self.y)
  296. """
  297. 改为另一个对象
  298. """
  299. def changeTo(self, point):
  300. self.x = point.x
  301. self.y = point.y
  302. MainWindow()
使用

完整源码在GitHub上,主要就是三种连通情况的判断。
很早之前用C#也是写过一个,但是写的不好,这次用python写,看看自己有木有提升。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/40897.html

相关文章

  • Just for fun——Nginx配Lua写个hello world

    摘要:是一个基于与的高性能平台,其内部集成了大量精良的库第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发扩展性极高的动态应用服务和动态网关。,,,阶段处理,比如记录访问量统计平均响应时间 Lua lua的特点 小巧:一个完整的Lua解释器不过200k 可扩展性:Lua的解释器是100%的ANSI编写的,它提供了非常易于使用的扩展接口和机制,所以Lua的脚本很容易的被C/C++ ...

    kevin 评论0 收藏0
  • [翻译]一个简单实Python Tkinter教程

    摘要:输入框和标签都带了一个神秘的参数。我们可以在之前调用的时候做这些事,但上面这样做也是个不错的选择第二行告诉让我们的输入框获取到焦点。 原文http://www.tkdocs.com/tutorial/firstexample.html 第一个实用的简易案例 A First (Real) ExampleWith that out of the way, lets try a slight...

    Noodles 评论0 收藏0
  • ❤️国庆假期快到了,python写个倒计时程序,助你熬到假期!❤️

            国庆假期快到了,想查查还有几天几小时到假期,这对程序员小菜一碟,轻轻松松用python写个倒计时程序(天、时、分、秒),助你熬到假期! 一、先看效果:  二、安装python: 1、下载安装python 下载安装python3.9.6,进入python官方网站://www.python.org/  点击Python 3.9.6 直接安装即可。 2、验证安装成功。 按win+R...

    loonggg 评论0 收藏0
  • Just for fun——写个爬虫抓取whois信息

    摘要:代码需要的字段模仿获取西部数码信息域名代理模拟执行代码解析出错添加代理解析出错查询西部数码失败请求西部数码失败生成失败提取西部数码数据使用结果另外这个域名是我的,有意出售。 目标对象和过程 爬取的网站是西部数码,该网站在https://www.west.cn/web/whois...可以查询whois信息,通过chrome调试知道,数据是从接口:https://www.west.cn/...

    Cheng_Gang 评论0 收藏0
  • Python写个了红包提醒,再不怕错过一个亿了

    摘要:先来看下效果实际使用不需要打开手机,此处为演示需要实现代码主要有两个部分接收红包消息直接从手机端微信获取数据比较麻烦,主流的方法都是通过微信网页版来获取。这里我用的是,通过即可安装,之前我也写过文章介绍微信机器人进化指南。 又到了辞旧迎新的时候,群里的红包也多起来了。然而大佬们总是喜欢趁我不在的时候发红包,经常打开手机,发现红包已被抢完,感觉错过了一个亿。 安卓上有不少红包助手工具,但...

    caikeal 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<