python利用tkinter制作一个扫雷游戏
时间: 2024-03-25 07:19:04 浏览: 82
好的,下面是一个简单的扫雷游戏代码示例,使用Python和Tkinter实现:
```python
import tkinter as tk
import random
# 设置游戏大小和地雷数量
WIDTH = 10
HEIGHT = 10
MINES = 10
class Cell:
def __init__(self, master, x, y):
self.master = master
self.x = x
self.y = y
self.button = tk.Button(master = master, width = 2, command = self.click)
self.button.grid(row = y, column = x)
self.mine = False
self.revealed = False
self.count = 0
def click(self):
if self.revealed:
return
if self.mine:
self.button.config(text = '*', bg = 'red')
self.master.game_over()
else:
self.reveal()
def reveal(self):
self.revealed = True
self.button.config(relief = tk.SUNKEN)
if self.count:
self.button.config(text = str(self.count))
else:
for dx in range(-1, 2):
for dy in range(-1, 2):
if (dx or dy) and self.x+dx >= 0 and self.y+dy >= 0 and self.x+dx < WIDTH and self.y+dy < HEIGHT:
self.master.cells[self.x+dx][self.y+dy].reveal()
class MineSweeper:
def __init__(self):
self.root = tk.Tk()
self.root.title('Mine Sweeper')
self.root.resizable(False, False)
self.cells = [[Cell(self.root, x, y) for y in range(HEIGHT)] for x in range(WIDTH)]
self.mines = 0
while self.mines < MINES:
x = random.randint(0, WIDTH-1)
y = random.randint(0, HEIGHT-1)
if not self.cells[x][y].mine:
self.cells[x][y].mine = True
self.mines += 1
for x in range(WIDTH):
for y in range(HEIGHT):
for dx in range(-1, 2):
for dy in range(-1, 2):
if (dx or dy) and x+dx >= 0 and y+dy >= 0 and x+dx < WIDTH and y+dy < HEIGHT:
self.cells[x][y].count += self.cells[x+dx][y+dy].mine
self.game_over = False
def run(self):
self.root.mainloop()
def game_over(self):
if not self.game_over:
self.game_over = True
for x in range(WIDTH):
for y in range(HEIGHT):
if self.cells[x][y].mine:
self.cells[x][y].button.config(text = '*', bg = 'yellow')
if __name__ == '__main__':
game = MineSweeper()
game.run()
```
运行程序后,就可以开始扫雷游戏了。
阅读全文