-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
82 lines (65 loc) · 2.22 KB
/
Copy pathmainwindow.cpp
File metadata and controls
82 lines (65 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "mainwindow.h"
#include <QMenuBar>
#include <QMenu>
#include <QAction>
#include <QMessageBox>
#include <QVBoxLayout>
#include <QWidget>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
setWindowTitle("Minesweeper");
// Create central widget and layout
QWidget *centralWidget = new QWidget(this);
QVBoxLayout *layout = new QVBoxLayout(centralWidget);
// Create game board
gameBoard = new GameBoard(this);
layout->addWidget(gameBoard);
// Set up central widget
centralWidget->setLayout(layout);
setCentralWidget(centralWidget);
// Create menus
createMenus();
// Connect signals
connect(gameBoard, &GameBoard::gameWon, this, &MainWindow::handleGameWon);
connect(gameBoard, &GameBoard::gameLost, this, &MainWindow::handleGameLost);
// Set fixed size based on game board
setFixedSize(sizeHint());
}
MainWindow::~MainWindow() {
if (gameBoard) {
delete gameBoard;
}
}
void MainWindow::createMenus() {
QMenu *gameMenu = menuBar()->addMenu(tr("&Game"));
QAction *newGameAction = new QAction(tr("&New Game"), this);
newGameAction->setShortcut(QKeySequence::New);
connect(newGameAction, &QAction::triggered, this, &MainWindow::startNewGame);
gameMenu->addAction(newGameAction);
gameMenu->addSeparator();
QAction *exitAction = new QAction(tr("&Exit"), this);
connect(exitAction, &QAction::triggered, this, &QWidget::close);
gameMenu->addAction(exitAction);
}
void MainWindow::handleGameWon() {
showGameOverDialog(true);
}
void MainWindow::handleGameLost() {
showGameOverDialog(false);
}
void MainWindow::showGameOverDialog(bool won) {
QMessageBox msgBox(this);
msgBox.setWindowTitle(won ? "Congratulations!" : "Game Over");
msgBox.setText(won ? "You've won! Would you like to play again?"
: "You hit a mine! Would you like to try again?");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::Yes);
int ret = msgBox.exec();
if (ret == QMessageBox::Yes) {
startNewGame();
} else {
close();
}
}
void MainWindow::startNewGame() {
gameBoard->resetGame();
}