用python写个扫雷游戏
时间: 2023-06-27 22:06:54 浏览: 189
Python实现自动扫雷游戏的方法源码
可以的,我可以为您提供一个简单的代码示例,如下所示:
```
import random
def create_board(rows, cols, num_mines):
# Create an empty board
board = [[0 for col in range(cols)] for row in range(rows)]
# Add mines to the board
mines = 0
while mines < num_mines:
row = random.randint(0, rows - 1)
col = random.randint(0, cols - 1)
if board[row][col] != -1:
board[row][col] = -1
mines += 1
# Fill in the numbers around the mines
for row in range(rows):
for col in range(cols):
if board[row][col] == -1:
# Add 1 to each adjacent square
for i in range(-1, 2):
for j in range(-1, 2):
if 0 <= row + i < rows and 0 <= col + j < cols and board[row + i][col + j] != -1:
board[row + i][col + j] += 1
return board
def print_board(board):
rows = len(board)
cols = len(board[0])
# Print the column numbers
print(" ", end="")
for col in range(cols):
print(col, end=" ")
print("")
# Print the board
for row in range(rows):
print(row, end=" ")
for col in range(cols):
if board[row][col] == -1:
print("*", end=" ")
elif board[row][col] == 0:
print(".", end=" ")
else:
print(board[row][col], end=" ")
print("")
def reveal(board, revealed, row, col):
if revealed[row][col]:
return
rows = len(board)
cols = len(board[0])
# Reveal the square and continue recursively if it's a zero
revealed[row][col] = True
if board[row][col] == 0:
for i in range(-1, 2):
for j in range(-1, 2):
if 0 <= row + i < rows and 0 <= col + j < cols:
reveal(board, revealed, row + i, col + j)
def play_game():
rows = int(input("Enter the number of rows: "))
cols = int(input("Enter the number of columns: "))
num_mines = int(input("Enter the number of mines: "))
board = create_board(rows, cols, num_mines)
revealed = [[False for col in range(cols)] for row in range(rows)]
while True:
print_board(revealed)
row = int(input("Enter a row: "))
col = int(input("Enter a column: "))
if board[row][col] == -1:
print("You hit a mine! Game over.")
break
else:
reveal(board, revealed, row, col)
# Check if the game is won
if all(all(revealed[row][col] or board[row][col] == -1 for col in range(cols)) for row in range(rows)):
print_board(board)
print("You win!")
break
play_game()
```
该脚本将使用Python语言实现一个简单的扫雷游戏。用户将输入行数、列数和地雷数量,游戏板将被创建并显示。玩家可以选择一个单元格来揭开,如果点击地雷则游戏失败,如果玩家成功在未触雷的情况下揭示了所有方格,则获胜。
阅读全文