import tkinter as tk import random from tkinter import messagebox class Minesweeper: def __init__(self, master, rows=10, cols=10, mines=10): self.master = master self.rows = rows self.cols = cols self.mines = mines self.buttons = {} self.mine_positions = set() self.flags = set() self.create_widgets() self.place_mines() def create_widgets(self): for r in range(self.rows): for c in range(self.cols): button = tk.Button(self.master, width=2, height=1, command=lambda r=r, c=c: self.on_click(r, c)) button.bind('', lambda event, r=r, c=c: self.on_right_click(r, c)) button.grid(row=r, column=c) self.buttons[(r, c)] = button def place_mines(self): while len(self.mine_positions) < self.mines: row = random.randint(0, self.rows - 1) col = random.randint(0, self.cols - 1) self.mine_positions.add((row, col)) def on_click(self, row, col): if (row, col) in self.mine_positions: self.reveal_mines() messagebox.showinfo("Game Over", "You clicked on a mine!") self.master.quit() else: count = self.count_adjacent_mines(row, col) if count > 0: self.buttons[(row, col)].config(text=str(count), state="disabled") else: self.buttons[(row, col)].config(text='', state="disabled") self.reveal_empty_cells(row, col) if self.check_win(): messagebox.showinfo("Congratulations", "You Win!") self.master.quit() def on_right_click(self, row, col): if (row, col) in self.flags: self.buttons[(row, col)].config(text='', bg='SystemButtonFace') self.flags.remove((row, col)) else: self.buttons[(row, col)].config(text='F', bg='yellow') self.flags.add((row, col)) def reveal_mines(self): for mine in self.mine_positions: self.buttons[mine].config(text='M', bg='red') def count_adjacent_mines(self, row, col): count = 0 for r in range(max(0, row - 1), min(self.rows, row + 2)): for c in range(max(0, col - 1), min(self.cols, col + 2)): if (r, c) in self.mine_positions: count += 1 return count def reveal_empty_cells(self, row, col): for r in range(max(0, row - 1), min(self.rows, row + 2)): for c in range(max(0, col - 1), min(self.cols, col + 2)): if self.buttons[(r, c)]['state'] == 'normal': count = self.count_adjacent_mines(r, c) if count > 0: self.buttons[(r, c)].config(text=str(count), state="disabled") else: self.buttons[(r, c)].config(text='', state="disabled") self.reveal_empty_cells(r, c) def check_win(self): covered_cells = [self.buttons[(r, c)] for r in range(self.rows) for c in range(self.cols) if self.buttons[(r, c)]['state'] == 'normal'] return len(covered_cells) == self.mines if __name__ == "__main__": root = tk.Tk() root.title("Minesweeper") game = Minesweeper(root) root.mainloop()