-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
199 lines (165 loc) · 7.31 KB
/
Copy pathmainwindow.cpp
File metadata and controls
199 lines (165 loc) · 7.31 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
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
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
// Установка флага первой загрузки
// Нужно, чтобы не настраивать виджеты дважды
firstStartFlag = true;
// Стартовое окно для начала
startDlg = new StartDialog(this);
connect(startDlg, SIGNAL(signalStart(int)), this, SLOT(slotStartGame(int)));
startDlg->exec();
QWidget *wgt = new QWidget(this);
// Обьявление виджетов
QLabel *lblInput = new QLabel(tr("Ввод:"), wgt);
QPushButton *btnOK = new QPushButton("&OK", wgt);
QStatusBar *sttBar = new QStatusBar(this);
QToolBar *toolBar = new QToolBar(this);
lblStatus = new QLabel(tr("Игра началась"), this);
tree = new QTreeWidget(wgt);
lineInput = new QLineEdit(wgt);
// Компоновка виджетов
QHBoxLayout *pHBox = new QHBoxLayout();
pHBox->addWidget(lblInput, 0, Qt::AlignRight | Qt::AlignTop);
pHBox->addWidget(lineInput, 0, Qt::AlignCenter | Qt::AlignTop);
pHBox->addWidget(btnOK, 0, Qt::AlignLeft | Qt::AlignTop);
QVBoxLayout *pVBox = new QVBoxLayout();
pVBox->addLayout(pHBox);
pVBox->addWidget(tree);
wgt->setLayout(pVBox);
this->setCentralWidget(wgt);
this->setStatusBar(sttBar);
this->addToolBar(toolBar);
// Настройка виджетов
lineInput->setValidator(new QRegExpValidator(QRegExp(QString("[0-9]{1,"+QString::number(countDig)+"}"))));
tree->setColumnCount(3);
QStringList columnHeaders;
columnHeaders << tr("Номер")
<< tr("Запрос")
<< tr("Ответ");
tree->setHeaderLabels(columnHeaders);
tree->setColumnWidth(0, 50);
// Настройка туллбара
// toolBar->setFloatable(false);
toolBar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolBar->setMovable(false);
QAction *acNewGame = new QAction(QIcon(":/icons/Icons/button_newGame.png"), tr("Новая игра"));
QAction *acQuit = new QAction(QIcon(":/icons/Icons/button_quit.png"), tr("Выйти"));
toolBar->addAction(acNewGame);
toolBar->addAction(acQuit);
connect(acNewGame, SIGNAL(triggered(bool)), SLOT(slotNewGame()));
connect(acQuit, SIGNAL(triggered(bool)), SLOT(slotQuit()));
// Настройка кнопок и других элементов
sttBar->addWidget(lblStatus);
btnOK->setAutoDefault(true);
btnOK->setDefault(true);
btnOK->setIcon(QIcon(":/icons/Icons/button_ok.png"));
lineInput->setFocus();
connect(btnOK, SIGNAL(clicked(bool)), SLOT(slotOkPress()));
tryNumber = 1;
connect(&game, SIGNAL(win()), SLOT(slotWin()));
winFlag = false;
}
void MainWindow::slotStartGame(int count)
{
// Количество цифр
countDig = count;
// Генерация числа
game.setDigits(count);
if (!firstStartFlag)
{
qDebug() << "Note:\tSetting the widgets...";
// Очистка виджетов и вектора избежания совпадений
lineInput->clear();
tree->clear();
withoutMatches.clear();
// Заполнение первоначальными данными
lblStatus->setText(tr("Игра началась"));
// Изменение валидатора на поле ввода
lineInput->setValidator(new QRegExpValidator(QRegExp(QString("[0-9]{1,"+QString::number(countDig)+"}"))));
// Указание фокуса при загрузке
lineInput->setFocus();
tryNumber = 1;
}
// Установка того, что новая игра запускается уже не в первый раз,
// чтобы потом перенастроить виджеты
if (firstStartFlag)
firstStartFlag = false;
}
void MainWindow::slotNewGame()
{
int wnd = QMessageBox::question(this, tr("Новая игра"),
tr("Вы действительно хотите начать игру заново?"),
QMessageBox::Yes | QMessageBox::No);
if (wnd == QMessageBox::Yes)
startDlg->exec();
qDebug() << "Note:\tNew game request";
}
void MainWindow::slotQuit()
{
int wnd = QMessageBox::question(this, tr("Выход из игры"),
tr("Вы действительно хотите завершить игру?"),
QMessageBox::Yes | QMessageBox::No);
if (wnd == QMessageBox::Yes)
StartDialog::slotExit();
}
void MainWindow::slotOkPress()
{
// Если количество цифр не подходит - игнорируем
if (lineInput->text().length() < countDig)
return;
// Проверка на совпадения с прошлыми попытками
bool matchFlag = false;
for (int i = 0; i < withoutMatches.length(); i++)
{
if (withoutMatches.at(i) == lineInput->text())
{
matchFlag = true;
break;
}
}
if (matchFlag)
{
qDebug() << "Note:\tMatching!";
lblStatus->setText(tr("<font color=red>Было уже</font>"));
}
else
{
// Переганяем в вектор строку
QVector<int> tmpVector;
for (int i = 0; i < countDig; i++)
tmpVector << lineInput->text().at(i).digitValue();
qDebug() << "Note:\tAdding:" << tmpVector;
// Получаем данные и записываем в таблицу
BullsAndCows tmp = game.checkDigits(tmpVector);
// Если стоит флаг победы, то мы не будем заново добавлять это же число еще раз в таблицу
if (!winFlag)
{
QTreeWidgetItem *item = new QTreeWidgetItem(tree);
item->setText(0, QString::number(tryNumber));
item->setText(1, lineInput->text());
item->setText(2, QString(QString::number(tmp.bulls)+tr("Б, ")+QString::number(tmp.cows)+tr("К")));
tree->addTopLevelItem(item);
tryNumber++;
withoutMatches << lineInput->text();
}
else
winFlag = false;
}
lineInput->setText("");
lineInput->setFocus();
}
void MainWindow::slotWin()
{
// Поставим флаг победы для избежания добавления элемента прошлой игры в таблицу
// Да, костыль
winFlag = true;
int wnd = QMessageBox::information(this, tr("Победа"),
QString(tr("Вы угадали число <font color=green><b>")+
game.getDigits()+tr("</b></font> с ")+
QString::number(tryNumber)+tr(" попытки. <br>Хотите начать заново?")),
QMessageBox::Yes | QMessageBox::Abort);
if (wnd == QMessageBox::Yes)
slotStartGame(countDig);
if (wnd == QMessageBox::Abort)
StartDialog::slotExit();
}