基于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支持断点续传的多线程下载示例
Jan 16 Python
Python求算数平方根和约数的方法汇总
Mar 09 Python
利用Python画ROC曲线和AUC值计算
Sep 19 Python
python实现数独游戏 java简单实现数独游戏
Mar 30 Python
python2.7实现邮件发送功能
Dec 12 Python
Python3.5面向对象程序设计之类的继承和多态详解
Apr 24 Python
python 多进程并行编程 ProcessPoolExecutor的实现
Oct 11 Python
python判断链表是否有环的实例代码
Jan 31 Python
python3读取文件指定行的三种方法
May 24 Python
浅谈Python数学建模之线性规划
Jun 23 Python
Python基础数据类型tuple元组的概念与用法
Aug 02 Python
Python装饰器的练习题
Nov 23 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
改造一台复古桌面收音机
2021/03/02 无线电
Apache2 httpd.conf 中文版
2006/11/17 PHP
详解php的魔术方法__get()和__set()使用介绍
2012/09/19 PHP
thinkphp实现发送邮件密码找回功能实例
2014/12/01 PHP
thinkPHP数据库增删改查操作方法实例详解
2016/12/06 PHP
一次因composer错误使用引发的问题与解决
2019/03/06 PHP
10个新的最有前途的JavaScript框架
2009/03/12 Javascript
使用jQuery.Validate进行客户端验证(初级篇) 不使用微软验证控件的理由
2010/06/28 Javascript
基于JQuery的asp.net树实现代码
2010/11/30 Javascript
jquery中ajax学习笔记3
2011/10/16 Javascript
jQuery之折叠面板的深入解析
2013/06/19 Javascript
调试JavaScript中正则表达式中遇到的问题
2015/01/27 Javascript
深入学习JavaScript中的Rest参数和参数默认值
2015/07/28 Javascript
WEB前端开发都应知道的jquery小技巧及jquery三个简写
2015/11/15 Javascript
使用React实现轮播效果组件示例代码
2016/09/05 Javascript
详解angular element()方法使用
2017/04/08 Javascript
js调用刷新界面的几种方式
2017/05/03 Javascript
mui js控制开关状态、修改switch开关的值方法
2019/09/03 Javascript
推荐几个不错的console调试技巧实现
2019/12/20 Javascript
Vue通过配置WebSocket并实现群聊功能
2019/12/31 Javascript
vue渲染方式render和template的区别
2020/06/05 Javascript
Vue触发input选取文件点击事件操作
2020/08/07 Javascript
python文件比较示例分享
2014/01/10 Python
Python中几种属性访问的区别与用法详解
2018/10/10 Python
Python实现桌面翻译工具【新手必学】
2020/02/12 Python
解决Django中checkbox复选框的传值问题
2020/03/31 Python
Python JSON常用编解码方法代码实例
2020/09/05 Python
美国钻石商店:Zales
2016/11/20 全球购物
公司门卫管理制度
2014/02/01 职场文书
学习心理学的体会
2014/11/07 职场文书
护士长2014年度工作总结
2014/11/11 职场文书
2014年前台文员工作总结
2014/12/08 职场文书
2016年秋季运动会广播稿
2015/12/21 职场文书
Java并发编程必备之Future机制
2021/06/30 Java/Android
MySQL的存储过程和相关函数
2022/04/26 MySQL
Li list-style-image 图片垂直居中实现方法
2023/05/21 HTML / CSS