基于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中使用sys模板和logging模块获取行号和函数名的方法
Apr 15 Python
python生成验证码图片代码分享
Jan 28 Python
详解Python的collections模块中的deque双端队列结构
Jul 07 Python
Python变量和数据类型详解
Feb 15 Python
使用Python实现简单的服务器功能
Aug 25 Python
python爬虫获取新浪新闻教学
Dec 23 Python
python将控制台输出保存至文件的方法
Jan 07 Python
python 直接赋值和copy的区别详解
Aug 07 Python
pycharm激活码快速激活及使用步骤
Mar 12 Python
Python selenium模块实现定位过程解析
Jul 09 Python
python 通过 pybind11 使用Eigen加速代码的步骤
Dec 07 Python
详解python中的异常捕获
Dec 15 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+JS无限级可伸缩菜单详解(简单易懂)
2007/01/02 PHP
php数组合并array_merge()函数使用注意事项
2014/06/19 PHP
PHP 5.3新增魔术方法__invoke概述
2014/07/23 PHP
yii2中的rules 自定义验证规则详解
2016/04/19 PHP
php外部执行命令函数用法小结
2016/10/11 PHP
浅谈PHP接入(第三方登录)QQ登录 OAuth2.0 过程中遇到的坑
2017/10/13 PHP
wordpress自定义标签云与随机获取标签的方法详解
2019/03/22 PHP
js 实现复制到粘贴板的功能代码
2010/05/13 Javascript
juery框架写的弹窗效果适合新手
2013/11/27 Javascript
javascript中处理时间戳为日期格式的方法
2014/01/02 Javascript
JavaScript中提前声明变量或函数例子
2014/11/12 Javascript
js实现的倒计时按钮实例
2015/06/24 Javascript
Javascript基于AJAX回调函数传递参数实例分析
2015/12/15 Javascript
webpack独立打包和缓存处理详解
2017/04/03 Javascript
关于vue的npm run dev和npm run build的区别介绍
2019/01/14 Javascript
jQuery使用jsonp实现百度搜索的示例代码
2020/07/08 jQuery
vue导入.md文件的步骤(markdown转HTML)
2020/12/31 Vue.js
[47:55]Ti4第二日主赛事败者组 NaVi vs EG 1
2014/07/20 DOTA
python通过urllib2获取带有中文参数url内容的方法
2015/03/13 Python
python实现决策树ID3算法的示例代码
2018/05/30 Python
Python 下载及安装详细步骤
2019/11/04 Python
Pytorch中Tensor与各种图像格式的相互转化详解
2019/12/26 Python
Python startswith()和endswith() 方法原理解析
2020/04/28 Python
Python调用飞书发送消息的示例
2020/11/10 Python
台湾母婴用品购物网站:Infant婴之房
2018/06/15 全球购物
如何在.net Winform里面显示PDF文档
2012/09/11 面试题
企业为何需要商业计划书
2013/12/26 职场文书
书法培训心得体会
2014/01/05 职场文书
应届毕业生个人求职信范文
2014/01/29 职场文书
2014年保育员个人工作总结
2014/12/02 职场文书
办公经费申请报告
2015/05/15 职场文书
详解如何用Python实现感知器算法
2021/06/18 Python
Python开发工具Pycharm的安装以及使用步骤总结
2021/06/24 Python
Oracle数据库中通用的函数实例详解
2022/03/25 Oracle
HTML实现仿Windows桌面主题特效的实现
2022/06/28 HTML / CSS
Android RecyclerView实现九宫格效果
2022/06/28 Java/Android