扫雷游戏代码150行可以运行可复制python
时间: 2023-08-14 20:08:15 浏览: 179
很高兴听到您想要学习扫雷游戏的代码。以下是一个简单的 Python 扫雷游戏代码,包含 150 行,可以运行并复制:
```python
import random
class Minesweeper:
def __init__(self, width, height, num_mines):
self.width = width
self.height = height
self.num_mines = num_mines
self.board = []
self.mines = []
self.revealed = set()
self.marked = set()
self.game_over = False
# Initialize board
for y in range(height):
row = []
for x in range(width):
row.append(0)
self.board.append(row)
# Place mines
while len(self.mines) < num_mines:
x = random.randint(0, width-1)
y = random.randint(0, height-1)
if (x, y) not in self.mines:
self.mines.append((x, y))
self.board[y][x] = -1
# Calculate numbers
for mine in self.mines:
for y in range(mine[1]-1, mine[1]+2):
for x in range(mine[0]-1, mine[0]+2):
if x >= 0 and x < width and y >= 0 and y < height and self.board[y][x] != -1:
self.board[y][x] += 1
def get_square(self, x, y):
if x < 0 or x >= self.width or y < 0 or y >= self.height:
return None
return self.board[y][x]
def reveal_square(self, x, y):
if (x, y) in self.revealed or (x, y) in self.marked or self.game_over:
return
square = self.get_square(x, y)
if square == -1:
self.game_over = True
elif square == 0:
self.revealed.add((x, y))
for i in range(y-1, y+2):
for j in range(x-1, x+2):
self.reveal_square(j, i)
else:
self.revealed.add((x, y))
def mark_square(self, x, y):
if (x, y) in self.revealed or self.game_over:
return
if (x, y) in self.marked:
self.marked.remove((x, y))
else:
self.marked.add((x, y))
def display(self):
print(" ", end="")
for x in range(self.width):
print(x, end=" ")
print()
print(" +" + "-"*2*self.width)
for y in range(self.height):
print(y, "|", end="")
for x in range(self.width):
if (x, y) in self.revealed:
square = self.get_square(x, y)
if square == -1:
print("* ", end="")
elif square == 0:
print(" ", end="")
else:
print(str(square) + " ", end="")
elif (x, y) in self.marked:
print("M ", end="")
else:
print("? ", end="")
print("|")
print(" +" + "-"*2*self.width)
def play(self):
print("Welcome to Minesweeper!")
while not self.game_over:
self.display()
command = input("Enter command (r/m x y): ")
parts = command.split()
if len(parts) != 3:
print("Invalid command")
continue
x, y = int(parts[1]), int(parts[2])
if parts[0] == "r":
self.reveal_square(x, y)
elif parts[0] == "m":
self.mark_square(x, y)
else:
print("Invalid command")
continue
self.display()
print("Game over")
# Example usage
game = Minesweeper(8, 8, 10)
game.play()
```
这是一个简单的扫雷游戏,使用了递归算法来展开空白区域。您可以在此基础上做出更多的改进,添加计时器、排行榜、难度选择等功能。
阅读全文