python实现扫雷游戏
时间: 2023-08-14 16:10:12 浏览: 86
以下是一个简单的使用Python实现的命令行扫雷游戏示例代码:
```python
import random
class Minesweeper:
def __init__(self, rows, cols, bombs):
self.rows = rows
self.cols = cols
self.bombs = bombs
self.board = [[0 for _ in range(cols)] for _ in range(rows)]
self.visible_board = [['-' for _ in range(cols)] for _ in range(rows)]
self.generate_board()
def generate_board(self):
bombs = self.bombs
while bombs > 0:
row = random.randint(0, self.rows - 1)
col = random.randint(0, self.cols - 1)
if self.board[row][col] != -1:
self.board[row][col] = -1
bombs -= 1
for row in range(self.rows):
for col in range(self.cols):
if self.board[row][col] == -1:
continue
count = 0
for r in range(max(row - 1, 0), min(row + 2, self.rows)):
for c in range(max(col - 1, 0), min(col + 2, self.cols)):
if self.board[r][c] == -1:
count += 1
self.board[row][col] = count
def show_board(self):
print(' ' + ' '.join(str(i) for i in range(self.cols)))
print(' +' + '-' * (2 * self.cols - 1) + '+')
for row in range(self.rows):
print(f'{row} |', end='')
for col in range(self.cols):
print(self.visible_board[row][col], end=' ')
print('|')
print(' +' + '-' * (2 * self.cols - 1) + '+')
def play(self, row, col):
if self.board[row][col] == -1:
return False
elif self.board[row][col] > 0:
self.visible_board[row][col] = str(self.board[row][col])
else:
self.visible_board[row][col] = ' '
for r in range(max(row - 1, 0), min(row + 2, self.rows)):
for c in range(max(col - 1, 0), min(col + 2, self.cols)):
if self.visible_board[r][c] == '-':
self.play(r, c)
return True
def play_game(self):
self.show_board()
while True:
row, col = input('Enter row and column (separated by space): ').split()
row, col = int(row), int(col)
if not self.play(row, col):
print('Game over!')
self.show_board()
break
elif self.check_win():
print('You win!')
self.show_board()
break
self.show_board()
def check_win(self):
for row in range(self.rows):
for col in range(self.cols):
if self.board[row][col] != -1 and self.visible_board[row][col] == '-':
return False
return True
if __name__ == '__main__':
rows = int(input('Enter number of rows: '))
cols = int(input('Enter number of columns: '))
bombs = int(input('Enter number of bombs: '))
game = Minesweeper(rows, cols, bombs)
game.play_game()
```
运行代码后,程序将会要求用户输入行数、列数和炸弹数量,并生成一个扫雷游戏。玩家可以通过输入行号和列号来选择一个方格,程序将会根据选中的方格进行游戏操作。游戏操作有两种情况:
- 如果选中的方格是炸弹,游戏结束;
- 如果选中的方格不是炸弹,则会显示该方格周围的炸弹数量。如果周围没有炸弹,程序将会递归地展开周围的方格,直到遇到有炸弹的方格。
当所有非炸弹方格都被选中时,游戏胜利。
阅读全文