基于Python实现的扫雷游戏实例代码


Posted in Python onAugust 01, 2014

本文实例借鉴mvc模式,核心数据为model,维护1个矩阵,0表无雷,1表雷,-1表已经检测过。
本例使用python的tkinter做gui,由于没考虑可用性问题,因此UI比较难看,pygame更有趣更强大更好看,做这些小游戏更合适,感兴趣的读者可以尝试一下!

具体的功能代码如下:

# -*- coding: utf-8 -*-
import random
import sys
from Tkinter import *

class Model:
  """
  核心数据类,维护一个矩阵
  """
  def __init__(self,row,col):
    self.width=col
    self.height=row
    self.items=[[0 for c in range(col)] for r in range(row)]

  def setItemValue(self,r,c,value):
    """
    设置某个位置的值为value
    """
    self.items[r][c]=value;

  def checkValue(self,r,c,value):
    """
    检测某个位置的值是否为value
    """
    if self.items[r][c]!=-1 and self.items[r][c]==value:
      self.items[r][c]=-1 #已经检测过
      return True
    else:
      return False
    
  def countValue(self,r,c,value):
    """
    统计某个位置周围8个位置中,值为value的个数
    """
    count=0
    if r-1>=0 and c-1>=0:
      if self.items[r-1][c-1]==1:count+=1
    if r-1>=0 and c>=0:
      if self.items[r-1][c]==1:count+=1
    if r-1>=0 and c+1<=self.width-1:
      if self.items[r-1][c+1]==1:count+=1
    if c-1>=0:
      if self.items[r][c-1]==1:count+=1
    if c+1<=self.width-1 :
      if self.items[r][c+1]==1:count+=1
    if r+1<=self.height-1 and c-1>=0:
      if self.items[r+1][c-1]==1:count+=1
    if r+1<=self.height-1 :
      if self.items[r+1][c]==1:count+=1
    if r+1<=self.height-1 and c+1<=self.width-1:
      if self.items[r+1][c+1]==1:count+=1
    return count

  
class Mines(Frame):
  def __init__(self,m,master=None):
    Frame.__init__(self,master)
    self.model=m
    self.initmine()
    self.grid()
    self.createWidgets()

 
  
  def createWidgets(self):
    #top=self.winfo_toplevel()
    #top.rowconfigure(self.model.height*2,weight=1)
    #top.columnconfigure(self.model.width*2,weight=1)
    self.rowconfigure(self.model.height,weight=1)
    self.columnconfigure(self.model.width,weight=1)
    self.buttongroups=[[Button(self,height=1,width=2) for i in range(self.model.width)]
              for j in range(self.model.height)]
    for r in range(self.model.width):
      for c in range(self.model.height):
        self.buttongroups[r][c].grid(row=r,column=c)
        self.buttongroups[r][c].bind('<Button-1>',self.clickevent)
        self.buttongroups[r][c]['padx']=r
        self.buttongroups[r][c]['pady']=c

  def showall(self):
    for r in range(model.height):
      for c in range(model.width):
        self.showone(r,c)

  def showone(self,r,c):
    if model.checkValue(r,c,0):
      self.buttongroups[r][c]['text']=model.countValue(r,c,1)
    else:
      self.buttongroups[r][c]['text']='Mines'

  def recureshow(self,r,c):
    if 0<=r<=self.model.height-1 and 0<=c<=self.model.width-1:
      if model.checkValue(r,c,0) and model.countValue(r,c,1)==0:
        self.buttongroups[r][c]['text']=''
        self.recureshow(r-1,c-1)
        self.recureshow(r-1,c)
        self.recureshow(r-1,c+1)
        self.recureshow(r,c-1)
        self.recureshow(r,c+1)
        self.recureshow(r+1,c-1)
        self.recureshow(r+1,c)
        self.recureshow(r+1,c+1)
      elif model.countValue(r,c,1)!=0:
        self.buttongroups[r][c]['text']=model.countValue(r,c,1)
    else:
      pass
        
      
  def clickevent(self,event):
    """
    点击事件
    case 1:是雷,所有都显示出来,游戏结束
    case 2:是周围雷数为0的,递归触发周围8个button的点击事件
    case 3:周围雷数不为0的,显示周围雷数
    """
    r=int(str(event.widget['padx']))
    c=int(str(event.widget['pady']))
    if model.checkValue(r,c,1):#是雷
      self.showall()
    else:#不是雷
      self.recureshow(r,c)
    
    
  def initmine(self):
    """
    埋雷,每行埋height/width+2个暂定
    """
    r=random.randint(1,model.height/model.width+2)
    for r in range(model.height):
      for i in range(2):
        rancol=random.randint(0,model.width-1)
        model.setItemValue(r,rancol,1)

  
  def printf(self):
    """
    打印
    """
    for r in range(model.height):
      for c in range(model.width):
        print model.items[r][c],
      print '/n'
      

def new(self):
  """
  重新开始游戏
  """
  pass

if __name__=='__main__':
  model=Model(10,10)
  root=Tk()
  
  #menu
  menu = Menu(root)
  root.config(menu=menu)
  filemenu = Menu(menu)
  menu.add_cascade(label="File", menu=filemenu)
  filemenu.add_command(label="New",command=new)
  filemenu.add_separator()
  filemenu.add_command(label="Exit", command=root.quit)

  #Mines
  m=Mines(model,root)
  #m.printf()
  root.mainloop()
Python 相关文章推荐
Python 元类使用说明
Dec 18 Python
python实现去除下载电影和电视剧文件名中的多余字符的方法
Sep 23 Python
python用来获得图片exif信息的库实例分析
Mar 16 Python
Python使用ftplib实现简易FTP客户端的方法
Jun 03 Python
你所不知道的Python奇技淫巧13招【实用】
Dec 14 Python
Python中模块string.py详解
Mar 12 Python
Python生成器以及应用实例解析
Feb 08 Python
python之DataFrame实现excel合并单元格
Feb 22 Python
Django渲染Markdown文章目录的方法示例
Jan 02 Python
python 实现提取某个索引中某个时间段的数据方法
Feb 01 Python
Python判断字符串是否为空和null方法实例
Apr 26 Python
pytorch 如何把图像数据集进行划分成train,test和val
May 31 Python
python脚本实现查找webshell的方法
Jul 31 #Python
用python删除java文件头上版权信息的方法
Jul 31 #Python
Python datetime时间格式化去掉前导0
Jul 31 #Python
python处理文本文件并生成指定格式的文件
Jul 31 #Python
Python中关键字is与==的区别简述
Jul 31 #Python
python处理文本文件实现生成指定格式文件的方法
Jul 31 #Python
Python中zip()函数用法实例教程
Jul 31 #Python
You might like
php下删除一篇文章生成的多个静态页面
2010/08/08 PHP
使用PHP生成二维码的两种方法(带logo图像)
2014/03/14 PHP
php中json_encode处理gbk与gb2312中文乱码问题的解决方法
2014/07/10 PHP
php批量添加数据与批量更新数据的实现方法
2014/12/16 PHP
PHP获取当前日期和时间及格式化方法参数
2015/05/11 PHP
Laravel 5.1 框架Blade模板引擎用法实例分析
2020/01/04 PHP
JavaScript国旗变换效果代码
2008/08/13 Javascript
让新消息在网页标题闪烁提示的jQuery代码
2013/11/04 Javascript
让table变成exls的示例代码
2014/03/24 Javascript
通过JS来动态的修改url,实现对url的增删查改
2014/09/01 Javascript
js中for in语句的用法讲解
2015/04/24 Javascript
javaScript生成支持中文带logo的二维码(jquery.qrcode.js)
2017/01/03 Javascript
简单实现js倒计时功能
2017/02/13 Javascript
Vue 2.X的状态管理vuex记录详解
2017/03/23 Javascript
jQuery实现获取及设置CSS样式操作详解
2018/09/05 jQuery
深入Node TCP模块的理解
2019/03/13 Javascript
JQueryDOM之样式操作
2019/03/27 jQuery
Openlayers学习之地图比例尺控件
2020/09/28 Javascript
vue切换菜单取消未完成接口请求的案例
2020/11/13 Javascript
Python 代码性能优化技巧分享
2012/08/07 Python
python实现巡检系统(solaris)示例
2014/04/02 Python
Python内置函数之filter map reduce介绍
2014/11/30 Python
详解python函数传参是传值还是传引用
2018/01/16 Python
Django重装mysql后启动报错:No module named ‘MySQLdb’的解决方法
2018/04/22 Python
python中不能连接超时的问题及解决方法
2018/06/10 Python
python框架flask表单实现详解
2019/11/04 Python
Django-migrate报错问题解决方案
2020/04/21 Python
python 怎样进行内存管理
2020/11/10 Python
Python爬虫爬取微博热搜保存为 Markdown 文件的源码
2021/02/22 Python
正宗的澳大利亚Ugg靴子零售商:UGG Express
2020/04/19 全球购物
SQL Server数据库笔试题和答案
2016/02/04 面试题
linux比较文件内容的命令是什么
2015/09/23 面试题
期中考试后的反思
2014/02/08 职场文书
优秀教师先进材料
2014/12/16 职场文书
师德承诺书
2015/01/20 职场文书
爸爸的三轮车观后感
2015/06/16 职场文书