import random
def minesweeper(m,n,p):
"""
:param m: 矩阵的行数
:param n: 矩阵的列数
:param p: 每个格点有p的概率生成雷
:return:
"""
# 避免边界,增加一圈边界
board = [[None] * (n+2) for i in range(m+2)]
for i in range(1,m+1):
for j in range(1,n+1):
r = random.random() # 产生0到1随机数
board[i][j] = -1 if r<p else 0
for i in range(1,m+1):
for j in range(1,n+1):
print("*",end=" ") if board[i][j]== -1 else print(".",end=" ")
print()
for i in range(1,m+1):
for j in range(1,n+1):
if board[i][j] != -1:
for ii in range(i - 1, i + 2):
for jj in range(j - 1, j + 2):
if board[ii][jj] == -1:
board[i][j] += 1
for i in range(1,m+1):
for j in range(1,n+1):
print("*",end=" ") if board[i][j]== -1 else print(board[i][j],end=" ")
print()
if __name__ == '__main__':
minesweeper(5,10,0.2)
python扫雷布雷小程序
最新推荐文章于 2024-06-14 18:18:48 发布