python扫雷游戏设计_python扫雷游戏

#-*- coding: utf-8 -*-#@Time : 2020/12/18 12:57#@Author : Zhenghui Lyu#@File : Main.py#@Software: PyCharm

from tkinter import *

from tkinter.messagebox import *

importrandomimportosimportsysdefnew():"""重新开始游戏"""

globalm

m.grid_remove()globalmodel

model= Model(10, 10)

m=Mines(model, root)classModel:"""Model类用于存储所有方块所在的(r,c)信息,有雷为1,无为0,还可检查周围雷的情况"""

def __init__(self, row, col):

self.width= col #列

self.height = row #行

self.items = [[0 for c in range(col)] for r inrange(row)]defsetItemValue(self, r, c, value):"""设置某个位置的值为value"""self.items[r][c]= value #model.setItemValue(r, rancol, 1)

defcheckValue(self, r, c, value):"""检查某个位置的值是否为value"""

if self.items[r][c] ==value:returnTrueelse:returnFalsedefcountValue(self, r, c, value):"""统计位置(r,c)周围8个位置,值为value的个数"""count=0if 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

returncountclassMines(Frame):def __init__(self, m, master=None):

Frame.__init__(self, master)

self.model=m

self.initmine()

self.grid()

self.createWidget()defcreateWidget(self):

self.rowconfigure(self.model.height* 2, weight=1)

self.columnconfigure(self.model.width* 2, weight=1)

self.buttongroups= [[Button(self, height=1, width=2) for j in range(self.model.width)] for j inrange(self.model.height)]for r inrange(self.model.width):for c inrange(self.model.height):

self.buttongroups[r][c].grid(row=r, column=c, sticky=(W, E, N, S))

self.buttongroups[r][c].bind('', self.clickevent)

self.buttongroups[r][c].bind('', self.Rightclickevent)

self.buttongroups[r][c]['padx'] =r

self.buttongroups[r][c]['pady'] =cdefclickevent(self, event):

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)if(self.Victory()):

showinfo(title='提示', message='你赢了')defRightclickevent(self, event):

r= int(str(event.widget['padx']))

c= int(str(event.widget['pady']))if self.buttongroups[r][c]['text'] == 'X':

self.buttongroups[r][c]['image'] =askImageelse:

self.buttongroups[r][c]['image'] =flagImage

self.buttongroups[r][c]['text'] = 'X'

ifself.Victory():

showinfo(title='提示', message='你赢了')defVictory(self):for r inrange(model.height):for c inrange(model.width):if self.buttongroups[r][c]['state'] == NORMAL and self.buttongroups[r][c]['text'] != 'X':returnFalseif model.checkValue(r, c, 0) and self.buttongroups[r][c]['text'] == 'X':returnFalsereturnTruedefshowall(self):for r inrange(model.height):for c inrange(model.width):

self.showone(r, c)defshowone(self, r, c):ifmodel.checkValue(r, c, 0):

self.buttongroups[r][c]['text'] = model.countValue(r, c, 1)else:

self.buttongroups[r][c]['text'] = 'Q'self.buttongroups[r][c]['image'] =mineImagedefrecureshow(self, r, c):if 0 <= r <= self.model.height - 1 and 0 <= c <= self.model.width - 1:if model.checkValue(r, c, 0) and self.buttongroups[r][c]['state'] == NORMAL andmodel.countValue(r, c,1) ==0:

self.buttongroups[r][c]['state'] =DISABLED

self.buttongroups[r][c]['bd'] = 4self.buttongroups[r][c]['disabledforeground'] = 'red'self.buttongroups[r][c]['text'] = '0'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)

self.buttongroups[r][c]['state'] =DISABLED

self.buttongroups[r][c]['bd'] = 4self.buttongroups[r][c]['disabledforeground'] = 'red'

else:pass

definitmine(self):"""埋雷,每行埋(1,height/width)个随机数量雷"""n= random.randint(1, model.height /model.width)for r inrange(model.height):for i inrange(n):

rancol= random.randint(0, model.width - 1)

model.setItemValue(r, rancol,1)defprintf(self):print('地图')for r inrange(model.height):for c inrange(model.width):print(model.items[r][c], end='')print('')if __name__ == '__main__':

model= Model(10, 10)

root=Tk()

mineImage= PhotoImage(file='mine.gif')

flagImage= PhotoImage(file='flag.gif')

askImage= PhotoImage(file='ask.gif')

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)

m=Mines(model, root)

m.printf()

root.mainloop()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Python 扫雷游戏代码示例: ```python import random # 定义常量 BOMB = -1 HIDDEN = 0 UNCOVERED = 1 class Minesweeper: def __init__(self, rows, cols, bombs): self.rows = rows self.cols = cols self.bombs = bombs self.grid = [[HIDDEN] * cols for _ in range(rows)] self.generate_bombs() def generate_bombs(self): bombs_placed = 0 while bombs_placed < self.bombs: row = random.randint(0, self.rows - 1) col = random.randint(0, self.cols - 1) if self.grid[row][col] != BOMB: self.grid[row][col] = BOMB bombs_placed += 1 def uncover(self, row, col): if self.grid[row][col] == BOMB: return False elif self.grid[row][col] == HIDDEN: self.grid[row][col] = UNCOVERED if self.neighbor_bomb_count(row, col) == 0: for r in range(max(0, row - 1), min(row + 2, self.rows)): for c in range(max(0, col - 1), min(col + 2, self.cols)): if r != row or c != col: self.uncover(r, c) return True def neighbor_bomb_count(self, row, col): count = 0 for r in range(max(0, row - 1), min(row + 2, self.rows)): for c in range(max(0, col - 1), min(col + 2, self.cols)): if self.grid[r][c] == BOMB: count += 1 return count def __str__(self): result = '' for row in self.grid: for cell in row: if cell == UNCOVERED: count = self.neighbor_bomb_count(self.grid.index(row), row.index(cell)) result += str(count) if count > 0 else ' ' elif cell == HIDDEN: result += '*' else: result += 'X' result += '\n' return result[:-1] # 示例用法 game = Minesweeper(5, 5, 5) print(game) game.uncover(2, 2) print(game) ``` 该示例代码使用了一个 `Minesweeper` 类来表示扫雷游戏,并包含了以下方法: - `__init__(self, rows, cols, bombs)`:构造方法,初始化游戏的行数、列数和炸弹数,并生成游戏网格。 - `generate_bombs(self)`:随机生成指定数量的炸弹。 - `uncover(self, row, col)`:揭开指定位置的格子,并递归揭开周围的空格(如果有的话)。 - `neighbor_bomb_count(self, row, col)`:返回指定位置周围的炸弹数量。 - `__str__(self)`:将游戏网格转换为字符串,方便输出。 你可以根据自己的需求对这个示例代码进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值