1 /**************************************************************************
2 Ghosts Overboard - a game for Maemo 5
4 Copyright (C) 2011 Heli Hyvättinen
6 This file is part of Ghosts Overboard
8 Ghosts Overboard is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 2 of the License, or
11 (at your option) any later version.
13 This program is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with this program. If not, see <http://www.gnu.org/licenses/>.
21 **************************************************************************/
23 #include "timercontrolledgraphicspixmapobject.h"
24 #include <QGraphicsScene>
28 TimerControlledGraphicsPixmapObject::TimerControlledGraphicsPixmapObject(QPixmap pixmap, int speed, QGraphicsItem* parent) :
29 QObject(), QGraphicsPixmapItem(pixmap, parent)
33 connect(&timer_,SIGNAL(timeout()),this,SLOT(move()));
36 void TimerControlledGraphicsPixmapObject::startMoving()
38 if (!stoppedBecauseInvalidTime_)
42 void TimerControlledGraphicsPixmapObject::stopMoving()
47 void TimerControlledGraphicsPixmapObject::setSpeed(int speed)
51 timer_.setInterval(1000/speed); //converts from pixels in second to milliseconds per pixel
52 stoppedBecauseInvalidTime_ = false;
55 stoppedBecauseInvalidTime_ = true;
60 void TimerControlledGraphicsPixmapObject::move()
70 //calculate the new position
72 if (direction_ == E || direction_ == SE || direction_ == NE)
77 if (direction_ == W || direction_ == SW || direction_ == NW)
82 if (direction_ == S || direction_ == SE || direction_ == SW)
87 if (direction_ == N || direction_ == NE || direction_ == NW)
94 //Bound the item into the scene and change direction if hitting a boundary
95 //Only works if the old position is inside the boundaries
97 if (!scene()) //no movement if this item does not belong to a scene
100 QRect sceneRectangle = scene()->sceneRect().toRect();
102 if (newx < sceneRectangle.left() || newx > sceneRectangle.right()-pixmap().width())
109 if (newy < sceneRectangle.top() || newy > sceneRectangle.bottom()-pixmap().height())
112 return; //the old x and y values remain intact
116 //Set the new position
122 //check for collisions and handle them (up to subclassess to implement)
123 //return to the old position if requested
125 if (handleCollisions() == false)
134 void TimerControlledGraphicsPixmapObject::changeDirection()
136 // qDebug () << "Supposed to change direction";
138 int direction = (qrand()%8);
139 // qDebug() << direction;
180 bool TimerControlledGraphicsPixmapObject::handleCollisions()