用Python写窗口扫雷
时间: 2023-07-19 19:48:44 浏览: 135
好的,下面是一个Python窗口扫雷游戏的实现,使用了PyQt5库来创建GUI界面:
```python
import sys
import random
from PyQt5.QtWidgets import QApplication, QMainWindow, QGridLayout, QWidget, QPushButton, QLabel, QMessageBox
class MineSweeper(QMainWindow):
def __init__(self, board_size, num_bombs):
super().__init__()
self.board_size = board_size
self.num_bombs = num_bombs
self.initUI()
def initUI(self):
self.setWindowTitle('扫雷')
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
self.grid_layout = QGridLayout(self.central_widget)
self.board = [[' ' for _ in range(self.board_size)] for _ in range(self.board_size)]
self.bombs = set()
while len(self.bombs) < self.num_bombs:
row = random.randint(0, self.board_size - 1)
col = random.randint(0, self.board_size - 1)
self.bombs.add((row, col))
for row, col in self.bombs:
self.board[row][col] = '*'
self.buttons = {}
for row in range(self.board_size):
for col in range(self.board_size):
button = QPushButton()
button.setFixedSize(30, 30)
button.row = row
button.col = col
button.clicked.connect(self.button_clicked)
self.buttons[(row, col)] = button
self.grid_layout.addWidget(button, row, col)
self.statusbar = self.statusBar()
self.remaining_bombs = self.num_bombs
self.statusbar.showMessage('剩余地雷数:{}'.format(self.remaining_bombs))
def button_clicked(self):
button = self.sender()
row = button.row
col = button.col
if self.board[row][col] == '*':
self.game_over()
else:
bombs = self.get_adjacent_bombs(row, col)
self.board[row][col] = str(bombs)
button.setText(str(bombs))
button.setEnabled(False)
if self.check_win():
self.game_win()
def get_adjacent_bombs(self, row, col):
bombs = 0
for r in range(max(0, row - 1), min(self.board_size, row + 2)):
for c in range(max(0, col - 1), min(self.board_size, col + 2)):
if self.board[r][c] == '*':
bombs += 1
return bombs
def game_over(self):
for row, col in self.bombs:
self.buttons[(row, col)].setText('*')
self.buttons[(row, col)].setEnabled(False)
QMessageBox.critical(self, '游戏结束', '你输了!')
self.close()
def check_win(self):
for row in range(self.board_size):
for col in range(self.board_size):
if self.board[row][col] == ' ' and self.buttons[(row, col)].isEnabled():
return False
return True
def game_win(self):
QMessageBox.information(self, '游戏结束', '你赢了!')
self.close()
def reduce_bomb_count(self):
self.remaining_bombs -= 1
self.statusbar.showMessage('剩余地雷数:{}'.format(self.remaining_bombs))
if __name__ == '__main__':
app = QApplication(sys.argv)
minesweeper = MineSweeper(10, 10)
minesweeper.show()
sys.exit(app.exec_())
```
这个程序创建了一个QMainWindow窗口,并在其中使用了一个QGridLayout布局来放置按钮。按钮通过clicked信号连接到了button_clicked槽函数,该函数会检查该位置是否有地雷,如果有则游戏结束,否则会显示周围地雷数量并继续进行游戏。程序还实现了游戏胜利和失败的判断,以及剩余地雷数的显示。
阅读全文