基于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目录操作之python遍历文件夹后将结果存储为xml
Jan 27 Python
python解析中国天气网的天气数据
Mar 21 Python
Python实现全角半角转换的方法
Aug 18 Python
Python字符串格式化
Jun 15 Python
使用Python和xlwt向Excel文件中写入中文的实例
Apr 21 Python
详解Django 中是否使用时区的区别
Jun 14 Python
使用python 3实现发送邮件功能
Jun 15 Python
Python3 导入上级目录中的模块实例
Feb 16 Python
200行python代码实现2048游戏
Jul 17 Python
利用python-pypcap抓取带VLAN标签的数据包方法
Jul 23 Python
python tkinter 设置窗口大小不可缩放实例
Mar 04 Python
在ipython notebook中使用argparse方式
Apr 20 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备份数据库生成SQL文件并下载的函数代码
2012/02/05 PHP
Yii2实现上下联动下拉框功能的方法
2016/08/10 PHP
PHP文字转图片功能原理与实现方法分析
2017/08/31 PHP
关于php开启错误提示的总结
2019/09/24 PHP
getElementById在任意一款浏览器中都可以用吗的疑问回复
2007/05/13 Javascript
JQuery开发的数独游戏代码
2010/10/29 Javascript
解析jQuery与其它js(Prototype)库兼容共存
2013/07/04 Javascript
jquery定时滑出可最小化的底部提示层特效代码
2013/10/02 Javascript
JavaScript jQuery 中定义数组与操作及jquery数组操作
2015/12/18 Javascript
值得分享的轻量级Bootstrap Table表格插件
2016/05/30 Javascript
详谈JS中实现种子随机数及作用
2016/07/19 Javascript
AngularJS $http模块POST请求实现
2017/04/08 Javascript
vue+Java后端进行调试时解决跨域问题的方式
2017/10/19 Javascript
vue组件发布到npm简单步骤
2017/11/30 Javascript
js+css实现红包雨效果
2018/07/12 Javascript
elementUI多选框反选的实现代码
2019/04/03 Javascript
vue路由教程之静态路由
2019/09/03 Javascript
wepy--用vantUI 实现上弹列表并选择相应的值操作
2020/11/03 Javascript
k8s node节点重新加入master集群的实现
2021/02/22 Javascript
[01:25]2014DOTA2国际邀请赛 zhou分析LGD比赛情况
2014/07/14 DOTA
python正则表达式match和search用法实例
2015/03/26 Python
Python实现的使用telnet登陆聊天室实例
2015/06/17 Python
利用Python自动监控网站并发送邮件告警的方法
2016/08/24 Python
Python request设置HTTPS代理代码解析
2018/02/12 Python
Pyqt5自适应布局实例
2019/12/13 Python
Django-rest-framework中过滤器的定制实例
2020/04/01 Python
python argparse模块通过后台传递参数实例
2020/04/20 Python
巧用CSS3 border实现图片遮罩效果代码
2012/04/09 HTML / CSS
移动端适配 使px自动转换rem
2019/08/26 HTML / CSS
教师评优的个人自我评价分享
2013/09/19 职场文书
证婚人搞笑证婚词
2014/01/10 职场文书
心理健康课教学反思
2014/02/13 职场文书
公务员个人总结
2015/02/12 职场文书
好好学习保证书
2015/02/26 职场文书
小学生节水倡议书
2015/04/29 职场文书
毕业论文答辩开场白和结束语
2015/05/27 职场文书