-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.cpp
More file actions
75 lines (61 loc) · 2.06 KB
/
Copy pathgame.cpp
File metadata and controls
75 lines (61 loc) · 2.06 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
#include "game.h"
#include "ui_game.h"
Game::Game(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Game)
{
ui->setupUi(this);
scene_ = new QGraphicsScene(this);
ui->graphicsView->setGeometry(50, 100, BORDER_RIGTH + 2, BORDER_DOWN + 2);
ui->graphicsView->setScene(scene_);
scene_->setSceneRect(0, 0, BORDER_RIGTH - 1, BORDER_DOWN - 1);
connect(&timer_, &QTimer::timeout, this, &Game::tick);
}
Game::~Game()
{
delete ui;
}
void Game::keyPressEvent(QKeyEvent *event)
{
if (event->key() == Qt::Key_D && board_->moveDir.x == 0) board_->moveDir = { 1, 0};
if (event->key() == Qt::Key_A && board_->moveDir.x == 0) board_->moveDir = {-1, 0};
if (event->key() == Qt::Key_S && board_->moveDir.y == 0) board_->moveDir = { 0, 1};
if (event->key() == Qt::Key_W && board_->moveDir.y == 0) board_->moveDir = { 0, -1};
}
void Game::draw()
{
scene_->clear();
for (Square* current = board_->head_; current != nullptr; current = current->next) {
QColor color = current->color_;
scene_->addRect((current->position.x * SQUARE_SIDE),
(current->position.y * SQUARE_SIDE),
SQUARE_SIDE, SQUARE_SIDE, QColor("black"), color);
}
scene_->addRect((board_->apple_->position.x * SQUARE_SIDE),
(board_->apple_->position.y * SQUARE_SIDE),
SQUARE_SIDE, SQUARE_SIDE, QColor("red"), board_->apple_->color_);
}
void Game::tick()
{
draw();
ui->scoreBoard->display(board_->getScore());
if (!board_->move()) {
scene_->clear();
timer_.stop();
ui->gameStatusLabel->setText("Game Over!");
ui->startButton->setDisabled(false);
ui->startButton->setText("Restart");
delete board_;
}
}
void Game::on_startButton_clicked()
{
// Initialize the game board
board_ = new Board(WIDTH, HEIGTH);
ui->gameStatusLabel->setText("");
ui->startButton->setDisabled(true);
ui->scoreBoard->display(board_->getScore());
timer_.setInterval(300);
timer_.start();
board_->moveDir = {1, 0};
}