输出一段python扫雷游戏代码
时间: 2023-10-30 10:05:06 浏览: 86
好的,以下是一个简单的 Python 扫雷游戏代码:
```python
import random
def create_board(board_size, num_mines):
board = [[0 for _ in range(board_size)] for _ in range(board_size)]
mines = set()
while len(mines) < num_mines:
row = random.randint(0, board_size-1)
col = random.randint(0, board_size-1)
if (row, col) not in mines:
mines.add((row, col))
board[row][col] = '*'
for r in range(row-1, row+2):
for c in range(col-1, col+2):
if (0 <= r < board_size and 0 <= c < board_size and board[r][c] != '*'):
board[r][c] += 1
return board
def print_board(board):
board_size = len(board[0])
for r in range(board_size):
print(" ".join(str(board[r][c]) for c in range(board_size)))
def play_game(board_size=10, num_mines=10):
board = create_board(board_size, num_mines)
print_board(board)
while True:
row = int(input("Enter row: "))
col = int(input("Enter col: "))
if board[row][col] == '*':
print("Game over!")
return
elif board[row][col] != 0:
board[row][col] = str(board[row][col])
else:
# reveal adjacent squares
reveal(board, row, col)
print_board(board)
def reveal(board, row, col):
board_size = len(board[0])
if (0 <= row < board_size and 0 <= col < board_size and board[row][col] == 0):
board[row][col] = ' '
for r in range(row-1, row+2):
for c in range(col-1, col+2):
reveal(board, r, c)
play_game()
```
请注意,这只是一个基本的扫雷游戏,没有考虑复杂的规则或多个玩家等因素。
阅读全文