0% found this document useful (0 votes)
15 views3 pages

Python Minesweeper Game Code

The document contains a Python implementation of a Minesweeper game. It includes classes and methods for initializing the game board, placing mines, calculating adjacent mines, revealing cells, and checking for win conditions. The game runs in a loop where the player inputs moves until they either win or hit a mine.

Uploaded by

ishikatanwar0125
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views3 pages

Python Minesweeper Game Code

The document contains a Python implementation of a Minesweeper game. It includes classes and methods for initializing the game board, placing mines, calculating adjacent mines, revealing cells, and checking for win conditions. The game runs in a loop where the player inputs moves until they either win or hit a mine.

Uploaded by

ishikatanwar0125
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

import random

import sys

class Minesweeper:
def __init__(self, rows=8, cols=8, mines=10):
[Link] = rows
[Link] = cols
[Link] = mines
[Link] = [['?' for _ in range(cols)] for _ in range(rows)] # Visible board
self.mine_board = [[0 for _ in range(cols)] for _ in range(rows)] # Hidden: 0=empty, -
1=mine, >0=adjacent mines
[Link] = [[False for _ in range(cols)] for _ in range(rows)]
self.game_over = False
[Link] = False
self._place_mines()
self._calculate_numbers()

def _place_mines(self):
"""Randomly place mines on the mine_board."""
mine_positions = [Link](range([Link] * [Link]), [Link])
for pos in mine_positions:
row, col = divmod(pos, [Link])
self.mine_board[row][col] = -1

def _calculate_numbers(self):
"""Calculate the number of adjacent mines for each cell."""
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
for r in range([Link]):
for c in range([Link]):
if self.mine_board[r][c] == -1:
continue # Skip mines
count = 0
for dr, dc in directions:
nr, nc = r + dr, c + dc
if 0 <= nr < [Link] and 0 <= nc < [Link] and self.mine_board[nr][nc] == -1:
count += 1
self.mine_board[r][c] = count

def display_board(self):
"""Display the current state of the board."""
print(" ", end="")
for c in range([Link]):
print(f"{c:2}", end="")
print()
for r in range([Link]):
print(f"{r:2}", end=" ")
for c in range([Link]):
if [Link][r][c]:
val = self.mine_board[r][c]
if val == -1:
print(" M", end="")
elif val == 0:
print(" .", end="")
else:
print(f" {val}", end="")
else:
print(" ? ", end="")
print()
print()

def reveal(self, r, c):


"""Reveal a cell and handle flood fill if it's a zero."""
if not (0 <= r < [Link] and 0 <= c < [Link]):
return False
if [Link][r][c]:
return True
[Link][r][c] = True
if self.mine_board[r][c] == -1:
self.game_over = True
return False
if self.mine_board[r][c] != 0:
return True
# Flood fill for zeros
directions = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
for dr, dc in directions:
nr, nc = r + dr, c + dc
[Link](nr, nc)
return True

def check_win(self):
"""Check if all non-mine cells are revealed."""
revealed_count = sum(sum(1 for c in range([Link]) if [Link][r][c]) for r in
range([Link]))
total_safe = [Link] * [Link] - [Link]
[Link] = revealed_count == total_safe
return [Link]

def play(self):
"""Main game loop."""
print(f"Minesweeper {[Link]}x{[Link]} with {[Link]} mines.")
print("Enter row and column (e.g., '3 4') to reveal a cell.")
print("Type 'quit' to exit.")
self.display_board()

while not self.game_over and not [Link]:


try:
user_input = input("Your move (row col): ").strip().lower()
if user_input == 'quit':
print("Thanks for playing!")
[Link](0)
parts = user_input.split()
if len(parts) != 2:
print("Invalid input. Use 'row col' format.")
continue
r, c = int(parts[0]), int(parts[1])
if [Link](r, c):
self.check_win()
self.display_board()
if [Link]:
print("Congratulations! You won!")
else:
self.display_board()
print("Boom! You hit a mine. Game over!")
except ValueError:
print("Invalid input. Row and column must be integers.")
except KeyboardInterrupt:
print("\nThanks for playing!")
[Link](0)

# Run the game


if __name__ == "__main__":
game = Minesweeper(rows=8, cols=8, mines=10)
[Link]()

You might also like