import random
import string
class Minefield:
def __init__(self, width, height, num_mines):
self.width = width
self.height = height
self.num_mines = num_mines
self.board = [[' ' for _ in range(self.width)] for _ in range(self.height)]
self.mines = set()
self.revealed = set()
self.game_over = False
self._plant_mines()
def _plant_mines(self):
while len(self.mines) < self.num_mines:
x = random.randint(0, self.width - 1)
y = random.randint(0, self.height - 1)
if (x, y) not in self.mines:
self.mines.add((x, y))
self.board[y][x] = '*'
self._increment_adjacent_mines(x, y)
def _increment_adjacent_mines(self, x, y):
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if (dx == 0 and dy == 0) or not (0 <= x + dx < self.width) or not (0 <= y + dy < self.height):
continue
if self.board[y + dy][x + dx] != '*':
self.board[y + dy][x + dx] = str(int(self.board[y + dy][x + dx]) + 1) if self.board[y + dy][x + dx] != ' ' else '1'
def reveal(self, x, y):
if (x, y) in self.revealed:
return
if (x, y) in self.mines:
self.game_over = True
return
self.revealed.add((x, y))
if self.board[y][x] == ' ':
for dx in [-1, 0, 1]:
for dy in [-1, 0, 1]:
if (dx == 0 and dy == 0) or not (0 <= x + dx < self.width) or not (0 <= y + dy < self.height):
continue
self.reveal(x + dx, y + dy)
def display(self):
print(" " + " ".join(string.ascii_uppercase[:self.width]))
for y in range(self.height):
row = f"{y + 1:2} " + " ".join(self.board[y][x] if (x,y) in self.revealed else '#' for x in range(self.width))
print(row)
def main():
width = 10
height = 10
num_mines = 10
minefield = Minefield(width, height, num_mines)
while not minefield.game_over:
minefield.display()
try:
user_input = input("Enter your move (e.g., A1): ")
col = string.ascii_uppercase.index(user_input[0])
row = int(user_input[1:]) - 1
if 0 <= col < width and 0 <= row < height:
minefield.reveal(col, row)
else:
print("Invalid move! Please try again.")
except (ValueError, IndexError):
print("Invalid input! Please use the format 'LetterNumber' (e.g., A1).")
print("Game Over!")
minefield.display()
if __name__ == "__main__":
main()
User
No file 'player.png' found in working directory 'E:\作业\Python vs练习\Python vs练习'.
from PIL import Image
# 尝试加载图片
try:
player_image = Image.open("player.png") # 假设 player.png 在当前工作目录
except FileNotFoundError:
print("No file 'player.png' found in the working directory.")