-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmainwindow.cpp
369 lines (319 loc) · 11.8 KB
/
mainwindow.cpp
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
#include "mainwindow.h"
#include "box.h"
#include <QComboBox>
#include <QDialog>
#include <QProcess>
#include <QStringList>
#include <QDir>
#include <algorithm>
#include <QMovie>
#include <QPixmap>
#include <QLabel>
#include <QLayout>
#include <QGroupBox>
#include <QPushButton>
#include <QTimer>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
createBoxesGrid();
createMenuButtons();
QWidget *centralWidget = new QWidget(this);
QHBoxLayout *mainLayout = new QHBoxLayout(centralWidget);
mainLayout->addWidget(boxesGroup);
mainLayout->addWidget(menuButtonsGroup);
mainLayout->setSizeConstraint(QLayout::SetFixedSize);
setCentralWidget(centralWidget);
setFixedSize(sizeHint());
for(size_t num = 0; num < 9; num++)
{
boxesOfSameValue.append(QSet<Box*>{});
}
}
void MainWindow::createBoxesGrid(void)
{
boxesGroup = new QGroupBox(this);
boxesLayout = new QGridLayout(boxesGroup);
boxesLayout->setSpacing(0);
boxesLayout->setContentsMargins(0, 0, 0, 0);
for (size_t row = 0; row < 9; row++) {
boxes.append(QList<Box*>{});
for (size_t column = 0; column < 9; column++) {
auto tempStackedWidget = new Box(row, column, this);
boxes[row].append(tempStackedWidget);
boxesLayout->addWidget(tempStackedWidget, row, column);
}
}
boxesGroup->setLayout(boxesLayout);
}
void MainWindow::createMenuButtons(void)
{
menuButtonsGroup = new QGroupBox(this);
menuButtonsLayout = new QVBoxLayout;
newGameButton = new QPushButton("New Game");
hintButton = new QPushButton("Hint");
undoButton = new QPushButton("Undo");
eraseButton = new QPushButton("Erase");
takeNoteButton = new QPushButton("Note");
timer = new QTimer(this);
timerDisplay = new QLabel("00:00");
timerDisplay->setAlignment(Qt::AlignCenter);
QFont timerFont;
timerFont.setPointSize(25);
timerDisplay->setFont(timerFont);
menuButtonsLayout->addWidget(timerDisplay);
menuButtonsLayout->addWidget(newGameButton);
menuButtonsLayout->addWidget(hintButton);
menuButtonsLayout->addWidget(undoButton);
menuButtonsLayout->addWidget(eraseButton);
menuButtonsLayout->addWidget(takeNoteButton);
menuButtonsGroup->setFixedWidth(180);
newGameButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
hintButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
undoButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
eraseButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
takeNoteButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
takeNoteButton->setCheckable(true);
connect(takeNoteButton, &QPushButton::toggled, this, &MainWindow::takeNoteHandler);
connect(eraseButton, &QPushButton::pressed, this, &MainWindow::eraseHandler);
connect(newGameButton, &QPushButton::pressed, this, &MainWindow::startNewGame);
connect(hintButton, &QPushButton::pressed, this, &MainWindow::giveHint);
connect(undoButton, &QPushButton::pressed, this, &MainWindow::undoHandler);
connect(timer, &QTimer::timeout, this, &MainWindow::updateTimer);
menuButtonsGroup->setLayout(menuButtonsLayout);
}
MainWindow::~MainWindow() {}
void highlightOrClean( QList<QList<Box*>> cell_grid, MainWindow::coordinateType coordinates, std::function<void(Box*)> func, MainWindow const * mainWindow, uint8_t cellValue)
{
auto row_index = coordinates.first;
auto column_index = coordinates.second;
for(auto& box : cell_grid[row_index]){ // highlight or clean all the cells of the focused row
func(box);
}
for(auto& row : cell_grid){ // highlight or clean all the cell of the focused column
func(row[column_index]);
}
if(0 != cellValue)
{
auto cells_to_highlight = mainWindow->getCellsOfSameValue(cellValue);
std::for_each(cells_to_highlight.begin(), cells_to_highlight.end(), func);
}
}
void MainWindow::cleanAndHighlightBoxes(std::pair<uint8_t, uint8_t> newFocusCell, uint8_t previousValue)
{
highlightOrClean(boxes, currentlyFocusedCell, &Box::cleanBox, this, previousValue);
highlightOrClean(boxes, newFocusCell, &Box::highlightBox, this, getBox(newFocusCell)->getCurrentBoxValue());
currentlyFocusedCell = newFocusCell;
if(isPuzzleComplete())
{
finishGame();
correctOrIncorrectBoxes = {};
}
}
void MainWindow::keepCellFocus(coordinateType cellCoordinate)
{
auto [row, column] = cellCoordinate;
auto box = boxes[row][column];
box->setFocus(Qt::MouseFocusReason);
}
void MainWindow::takeNoteHandler(bool checked)
{
m_takingNote = checked;
keepCellFocus(currentlyFocusedCell);
}
void MainWindow::removeCellFromHighlight(uint8_t value, const coordinateType coord)
{
boxesOfSameValue[value - 1].removeIf([coord](Box const * box){
return (box->getCoordinates() == coord);
});
}
void MainWindow::addCellToHighlight(uint8_t value, Box * box)
{
boxesOfSameValue[value - 1].insert(box);
}
void MainWindow::eraseHandler(void)
{
auto box = getBox(currentlyFocusedCell);
box->erase(false);
keepCellFocus(currentlyFocusedCell);
}
void MainWindow::startNewGame(void)
{
QDialog newGameSetting{this};
difficultySetting = &newGameSetting;
newGameSetting.setWindowTitle("Difficulty");
// newGameSetting.setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
newGameSetting.setFixedSize({290, 80});
QGridLayout layout;
newGameLayout = &layout;
QLabel label{"Choose Difficulty:"}, imageLabel;
QComboBox levels{};
levels.addItem("Easy");
levels.addItem("Medium");
levels.addItem("Hard");
levels.addItem("Insane");
connect(&levels, &QComboBox::currentIndexChanged, this, &MainWindow::setDifficulty);
layout.addWidget(&label, 0, 1);
layout.addWidget(&levels, 0, 2);
QPushButton okButton{"Start Game"}, cancelButton{"Cancel"};
connect(&okButton, &QPushButton::pressed, this, &MainWindow::generateNewPuzzle);
connect(&cancelButton, &QPushButton::pressed, &newGameSetting, &QDialog::close);
layout.addWidget(&okButton, 1, 1);
layout.addWidget(&cancelButton, 1, 2);
layout.addWidget(&imageLabel, 0, 0, 2, 1);
QString sourceFilePath = __FILE__;
QFileInfo fileInfo(sourceFilePath);
auto imagePath = fileInfo.absolutePath() + "/assets/brain.jpg";
QPixmap pixmap( imagePath );
imageLabel.setPixmap(pixmap);
imageLabel.setScaledContents(true);
imageLabel.setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
newGameSetting.setLayout(&layout);
newGameSetting.exec();
}
void MainWindow::setDifficulty(int difficulty)
{
m_difficulty_index = difficulty;
}
void MainWindow::setValuesOnPuzzle(void)
{
using namespace std;
auto stdout = puzzleGenerator->readAllStandardOutput();
auto marker = '\n';
auto answerKeyStart = next(std::find(begin(stdout), end(stdout), marker));
auto puzzleStart = next(std::find(next(answerKeyStart), end(stdout), marker));
vector<int> answers, puzzleValues;
copy_if(answerKeyStart, puzzleStart, back_inserter(answers), [](char c){
return (c >= '0' && c <= '9');
});
copy_if(puzzleStart, end(stdout), back_inserter(puzzleValues), [](char c){
return (c >= '0' && c <= '9');
});
getBox(currentlyFocusedCell)->erase(false);
for (size_t i = 0; i < 81; i++)
{
auto row = i / 9;
auto column = i % 9;
auto box = getBox({row, column});
box->erase(true);
box->setBoxTrueValue(answers[i] - '0');
if('0' != puzzleValues[i])
{
box->setBoxValue(puzzleValues[i] - '0', true, false);
}
}
getBox({4, 4})->mousePressEvent({});
keepCellFocus({4, 4});
timer->start(1000);
}
void MainWindow::generateNewPuzzle(void)
{
auto puzzleGeneratorProcess = new QProcess{this};
puzzleGenerator = puzzleGeneratorProcess;
const QString difficulties[] = {"Easy", "Medium", "Hard", "Insane"};
// Get the path to this source file
QString sourceFilePath = __FILE__;
QFileInfo fileInfo(sourceFilePath);
QString scriptPath = fileInfo.absolutePath() + "/puzzle_generator.py";
const QString command = "python3";
QStringList arguments{};
arguments << scriptPath << difficulties[m_difficulty_index];
timeElapsed = 0;
logsToUndo.clear();
correctOrIncorrectBoxes = {};
connect(puzzleGeneratorProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, &MainWindow::setValuesOnPuzzle);
connect(puzzleGeneratorProcess, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), difficultySetting, &QDialog::close);
puzzleGeneratorProcess->start(command, arguments);
auto imageLabel = qobject_cast<QLabel*>(newGameLayout->itemAtPosition(0, 0)->widget());
imageLabel->clear();
auto moviePath = fileInfo.absolutePath() + "/assets/loading.gif";
QMovie* movie = new QMovie{moviePath};
connect(imageLabel, &QWidget::destroyed, movie, &QMovie::deleteLater);
imageLabel->setMovie(movie);
movie->start();
}
void MainWindow::logEvent(LogElement logElement)
{
logsToUndo.push(std::move(logElement));
}
void MainWindow::giveHint(void)
{
auto focusedBox = getBox(currentlyFocusedCell);
const auto trueValue = focusedBox->getBoxTrueValue();
const auto currentValue = focusedBox->getCurrentBoxValue();
if( trueValue != currentValue )
{
auto oldValue = focusedBox->getCurrentBoxValue();
focusedBox->setBoxValue(trueValue, false, false);
logEvent(ChangeValueLog{focusedBox->getCoordinates(), oldValue, focusedBox->getNotes()});
}
keepCellFocus(currentlyFocusedCell);
}
struct UndoProcessor{
explicit UndoProcessor(MainWindow * mainWindow) :
mainWindow(mainWindow)
{}
void operator()(ChangeValueLog logElement){
auto prevBox = mainWindow->getBox(logElement.m_coordinate);
if( auto notes = logElement.m_notesTakenBeforeAction; notes.any())
{
for(auto note = 0; note < 9; note++)
{
if( auto bit = notes.test(note); true == bit )
{
prevBox->setBoxValue(note + 1, false, true);
}
}
}
else{
auto prevValue = logElement.m_prevValue;
prevBox->setBoxValue(prevValue, false, false);
}
prevBox->mousePressEvent({});
}
void operator()(TakeNoteLog logElement){
auto prevBox = mainWindow->getBox(logElement.m_coordinate);
prevBox->setBoxValue(logElement.m_NoteValue, false, true);
prevBox->mousePressEvent({});
}
MainWindow * mainWindow;
};
void MainWindow::undoHandler(void)
{
if(false == logsToUndo.empty())
{
auto lastAction = logsToUndo.pop();
std::visit(UndoProcessor{this}, lastAction);
}
keepCellFocus(currentlyFocusedCell);
}
void MainWindow::updateTimer(void)
{
timeElapsed++;
int minutes = timeElapsed / 60;
int seconds = timeElapsed % 60;
timerDisplay->setText(QString("%1:%2").arg(minutes, 2, 10, QChar('0')).arg(seconds, 2, 10, QChar('0')));
}
void MainWindow::setCellResult(coordinateType coordinates, bool result)
{
auto row = coordinates.first;
auto column = coordinates.second;
correctOrIncorrectBoxes.set(9 * row + column, result);
}
void MainWindow::finishGame(void)
{
int minutes = timeElapsed / 60;
int seconds = timeElapsed % 60;
timer->stop();
if(0 == minutes)
{
QString message = QString("You solved puzzle in %1 seconds!").arg(seconds, 2, 10, QChar('0'));
QMessageBox::information(this, "Congratulations!", message);
}
else
{
QString message = QString("You solved puzzle in %1 minutes and %2 seconds!").arg(minutes, 2, 10, QChar('0')).arg(seconds, 2, 10, QChar('0'));
QMessageBox::information(this, "Congratulations!", message);
}
}