用python的tkinter写一个扫雷游戏
时间: 2023-12-29 17:18:24 浏览: 82
好的,以下是一个简单的扫雷游戏的代码示例,使用 Python 的 tkinter 模块:
```python
import tkinter as tk
import random
class Minesweeper:
def __init__(self, master, rows, cols, mines):
self.master = master
self.rows = rows
self.cols = cols
self.mines = mines
self.buttons = []
self.flags = []
self.mine_coords = []
self.create_board()
self.place_mines()
self.bind_buttons()
def create_board(self):
for row in range(self.rows):
button_row = []
flag_row = []
for col in range(self.cols):
button = tk.Button(self.master, width=2, height=1, font=('Helvetica', 10, 'bold'), bg='gray', relief='raised')
flag = False
button.grid(row=row, column=col)
button_row.append(button)
flag_row.append(flag)
self.buttons.append(button_row)
self.flags.append(flag_row)
def place_mines(self):
self.mine_coords = random.sample([(r, c) for r in range(self.rows) for c in range(self.cols)], self.mines)
for row, col in self.mine_coords:
self.buttons[row][col].config(bg='red')
def bind_buttons(self):
for row in range(self.rows):
for col in range(self.cols):
button = self.buttons[row][col]
button.bind('<Button-1>', lambda event, row=row, col=col: self.reveal(row, col))
button.bind('<Button-3>', lambda event, row=row, col=col: self.toggle_flag(row, col))
def reveal(self, row, col):
if (row, col) in self.mine_coords:
self.lose()
else:
count = self.count_mines(row, col)
if count > 0:
self.buttons[row][col].config(text=str(count))
else:
self.buttons[row][col].config(bg='white')
self.clear_neighbors(row, col)
def count_mines(self, row, col):
count = 0
for r in range(row-1, row+2):
for c in range(col-1, col+2):
if (r, c) in self.mine_coords:
count += 1
return count
def clear_neighbors(self, row, col):
for r in range(row-1, row+2):
for c in range(col-1, col+2):
if 0 <= r < self.rows and 0 <= c < self.cols and (r, c) not in self.mine_coords and self.buttons[r][c]['bg'] == 'gray':
self.reveal(r, c)
def toggle_flag(self, row, col):
if not self.flags[row][col]:
self.flags[row][col] = True
self.buttons[row][col].config(text='F', bg='yellow')
else:
self.flags[row][col] = False
self.buttons[row][col].config(text='', bg='gray')
def win(self):
for row in range(self.rows):
for col in range(self.cols):
if (row, col) not in self.mine_coords and self.buttons[row][col]['bg'] == 'gray':
return False
return True
def lose(self):
for row, col in self.mine_coords:
self.buttons[row][col].config(bg='black')
tk.messagebox.showerror('Game Over', 'You Lose!')
def play(self):
self.master.mainloop()
# create the game window
game_window = tk.Tk()
game_window.title('Minesweeper')
# create the game instance
game = Minesweeper(game_window, 10, 10, 10)
# start the game
game.play()
```
在这个游戏中,我们使用了 `tkinter` 模块来创建窗口和按钮。游戏的主要逻辑由 `Minesweeper` 类处理,其中包括初始化游戏板、放置地雷、绑定按钮事件、展示数字/清除相邻方格等方法。最后,我们创建一个游戏实例并启动游戏。
注意,这只是一个简单的示例,还有许多可以改进和优化的地方,例如添加计时器、游戏胜利的判断等。
阅读全文