write a game in python for mine sweeperr
- User
write a game in python for mine sweeperr
- Assistant
write a game in python for mine sweeperr
Sure! Let's create a simple Minesweeper game in Python using the tkinter library for the graphical user interface (GUI). This implementation will provide a basic version of Minesweeper where you can click on cells to reveal them and try to avoid the mines.
Below is the complete code for the Minesweeper game:
import tkinter as tk
import random
class MinesweeperCell(tk.Button):
def __init__(self, master, x, y, *args, **kwargs):
super(MinesweeperCell, self).__init__(master, width=2, font=('Arial', 14), *args, **kwargs)
self.master = master
self.x = x
self.y = y
self.is_mine = False
self.is_revealed = False
self.mine_count = 0
self.config(command=self.on_left_click)
self.bind('<Button-3>', self.on_right_click) # Right-click for flagging
def on_left_click(self):
if self.is_revealed or self['text'] == 'F':
return
if self.is_mine:
self.config(text='M', bg='red')
self.master.game_over(False)
else:
self.reveal()
if self.master.check_win():
self.master.game_over(True)
def on_right_click(self, event):
if not self.is_revealed:
if self['text'] == '':
self.config(text='F', fg='red')
elif self['text'] == 'F':
self.config(text='')
def reveal(self):
if self.is_revealed:
return
self.is_revealed = True
if self.mine_count > 0:
self.config(text=str(self.mine_count), relief=tk.SUNKEN, bg='lightgrey')
else:
self.config(relief=tk.SUNKEN, bg='lightgrey')
for nx, ny in self.master.get_neighbors(self.x, self.y):
neighbor = self.master.cells[nx][ny]
if not neighbor.is_revealed and not neighbor.is_mine:
neighbor.reveal()
class MinesweeperGame(tk.Frame):
def __init__(self, master, width=10, height=10, mines=10):
super(MinesweeperGame, self).__init__(master)
self.width = width
self.height = height
self.mines = mines
self.cells = []
self.create_widgets()
self.place_mines()
self.calculate_mine_counts()
def create_widgets(self):
for x in range(self.width):
row = []
for y in range(self.height):
cell = MinesweeperCell(self, x, y)
cell.grid(row=y, column=x)
row.append(cell)
self.cells.append(row)
def place_mines(self):
positions = [(x, y) for x in range(self.width) for y in range(self.height)]
random.shuffle(positions)
for i in range(self.mines):
x, y = positions[i]
self.cells[x][y].is_mine = True
def calculate_mine_counts(self):
for x in range(self.width):
for y in range(self.height):
cell = self.cells[x][y]
if cell.is_mine:
continue
count = 0
for nx, ny in self.get_neighbors(x, y):
if self.cells[nx][ny].is_mine:
count += 1
cell.mine_count = count
def get_neighbors(self, x, y):
neighbors = []
for nx in range(max(0, x - 1), min(self.width, x + 2)):
for ny in range(max(0, y - 1), min(self.height, y + 2)):
if nx == x and ny == y:
continue
neighbors.append((nx, ny))
return neighbors
def game_over(self, won):
for row in self.cells:
for cell in row:
if cell.is_mine:
cell.config(text='M', bg='red')
message = "You win!" if won else "Game over!"
result = tk.messagebox.showinfo("Game Over", message)
if result == 'ok':
self.master.destroy()
def check_win(self):
for row in self.cells:
for cell in row:
if not cell.is_mine and not cell.is_revealed:
return False
return True
if __name__ == '__main__':
root = tk.Tk()
root.title("Minesweeper")
game = MinesweeperGame(root, width=10, height=10, mines=15)
game.pack()
root.mainloop()
MinesweeperCell Class: Represents each cell in the Minesweeper grid. It extends tk.Button and handles user interactions like left-click (to reveal) and right-click (to flag/unflag).
on_left_click: Reveals the cell. If it's a mine, the game ends. If not, it shows the number of adjacent mines.on_right_click: Flags or unflags a cell when the user right-clicks.reveal: Reveals the cell and recursively reveals neighboring cells if there are no adjacent mines.MinesweeperGame Class: Manages the game grid, placing mines, and checking game status.
create_widgets: Creates the grid of MinesweeperCell instances.place_mines: Randomly places mines in the grid.calculate_mine_counts: Calculates the number of adjacent mines for each cell.get_neighbors: Returns the coordinates of neighboring cells for a given cell.game_over: Reveals all mines and displays a message when the game ends.check_win: Checks if the player has revealed all non-mine cells.Main Section: Initializes the game window and starts the Tkinter main loop.
Ensure Python is Installed: You need Python 3 installed on your system. You can download it from python.org.
Save the Code: Copy the code above and save it in a file named minesweeper.py.
Run the Script:
minesweeper.py.python minesweeper.py
python3 minesweeper.py
Playing the Game:
F) indicating you suspect a mine is there.You can adjust the difficulty by changing the parameters in the MinesweeperGame initialization:
game = MinesweeperGame(root, width=10, height=10, mines=15)
width and height: Set the grid size.mines: Set the number of mines in the grid.For example, to create an expert-level game:
game = MinesweeperGame(root, width=30, height=16, mines=99)
This game uses the built-in tkinter library, which comes with most Python installations. You don't need to install any external packages.
Enjoy playing Minesweeper!
Not yet included in a published release.