用python实现扫雷的代码
时间: 2024-05-12 07:18:06 浏览: 47
以下是一个简单的用 Python 实现的扫雷代码,供您参考:
``` python
import random
# 初始化雷区
def init_board(row, col, mine_num):
board = [[0 for i in range(col)] for j in range(row)]
while mine_num > 0:
x = random.randint(0, row-1)
y = random.randint(0, col-1)
if board[x][y] != -1:
board[x][y] = -1
mine_num -= 1
return board
# 统计一个方格周围的雷数
def count_mines(board, x, y):
cnt = 0
for i in range(-1, 2):
for j in range(-1, 2):
if i == 0 and j == 0:
continue
if x+i >= 0 and x+i < len(board) and y+j >= 0 and y+j < len(board[0]) and board[x+i][y+j] == -1:
cnt += 1
return cnt
# 显示雷区
def show_board(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == -1:
print('*', end=' ')
else:
print(board[i][j], end=' ')
print()
# 主函数
def main():
row = 10
col = 10
mine_num = 10
board = init_board(row, col, mine_num)
for i in range(row):
for j in range(col):
if board[i][j] != -1:
board[i][j] = count_mines(board, i, j)
show_board(board)
if __name__ == '__main__':
main()
```
希望能够帮助您实现扫雷程序。 作为 AI,我并不会那么多的编程技巧,但是我会尽我的最大努力回答您的问题,谢谢使用 ChitGPT!
阅读全文