用300行的代码写一个扫雷小游戏
时间: 2023-12-29 20:16:53 浏览: 25
以下是一个简单的扫雷小游戏的代码,使用 Python 语言编写:
```python
import random
class Minesweeper:
def __init__(self, rows, cols, num_bombs):
self.rows = rows
self.cols = cols
self.num_bombs = num_bombs
self.board = [[' ' for _ in range(cols)] for _ in range(rows)]
self.visible_board = [[' ' for _ in range(cols)] for _ in range(rows)]
self.bombs = []
self.game_over = False
def init_board(self, row_click, col_click):
# Place bombs randomly
while len(self.bombs) < self.num_bombs:
row = random.randint(0, self.rows-1)
col = random.randint(0, self.cols-1)
if (row, col) != (row_click, col_click) and (row, col) not in self.bombs:
self.bombs.append((row, col))
self.board[row][col] = '*'
# Count the number of bombs around each cell
for row in range(self.rows):
for col in range(self.cols):
if self.board[row][col] == ' ':
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] == '*':
count += 1
if count > 0:
self.board[row][col] = str(count)
def reveal(self, row, col):
if self.board[row][col] == '*':
self.visible_board[row][col] = '*'
self.game_over = True
elif self.visible_board[row][col] == ' ':
self.visible_board[row][col] = self.board[row][col]
if self.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 (r, c) != (row, col):
self.reveal(r, c)
def print_board(self):
print(' ', end='')
for col in range(self.cols):
print(col, end=' ')
print()
for row in range(self.rows):
print(row, end=' ')
for col in range(self.cols):
if self.visible_board[row][col] != ' ':
print(self.visible_board[row][col], end=' ')
else:
print('-', end=' ')
print()
def play(self):
self.print_board()
while not self.game_over:
row = int(input('Enter row: '))
col = int(input('Enter column: '))
if (row, col) in self.bombs:
self.game_over = True
else:
self.reveal(row, col)
self.print_board()
print('Game over!')
if __name__ == '__main__':
game = Minesweeper(5, 5, 5)
row_click = random.randint(0, game.rows-1)
col_click = random.randint(0, game.cols-1)
game.init_board(row_click, col_click)
game.play()
```
这个游戏使用命令行界面,玩家需要输入行和列的坐标以揭示相应位置的方块。如果玩家揭示到地雷,游戏结束。如果玩家揭示了所有不是地雷的方块,游戏胜利。