May-03-2021, 07:04 PM
(This post was last modified: May-03-2021, 07:05 PM by Yoriz.
Edit Reason: Changed TRUE to True
)
You would get a lot of benefit from a couple of simple classes. This is my attempt at Minesweeper using classes to represent the map and a single cell of the map. The cell knows how to do all the cell things like placing a flag marker (I used "F" instead of an image) or exposing the bomb our bomb count info. The board class creates all the cells and could easily be enhanced to display a remaining safe cell count and win/lose messages.
import random import tkinter as tk class Cell(tk.Button): """A button for the Minsweeper game. Press me to reveal a bomb or information about surrounding bombs. """ def __init__(self, parent, row, column, count): super().__init__(parent, text=' ', width=2, relief=tk.RAISED, command=self.press) self.parent = parent self.row = row self.column = column self.count = count self.pressed = False self.flagged = False self.bind("<Button-3>", self.flag) def press(self): """Button pressed. Show bomb info""" if not self.pressed: self.configure(relief=tk.SUNKEN) self.pressed = True self['text'] = 'X' if self.count < 0 else str(self.count) self.parent.clear_cell(self) def flag(self, _): """Right mouse button pressed. Toggle flag marker""" if not self.pressed: self.flagged = not self.flagged self['text'] = 'F' if self.flagged else ' ' class Board(tk.Frame): """Map for Minesweeper game. I make a grid of buttons that are pressed to reveal bombs or information about surrounding bombs. """ def __init__(self, parent, rows, columns, bomb_count): super().__init__(parent) self.safe_count = rows * columns - bomb_count # Make map of all the bombs bombs = [[0]*columns for row in range(rows)] for bomb in random.choices(range(rows*columns), k=bomb_count): bombs[bomb // columns][bomb % columns] = 1 # Make the board map self.cells = [] for row in range(rows): for column in range(columns): # Count bombs in surrounding cells. Use -1 to indicate cell has bomb if bombs[row][column]: count = -1 else: count = sum([bombs[r][c] for r in range(max(0, row-1), min(rows, row+2)) \ for c in range(max(0, column-1), min(columns, column+2))]) cell = Cell(self, row, column, count) cell.grid(row=row, column=column) self.cells.append(cell) def clear_cell(self, cell): """Cell was selected""" if cell.count < 0: print('BOOM!!!') else: self.safe_count -= 1 if self.safe_count <= 0: print('You won!!') root = tk.Tk() root.title("Minesweeper") root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) board = Board(root, 20, 20, 30) board.grid(column=0, row=0, sticky='NEWS') root.mainloop()