有没有喜欢看火影忍者的小伙伴,我个比较喜欢鸣人,小樱,佐助,雏田,鼬等一些人物。
这次就跟大家弄一个他们的连连看吧!

Python源码、学习、问题解决

4656 885 91

(备注:苏)

首先先定义这次我们需要的模块

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 = NoneEMPTY = -1NONE_LINK = 0STRAIGHT_LINK = 1ONE_CORNER_LINK = 2TWO_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('<Button-1>', 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 = Truedef 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= Falseself.__formerPoint = pointelse:if self.__formerPoint.isEqual(point):self.__isFirst = Trueself.canvas.delete("rectRedOne")else:linkType = self.getLinkType(self.__formerPoint, point)if linkType['type'] != self.NONE_LINK:# TODO Animationself.ClearLinkedBlocks(self.__formerPoint, point)self.canvas.delete("rectRedOne")self.__isFirst = Trueif self.isGameEnd():tk.messagebox.showinfo("You Win!", "Tip")self.__isGameStart = Falseelse:self.__formerPoint = pointself.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 Falsereturn True

提取小头像数组

def extractSmallIconList(self):imageSouce = Image.open(r'images\NARUTO.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.__gameSizefor 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.__deltadef getY(self, y):return y * self.__iconHeight + self.__delta

获取内部坐标

def getInnerPoint(self, point):x = -1y = -1for i in range(0, self.__gameSize):x1 = self.getX(i)x2 = self.getX(i + 1)if point.x >= x1 and point.x < x2:x = ifor j in range(0, self.__gameSize):j1 = self.getY(j)j2 = self.getY(j + 1)if point.y >= j1 and point.y < j2:y = jreturn 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.EMPTYself.__map[p2.y][p2.x] = self.EMPTYself.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 Trueelse: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 = -1end = -1# 水平if p1.y == p2.y:# 大小判断if p2.x < p1.x:start = p2.xend = p1.xelse:start = p1.xend = p2.xfor x in range(start + 1, end):if self.__map[p1.y][x] != self.EMPTY:return Falsereturn Trueelif p1.x == p2.x:if p1.y > p2.y:start = p2.yend = p1.yelse:start = p1.yend = p2.yfor y in range(start + 1, end):if self.__map[y][p1.x] != self.EMPTY:return Falsereturn Truereturn Falsedef 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 pointCornerpointCorner = Point(p2.x, p1.y)if self.isStraightLink(p1, pointCorner) and self.isStraightLink(pointCorner, p2) and self.isEmptyInMap(pointCorner):return pointCornerdef 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:continueif 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:continueif 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 = xself.y = ydef isUserful(self):if self.x >= 0 and self.y >= 0:return Trueelse:return False'''判断两个点是否相同'''def isEqual(self, point):if self.x == point.x and self.y == point.y:return Trueelse:return False'''克隆一份对象'''def clone(self):return Point(self.x, self.y)'''改为另一个对象'''def changeTo(self, point):self.x = point.xself.y = point.yMainWindow()

这个就是这些代码写出来的效果图啦!!火影迷快来一起get吧!

使用Python写一个火影忍者连连看相关推荐

  1. 用python写一个火影忍者连连看

    有没有喜欢看火影忍者的小伙伴,我个比较喜欢鸣人,小樱,佐助,雏田,鼬等一些人物. 这次就跟大家弄一个他们的连连看吧! 喜欢的记得关注我 首先先定义这次我们需要的模块 import os, random ...

  2. python写一个通讯录step by step V3.0

    python写一个通讯录step by step V3.0 更新功能: 数据库进行数据存入和读取操作 字典配合函数调用实现switch功能 其他:函数.字典.模块调用 注意问题: 1.更优美的格式化输 ...

  3. python俄罗斯方块算法详解_用 Python 写一个俄罗斯方块游戏 (

    @@ -2,34 +2,34 @@ > * 原文作者:[Dr Pommes](https://medium.com/@pommes) > * 译文出自:[掘金翻译计划](https://g ...

  4. python编写测试工具-python 写一个性能测试工具(一)

    国庆重新学习了一下go的gin高性能测试框架. 用JMeter来测试gin与flask接口的性能,差别很大. 为什么我自己不尝试写一个性能工具,性能工具的核心就是 并发 和 请求. 请求可以选择Pyt ...

  5. pythongui登录界面密码显示_用python写一个带有gui界面的密码生成器

    需要用到的库: tkinter:构建gui界面 pyperclip:复制功能 random:生成随机数 string:处理字符串 代码: from tkinter import * import ra ...

  6. python写一个通讯录V2.0

    python写一个通讯录step by step V2.0 引用知识 list + dict用于临时存储用户数据信息 cPickle用于格式化文件存取 依旧使用file来进行文件的存储 解决问题 1. ...

  7. python软件界面-用Python写一个语音播放软件

    原标题:用Python写一个语音播放软件 单位经常使用广播进行临时事项的通知(将文字转换为语音然后通过功放广播),但是市面上多数语音播放软件都是收费的,要么发音失真,要么不够稳定--经常出现莫名其妙的 ...

  8. python写一个系统-使用Python写一个量化股票提醒系统

    大家在没有阅读本文之前先看下python的基本概念, Python是一种解释型.面向对象.动态数据类型的高级程序设计语言. Python由Guido van Rossum于1989年底发明,第一个公开 ...

  9. python写一个系统-熬了一晚上,小白用Python写了一个股票提醒系统

    码农小马七夕节去相亲了,见了一个不错的姑娘,长的非常甜美!聊着聊着很投缘!通过介绍人了解到,对方也很满意--想着自己单身多年的生活就要结束啦,心里满是欢喜,美美哒!但是突然想起年初还有几万块在股市里面 ...

最新文章

  1. 996.icu 不加班的程序员有前途吗?
  2. hdu1576 mod 运算的逆元
  3. 实现点击空白关闭模态框
  4. Java中的自增操作符与中间缓存变量机制
  5. 《手把手教你》系列基础篇之2-python+ selenium自动化测试-打开和关闭浏览器(详细)
  6. 如何关闭热点资讯,如何关闭360浏览器热点资讯
  7. LeetCode(226)——翻转二叉树(JavaScript)
  8. linux系统自行清理归档日志_Linux下自动删除归档日志文件的方法
  9. hualinux0.9 网络篇:CCNA学习及思科模拟器选择
  10. 取消android所有动画,android – 动画取消动画
  11. 【数据结构试验】树的基本操作
  12. 各省历年排污费入库金额(2008-2017年)
  13. c语言flag什么意思,立flag是什么意思flag是什么?立flag用语出处和使用方法
  14. layui 表单模板
  15. This is a CONNECT tunnel, through which encrypted HTTPS traffic flows.
  16. 代码维护服务器,维护服务器的利器-pubwin 2009程序代码
  17. OpenPose 运行指令 (Version@1.7)
  18. edg击败we视频_LOL2019德杯EDG vs WE第五局比赛视频回放 EDG让二追三晋级四强
  19. SSLHandshakeException: No appropriate protocol
  20. 第一篇博客——C语言实现简单的学生成绩管理系统

热门文章

  1. Elasticsearch:分析器中的 character filter 介绍
  2. SolidWorks242个使用技巧
  3. 腐烂国度计算机配置要求,《腐烂国度2》PC配置公布 最低要求GTX 760
  4. php 人脸识别接口,php调用百度人脸识别接口查询数据库人脸信息实现验证登录功能...
  5. 怀旧服10月3日服务器维护,魔兽怀旧服:即将开放怀旧服PTR服务器 3/10开放阿拉希...
  6. 达人评测 苹果 M1 iPad Pro 2021 怎么样
  7. 3D Res-UNet和3D V-Net修改输入图片张数
  8. Code Splitting代码分包(路由懒加载)
  9. AS608指纹模块——其实从初学Arduino到做出指纹锁只需要一周
  10. Windows10系统下wsappx占用CPU资源过高