用python写个扫雷
时间: 2023-02-21 19:26:15 浏览: 78
好的,这是一个简单的扫雷代码:
```
import random
class MineSweeper:
def __init__(self, row, col, mines):
self.row = row
self.col = col
self.mines = mines
self.board = [[0 for j in range(col)] for i in range(row)]
self.mines_pos = []
self.visited = [[False for j in range(col)] for i in range(row)]
def place_mines(self):
mines_placed = 0
while mines_placed < self.mines:
x = random.randint(0, self.row-1)
y = random.randint(0, self.col-1)
if [x, y] not in self.mines_pos:
self.mines_pos.append([x, y])
mines_placed += 1
def get_adjacent(self, x, y):
adj = []
if x > 0:
adj.append([x-1, y])
if x < self.row-1:
adj.append([x+1, y])
if y > 0:
adj.append([x, y-1])
if y < self.col-1:
adj.append([x, y+1])
if x > 0 and y > 0:
adj.append([x-1, y-1])
if x > 0 and y < self.col-1:
adj.append([x-1, y+1])
if x < self.row-1 and y > 0:
adj.append([x+1, y-1])
if x < self.row-1 and y < self.col-1:
adj.append([x+1, y+1])
return adj
def place_numbers(self):
for pos in self.mines_pos:
x, y = pos
adj = self.get_adjacent(x, y)
for a in adj:
a_x, a_y = a
self.board[a_x][a_y] += 1
def dfs(self, x, y):
if self.board[x][y] == 0:
self.visited[x][y] = True
adj = self.get_adjacent(x, y)
for a in adj:
a_x, a_y = a
if not self.visited[a_x][a_y]:
self.dfs(a_x, a_y)
def play(self, x, y):
if [x, y] in self.mines_pos:
print("Game Over")
return False
else:
self.dfs(x, y)
return True
def print_board(self):
for row in self.board:
print(row)
game = MineSweeper(5, 5, 5)
game.place_mines()
game.place_numbers()
game
阅读全文