import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QGridLayout
from PyQt5.QtGui import QPainter, QColor, QFont
class QueenBoard(QWidget):
# 初始化,设置默认大小为400x400
def __init__(self, n, size=400):
super().__init__()
self.n = n
self.size = size
self.setWindowTitle('N-Queens Problem')
self.setGeometry(100, 100, self.size, self.size)
self.layout = QGridLayout()
self.setLayout(self.layout)
self.solution = []
self.count = 0
self.current_board = 0
self.solve()
# 解决N皇后问题
def solve(self):
def backtrack(board):
if len(board) == self.n:
self.count += 1
self.solution.append(board[:])
else:
for i in range(self.n):
if all(i != board[j] and abs(i - board[j]) != len(board) - j for j in range(len(board))):
board.append(i)
backtrack(board)
board.pop()
backtrack([])
self.paintEvent(None)
# 绘制当前N皇后问题的棋盘状态
def paintEvent(self, e):
painter = QPainter()
painter.begin(self)
self.draw_board(painter)
if self.solution:
self.draw_queens(painter)
self.draw_info(painter)
painter.end()
# 绘制棋盘的网格线
def draw_board(self, painter):
b_width = self.size / self.n
painter.setPen(QColor(0, 0, 0))
for i in range(self.n):
for j in range(self.n):
x = j * b_width
y = i * b_width
painter.drawRect(x, y, b_width, b_width)
# 绘制皇后的位置
def draw_queens(self, painter):
b_width = self.size / self.n
queens = self.solution[self.current_board]
painter.setBrush(QColor(0, 160, 230))
for i in range(self.n):
x = queens[i] * b_width
y = i * b_width
painter.drawEllipse(x + b_width/4, y + b_width/4, b_width/2, b_width/2)
# 绘制当前解的编号与总解数
def draw_info(self, painter):
font = QFont('Serif', 18, QFont.Light)
painter.setFont(font)
painter.drawText(self.width()/2 - 50, self.height() - 50, f'Solution {self.current_board+1}/{self.count}')
# 更新棋盘状态,切换到下一个布局
def next_board(self):
if self.solution and self.current_board < self.count-1:
self.current_board += 1
self.update()
# 更新棋盘状态,切换到上一个布局
def prev_board(self):
if self.solution and self.current_board > 0:
self.current_board -= 1
self.update()
if __name__ == '__main__':
app = QApplication(sys.argv)
board = QueenBoard(8)
board.show()
# 添加前一个和后一个布局的按钮
prev_btn = QPushButton('Prev', board)
prev_btn.setToolTip('Previous Board')
prev_btn.move(10, board.size - 40)
prev_btn.resize(80, 30)
prev_btn.clicked.connect(board.prev_board)
next_btn = QPushButton('Next', board)
next_btn.setToolTip('Next Board')
next_btn.move(board.size - 90, board.size - 40)
next_btn.resize(80, 30)
next_btn.clicked.connect(board.next_board)
sys.exit(app.exec_())
标签:self,width,实验,board,皇后,btn,painter,size From: https://www.cnblogs.com/yunbianshangdadun/p/17404420.html