This repository has been archived by the owner on May 24, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
boardview.cpp
95 lines (74 loc) · 2.56 KB
/
boardview.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
#include <QString>
#include <QMessageBox>
#include "boardview.h"
BoardView::BoardView(QWidget *parent)
: QWidget(parent),
_grid(nullptr),
_model(nullptr),
_buttons(BoardModel::GAME_SIZE, nullptr) {}
BoardView::~BoardView() {
delete _model;
}
void BoardView::set_new_model(bool is_rnd, int complexity) {
if (_model == nullptr) {
_model = new BoardModel(is_rnd, complexity);
} else {
_model->set_new_board(is_rnd, complexity);
}
if (_grid == nullptr) {
_grid = new QGridLayout(this);
for (int i = 0; i < BoardModel::GAME_SIZE; i++) {
auto new_btn = new FifteenPushButton(this);
new_btn->set_idx(i);
_grid->addWidget(new_btn, i / BoardModel::GAME_SHAPE, i % BoardModel::GAME_SHAPE);
connect(new_btn, &FifteenPushButton::fifteen_btn_clicked, this, &BoardView::_move);
_buttons[i] = new_btn;
}
setLayout(_grid);
}
const auto board = _model->get_board();
for (int i = 0; i < BoardModel::GAME_SIZE; i++) {
_buttons[i]->set_num(board[i]);
}
}
void BoardView::set_start_board() {
_model->set_start_board();
const auto board = _model->get_board();
for (int i = 0; i < BoardModel::GAME_SIZE; i++) {
_buttons[i]->set_num(board[i]);
}
}
void BoardView::_move(int idx) {
const auto result = _model->move(idx);
const auto is_moved = result.first;
if (is_moved) {
const int nul_idx = result.second.toInt();
FifteenPushButton::swap_nums(_buttons[idx], _buttons[nul_idx]);
emit moved();
_check_game_end();
}
}
void BoardView::back_move() {
const auto result = _model->back_move();
const auto is_moved = result.first;
if (is_moved) {
const int lhs_idx = result.second.first.toInt();
const int rhs_idx = result.second.second.toInt();
auto lhs = _buttons[lhs_idx];
auto rhs = _buttons[rhs_idx];
FifteenPushButton::swap_nums(lhs, rhs);
_check_game_end();
}
}
void BoardView::_check_game_end() {
const auto is_solved_result = _model->is_solved();
const auto is_solved = is_solved_result.first;
if (is_solved) {
const int num_shifts = is_solved_result.second.toInt();
const auto msg = tr("Задача решена." "\n" "Использовано %1 перестановок.").arg(num_shifts);
QMessageBox::information(this, tr("Игра закончена"), msg);
}
}
bool BoardView::check_back_moves_available() {
return _model->check_back_moves_available();
}