- 2nd Jan 2024
- 21:32 pm
import random
class Minesweeper:
def __init__(self, width=10, height=10, num_mines=10):
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 = []
self.generate_board()
self.revealed = set()
def generate_board(self):
mine_positions = random.sample(range(self.width * self.height), self.num_mines)
self.mines = [(pos // self.width, pos % self.width) for pos in mine_positions]
def is_valid(self, x, y):
return 0 <= x < self.height and 0 <= y < self.width
def count_adjacent_mines(self, x, y):
count = 0
for i in range(-1, 2):
for j in range(-1, 2):
new_x, new_y = x + i, y + j
if self.is_valid(new_x, new_y) and (new_x, new_y) in self.mines:
count += 1
return count
def reveal(self, x, y):
if (x, y) in self.revealed:
return
if (x, y) in self.mines:
self.board[x][y] = '*'
return
mines_count = self.count_adjacent_mines(x, y)
self.board[x][y] = str(mines_count) if mines_count > 0 else ' '
self.revealed.add((x, y))
if mines_count == 0:
for i in range(-1, 2):
for j in range(-1, 2):
new_x, new_y = x + i, y + j
if self.is_valid(new_x, new_y):
self.reveal(new_x, new_y)
def display_board(self):
for row in self.board:
print(' '.join(row))
def play(self):
print("Welcome to Minesweeper!")
print("Enter row and column numbers to reveal the cell.")
while True:
self.display_board()
user_input = input("Enter row and column (separated by space) to reveal: ").split()
if len(user_input) != 2 or not user_input[0].isdigit() or not user_input[1].isdigit():
print("Invalid input. Please enter row and column numbers separated by a space.")
continue
row, col = map(int, user_input)
if not self.is_valid(row, col):
print("Invalid row or column.")
continue
if (row, col) in self.mines:
print("Game Over! You hit a mine.")
self.reveal(row, col)
self.display_board()
break
self.reveal(row, col)
if len(self.revealed) == self.width * self.height - self.num_mines:
print("Congratulations! You win.")
self.display_board()
break
# Start the game
minesweeper = Minesweeper()
minesweeper.play()
This implementation of Minesweeper is a text-based game where the player inputs row and column numbers to reveal cells on the board. The game ends if the player reveals a mine or wins by revealing all non-mine cells.