qt五子棋c++源码
时间: 2023-08-25 14:17:42 浏览: 53
当然可以!以下是一个简单的五子棋游戏的C++源码,使用了Qt框架进行界面开发:
```cpp
#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QGridLayout>
#include <QMessageBox>
enum class ChessType {
Empty,
Black,
White
};
class ChessBoard : public QWidget {
Q_OBJECT
public:
explicit ChessBoard(QWidget *parent = nullptr) : QWidget(parent) {
setFixedSize(500, 500);
gridLayout = new QGridLayout(this);
gridLayout->setSpacing(0);
for (int row = 0; row < 15; ++row) {
for (int col = 0; col < 15; ++col) {
QPushButton *btn = new QPushButton("", this);
btn->setFixedSize(30, 30);
btn->setProperty("row", row);
btn->setProperty("col", col);
btn->setStyleSheet("background-color: white;");
connect(btn, &QPushButton::clicked, this, &ChessBoard::handleButtonClick);
gridLayout->addWidget(btn, row, col);
chessboard[row][col] = ChessType::Empty;
}
}
}
private slots:
void handleButtonClick() {
QPushButton *btn = qobject_cast<QPushButton *>(sender());
int row = btn->property("row").toInt();
int col = btn->property("col").toInt();
if (chessboard[row][col] != ChessType::Empty) {
return;
}
if (currentPlayer == ChessType::Black) {
btn->setStyleSheet("background-color: black;");
chessboard[row][col] = ChessType::Black;
currentPlayer = ChessType::White;
} else {
btn->setStyleSheet("background-color: white;");
chessboard[row][col] = ChessType::White;
currentPlayer = ChessType::Black;
}
if (checkWin(row, col)) {
QString winner = (currentPlayer == ChessType::Black) ? "White" : "Black";
QMessageBox::information(this, "Game Over", winner + " wins!");
resetBoard();
}
}
private:
QGridLayout *gridLayout;
ChessType chessboard[15][15];
ChessType currentPlayer = ChessType::Black;
bool checkWin(int row, int col) {
int dx[] = {0, 1, 1, 1};
int dy[] = {1, 0, 1, -1};
for (int i = 0; i < 4; ++i) {
int count = 1;
int r = row + dx[i];
int c = col + dy[i];
while (r >= 0 && r < 15 && c >= 0 && c < 15 && chessboard[r][c] == chessboard[row][col]) {
++count;
r += dx[i];
c += dy[i];
}
r = row - dx[i];
c = col - dy[i];
while (r >= 0 && r < 15 && c >= 0 && c < 15 && chessboard[r][c] == chessboard[row][col]) {
++count;
r -= dx[i];
c -= dy[i];
}
if (count >= 5) {
return true;
}
}
return false;
}
void resetBoard() {
for (int row = 0; row < 15; ++row) {
for (int col = 0; col < 15; ++col) {
chessboard[row][col] = ChessType::Empty;
}
}
QList<QPushButton *> buttons = findChildren<QPushButton *>();
for (QPushButton *btn : buttons) {
btn->setStyleSheet("background-color: white;");
}
currentPlayer = ChessType::Black;
}
};
int main(int argc, char *argv[]) {
QApplication app(argc, argv);
ChessBoard chessBoard;
chessBoard.show();
return app.exec();
}
#include "main.moc"
```
这个源码实现了一个简单的五子棋游戏,使用了Qt的QPushButton来表示棋盘上的每一个格子。玩家可以通过点击按钮来下子,当有一方连成五子时,游戏结束。如果你需要更多的功能,可以在此基础上进行扩展。希望对你有帮助!如果有任何问题,请随时提问。