扫雷 Python 完整代码
时间: 2024-06-20 12:01:38 浏览: 175
扫雷是一个经典的策略游戏,使用 Python 编写一个简单的扫雷游戏需要一些基本的 GUI 库和逻辑处理。这里给出一个基础的 Python 扫雷游戏的代码示例,使用 Tkinter 库作为图形用户界面:
```python
import tkinter as tk
from random import randint
# 定义游戏板大小和地雷数量
ROW = 10
COLUMN = 10
MINE_COUNT = 10
class Minesweeper:
def __init__(self, root):
self.root = root
self.board = [[' ' for _ in range(COLUMN)] for _ in range(ROW)]
self.mines = set()
self.place_mines()
self.init_game()
def place_mines(self):
for _ in range(MINE_COUNT):
x = randint(0, ROW - 1)
y = randint(0, COLUMN - 1)
if (x, y) not in self.mines:
self.mines.add((x, y))
self.board[x][y] = '*'
def reveal(self, x, y):
if (x, y) in self.mines:
self.root.destroy()
return "Game Over!"
else:
count = sum(1 for i in range(x-1, x+2) for j in range(y-1, y+2) if (i, j) in self.mines)
self.board[x][y] = str(count)
if count == 0:
for i in range(max(0, x-1), min(x+2, ROW)):
for j in range(max(0, y-1), min(y+2, COLUMN)):
if (i, j) not in self.mines:
self.reveal(i, j)
def init_game(self):
for i in range(ROW):
tk.Label(root, text=' '.join(self.board[i]), height=1, width=COLUMN).grid(row=i, sticky=tk.W+tk.E)
self.root.bind("<Button-1>", lambda event: self.reveal(event.x // COLUMN, event.y // ROW))
root = tk.Tk()
game = Minesweeper(root)
root.mainloop()
```
阅读全文