-
Notifications
You must be signed in to change notification settings - Fork 0
/
SpaceShip.cpp
87 lines (73 loc) · 1.94 KB
/
SpaceShip.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
#include "SpaceShip.h"
#include <QPixmap>
#include <QKeyEvent>
#include <QGraphicsScene>
#include <QDebug>
#include "SpaceBullet.h"
#include "Game.h"
extern Game* game;
SpaceShip::SpaceShip(QGraphicsItem *parent)
{
// initialize the image.
QPixmap ship(":/images/spaceShip.png");
height = 80;
width = 80;
// resize the image.
ship = ship.scaled(QSize(getWidth(),getHeight()), Qt::KeepAspectRatio);
// set the image.
setPixmap(ship);
health_ = 100;
timer = new QTimer();
timer->setSingleShot(true);
}
bool SpaceShip::sceneEvent(QEvent *event)
{
if(event->type()==QEvent::KeyPress) {
pressedKeys += ((QKeyEvent*)event)->key();
if(pressedKeys.contains(Qt::Key_Space) ){
if(!timer->isActive()){
SpaceBullet *b = new SpaceBullet();
b->setPos(x() + 34,y() - 37);
scene()->addItem(b);
timer->start(600);
}
}
if(pressedKeys.contains(Qt::Key_Left)){
if(x() - 10 >= 0)
setPos(x() - 10, y());
}
else if(pressedKeys.contains(Qt::Key_Right)){
if(x() + 10 + getWidth() <= scene()->width())
setPos(x() + 10, y());
}
}
else if(event->type()==QEvent::KeyRelease)
{
if(((QKeyEvent*)event)->key() == Qt::Key_Space){
if(pressedKeys.contains(Qt::Key_Left)){
if(x() - 10 >= 0)
setPos(x() - 10, y());
}
else if(pressedKeys.contains(Qt::Key_Right)){
if(x() + 10 + getWidth() <= scene()->width())
setPos(x() + 10, y());
}
}
pressedKeys -= ((QKeyEvent*)event)->key();
}
return false;
}
int SpaceShip::getWidth()
{
return width;
}
int SpaceShip::getHeight()
{
return height;
}
void SpaceShip::updateHealth(int h){
health_ = h;
}
int SpaceShip::health(){
return health_;
}