用Python写一个扫雷游戏
时间: 2023-03-14 21:19:25 浏览: 10
使用Python的扫雷游戏
5星 · 资源好评率100%
好的,我可以为您提供一个简单的扫雷游戏代码。
```
import random
class Minesweeper:
def __init__(self, height, width, mines):
self.height = height
self.width = width
self.mines = mines
self.board = [[0 for x in range(self.width)] for y in range(self.height)]
self.hidden_board = [['-' for x in range(self.width)] for y in range(self.height)]
def place_mines(self):
mines_placed = 0
while mines_placed < self.mines:
x, y = random.randint(0, self.height - 1), random.randint(0, self.width - 1)
if self.board[x][y] == '*':
continue
self.board[x][y] = '*'
mines_placed += 1
def show(self):
print(' ', end='')
for i in range(self.width):
print(i, end=' ')
print()
for i in range(self.height):
print(i, end=' ')
for j in range(self.width):
print(self.hidden_board[i][j], end=' ')
print()
def get_adjacent_mines(self, x, y):
count = 0
for i in range(x - 1, x + 2):
for j in range(y - 1, y + 2):
if i >= 0 and i < self.height and j >= 0 and j < self.width and self.board[i][j] == '*':
count += 1
return count
def play(self):
self.place_mines()
while True:
self.show()
x, y = map(int, input("请输入您想打开的格子的行列坐标(例如:0 0):").strip().split())
if self.board[x][y] == '*':
print("游戏结束!")
break
else:
adj_mines = self.get_adjacent_mines(x, y)
self.hidden_board[x][y] = adj_mines
if adj_mines == 0:
self.open_adjacent_tiles(x, y)
def open_adjacent_tiles(self, x, y):
for i in range(x - 1, x + 2):
for j in range(y - 1, y + 2):
if i >= 0 and i < self.height and j >= 0 and j < self.width and self.hidden_board[i][j] == '-':
adj_mines = self.get_adjacent_mines(i, j)
self.hidden_board[i
阅读全文