基于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中的正则表达式的用法
Apr 09 Python
Python win32com 操作Exce的l简单方法(必看)
May 25 Python
基于Python os模块常用命令介绍
Nov 03 Python
Python对HTML转义字符进行反转义的实现方法
Apr 28 Python
windows系统中Python多版本与jupyter notebook使用虚拟环境的过程
May 15 Python
Django利用cookie保存用户登录信息的简单实现方法
May 27 Python
梅尔倒谱系数(MFCC)实现
Jun 19 Python
python中的decimal类型转换实例详解
Jun 26 Python
Python 占位符的使用方法详解
Jul 10 Python
python requests抓取one推送文字和图片代码实例
Nov 04 Python
Python基础之高级变量类型实例详解
Jan 03 Python
python GUI库图形界面开发之PyQt5切换按钮控件QPushButton详细使用方法与实例
Feb 28 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一些有意思的小区别
2006/12/06 PHP
PHP操作MongoDB GridFS 存储文件的详解
2013/06/20 PHP
浅谈PDO的rowCount函数
2015/06/18 PHP
[原创]ThinkPHP让../Public在模板不解析(直接输出)的方法
2015/10/09 PHP
php实现解析xml并生成sql语句的方法
2018/02/03 PHP
Laravel 实现Controller向blade前台模板赋值的四种方式小结
2019/10/22 PHP
php中yii框架实例用法
2020/12/22 PHP
自己实现string的substring方法 人民币小写转大写,数字反转,正则优化
2012/09/02 Javascript
Jquery操作Ajax方法小结
2015/11/29 Javascript
jQuery+PHP实现微信转盘抽奖功能的方法
2016/05/25 Javascript
JS/jQ实现免费获取手机验证码倒计时效果
2016/06/13 Javascript
js方法数据验证的简单实例
2016/09/17 Javascript
jQuery编写网页版2048小游戏
2017/01/06 Javascript
Node.js五大应用性能技巧小结(必须收藏)
2017/08/09 Javascript
react-native 完整实现登录功能的示例代码
2017/09/11 Javascript
vue-baidu-map 进入页面自动定位的解决方案(推荐)
2018/04/28 Javascript
JavaScript 生成唯一ID的几种方式
2021/02/19 Javascript
Python 调用VC++的动态链接库(DLL)
2008/09/06 Python
跟老齐学Python之print详解
2014/09/28 Python
Python中下划线的使用方法
2015/03/27 Python
解决Python出现_warn_unsafe_extraction问题的方法
2016/03/24 Python
用Python一键搭建Http服务器的方法
2018/06/01 Python
python保存网页图片到本地的方法
2018/07/24 Python
matplotlib.pyplot绘图显示控制方法
2019/01/15 Python
深入学习python多线程与GIL
2019/08/26 Python
关于pytorch处理类别不平衡的问题
2019/12/31 Python
python实现堆排序的实例讲解
2020/02/21 Python
Python中的Cookie模块如何使用
2020/06/04 Python
python try...finally...的实现方法
2020/11/25 Python
video下autoplay属性无效的解决方法(添加muted属性)
2020/05/19 HTML / CSS
澳大利亚婴儿礼品公司:The Baby Gift Company
2018/11/04 全球购物
餐饮收银员岗位职责
2014/02/07 职场文书
模特职业生涯规划范文
2014/02/26 职场文书
就业协议书怎么填
2014/09/15 职场文书
幼儿园开学家长寄语(2016春季)
2015/12/03 职场文书
React如何创建组件
2021/06/27 Javascript