-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgametileswidget.cpp
More file actions
86 lines (83 loc) · 3.03 KB
/
gametileswidget.cpp
File metadata and controls
86 lines (83 loc) · 3.03 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
#include "gametileswidget.h"
#include "ui_gametileswidget.h"
#include <QPushButton>
#include <QGridLayout>
#include "GlobalSettings.h"
#include <QLayoutItem>
#include <QDebug>
#include "TilesGame.h"
#include <QSignalMapper>
GameTilesWidget::GameTilesWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::GameTilesWidget)
{
ui->setupUi(this);
settings = GlobalSettings::Instance();
gameLogic = NULL;
signalMapper = NULL;
}
// получили сигнал, что изменилось состояние
// получили вектор плиток, собираем поле
void GameTilesWidget::remakeBoard(QVector<Tile*>* tiles){
removeAllChilds(ui->gridLayout);
Tile* element;
for(int x = 0; x < tiles->size(); x++){
element = tiles->at(x);
QPushButton* btn = new QPushButton(this);
btn->setProperty("isCell", "true"); // for QSS
btn->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
ui->gridLayout->addWidget(dynamic_cast<QWidget*>(btn), element->getY(), element->getX());
signalMapper->setMapping(btn, dynamic_cast<QObject*>(element));
if(!element->isEmpty()){
btn->setText(QString::number(element->getValue()));
connect(btn, SIGNAL(pressed()), signalMapper, SLOT(map()));
btn->setCursor(Qt::PointingHandCursor);
} else {
btn->setProperty("isEmptyCell", "true"); // for QSS
}
}
}
// на плитку кликнули - дёргаем функцию логики
// если что-то изменилось, мы получим об этом сигнал
void GameTilesWidget::tileWasClicked(QObject* obj)
{
Tile* tile = dynamic_cast<Tile*>(obj);
if(gameLogic != NULL && tile != NULL)
gameLogic->move(tile);
}
void GameTilesWidget::winner()
{
emit iAmWinner();
}
// удаляем все конекты, пересоздаём логику и переписываем коннекты
void GameTilesWidget::createLogicAndBoard()
{
int size = settings->getGameBoardSize();
removeAllChilds(ui->gridLayout);
if(gameLogic != NULL)
delete gameLogic;
if(signalMapper != NULL)
delete signalMapper;
gameLogic = settings->getGameLogicObject(size);
signalMapper = new QSignalMapper(this);
connect(gameLogic, SIGNAL(gameBoardChanged(QVector<Tile*>*)),this,SLOT(remakeBoard(QVector<Tile*>*)));
connect(signalMapper, SIGNAL(mapped(QObject*)), this, SLOT(tileWasClicked(QObject*)));
connect(gameLogic, SIGNAL(winner()), this, SLOT(winner()));
gameLogic->start();
}
// фуункция хелпер для отчитки QGridLayout
void GameTilesWidget::removeAllChilds(QGridLayout *layout) {
QLayoutItem *child;
QWidget *w;
while((child = layout->takeAt(0)) != 0){
w = child->widget();
layout->removeItem(child);
delete child;
delete w;
}
}
GameTilesWidget::~GameTilesWidget()
{
delete ui;
delete gameLogic;
}