基于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 相关文章推荐
pycharm 使用心得(三)Hello world!
Jun 05 Python
仅用50行代码实现一个Python编写的计算器的教程
Apr 17 Python
Python设计足球联赛赛程表程序的思路与简单实现示例
Jun 28 Python
Python利用IPython提高开发效率
Aug 10 Python
详解Python 序列化Serialize 和 反序列化Deserialize
Aug 20 Python
Linux下多个Python版本安装教程
Aug 15 Python
Python数据可视化:泊松分布详解
Dec 07 Python
Python综合应用名片管理系统案例详解
Jan 03 Python
python对文件的操作方法汇总
Feb 28 Python
python实现udp传输图片功能
Mar 20 Python
Pytorch 统计模型参数量的操作 param.numel()
May 13 Python
pytorch实现ResNet结构的实例代码
May 17 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学习笔记(三)操作符与控制结构
2011/08/06 PHP
php curl基本操作详解
2013/07/23 PHP
php jsonp单引号转义
2014/11/23 PHP
实现checkbox全选、反选、取消JavaScript小脚本异常
2014/04/10 Javascript
Javscript调用iframe框架页面中函数的方法
2014/11/01 Javascript
javascript格式化指定日期对象的方法
2015/04/21 Javascript
JS+CSS相对定位实现的下拉菜单
2015/10/06 Javascript
javascript 判断页面访问方式电脑或者移动端
2016/09/19 Javascript
基于Bootstrap 3 JQuery及RegExp的表单验证功能
2017/02/16 Javascript
基于cookie实现zTree树刷新后展开状态不变
2017/02/28 Javascript
微信小程序 动态传参实例详解
2017/04/27 Javascript
js实现京东轮播图效果
2017/06/30 Javascript
微信小程序选择图片和放大预览图片功能
2017/11/02 Javascript
基于 D3.js 绘制动态进度条的实例详解
2018/02/26 Javascript
使用Vue动态生成form表单的实例代码
2018/04/26 Javascript
详解vue项目中使用token的身份验证的简单实践
2019/03/08 Javascript
JS如何在不同平台实现多语言方式
2020/07/16 Javascript
利用Python的Flask框架来构建一个简单的数字商品支付解决方案
2015/03/31 Python
python实现复制整个目录的方法
2015/05/12 Python
CentOS安装pillow报错的解决方法
2016/01/27 Python
Python使用Matplotlib实现Logos设计代码
2017/12/25 Python
详解python中递归函数
2019/04/16 Python
anaconda如何查看并管理python环境
2019/07/05 Python
浅谈python3中input输入的使用
2019/08/02 Python
Python并发请求下限制QPS(每秒查询率)的实现代码
2020/06/05 Python
德国最大的网上鞋店之一:Schuhe24.de
2017/06/10 全球购物
Whittard官方海外旗舰店:英国百年茶叶品牌
2018/02/22 全球购物
任意存:BOXFUL
2018/05/21 全球购物
英国门把手公司:Door Handle Company
2019/05/12 全球购物
ruby如何进行集成操作?Ruby能进行多重继承吗?
2013/10/16 面试题
大学迎新晚会主持词
2014/03/24 职场文书
租房协议书范例
2014/10/14 职场文书
龙潭大峡谷导游词
2015/02/10 职场文书
2016中学教师读书心得体会
2016/01/13 职场文书
《丑小鸭》教学反思
2016/02/19 职场文书
Nginx的基本概念和原理
2022/03/21 Servers