基于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在linux系统下获取系统内存使用情况的方法
May 11 Python
剖析Python的Tornado框架中session支持的实现代码
Aug 21 Python
常用python编程模板汇总
Feb 12 Python
Python编程实现双击更新所有已安装python模块的方法
Jun 05 Python
解决pandas中读取中文名称的csv文件报错的问题
Jul 04 Python
Python3利用print输出带颜色的彩色字体示例代码
Apr 08 Python
python代码编写计算器小程序
Mar 30 Python
python 数据生成excel导出(xlwt,wlsxwrite)代码实例
Aug 23 Python
Python数据可视化:顶级绘图库plotly详解
Dec 07 Python
Python字典中的值为列表或字典的构造实例
Dec 16 Python
Python中对象的比较操作==和is区别详析
Feb 12 Python
Python对excel的基本操作方法
Feb 18 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与flash as3 socket通信传送文件实现代码
2014/08/16 PHP
php+mysql实现数据库随机重排实例
2014/10/17 PHP
JQuery开发的数独游戏代码
2010/10/29 Javascript
juqery 学习之五 文档处理 包裹、替换、删除、复制
2011/02/11 Javascript
javascript动态添加样式(行内式/嵌入式/外链式等规则)
2013/06/24 Javascript
JS批量操作CSS属性详细解析
2013/12/16 Javascript
2014 年最热门的21款JavaScript框架推荐
2014/12/25 Javascript
AngularJS自定义控件实例详解
2016/12/13 Javascript
ES6新特性六:promise对象实例详解
2017/04/21 Javascript
简单谈谈关于 npm 5.0 的新坑
2017/06/08 Javascript
jQuery dateRangePicker插件使用方法详解
2017/07/28 jQuery
基于vue 动态加载图片src的解决方法
2018/02/05 Javascript
解决vue.js 数据渲染成功仍报错的问题
2018/08/25 Javascript
python使用cookie库操保存cookie详解
2014/03/03 Python
Python使用MySQLdb for Python操作数据库教程
2014/10/11 Python
Python httplib模块使用实例
2015/04/11 Python
使用Python发送邮件附件以定时备份MySQL的教程
2015/04/25 Python
Python中使用items()方法返回字典元素对的教程
2015/05/21 Python
Python实现读取TXT文件数据并存进内置数据库SQLite3的方法
2017/08/08 Python
基于python时间处理方法(详解)
2017/08/14 Python
python中如何正确使用正则表达式的详细模式(Verbose mode expression)
2017/11/08 Python
对python中if语句的真假判断实例详解
2019/02/18 Python
python中自带的三个装饰器的实现
2019/11/08 Python
Python pip使用超时问题解决方案
2020/08/03 Python
Python中Yield的基本用法
2020/10/18 Python
AmazeUI 加载进度条的实现示例
2020/08/20 HTML / CSS
Nike瑞典官方网站:Nike.com (SE)
2018/11/26 全球购物
意大利比基尼品牌:MISS BIKINI
2019/11/02 全球购物
软件工程专业推荐信
2013/10/28 职场文书
人力资源管理毕业生自荐信
2014/06/26 职场文书
党委书记个人检查对照材料思想汇报
2014/10/11 职场文书
清明节寄语2015
2015/03/23 职场文书
小学四年级作文之写景
2019/08/23 职场文书
Mysql数据库命令大全
2021/05/26 MySQL
Redis+Lua脚本实现计数器接口防刷功能(升级版)
2022/02/12 Redis
Python学习之时间包使用教程详解
2022/03/21 Python