给我一个有趣的Python程序,要求可以在Python3.10运行
时间: 2024-02-16 19:29:49 浏览: 61
有意思的Python小程序
好的,这里是一个有趣的Python程序,可以在Python3.10运行,它可以模拟一个简单的扫雷游戏。
```python
import random
class Minesweeper:
def __init__(self, size=10, mines=20):
self.size = size
self.mines = mines
self.board = [[0 for i in range(size)] for j in range(size)]
self.gameover = False
self.win = False
self.revealed = [[False for i in range(size)] for j in range(size)]
self.flagged = [[False for i in range(size)] for j in range(size)]
def get_adjacent_cells(self, x, y):
cells = []
for i in range(max(0, x-1), min(x+2, self.size)):
for j in range(max(0, y-1), min(y+2, self.size)):
if i != x or j != y:
cells.append((i, j))
return cells
def generate_board(self, x, y):
positions = [(i, j) for i in range(self.size) for j in range(self.size)]
for i in range(self.mines):
position = random.choice(positions)
positions.remove(position)
if position == (x, y):
continue
self.board[position[0]][position[1]] = -1
for cell in self.get_adjacent_cells(position[0], position[1]):
if self.board[cell[0]][cell[1]] != -1:
self.board[cell[0]][cell[1]] += 1
def reveal_cell(self, x, y):
if self.flagged[x][y]:
return
if self.board[x][y] == -1:
self.gameover = True
return
self.revealed[x][y] = True
if self.board[x][y] == 0:
for cell in self.get_adjacent_cells(x, y):
if not self.revealed[cell[0]][cell[1]]:
self.reveal_cell(cell[0], cell[1])
if self.check_win():
self.win = True
def flag_cell(self, x, y):
if not self.revealed[x][y]:
self.flagged[x][y] = not self.flagged[x][y]
def check_win(self):
for i in range(self.size):
for j in range(self.size):
if self.board[i][j] != -1 and not self.revealed[i][j]:
return False
return True
def print_board(self):
print(" ", end="")
for i in range(self.size):
print(i, end=" ")
print()
for i in range(self.size):
print(i, end="")
for j in range(self.size):
if self.flagged[i][j]:
print("F", end=" ")
elif not self.revealed[i][j]:
print(".", end=" ")
elif self.board[i][j] == -1:
print("*", end=" ")
else:
print(self.board[i][j], end=" ")
print()
def play(self):
x = random.randint(0, self.size-1)
y = random.randint(0, self.size-1)
self.generate_board(x, y)
while not self.gameover and not self.win:
self.print_board()
command = input("Enter command (R/F x y): ")
parts = command.split()
if len(parts) != 3:
continue
try:
x = int(parts[1])
y = int(parts[2])
except ValueError:
continue
if x < 0 or x >= self.size or y < 0 or y >= self.size:
continue
if parts[0].lower() == "r":
self.reveal_cell(x, y)
elif parts[0].lower() == "f":
self.flag_cell(x, y)
self.print_board()
if self.gameover:
print("Game over!")
elif self.win:
print("You win!")
minesweeper = Minesweeper()
minesweeper.play()
```
这个程序将生成一个随机的扫雷棋盘,并让玩家尝试找到所有的雷。玩家可以通过输入命令来揭示或标记单元格。祝你好运!
阅读全文