基于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中使用中文的方法
Feb 19 Python
Python守护进程(daemon)代码实例
Mar 06 Python
Python建立Map写Excel表实例解析
Jan 17 Python
利用Python在一个文件的头部插入数据的实例
May 02 Python
Python文件打开方式实例详解【a、a+、r+、w+区别】
Mar 30 Python
Python3 列表,数组,矩阵的相互转换的方法示例
Aug 05 Python
python os.path.isfile()因参数问题判断错误的解决
Nov 29 Python
Python破解BiliBili滑块验证码的思路详解(完美避开人机识别)
Feb 17 Python
python如何运行js语句
Sep 09 Python
python 带时区的日期格式化操作
Oct 23 Python
Python基础之赋值,浅拷贝,深拷贝的区别
Apr 30 Python
使用pipenv管理python虚拟环境的全过程
Sep 25 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的explode和implode的使用说明
2011/07/17 PHP
PHP生成随机用户名和密码的实现代码
2013/02/27 PHP
php jq jquery getJSON跨域提交数据完整版
2013/09/13 PHP
PHP中的traits实现代码复用使用实例
2015/05/13 PHP
PHP之将POST数据转化为字符串的实现代码
2016/11/03 PHP
Yii2.0框架实现带分页的多条件搜索功能示例
2019/02/20 PHP
Laravel 读取 config 下的数据方法
2019/10/13 PHP
将CKfinder整合进CKEditor3.0的新方法
2010/01/10 Javascript
javascript利用控件对windows的操作实现原理与应用
2012/12/23 Javascript
jquery实现marquee效果(文字或者图片的水平垂直滚动)
2013/01/07 Javascript
Angular.js回顾ng-app和ng-model使用技巧
2016/04/26 Javascript
Bootstrap布局组件教程之Bootstrap下拉菜单
2016/06/12 Javascript
jquery.form.js异步提交表单详解
2017/04/25 jQuery
JavaScript for循环 if判断语句(学习笔记)
2017/10/11 Javascript
BootStrap自定义popover,点击区域隐藏功能的实现
2018/01/23 Javascript
js 计算图片内点个数的示例代码
2019/04/04 Javascript
vue使用代理解决请求跨域问题详解
2019/07/24 Javascript
JS实现分页导航效果
2020/02/19 Javascript
vue实现表格合并功能
2020/12/01 Vue.js
Python 基于Twisted框架的文件夹网络传输源码
2016/08/28 Python
python提取图像的名字*.jpg到txt文本的方法
2018/05/10 Python
Python 微信之获取好友昵称并制作wordcloud的实例
2019/02/21 Python
python根据文本生成词云图代码实例
2019/11/15 Python
安装pyecharts1.8.0版本后导入pyecharts模块绘图时报错: “所有图表类型将在 v1.9.0 版本开始强制使用 ChartItem 进行数据项配置 ”的解决方法
2020/08/18 Python
mac安装python3后使用pip和pip3的区别说明
2020/09/01 Python
python实现数据结构中双向循环链表操作的示例
2020/10/09 Python
Canvas环形饼图与手势控制的实现代码
2019/11/08 HTML / CSS
服务宗旨标语
2014/07/01 职场文书
2014七年级班主任工作总结
2014/12/05 职场文书
综合素质自我评价评语
2015/03/06 职场文书
六一亲子活动感想
2015/08/07 职场文书
《迟到》教学反思
2016/02/24 职场文书
css3实现背景图片半透明内容不透明的方法示例
2021/04/13 HTML / CSS
Oracle11g r2 卸载干净重装的详细教程(亲测有效已重装过)
2021/06/04 Oracle
Python Pandas pandas.read_sql函数实例用法
2021/06/21 Python
Vue Mint UI mt-swipe的使用方式
2022/06/05 Vue.js