用python写个扫雷代码
时间: 2023-02-22 22:21:43 浏览: 3
好的,我可以给你一份扫雷的代码:
```
import random
def init_board(size, num_mines):
board = [[0 for j in range(size)] for i in range(size)]
mines = random.sample(range(0, size * size), num_mines)
for mine in mines:
x, y = divmod(mine, size)
board[x][y] = 'X'
return board
def show_board(board):
print(' ', end='')
for i in range(len(board)):
print(f' {i}', end='')
print()
for i, row in enumerate(board):
print(i, end=' ')
for j in row:
print(f' {j}', end=' ')
print()
def count_mines(board, x, y):
count = 0
for i in range(x - 1, x + 2):
for j in range(y - 1, y + 2):
if 0 <= i < len(board) and 0 <= j < len(board[0]) and board[i][j] == 'X':
count += 1
return count
def fill_board(board):
for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 0:
board[i][j] = count_mines(board, i, j)
def main():
size = int(input("请输入地图的大小:"))
num_mines = int(input("请输入地雷数量:"))
board = init_board(size, num_mines)
fill_board(board)
show_board(board)
if __name__ == '__main__':
main()
```
这份代码可以实现一个简单的扫雷游戏,你可以输入地图的大小和地雷数量来生成一个扫雷地图。地图中数字代表周围有多少颗地雷。
阅读全文