From d26a56e2d94bea2b5a1135b8336bbeefebf3ba1c Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Tue, 12 May 2009 16:40:44 +0200 Subject: Change name of "errorstate" example to "tankgame" The error state is not a big enough part of the example to justify naming it after it. --- examples/statemachine/errorstate/errorstate.pro | 13 - examples/statemachine/errorstate/gameitem.cpp | 88 ------- examples/statemachine/errorstate/gameitem.h | 23 -- examples/statemachine/errorstate/main.cpp | 12 - examples/statemachine/errorstate/mainwindow.cpp | 257 -------------------- examples/statemachine/errorstate/mainwindow.h | 46 ---- examples/statemachine/errorstate/plugin.h | 17 -- examples/statemachine/errorstate/rocketitem.cpp | 60 ----- examples/statemachine/errorstate/rocketitem.h | 26 -- examples/statemachine/errorstate/tankitem.cpp | 262 -------------------- examples/statemachine/errorstate/tankitem.h | 65 ----- .../errorstateplugins/errorstateplugins.pro | 11 - .../errorstateplugins/random_ai/random_ai.pro | 13 - .../random_ai/random_ai_plugin.cpp | 38 --- .../errorstateplugins/random_ai/random_ai_plugin.h | 64 ----- .../errorstateplugins/seek_ai/seek_ai.cpp | 48 ---- .../errorstateplugins/seek_ai/seek_ai.h | 204 ---------------- .../errorstateplugins/seek_ai/seek_ai.pro | 13 - .../errorstateplugins/spin_ai/spin_ai.cpp | 29 --- .../errorstateplugins/spin_ai/spin_ai.h | 46 ---- .../errorstateplugins/spin_ai/spin_ai.pro | 13 - .../spin_ai_with_error/spin_ai_with_error.cpp | 29 --- .../spin_ai_with_error/spin_ai_with_error.h | 46 ---- .../spin_ai_with_error/spin_ai_with_error.pro | 13 - examples/statemachine/statemachine.pro | 4 +- examples/statemachine/tankgame/gameitem.cpp | 88 +++++++ examples/statemachine/tankgame/gameitem.h | 23 ++ examples/statemachine/tankgame/main.cpp | 12 + examples/statemachine/tankgame/mainwindow.cpp | 264 +++++++++++++++++++++ examples/statemachine/tankgame/mainwindow.h | 46 ++++ examples/statemachine/tankgame/plugin.h | 17 ++ examples/statemachine/tankgame/rocketitem.cpp | 60 +++++ examples/statemachine/tankgame/rocketitem.h | 26 ++ examples/statemachine/tankgame/tankgame.pro | 13 + examples/statemachine/tankgame/tankitem.cpp | 262 ++++++++++++++++++++ examples/statemachine/tankgame/tankitem.h | 67 ++++++ .../tankgameplugins/random_ai/random_ai.pro | 13 + .../tankgameplugins/random_ai/random_ai_plugin.cpp | 38 +++ .../tankgameplugins/random_ai/random_ai_plugin.h | 64 +++++ .../tankgameplugins/seek_ai/seek_ai.cpp | 48 ++++ .../statemachine/tankgameplugins/seek_ai/seek_ai.h | 204 ++++++++++++++++ .../tankgameplugins/seek_ai/seek_ai.pro | 13 + .../tankgameplugins/spin_ai/spin_ai.cpp | 29 +++ .../statemachine/tankgameplugins/spin_ai/spin_ai.h | 46 ++++ .../tankgameplugins/spin_ai/spin_ai.pro | 13 + .../spin_ai_with_error/spin_ai_with_error.cpp | 29 +++ .../spin_ai_with_error/spin_ai_with_error.h | 46 ++++ .../spin_ai_with_error/spin_ai_with_error.pro | 13 + .../tankgameplugins/tankgameplugins.pro | 11 + 49 files changed, 1448 insertions(+), 1437 deletions(-) delete mode 100644 examples/statemachine/errorstate/errorstate.pro delete mode 100644 examples/statemachine/errorstate/gameitem.cpp delete mode 100644 examples/statemachine/errorstate/gameitem.h delete mode 100644 examples/statemachine/errorstate/main.cpp delete mode 100644 examples/statemachine/errorstate/mainwindow.cpp delete mode 100644 examples/statemachine/errorstate/mainwindow.h delete mode 100644 examples/statemachine/errorstate/plugin.h delete mode 100644 examples/statemachine/errorstate/rocketitem.cpp delete mode 100644 examples/statemachine/errorstate/rocketitem.h delete mode 100644 examples/statemachine/errorstate/tankitem.cpp delete mode 100644 examples/statemachine/errorstate/tankitem.h delete mode 100644 examples/statemachine/errorstateplugins/errorstateplugins.pro delete mode 100644 examples/statemachine/errorstateplugins/random_ai/random_ai.pro delete mode 100644 examples/statemachine/errorstateplugins/random_ai/random_ai_plugin.cpp delete mode 100644 examples/statemachine/errorstateplugins/random_ai/random_ai_plugin.h delete mode 100644 examples/statemachine/errorstateplugins/seek_ai/seek_ai.cpp delete mode 100644 examples/statemachine/errorstateplugins/seek_ai/seek_ai.h delete mode 100644 examples/statemachine/errorstateplugins/seek_ai/seek_ai.pro delete mode 100644 examples/statemachine/errorstateplugins/spin_ai/spin_ai.cpp delete mode 100644 examples/statemachine/errorstateplugins/spin_ai/spin_ai.h delete mode 100644 examples/statemachine/errorstateplugins/spin_ai/spin_ai.pro delete mode 100644 examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.cpp delete mode 100644 examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.h delete mode 100644 examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.pro create mode 100644 examples/statemachine/tankgame/gameitem.cpp create mode 100644 examples/statemachine/tankgame/gameitem.h create mode 100644 examples/statemachine/tankgame/main.cpp create mode 100644 examples/statemachine/tankgame/mainwindow.cpp create mode 100644 examples/statemachine/tankgame/mainwindow.h create mode 100644 examples/statemachine/tankgame/plugin.h create mode 100644 examples/statemachine/tankgame/rocketitem.cpp create mode 100644 examples/statemachine/tankgame/rocketitem.h create mode 100644 examples/statemachine/tankgame/tankgame.pro create mode 100644 examples/statemachine/tankgame/tankitem.cpp create mode 100644 examples/statemachine/tankgame/tankitem.h create mode 100644 examples/statemachine/tankgameplugins/random_ai/random_ai.pro create mode 100644 examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp create mode 100644 examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h create mode 100644 examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp create mode 100644 examples/statemachine/tankgameplugins/seek_ai/seek_ai.h create mode 100644 examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro create mode 100644 examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp create mode 100644 examples/statemachine/tankgameplugins/spin_ai/spin_ai.h create mode 100644 examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro create mode 100644 examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp create mode 100644 examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h create mode 100644 examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro create mode 100644 examples/statemachine/tankgameplugins/tankgameplugins.pro diff --git a/examples/statemachine/errorstate/errorstate.pro b/examples/statemachine/errorstate/errorstate.pro deleted file mode 100644 index b93a691..0000000 --- a/examples/statemachine/errorstate/errorstate.pro +++ /dev/null @@ -1,13 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) on 22. apr 14:11:33 2009 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += C:/dev/kinetic/examples/statemachine/errorstate/. . - -# Input -HEADERS += mainwindow.h plugin.h tankitem.h rocketitem.h gameitem.h -SOURCES += main.cpp mainwindow.cpp tankitem.cpp rocketitem.cpp gameitem.cpp -CONFIG += console diff --git a/examples/statemachine/errorstate/gameitem.cpp b/examples/statemachine/errorstate/gameitem.cpp deleted file mode 100644 index 1a2af71..0000000 --- a/examples/statemachine/errorstate/gameitem.cpp +++ /dev/null @@ -1,88 +0,0 @@ -#include "gameitem.h" - -#include -#include - -GameItem::GameItem(QObject *parent) : QObject(parent) -{ -} - -QPointF GameItem::tryMove(const QPointF &requestedPosition, QLineF *collidedLine, - QGraphicsItem **collidedItem) const -{ - QLineF movementPath(pos(), requestedPosition); - - qreal cannonLength = 0.0; - { - QPointF p1 = boundingRect().center(); - QPointF p2 = QPointF(boundingRect().right() + 10.0, p1.y()); - - cannonLength = QLineF(mapToScene(p1), mapToScene(p2)).length(); - } - - movementPath.setLength(movementPath.length() + cannonLength); - - QRectF boundingRectPath(QPointF(qMin(movementPath.x1(), movementPath.x2()), qMin(movementPath.y1(), movementPath.y2())), - QPointF(qMax(movementPath.x1(), movementPath.x2()), qMax(movementPath.y1(), movementPath.y2()))); - - QList itemsInRect = scene()->items(boundingRectPath, Qt::IntersectsItemBoundingRect); - - QPointF nextPoint = requestedPosition; - QRectF sceneRect = scene()->sceneRect(); - - foreach (QGraphicsItem *item, itemsInRect) { - if (item == static_cast(this)) - continue; - - QPolygonF mappedBoundingRect = item->mapToScene(item->boundingRect()); - for (int i=0; isceneRect().topLeft(), scene()->sceneRect().bottomLeft()); - } - - if (nextPoint.x() > sceneRect.right()) { - nextPoint.rx() = sceneRect.right(); - if (collidedLine != 0) - *collidedLine = QLineF(scene()->sceneRect().topRight(), scene()->sceneRect().bottomRight()); - } - - if (nextPoint.y() < sceneRect.top()) { - nextPoint.ry() = sceneRect.top(); - if (collidedLine != 0) - *collidedLine = QLineF(scene()->sceneRect().topLeft(), scene()->sceneRect().topRight()); - } - - if (nextPoint.y() > sceneRect.bottom()) { - nextPoint.ry() = sceneRect.bottom(); - if (collidedLine != 0) - *collidedLine = QLineF(scene()->sceneRect().bottomLeft(), scene()->sceneRect().bottomRight()); - } - - return nextPoint; -} - diff --git a/examples/statemachine/errorstate/gameitem.h b/examples/statemachine/errorstate/gameitem.h deleted file mode 100644 index 43b8785..0000000 --- a/examples/statemachine/errorstate/gameitem.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef GAMEITEM_H -#define GAMEITEM_H - -#include - -class QLineF; -class GameItem: public QObject, public QGraphicsItem -{ - Q_OBJECT -public: - enum { Type = UserType + 1 }; - int type() const { return Type; } - - GameItem(QObject *parent = 0); - - virtual void idle(qreal elapsed) = 0; - -protected: - QPointF tryMove(const QPointF &requestedPosition, QLineF *collidedLine = 0, - QGraphicsItem **collidedItem = 0) const; -}; - -#endif diff --git a/examples/statemachine/errorstate/main.cpp b/examples/statemachine/errorstate/main.cpp deleted file mode 100644 index 26fc1bb..0000000 --- a/examples/statemachine/errorstate/main.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include -#include "mainwindow.h" - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - MainWindow mainWindow; - mainWindow.show(); - - return app.exec(); -} diff --git a/examples/statemachine/errorstate/mainwindow.cpp b/examples/statemachine/errorstate/mainwindow.cpp deleted file mode 100644 index 07719bc..0000000 --- a/examples/statemachine/errorstate/mainwindow.cpp +++ /dev/null @@ -1,257 +0,0 @@ -#include "mainwindow.h" -#include "tankitem.h" -#include "rocketitem.h" -#include "plugin.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), m_scene(0), m_machine(0), m_runningState(0), m_started(false) -{ - init(); -} - -MainWindow::~MainWindow() -{ -} - -void MainWindow::addWall(const QRectF &wall) -{ - QGraphicsRectItem *item = new QGraphicsRectItem; - item->setRect(wall); - item->setBrush(Qt::darkGreen); - item->setPen(QPen(Qt::black, 0)); - - m_scene->addItem(item); -} - -void MainWindow::init() -{ - setWindowTitle("Pluggable Tank Game"); - - QGraphicsView *view = new QGraphicsView(this); - view->setRenderHints(QPainter::Antialiasing); - setCentralWidget(view); - - m_scene = new QGraphicsScene(this); - view->setScene(m_scene); - - QRectF sceneRect = QRectF(-200.0, -200.0, 400.0, 400.0); - m_scene->setSceneRect(sceneRect); - - { - TankItem *item = new TankItem(this); - - item->setPos(m_scene->sceneRect().topLeft() + QPointF(15.0, 15.0)); - item->setDirection(45.0); - item->setColor(Qt::red); - - m_spawns.append(item); - } - - { - TankItem *item = new TankItem(this); - - item->setPos(m_scene->sceneRect().topRight() + QPointF(-15.0, 15.0)); - item->setDirection(135.0); - item->setColor(Qt::green); - - m_spawns.append(item); - } - - { - TankItem *item = new TankItem(this); - - item->setPos(m_scene->sceneRect().bottomRight() + QPointF(-15.0, -15.0)); - item->setDirection(225.0); - item->setColor(Qt::blue); - - m_spawns.append(item); - } - - { - TankItem *item = new TankItem(this); - - item->setPos(m_scene->sceneRect().bottomLeft() + QPointF(15.0, -15.0)); - item->setDirection(315.0); - item->setColor(Qt::yellow); - - m_spawns.append(item); - } - - QPointF centerOfMap = sceneRect.center(); - - addWall(QRectF(centerOfMap + QPointF(-50.0, -60.0), centerOfMap + QPointF(50.0, -50.0))); - addWall(QRectF(centerOfMap - QPointF(-50.0, -60.0), centerOfMap - QPointF(50.0, -50.0))); - addWall(QRectF(centerOfMap + QPointF(-50.0, -50.0), centerOfMap + QPointF(-40.0, 50.0))); - addWall(QRectF(centerOfMap - QPointF(-50.0, -50.0), centerOfMap - QPointF(-40.0, 50.0))); - - addWall(QRectF(sceneRect.topLeft() + QPointF(sceneRect.width() / 2.0 - 5.0, -10.0), - sceneRect.topLeft() + QPointF(sceneRect.width() / 2.0 + 5.0, 100.0))); - addWall(QRectF(sceneRect.bottomLeft() + QPointF(sceneRect.width() / 2.0 - 5.0, 10.0), - sceneRect.bottomLeft() + QPointF(sceneRect.width() / 2.0 + 5.0, -100.0))); - addWall(QRectF(sceneRect.topLeft() + QPointF(-10.0, sceneRect.height() / 2.0 - 5.0), - sceneRect.topLeft() + QPointF(100.0, sceneRect.height() / 2.0 + 5.0))); - addWall(QRectF(sceneRect.topRight() + QPointF(10.0, sceneRect.height() / 2.0 - 5.0), - sceneRect.topRight() + QPointF(-100.0, sceneRect.height() / 2.0 + 5.0))); - - - QAction *addTankAction = menuBar()->addAction("&Add tank"); - QAction *runGameAction = menuBar()->addAction("&Run game"); - runGameAction->setObjectName("runGameAction"); - QAction *stopGameAction = menuBar()->addAction("&Stop game"); - menuBar()->addSeparator(); - QAction *quitAction = menuBar()->addAction("&Quit"); - - connect(addTankAction, SIGNAL(triggered()), this, SLOT(addTank())); - connect(quitAction, SIGNAL(triggered()), this, SLOT(close())); - - m_machine = new QStateMachine(this); - QState *stoppedState = new QState(m_machine->rootState()); - stoppedState->setObjectName("stoppedState"); - stoppedState->assignProperty(runGameAction, "enabled", true); - stoppedState->assignProperty(stopGameAction, "enabled", false); - stoppedState->assignProperty(this, "started", false); - m_machine->setInitialState(stoppedState); - - QState *spawnsAvailable = new QState(stoppedState); - spawnsAvailable->setObjectName("spawnsAvailable"); - spawnsAvailable->assignProperty(addTankAction, "enabled", true); - - QState *noSpawnsAvailable = new QState(stoppedState); - noSpawnsAvailable->setObjectName("noSpawnsAvailable"); - noSpawnsAvailable->assignProperty(addTankAction, "enabled", false); - - spawnsAvailable->addTransition(this, SIGNAL(mapFull()), noSpawnsAvailable); - - QHistoryState *hs = new QHistoryState(stoppedState); - hs->setDefaultState(spawnsAvailable); - - stoppedState->setInitialState(hs); - - m_runningState = new QState(QState::ParallelStates, m_machine->rootState()); - m_runningState->setObjectName("runningState"); - m_runningState->assignProperty(addTankAction, "enabled", false); - m_runningState->assignProperty(runGameAction, "enabled", false); - m_runningState->assignProperty(stopGameAction, "enabled", true); - - stoppedState->addTransition(runGameAction, SIGNAL(triggered()), m_runningState); - m_runningState->addTransition(stopGameAction, SIGNAL(triggered()), stoppedState); - - QTimer *timer = new QTimer(this); - timer->setInterval(100); - connect(timer, SIGNAL(timeout()), this, SLOT(runStep())); - connect(m_runningState, SIGNAL(entered()), timer, SLOT(start())); - connect(m_runningState, SIGNAL(exited()), timer, SLOT(stop())); - - m_machine->start(); - m_time.start(); -} - -void MainWindow::runStep() -{ - if (!m_started) { - m_time.restart(); - m_started = true; - } else { - int elapsed = m_time.elapsed(); - if (elapsed > 0) { - m_time.restart(); - qreal elapsedSecs = elapsed / 1000.0; - QList items = m_scene->items(); - foreach (QGraphicsItem *item, items) { - if (GameItem *gameItem = qgraphicsitem_cast(item)) - gameItem->idle(elapsedSecs); - } - } - } -} - -void MainWindow::addRocket() -{ - TankItem *tankItem = qobject_cast(sender()); - if (tankItem != 0) { - RocketItem *rocketItem = new RocketItem; - - QPointF s = tankItem->mapToScene(QPointF(tankItem->boundingRect().right() + 10.0, - tankItem->boundingRect().center().y())); - rocketItem->setPos(s); - rocketItem->setDirection(tankItem->direction()); - m_scene->addItem(rocketItem); - } -} - -void MainWindow::addTank() -{ - Q_ASSERT(!m_spawns.isEmpty()); - - QDir pluginsDir(qApp->applicationDirPath()); -#if defined(Q_OS_WIN) - if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") - pluginsDir.cdUp(); -#elif defined(Q_OS_MAC) - if (pluginsDir.dirName() == "MacOS") { - pluginsDir.cdUp(); - pluginsDir.cdUp(); - pluginsDir.cdUp(); - } -#endif - - pluginsDir.cd("plugins"); - - QStringList itemNames; - QList items; - foreach (QString fileName, pluginsDir.entryList(QDir::Files)) { - QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); - QObject *possiblePlugin = loader.instance(); - if (Plugin *plugin = qobject_cast(possiblePlugin)) { - QString objectName = possiblePlugin->objectName(); - if (objectName.isEmpty()) - objectName = fileName; - - itemNames.append(objectName); - items.append(plugin); - } - } - - if (items.isEmpty()) { - QMessageBox::information(this, "No tank types found", "Please build the errorstateplugins directory"); - return; - } - - bool ok; - QString selectedName = QInputDialog::getItem(this, "Select a tank type", "Tank types", - itemNames, 0, false, &ok); - - if (ok && !selectedName.isEmpty()) { - int idx = itemNames.indexOf(selectedName); - if (Plugin *plugin = idx >= 0 ? items.at(idx) : 0) { - TankItem *tankItem = m_spawns.takeLast(); - m_scene->addItem(tankItem); - connect(tankItem, SIGNAL(cannonFired()), this, SLOT(addRocket())); - if (m_spawns.isEmpty()) - emit mapFull(); - - QState *region = new QState(m_runningState); - QState *pluginState = plugin->create(region, tankItem); - region->setInitialState(pluginState); - - // If the plugin has an error it is disabled - QState *errorState = new QState(region); - errorState->assignProperty(tankItem, "enabled", false); - pluginState->setErrorState(errorState); - } - } -} - diff --git a/examples/statemachine/errorstate/mainwindow.h b/examples/statemachine/errorstate/mainwindow.h deleted file mode 100644 index 622dabe..0000000 --- a/examples/statemachine/errorstate/mainwindow.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef MAINWINDOW_H -#define MAINWINDOW_H - -#include -#include - -class QGraphicsScene; -class QStateMachine; -class QState; -class TankItem; -class MainWindow: public QMainWindow -{ - Q_OBJECT - Q_PROPERTY(bool started READ started WRITE setStarted) -public: - MainWindow(QWidget *parent = 0); - ~MainWindow(); - - void setStarted(bool b) { m_started = b; } - bool started() const { return m_started; } - -public slots: - void addTank(); - void addRocket(); - void runStep(); - -signals: - void mapFull(); - -private: - void init(); - void addWall(const QRectF &wall); - - QGraphicsScene *m_scene; - - QStateMachine *m_machine; - QState *m_runningState; - - QList m_spawns; - QTime m_time; - - bool m_started : 1; -}; - -#endif - diff --git a/examples/statemachine/errorstate/plugin.h b/examples/statemachine/errorstate/plugin.h deleted file mode 100644 index 2b48d43..0000000 --- a/examples/statemachine/errorstate/plugin.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef PLUGIN_H -#define PLUGIN_H - -#include - -class QState; -class Plugin -{ -public: - virtual ~Plugin() {} - - virtual QState *create(QState *parentState, QObject *tank) = 0; -}; - -Q_DECLARE_INTERFACE(Plugin, "TankPlugin") - -#endif diff --git a/examples/statemachine/errorstate/rocketitem.cpp b/examples/statemachine/errorstate/rocketitem.cpp deleted file mode 100644 index c324980..0000000 --- a/examples/statemachine/errorstate/rocketitem.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "rocketitem.h" -#include "tankitem.h" - -#include -#include - -#include - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -RocketItem::RocketItem(QObject *parent) - : GameItem(parent), m_direction(0.0), m_distance(300.0) -{ -} - -QRectF RocketItem::boundingRect() const -{ - return QRectF(-1.0, -1.0, 2.0, 2.0); -} - -void RocketItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - painter->setBrush(Qt::black); - painter->drawEllipse(boundingRect()); -} - -void RocketItem::idle(qreal elapsed) -{ - qreal dist = elapsed * speed(); - - m_distance -= dist; - if (m_distance < 0.0) { - scene()->removeItem(this); - delete this; - return; - } - - qreal a = m_direction * M_PI / 180.0; - - qreal yd = dist * sin(a); - qreal xd = dist * sin(M_PI / 2.0 - a); - - QPointF requestedPosition = pos() + QPointF(xd, yd); - QGraphicsItem *collidedItem = 0; - QPointF nextPosition = tryMove(requestedPosition, 0, &collidedItem); - if (requestedPosition == nextPosition) { - setPos(nextPosition); - } else { - if (GameItem *gameItem = qgraphicsitem_cast(collidedItem)) { - TankItem *tankItem = qobject_cast(gameItem); - if (tankItem != 0) - tankItem->hitByRocket(); - } - - scene()->removeItem(this); - delete this; - } -} diff --git a/examples/statemachine/errorstate/rocketitem.h b/examples/statemachine/errorstate/rocketitem.h deleted file mode 100644 index 189a1dd..0000000 --- a/examples/statemachine/errorstate/rocketitem.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef ROCKETITEM_H -#define ROCKETITEM_H - -#include "gameitem.h" - -class RocketItem: public GameItem -{ - Q_OBJECT -public: - RocketItem(QObject *parent = 0); - - virtual void idle(qreal elapsed); - qreal speed() const { return 100.0; } - void setDirection(qreal direction) { m_direction = direction; } - -protected: - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - QRectF boundingRect() const; - -private: - qreal m_direction; - qreal m_distance; -}; - - -#endif diff --git a/examples/statemachine/errorstate/tankitem.cpp b/examples/statemachine/errorstate/tankitem.cpp deleted file mode 100644 index 5506a7e..0000000 --- a/examples/statemachine/errorstate/tankitem.cpp +++ /dev/null @@ -1,262 +0,0 @@ -#include "tankitem.h" - -#include -#include -#include - -#include - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -class Action -{ -public: - Action(TankItem *item) : m_item(item) - { - } - - TankItem *item() const { return m_item; } - void setItem(TankItem *item) { m_item = item; } - - virtual bool apply(qreal timeDelta) = 0; - -private: - TankItem *m_item; -}; - -class MoveAction: public Action -{ -public: - MoveAction(TankItem *item, qreal distance) - : Action(item), m_distance(distance) - { - m_reverse = m_distance < 0.0; - } - - bool apply(qreal timeDelta) - { - qreal dist = timeDelta * item()->speed() * (m_reverse ? -1.0 : 1.0); - - bool done = false; - if (qAbs(m_distance) < qAbs(dist)) { - done = true; - dist = m_distance; - } - m_distance -= dist; - - qreal a = item()->direction() * M_PI / 180.0; - - qreal yd = dist * sin(a); - qreal xd = dist * sin(M_PI / 2.0 - a); - - item()->setPos(item()->pos() + QPointF(xd, yd)); - return !done; - } - -private: - qreal m_distance; - bool m_reverse; -}; - -class TurnAction: public Action -{ -public: - TurnAction(TankItem *item, qreal distance) - : Action(item), m_distance(distance) - { - m_reverse = m_distance < 0.0; - } - - bool apply(qreal timeDelta) - { - qreal dist = timeDelta * item()->angularSpeed() * (m_reverse ? -1.0 : 1.0); - bool done = false; - if (qAbs(m_distance) < qAbs(dist)) { - done = true; - dist = m_distance; - } - m_distance -= dist; - - item()->setDirection(item()->direction() + dist); - return !done; - } - -private: - qreal m_distance; - bool m_reverse; -}; - -TankItem::TankItem(QObject *parent) - : GameItem(parent), m_currentAction(0), m_currentDirection(0.0), m_enabled(true) -{ - connect(this, SIGNAL(cannonFired()), this, SIGNAL(actionCompleted())); -} - -void TankItem::idle(qreal elapsed) -{ - if (m_enabled) { - if (m_currentAction != 0) { - if (!m_currentAction->apply(elapsed)) { - setAction(0); - emit actionCompleted(); - } - - QGraphicsItem *item = 0; - qreal distance = distanceToObstacle(&item); - if (TankItem *tankItem = qgraphicsitem_cast(item)) - emit tankSpotted(tankItem->direction(), distance); - } - } -} - -void TankItem::hitByRocket() -{ - deleteLater(); -} - -void TankItem::setAction(Action *newAction) -{ - if (m_currentAction != 0) - delete m_currentAction; - - m_currentAction = newAction; -} - -void TankItem::fireCannon() -{ - emit cannonFired(); -} - -void TankItem::moveForwards(qreal length) -{ - setAction(new MoveAction(this, length)); -} - -void TankItem::moveBackwards(qreal length) -{ - setAction(new MoveAction(this, -length)); -} - -void TankItem::turn(qreal degrees) -{ - setAction(new TurnAction(this, degrees)); -} - -void TankItem::turnTo(qreal degrees) -{ - setAction(new TurnAction(this, degrees - direction())); -} - -void TankItem::stop() -{ - setAction(0); -} - -QVariant TankItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) -{ - if (change == ItemPositionChange && scene()) { - QPointF requestedPosition = value.toPointF(); - QLineF collidedLine; - QPointF nextPoint = tryMove(requestedPosition, &collidedLine); - if (nextPoint != requestedPosition) - emit collision(collidedLine); - return nextPoint; - } else { - return QGraphicsItem::itemChange(change, value); - } -} - - -void TankItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - QRectF brect = boundingRect(); - - painter->setBrush(m_color); - painter->setPen(Qt::black); - - // body - painter->drawRect(brect.adjusted(0.0, 4.0, -2.0, -4.0)); - - // cannon - QRectF cannonBase = brect.adjusted(10.0, 6.0, -12.0, -6.0); - painter->drawEllipse(cannonBase); - - painter->drawRect(QRectF(QPointF(cannonBase.center().x(), cannonBase.center().y() - 2.0), - QPointF(brect.right(), cannonBase.center().y() + 2.0))); - - // left track - painter->setBrush(QBrush(Qt::black, Qt::VerPattern)); - QRectF leftTrackRect = QRectF(brect.topLeft(), QPointF(brect.right() - 2.0, brect.top() + 4.0)); - painter->fillRect(leftTrackRect, Qt::darkYellow); - painter->drawRect(leftTrackRect); - - // right track - QRectF rightTrackRect = QRectF(QPointF(brect.left(), brect.bottom() - 4.0), - QPointF(brect.right() - 2.0, brect.bottom())); - painter->fillRect(rightTrackRect, Qt::darkYellow); - painter->drawRect(rightTrackRect); - - if (!m_enabled) { - painter->setPen(QPen(Qt::red, 5)); - - painter->drawEllipse(brect); - - QPainterPath path; - path.addEllipse(brect); - painter->setClipPath(path); - painter->drawLine(brect.topRight(), brect.bottomLeft()); - } -} - -QRectF TankItem::boundingRect() const -{ - return QRectF(-20.0, -10.0, 40.0, 20.0); -} - -qreal TankItem::direction() const -{ - return m_currentDirection; -} - -void TankItem::setDirection(qreal newDirection) -{ - int fullRotations = int(newDirection) / 360; - newDirection -= fullRotations * 360.0; - - qreal diff = newDirection - m_currentDirection; - m_currentDirection = newDirection; - rotate(diff); -} - -qreal TankItem::distanceToObstacle(QGraphicsItem **obstacle) const -{ - qreal dist = sqrt(pow(scene()->sceneRect().width(), 2) + pow(scene()->sceneRect().height(), 2)); - - qreal a = m_currentDirection * M_PI / 180.0; - - qreal yd = dist * sin(a); - qreal xd = dist * sin(M_PI / 2.0 - a); - - QPointF requestedPosition = pos() + QPointF(xd, yd); - QGraphicsItem *collidedItem = 0; - QPointF nextPosition = tryMove(requestedPosition, 0, &collidedItem); - if (collidedItem != 0) { - if (obstacle != 0) - *obstacle = collidedItem; - - QPointF d = nextPosition - pos(); - return sqrt(pow(d.x(), 2) + pow(d.y(), 2)); - } else { - return 0.0; - } -} - -qreal TankItem::distanceToObstacle() const -{ - return distanceToObstacle(0); -} - - - diff --git a/examples/statemachine/errorstate/tankitem.h b/examples/statemachine/errorstate/tankitem.h deleted file mode 100644 index cefed69..0000000 --- a/examples/statemachine/errorstate/tankitem.h +++ /dev/null @@ -1,65 +0,0 @@ -#ifndef TANKITEM_H -#define TANKITEM_H - -#include "gameitem.h" - -#include - -class Action; -class TankItem: public GameItem -{ - Q_OBJECT - Q_PROPERTY(bool enabled READ enabled WRITE setEnabled) - Q_PROPERTY(qreal direction READ direction WRITE turnTo) - Q_PROPERTY(qreal distanceToObstacle READ distanceToObstacle) -public: - TankItem(QObject *parent = 0); - - void setColor(const QColor &color) { m_color = color; } - QColor color() const { return m_color; } - - void idle(qreal elapsed); - void setDirection(qreal newDirection); - - qreal speed() const { return 90.0; } - qreal angularSpeed() const { return 90.0; } - - QRectF boundingRect() const; - - void hitByRocket(); - - void setEnabled(bool b) { m_enabled = b; } - bool enabled() const { return m_enabled; } - - qreal direction() const; - qreal distanceToObstacle() const; - qreal distanceToObstacle(QGraphicsItem **item) const; - -signals: - void tankSpotted(qreal direction, qreal distance); - void collision(const QLineF &collidedLine); - void actionCompleted(); - void cannonFired(); - -public slots: - void moveForwards(qreal length = 10.0); - void moveBackwards(qreal length = 10.0); - void turn(qreal degrees = 30.0); - void turnTo(qreal degrees = 0.0); - void stop(); - void fireCannon(); - -protected: - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value); - -private: - void setAction(Action *newAction); - - Action *m_currentAction; - qreal m_currentDirection; - QColor m_color; - bool m_enabled; -}; - -#endif diff --git a/examples/statemachine/errorstateplugins/errorstateplugins.pro b/examples/statemachine/errorstateplugins/errorstateplugins.pro deleted file mode 100644 index 5b6b758..0000000 --- a/examples/statemachine/errorstateplugins/errorstateplugins.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = random_ai \ - spin_ai_with_error \ - spin_ai \ - seek_ai - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/errorstateplugins -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS errorstateplugins.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/errorstateplugins -INSTALLS += target sources diff --git a/examples/statemachine/errorstateplugins/random_ai/random_ai.pro b/examples/statemachine/errorstateplugins/random_ai/random_ai.pro deleted file mode 100644 index f290250..0000000 --- a/examples/statemachine/errorstateplugins/random_ai/random_ai.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = lib -CONFIG += plugin -INCLUDEPATH += ../.. -HEADERS = random_ai_plugin.h -SOURCES = random_ai_plugin.cpp -TARGET = $$qtLibraryTarget(random_ai) -DESTDIR = ../../errorstate/plugins - -#! [0] -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/errorstate/plugins -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS random_ai.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/errorstateplugins/random_ai \ No newline at end of file diff --git a/examples/statemachine/errorstateplugins/random_ai/random_ai_plugin.cpp b/examples/statemachine/errorstateplugins/random_ai/random_ai_plugin.cpp deleted file mode 100644 index c196247..0000000 --- a/examples/statemachine/errorstateplugins/random_ai/random_ai_plugin.cpp +++ /dev/null @@ -1,38 +0,0 @@ -#include "random_ai_plugin.h" - -#include -#include - -#include - -QState *RandomAiPlugin::create(QState *parentState, QObject *tank) -{ - qsrand(uint(time(NULL))); - - QState *topLevel = new QState(parentState); - - QState *selectNextActionState = new SelectActionState(topLevel); - topLevel->setInitialState(selectNextActionState); - - QState *fireState = new RandomDistanceState(topLevel); - connect(fireState, SIGNAL(distanceComputed(qreal)), tank, SLOT(fireCannon())); - selectNextActionState->addTransition(selectNextActionState, SIGNAL(fireSelected()), fireState); - - QState *moveForwardsState = new RandomDistanceState(topLevel); - connect(moveForwardsState, SIGNAL(distanceComputed(qreal)), tank, SLOT(moveForwards(qreal))); - selectNextActionState->addTransition(selectNextActionState, SIGNAL(moveForwardsSelected()), moveForwardsState); - - QState *moveBackwardsState = new RandomDistanceState(topLevel); - connect(moveBackwardsState, SIGNAL(distanceComputed(qreal)), tank, SLOT(moveBackwards(qreal))); - selectNextActionState->addTransition(selectNextActionState, SIGNAL(moveBackwardsSelected()), moveBackwardsState); - - QState *turnState = new RandomDistanceState(topLevel); - connect(turnState, SIGNAL(distanceComputed(qreal)), tank, SLOT(turn(qreal))); - selectNextActionState->addTransition(selectNextActionState, SIGNAL(turnSelected()), turnState); - - topLevel->addTransition(tank, SIGNAL(actionCompleted()), selectNextActionState); - - return topLevel; -} - -Q_EXPORT_PLUGIN2(random_ai, RandomAiPlugin) diff --git a/examples/statemachine/errorstateplugins/random_ai/random_ai_plugin.h b/examples/statemachine/errorstateplugins/random_ai/random_ai_plugin.h deleted file mode 100644 index 10e6f48..0000000 --- a/examples/statemachine/errorstateplugins/random_ai/random_ai_plugin.h +++ /dev/null @@ -1,64 +0,0 @@ -#ifndef RANDOM_AI_PLUGIN_H -#define RANDOM_AI_PLUGIN_H - -#include -#include - -#include - -class SelectActionState: public QState -{ - Q_OBJECT -public: - SelectActionState(QState *parent = 0) : QState(parent) - { - } - -signals: - void fireSelected(); - void moveForwardsSelected(); - void moveBackwardsSelected(); - void turnSelected(); - -protected: - void onEntry(QEvent *) - { - int rand = qrand() % 4; - switch (rand) { - case 0: emit fireSelected(); break; - case 1: emit moveForwardsSelected(); break; - case 2: emit moveBackwardsSelected(); break; - case 3: emit turnSelected(); break; - }; - } -}; - -class RandomDistanceState: public QState -{ - Q_OBJECT -public: - RandomDistanceState(QState *parent = 0) : QState(parent) - { - } - -signals: - void distanceComputed(qreal distance); - -protected: - void onEntry(QEvent *) - { - emit distanceComputed(qreal(qrand() % 180)); - } -}; - -class RandomAiPlugin: public QObject, public Plugin -{ - Q_OBJECT - Q_INTERFACES(Plugin) -public: - RandomAiPlugin() { setObjectName("Random"); } - - virtual QState *create(QState *parentState, QObject *tank); -}; - -#endif // RANDOM_AI_PLUGIN_H diff --git a/examples/statemachine/errorstateplugins/seek_ai/seek_ai.cpp b/examples/statemachine/errorstateplugins/seek_ai/seek_ai.cpp deleted file mode 100644 index 2fb05d4..0000000 --- a/examples/statemachine/errorstateplugins/seek_ai/seek_ai.cpp +++ /dev/null @@ -1,48 +0,0 @@ -#include "seek_ai.h" - -QState *SeekAi::create(QState *parentState, QObject *tank) -{ - QState *topLevel = new QState(parentState); - topLevel->setObjectName("topLevel"); - - QState *seek = new QState(topLevel); - seek->setObjectName("seek"); - topLevel->setInitialState(seek); - - QState *lookForNearestWall = new SearchState(tank, seek); - lookForNearestWall->setObjectName("lookForNearestWall"); - seek->setInitialState(lookForNearestWall); - - QState *driveToFirstObstacle = new QState(seek); - driveToFirstObstacle->setObjectName("driveToFirstObstacle"); - lookForNearestWall->addTransition(lookForNearestWall, SIGNAL(nearestObstacleStraightAhead()), - driveToFirstObstacle); - - QState *drive = new QState(driveToFirstObstacle); - drive->setObjectName("drive"); - driveToFirstObstacle->setInitialState(drive); - connect(drive, SIGNAL(entered()), tank, SLOT(moveForwards())); - connect(drive, SIGNAL(exited()), tank, SLOT(stop())); - - // Go in loop - QState *finishedDriving = new QState(driveToFirstObstacle); - finishedDriving->setObjectName("finishedDriving"); - drive->addTransition(tank, SIGNAL(actionCompleted()), finishedDriving); - finishedDriving->addTransition(drive); - - QState *turnTo = new QState(seek); - turnTo->setObjectName("turnTo"); - driveToFirstObstacle->addTransition(new CollisionTransition(tank, turnTo)); - - turnTo->addTransition(tank, SIGNAL(actionCompleted()), driveToFirstObstacle); - - ChaseState *chase = new ChaseState(tank, topLevel); - chase->setObjectName("chase"); - seek->addTransition(new TankSpottedTransition(tank, chase)); - chase->addTransition(chase, SIGNAL(finished()), driveToFirstObstacle); - chase->addTransition(new TankSpottedTransition(tank, chase)); - - return topLevel; -} - -Q_EXPORT_PLUGIN2(seek_ai, SeekAi) diff --git a/examples/statemachine/errorstateplugins/seek_ai/seek_ai.h b/examples/statemachine/errorstateplugins/seek_ai/seek_ai.h deleted file mode 100644 index a1b5749..0000000 --- a/examples/statemachine/errorstateplugins/seek_ai/seek_ai.h +++ /dev/null @@ -1,204 +0,0 @@ -#ifndef SEEK_AI_H -#define SEEK_AI_H - -#include - -#include -#include -#include -#include -#include -#include -#include - -class SearchState: public QState -{ - Q_OBJECT -public: - SearchState(QObject *tank, QState *parentState = 0) - : QState(parentState), - m_tank(tank), - m_distanceToTurn(360.0), - m_nearestDistance(-1.0), - m_directionOfNearestObstacle(0.0) - { - } - -public slots: - void turnAlittle() - { - qreal dist = m_tank->property("distanceToObstacle").toDouble(); - - if (m_nearestDistance < 0.0 || dist < m_nearestDistance) { - m_nearestDistance = dist; - m_directionOfNearestObstacle = m_tank->property("direction").toDouble(); - } - - m_distanceToTurn -= 10.0; - if (m_distanceToTurn < 0.0) { - disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); - connect(m_tank, SIGNAL(actionCompleted()), this, SIGNAL(nearestObstacleStraightAhead())); - m_tank->setProperty("direction", m_directionOfNearestObstacle); - } - - qreal currentDirection = m_tank->property("direction").toDouble(); - m_tank->setProperty("direction", currentDirection + 10.0); - } - -signals: - void nearestObstacleStraightAhead(); - -protected: - void onEntry(QEvent *) - { - connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); - turnAlittle(); - } - - void onExit(QEvent *) - { - disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); - disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(nearestObstacleStraightAhead())); - } - -private: - QObject *m_tank; - - qreal m_distanceToTurn; - qreal m_nearestDistance; - qreal m_directionOfNearestObstacle; -}; - -class CollisionTransition: public QSignalTransition -{ -public: - CollisionTransition(QObject *tank, QState *turnTo) - : QSignalTransition(tank, SIGNAL(collision(QLineF))), - m_tank(tank), - m_turnTo(turnTo) - { - setTargetState(turnTo); - } - -protected: - bool eventTest(QEvent *event) const - { - bool b = QSignalTransition::eventTest(event); - if (b) { - QSignalEvent *se = static_cast(event); - m_lastLine = se->arguments().at(0).toLineF(); - } - return b; - } - - void onTransition(QEvent *) - { - qreal angleOfWall = m_lastLine.angle(); - - qreal newDirection; - if (qrand() % 2 == 0) - newDirection = angleOfWall; - else - newDirection = angleOfWall - 180.0; - - m_turnTo->assignProperty(m_tank, "direction", newDirection); - } - -private: - mutable QLineF m_lastLine; - QObject *m_tank; - QState *m_turnTo; -}; - -class ChaseState: public QState -{ - class GoToLocationState: public QState - { - public: - GoToLocationState(QObject *tank, QState *parentState = 0) - : QState(parentState), m_tank(tank), m_distance(0.0) - { - } - - void setDistance(qreal distance) { m_distance = distance; } - - protected: - void onEntry() - { - QMetaObject::invokeMethod(m_tank, "moveForwards", Q_ARG(qreal, m_distance)); - } - - private: - QObject *m_tank; - qreal m_distance; - }; - -public: - ChaseState(QObject *tank, QState *parentState = 0) : QState(parentState), m_tank(tank) - { - QState *fireCannon = new QState(this); - connect(fireCannon, SIGNAL(entered()), tank, SLOT(fireCannon())); - setInitialState(fireCannon); - - m_goToLocation = new GoToLocationState(this); - fireCannon->addTransition(tank, SIGNAL(actionCompleted()), m_goToLocation); - - m_turnToDirection = new QState(this); - m_goToLocation->addTransition(tank, SIGNAL(actionCompleted()), m_turnToDirection); - - QFinalState *finalState = new QFinalState(this); - m_turnToDirection->addTransition(tank, SIGNAL(actionCompleted()), finalState); - } - - void setDirection(qreal direction) - { - m_turnToDirection->assignProperty(m_tank, "direction", direction); - } - - void setDistance(qreal distance) - { - m_goToLocation->setDistance(distance); - } - -private: - QObject *m_tank; - GoToLocationState *m_goToLocation; - QState *m_turnToDirection; - -}; - -class TankSpottedTransition: public QSignalTransition -{ -public: - TankSpottedTransition(QObject *tank, ChaseState *target) : QSignalTransition(tank, SIGNAL(tankSpotted(qreal,qreal))), m_chase(target) - { - setTargetState(target); - } - -protected: - bool eventTest(QEvent *event) const - { - bool b = QSignalTransition::eventTest(event); - if (b) { - QSignalEvent *se = static_cast(event); - m_chase->setDirection(se->arguments().at(0).toDouble()); - m_chase->setDistance(se->arguments().at(1).toDouble()); - } - return b; - } - -private: - ChaseState *m_chase; -}; - -class SeekAi: public QObject, public Plugin -{ - Q_OBJECT - Q_INTERFACES(Plugin) -public: - SeekAi() { setObjectName("Seek and destroy"); } - - virtual QState *create(QState *parentState, QObject *tank); -}; - -#endif diff --git a/examples/statemachine/errorstateplugins/seek_ai/seek_ai.pro b/examples/statemachine/errorstateplugins/seek_ai/seek_ai.pro deleted file mode 100644 index 11bd242..0000000 --- a/examples/statemachine/errorstateplugins/seek_ai/seek_ai.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = lib -CONFIG += plugin -INCLUDEPATH += ../.. -HEADERS = seek_ai.h -SOURCES = seek_ai.cpp -TARGET = $$qtLibraryTarget(seek_ai) -DESTDIR = ../../errorstate/plugins - -#! [0] -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/errorstate/plugins -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS seek_ai.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/errorstateplugins/seek_ai \ No newline at end of file diff --git a/examples/statemachine/errorstateplugins/spin_ai/spin_ai.cpp b/examples/statemachine/errorstateplugins/spin_ai/spin_ai.cpp deleted file mode 100644 index de95f41..0000000 --- a/examples/statemachine/errorstateplugins/spin_ai/spin_ai.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "spin_ai.h" - -#include - -QState *SpinAi::create(QState *parentState, QObject *tank) -{ - QState *topLevel = new QState(parentState); - QState *spinState = new SpinState(tank, topLevel); - topLevel->setInitialState(spinState); - - // When tank is spotted, fire two times and go back to spin state - QState *fireState = new QState(topLevel); - - QState *fireOnce = new QState(fireState); - fireState->setInitialState(fireOnce); - connect(fireOnce, SIGNAL(entered()), tank, SLOT(fireCannon())); - - QState *fireTwice = new QState(fireState); - connect(fireTwice, SIGNAL(entered()), tank, SLOT(fireCannon())); - - fireOnce->addTransition(tank, SIGNAL(actionCompleted()), fireTwice); - fireTwice->addTransition(tank, SIGNAL(actionCompleted()), spinState); - - spinState->addTransition(tank, SIGNAL(tankSpotted(qreal,qreal)), fireState); - - return topLevel; -} - -Q_EXPORT_PLUGIN2(spin_ai, SpinAi) diff --git a/examples/statemachine/errorstateplugins/spin_ai/spin_ai.h b/examples/statemachine/errorstateplugins/spin_ai/spin_ai.h deleted file mode 100644 index 6e220ed..0000000 --- a/examples/statemachine/errorstateplugins/spin_ai/spin_ai.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef SPIN_AI_H -#define SPIN_AI_H - -#include - -#include -#include -#include - -class SpinState: public QState -{ - Q_OBJECT -public: - SpinState(QObject *tank, QState *parent) : QState(parent), m_tank(tank) - { - } - -public slots: - void spin() - { - m_tank->setProperty("direction", 90.0); - } - -protected: - void onEntry(QEvent *) - { - connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); - spin(); - } - -private: - QObject *m_tank; - -}; - -class SpinAi: public QObject, public Plugin -{ - Q_OBJECT - Q_INTERFACES(Plugin) -public: - SpinAi() { setObjectName("Spin and destroy"); } - - virtual QState *create(QState *parentState, QObject *tank); -}; - -#endif diff --git a/examples/statemachine/errorstateplugins/spin_ai/spin_ai.pro b/examples/statemachine/errorstateplugins/spin_ai/spin_ai.pro deleted file mode 100644 index c2fd937..0000000 --- a/examples/statemachine/errorstateplugins/spin_ai/spin_ai.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = lib -CONFIG += plugin -INCLUDEPATH += ../.. -HEADERS = spin_ai.h -SOURCES = spin_ai.cpp -TARGET = $$qtLibraryTarget(spin_ai) -DESTDIR = ../../errorstate/plugins - -#! [0] -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/errorstate/plugins -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS spin_ai.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/errorstateplugins/spin_ai \ No newline at end of file diff --git a/examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.cpp b/examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.cpp deleted file mode 100644 index 5499ba3..0000000 --- a/examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.cpp +++ /dev/null @@ -1,29 +0,0 @@ -#include "spin_ai_with_error.h" - -#include - -QState *SpinAiWithError::create(QState *parentState, QObject *tank) -{ - QState *topLevel = new QState(parentState); - QState *spinState = new SpinState(tank, topLevel); - topLevel->setInitialState(spinState); - - // When tank is spotted, fire two times and go back to spin state - // (no initial state set for fireState will lead to run-time error in machine) - QState *fireState = new QState(topLevel); - - QState *fireOnce = new QState(fireState); - connect(fireOnce, SIGNAL(entered()), tank, SLOT(fireCannon())); - - QState *fireTwice = new QState(fireState); - connect(fireTwice, SIGNAL(entered()), tank, SLOT(fireCannon())); - - fireOnce->addTransition(tank, SIGNAL(actionCompleted()), fireTwice); - fireTwice->addTransition(tank, SIGNAL(actionCompleted()), spinState); - - spinState->addTransition(tank, SIGNAL(tankSpotted(qreal,qreal)), fireState); - - return topLevel; -} - -Q_EXPORT_PLUGIN2(spin_ai_with_error, SpinAiWithError) diff --git a/examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.h b/examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.h deleted file mode 100644 index d520455..0000000 --- a/examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifndef SPIN_AI_WITH_ERROR_H -#define SPIN_AI_WITH_ERROR_H - -#include - -#include -#include -#include - -class SpinState: public QState -{ - Q_OBJECT -public: - SpinState(QObject *tank, QState *parent) : QState(parent), m_tank(tank) - { - } - -public slots: - void spin() - { - m_tank->setProperty("direction", 90.0); - } - -protected: - void onEntry(QEvent *) - { - connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); - spin(); - } - -private: - QObject *m_tank; - -}; - -class SpinAiWithError: public QObject, public Plugin -{ - Q_OBJECT - Q_INTERFACES(Plugin) -public: - SpinAiWithError() { setObjectName("Spin and destroy with runtime error in state machine"); } - - virtual QState *create(QState *parentState, QObject *tank); -}; - -#endif diff --git a/examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.pro b/examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.pro deleted file mode 100644 index 31f4c7f..0000000 --- a/examples/statemachine/errorstateplugins/spin_ai_with_error/spin_ai_with_error.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = lib -CONFIG += plugin -INCLUDEPATH += ../.. -HEADERS = spin_ai_with_error.h -SOURCES = spin_ai_with_error.cpp -TARGET = $$qtLibraryTarget(spin_ai_with_error) -DESTDIR = ../../errorstate/plugins - -#! [0] -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/errorstate/plugins -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS spin_ai_with_error.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/errorstateplugins/spin_ai_with_error \ No newline at end of file diff --git a/examples/statemachine/statemachine.pro b/examples/statemachine/statemachine.pro index ea3e7a8..5074a3c 100644 --- a/examples/statemachine/statemachine.pro +++ b/examples/statemachine/statemachine.pro @@ -4,7 +4,9 @@ SUBDIRS = \ factorial \ pingpong \ trafficlight \ - twowaybutton + twowaybutton \ + tankgame \ + tankgameplugins # install target.path = $$[QT_INSTALL_EXAMPLES]/statemachine diff --git a/examples/statemachine/tankgame/gameitem.cpp b/examples/statemachine/tankgame/gameitem.cpp new file mode 100644 index 0000000..1a2af71 --- /dev/null +++ b/examples/statemachine/tankgame/gameitem.cpp @@ -0,0 +1,88 @@ +#include "gameitem.h" + +#include +#include + +GameItem::GameItem(QObject *parent) : QObject(parent) +{ +} + +QPointF GameItem::tryMove(const QPointF &requestedPosition, QLineF *collidedLine, + QGraphicsItem **collidedItem) const +{ + QLineF movementPath(pos(), requestedPosition); + + qreal cannonLength = 0.0; + { + QPointF p1 = boundingRect().center(); + QPointF p2 = QPointF(boundingRect().right() + 10.0, p1.y()); + + cannonLength = QLineF(mapToScene(p1), mapToScene(p2)).length(); + } + + movementPath.setLength(movementPath.length() + cannonLength); + + QRectF boundingRectPath(QPointF(qMin(movementPath.x1(), movementPath.x2()), qMin(movementPath.y1(), movementPath.y2())), + QPointF(qMax(movementPath.x1(), movementPath.x2()), qMax(movementPath.y1(), movementPath.y2()))); + + QList itemsInRect = scene()->items(boundingRectPath, Qt::IntersectsItemBoundingRect); + + QPointF nextPoint = requestedPosition; + QRectF sceneRect = scene()->sceneRect(); + + foreach (QGraphicsItem *item, itemsInRect) { + if (item == static_cast(this)) + continue; + + QPolygonF mappedBoundingRect = item->mapToScene(item->boundingRect()); + for (int i=0; isceneRect().topLeft(), scene()->sceneRect().bottomLeft()); + } + + if (nextPoint.x() > sceneRect.right()) { + nextPoint.rx() = sceneRect.right(); + if (collidedLine != 0) + *collidedLine = QLineF(scene()->sceneRect().topRight(), scene()->sceneRect().bottomRight()); + } + + if (nextPoint.y() < sceneRect.top()) { + nextPoint.ry() = sceneRect.top(); + if (collidedLine != 0) + *collidedLine = QLineF(scene()->sceneRect().topLeft(), scene()->sceneRect().topRight()); + } + + if (nextPoint.y() > sceneRect.bottom()) { + nextPoint.ry() = sceneRect.bottom(); + if (collidedLine != 0) + *collidedLine = QLineF(scene()->sceneRect().bottomLeft(), scene()->sceneRect().bottomRight()); + } + + return nextPoint; +} + diff --git a/examples/statemachine/tankgame/gameitem.h b/examples/statemachine/tankgame/gameitem.h new file mode 100644 index 0000000..43b8785 --- /dev/null +++ b/examples/statemachine/tankgame/gameitem.h @@ -0,0 +1,23 @@ +#ifndef GAMEITEM_H +#define GAMEITEM_H + +#include + +class QLineF; +class GameItem: public QObject, public QGraphicsItem +{ + Q_OBJECT +public: + enum { Type = UserType + 1 }; + int type() const { return Type; } + + GameItem(QObject *parent = 0); + + virtual void idle(qreal elapsed) = 0; + +protected: + QPointF tryMove(const QPointF &requestedPosition, QLineF *collidedLine = 0, + QGraphicsItem **collidedItem = 0) const; +}; + +#endif diff --git a/examples/statemachine/tankgame/main.cpp b/examples/statemachine/tankgame/main.cpp new file mode 100644 index 0000000..26fc1bb --- /dev/null +++ b/examples/statemachine/tankgame/main.cpp @@ -0,0 +1,12 @@ +#include +#include "mainwindow.h" + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + MainWindow mainWindow; + mainWindow.show(); + + return app.exec(); +} diff --git a/examples/statemachine/tankgame/mainwindow.cpp b/examples/statemachine/tankgame/mainwindow.cpp new file mode 100644 index 0000000..3bc9bbe --- /dev/null +++ b/examples/statemachine/tankgame/mainwindow.cpp @@ -0,0 +1,264 @@ +#include "mainwindow.h" +#include "tankitem.h" +#include "rocketitem.h" +#include "plugin.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), m_scene(0), m_machine(0), m_runningState(0), m_started(false) +{ + init(); +} + +MainWindow::~MainWindow() +{ +} + +void MainWindow::addWall(const QRectF &wall) +{ + QGraphicsRectItem *item = new QGraphicsRectItem; + item->setRect(wall); + item->setBrush(Qt::darkGreen); + item->setPen(QPen(Qt::black, 0)); + + m_scene->addItem(item); +} + +void MainWindow::init() +{ + setWindowTitle("Pluggable Tank Game"); + + QGraphicsView *view = new QGraphicsView(this); + view->setRenderHints(QPainter::Antialiasing); + setCentralWidget(view); + + m_scene = new QGraphicsScene(this); + view->setScene(m_scene); + + QRectF sceneRect = QRectF(-200.0, -200.0, 400.0, 400.0); + m_scene->setSceneRect(sceneRect); + + { + TankItem *item = new TankItem(this); + + item->setPos(m_scene->sceneRect().topLeft() + QPointF(15.0, 15.0)); + item->setDirection(45.0); + item->setColor(Qt::red); + + m_spawns.append(item); + } + + { + TankItem *item = new TankItem(this); + + item->setPos(m_scene->sceneRect().topRight() + QPointF(-15.0, 15.0)); + item->setDirection(135.0); + item->setColor(Qt::green); + + m_spawns.append(item); + } + + { + TankItem *item = new TankItem(this); + + item->setPos(m_scene->sceneRect().bottomRight() + QPointF(-15.0, -15.0)); + item->setDirection(225.0); + item->setColor(Qt::blue); + + m_spawns.append(item); + } + + { + TankItem *item = new TankItem(this); + + item->setPos(m_scene->sceneRect().bottomLeft() + QPointF(15.0, -15.0)); + item->setDirection(315.0); + item->setColor(Qt::yellow); + + m_spawns.append(item); + } + + QPointF centerOfMap = sceneRect.center(); + + addWall(QRectF(centerOfMap + QPointF(-50.0, -60.0), centerOfMap + QPointF(50.0, -50.0))); + addWall(QRectF(centerOfMap - QPointF(-50.0, -60.0), centerOfMap - QPointF(50.0, -50.0))); + addWall(QRectF(centerOfMap + QPointF(-50.0, -50.0), centerOfMap + QPointF(-40.0, 50.0))); + addWall(QRectF(centerOfMap - QPointF(-50.0, -50.0), centerOfMap - QPointF(-40.0, 50.0))); + + addWall(QRectF(sceneRect.topLeft() + QPointF(sceneRect.width() / 2.0 - 5.0, -10.0), + sceneRect.topLeft() + QPointF(sceneRect.width() / 2.0 + 5.0, 100.0))); + addWall(QRectF(sceneRect.bottomLeft() + QPointF(sceneRect.width() / 2.0 - 5.0, 10.0), + sceneRect.bottomLeft() + QPointF(sceneRect.width() / 2.0 + 5.0, -100.0))); + addWall(QRectF(sceneRect.topLeft() + QPointF(-10.0, sceneRect.height() / 2.0 - 5.0), + sceneRect.topLeft() + QPointF(100.0, sceneRect.height() / 2.0 + 5.0))); + addWall(QRectF(sceneRect.topRight() + QPointF(10.0, sceneRect.height() / 2.0 - 5.0), + sceneRect.topRight() + QPointF(-100.0, sceneRect.height() / 2.0 + 5.0))); + + + QAction *addTankAction = menuBar()->addAction("&Add tank"); + QAction *runGameAction = menuBar()->addAction("&Run game"); + runGameAction->setObjectName("runGameAction"); + QAction *stopGameAction = menuBar()->addAction("&Stop game"); + menuBar()->addSeparator(); + QAction *quitAction = menuBar()->addAction("&Quit"); + + connect(addTankAction, SIGNAL(triggered()), this, SLOT(addTank())); + connect(quitAction, SIGNAL(triggered()), this, SLOT(close())); + + m_machine = new QStateMachine(this); + QState *stoppedState = new QState(m_machine->rootState()); + stoppedState->setObjectName("stoppedState"); + stoppedState->assignProperty(runGameAction, "enabled", true); + stoppedState->assignProperty(stopGameAction, "enabled", false); + stoppedState->assignProperty(this, "started", false); + m_machine->setInitialState(stoppedState); + + QState *spawnsAvailable = new QState(stoppedState); + spawnsAvailable->setObjectName("spawnsAvailable"); + spawnsAvailable->assignProperty(addTankAction, "enabled", true); + + QState *noSpawnsAvailable = new QState(stoppedState); + noSpawnsAvailable->setObjectName("noSpawnsAvailable"); + noSpawnsAvailable->assignProperty(addTankAction, "enabled", false); + + spawnsAvailable->addTransition(this, SIGNAL(mapFull()), noSpawnsAvailable); + + QHistoryState *hs = new QHistoryState(stoppedState); + hs->setDefaultState(spawnsAvailable); + + stoppedState->setInitialState(hs); + +//! [0] + m_runningState = new QState(QState::ParallelStates, m_machine->rootState()); +//! [0] + m_runningState->setObjectName("runningState"); + m_runningState->assignProperty(addTankAction, "enabled", false); + m_runningState->assignProperty(runGameAction, "enabled", false); + m_runningState->assignProperty(stopGameAction, "enabled", true); + + stoppedState->addTransition(runGameAction, SIGNAL(triggered()), m_runningState); + m_runningState->addTransition(stopGameAction, SIGNAL(triggered()), stoppedState); + + QTimer *timer = new QTimer(this); + timer->setInterval(100); + connect(timer, SIGNAL(timeout()), this, SLOT(runStep())); + connect(m_runningState, SIGNAL(entered()), timer, SLOT(start())); + connect(m_runningState, SIGNAL(exited()), timer, SLOT(stop())); + + m_machine->start(); + m_time.start(); +} + +void MainWindow::runStep() +{ + if (!m_started) { + m_time.restart(); + m_started = true; + } else { + int elapsed = m_time.elapsed(); + if (elapsed > 0) { + m_time.restart(); + qreal elapsedSecs = elapsed / 1000.0; + QList items = m_scene->items(); + foreach (QGraphicsItem *item, items) { + if (GameItem *gameItem = qgraphicsitem_cast(item)) + gameItem->idle(elapsedSecs); + } + } + } +} + +void MainWindow::addRocket() +{ + TankItem *tankItem = qobject_cast(sender()); + if (tankItem != 0) { + RocketItem *rocketItem = new RocketItem; + + QPointF s = tankItem->mapToScene(QPointF(tankItem->boundingRect().right() + 10.0, + tankItem->boundingRect().center().y())); + rocketItem->setPos(s); + rocketItem->setDirection(tankItem->direction()); + m_scene->addItem(rocketItem); + } +} + +void MainWindow::addTank() +{ + Q_ASSERT(!m_spawns.isEmpty()); + + QDir pluginsDir(qApp->applicationDirPath()); +#if defined(Q_OS_WIN) + if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") + pluginsDir.cdUp(); +#elif defined(Q_OS_MAC) + if (pluginsDir.dirName() == "MacOS") { + pluginsDir.cdUp(); + pluginsDir.cdUp(); + pluginsDir.cdUp(); + } +#endif + + pluginsDir.cd("plugins"); + + QStringList itemNames; + QList items; + foreach (QString fileName, pluginsDir.entryList(QDir::Files)) { + QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); + QObject *possiblePlugin = loader.instance(); + if (Plugin *plugin = qobject_cast(possiblePlugin)) { + QString objectName = possiblePlugin->objectName(); + if (objectName.isEmpty()) + objectName = fileName; + + itemNames.append(objectName); + items.append(plugin); + } + } + + if (items.isEmpty()) { + QMessageBox::information(this, "No tank types found", "Please build the errorstateplugins directory"); + return; + } + + bool ok; +//! [1] + QString selectedName = QInputDialog::getItem(this, "Select a tank type", "Tank types", + itemNames, 0, false, &ok); +//! [1] + + if (ok && !selectedName.isEmpty()) { + int idx = itemNames.indexOf(selectedName); + if (Plugin *plugin = idx >= 0 ? items.at(idx) : 0) { + TankItem *tankItem = m_spawns.takeLast(); + m_scene->addItem(tankItem); + connect(tankItem, SIGNAL(cannonFired()), this, SLOT(addRocket())); + if (m_spawns.isEmpty()) + emit mapFull(); + + QState *region = new QState(m_runningState); +//! [2] + QState *pluginState = plugin->create(region, tankItem); +//! [2] + region->setInitialState(pluginState); + + + // If the plugin has an error it is disabled + QState *errorState = new QState(region); + errorState->assignProperty(tankItem, "enabled", false); + pluginState->setErrorState(errorState); + } + } +} + diff --git a/examples/statemachine/tankgame/mainwindow.h b/examples/statemachine/tankgame/mainwindow.h new file mode 100644 index 0000000..622dabe --- /dev/null +++ b/examples/statemachine/tankgame/mainwindow.h @@ -0,0 +1,46 @@ +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include + +class QGraphicsScene; +class QStateMachine; +class QState; +class TankItem; +class MainWindow: public QMainWindow +{ + Q_OBJECT + Q_PROPERTY(bool started READ started WRITE setStarted) +public: + MainWindow(QWidget *parent = 0); + ~MainWindow(); + + void setStarted(bool b) { m_started = b; } + bool started() const { return m_started; } + +public slots: + void addTank(); + void addRocket(); + void runStep(); + +signals: + void mapFull(); + +private: + void init(); + void addWall(const QRectF &wall); + + QGraphicsScene *m_scene; + + QStateMachine *m_machine; + QState *m_runningState; + + QList m_spawns; + QTime m_time; + + bool m_started : 1; +}; + +#endif + diff --git a/examples/statemachine/tankgame/plugin.h b/examples/statemachine/tankgame/plugin.h new file mode 100644 index 0000000..2b48d43 --- /dev/null +++ b/examples/statemachine/tankgame/plugin.h @@ -0,0 +1,17 @@ +#ifndef PLUGIN_H +#define PLUGIN_H + +#include + +class QState; +class Plugin +{ +public: + virtual ~Plugin() {} + + virtual QState *create(QState *parentState, QObject *tank) = 0; +}; + +Q_DECLARE_INTERFACE(Plugin, "TankPlugin") + +#endif diff --git a/examples/statemachine/tankgame/rocketitem.cpp b/examples/statemachine/tankgame/rocketitem.cpp new file mode 100644 index 0000000..c324980 --- /dev/null +++ b/examples/statemachine/tankgame/rocketitem.cpp @@ -0,0 +1,60 @@ +#include "rocketitem.h" +#include "tankitem.h" + +#include +#include + +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +RocketItem::RocketItem(QObject *parent) + : GameItem(parent), m_direction(0.0), m_distance(300.0) +{ +} + +QRectF RocketItem::boundingRect() const +{ + return QRectF(-1.0, -1.0, 2.0, 2.0); +} + +void RocketItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + painter->setBrush(Qt::black); + painter->drawEllipse(boundingRect()); +} + +void RocketItem::idle(qreal elapsed) +{ + qreal dist = elapsed * speed(); + + m_distance -= dist; + if (m_distance < 0.0) { + scene()->removeItem(this); + delete this; + return; + } + + qreal a = m_direction * M_PI / 180.0; + + qreal yd = dist * sin(a); + qreal xd = dist * sin(M_PI / 2.0 - a); + + QPointF requestedPosition = pos() + QPointF(xd, yd); + QGraphicsItem *collidedItem = 0; + QPointF nextPosition = tryMove(requestedPosition, 0, &collidedItem); + if (requestedPosition == nextPosition) { + setPos(nextPosition); + } else { + if (GameItem *gameItem = qgraphicsitem_cast(collidedItem)) { + TankItem *tankItem = qobject_cast(gameItem); + if (tankItem != 0) + tankItem->hitByRocket(); + } + + scene()->removeItem(this); + delete this; + } +} diff --git a/examples/statemachine/tankgame/rocketitem.h b/examples/statemachine/tankgame/rocketitem.h new file mode 100644 index 0000000..189a1dd --- /dev/null +++ b/examples/statemachine/tankgame/rocketitem.h @@ -0,0 +1,26 @@ +#ifndef ROCKETITEM_H +#define ROCKETITEM_H + +#include "gameitem.h" + +class RocketItem: public GameItem +{ + Q_OBJECT +public: + RocketItem(QObject *parent = 0); + + virtual void idle(qreal elapsed); + qreal speed() const { return 100.0; } + void setDirection(qreal direction) { m_direction = direction; } + +protected: + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + QRectF boundingRect() const; + +private: + qreal m_direction; + qreal m_distance; +}; + + +#endif diff --git a/examples/statemachine/tankgame/tankgame.pro b/examples/statemachine/tankgame/tankgame.pro new file mode 100644 index 0000000..f7b0760 --- /dev/null +++ b/examples/statemachine/tankgame/tankgame.pro @@ -0,0 +1,13 @@ +###################################################################### +# Automatically generated by qmake (2.01a) on 22. apr 14:11:33 2009 +###################################################################### + +TEMPLATE = app +TARGET = +DEPENDPATH += . +INCLUDEPATH += C:/dev/kinetic/examples/statemachine/tankgame/. . + +# Input +HEADERS += mainwindow.h plugin.h tankitem.h rocketitem.h gameitem.h +SOURCES += main.cpp mainwindow.cpp tankitem.cpp rocketitem.cpp gameitem.cpp +CONFIG += console diff --git a/examples/statemachine/tankgame/tankitem.cpp b/examples/statemachine/tankgame/tankitem.cpp new file mode 100644 index 0000000..5506a7e --- /dev/null +++ b/examples/statemachine/tankgame/tankitem.cpp @@ -0,0 +1,262 @@ +#include "tankitem.h" + +#include +#include +#include + +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +class Action +{ +public: + Action(TankItem *item) : m_item(item) + { + } + + TankItem *item() const { return m_item; } + void setItem(TankItem *item) { m_item = item; } + + virtual bool apply(qreal timeDelta) = 0; + +private: + TankItem *m_item; +}; + +class MoveAction: public Action +{ +public: + MoveAction(TankItem *item, qreal distance) + : Action(item), m_distance(distance) + { + m_reverse = m_distance < 0.0; + } + + bool apply(qreal timeDelta) + { + qreal dist = timeDelta * item()->speed() * (m_reverse ? -1.0 : 1.0); + + bool done = false; + if (qAbs(m_distance) < qAbs(dist)) { + done = true; + dist = m_distance; + } + m_distance -= dist; + + qreal a = item()->direction() * M_PI / 180.0; + + qreal yd = dist * sin(a); + qreal xd = dist * sin(M_PI / 2.0 - a); + + item()->setPos(item()->pos() + QPointF(xd, yd)); + return !done; + } + +private: + qreal m_distance; + bool m_reverse; +}; + +class TurnAction: public Action +{ +public: + TurnAction(TankItem *item, qreal distance) + : Action(item), m_distance(distance) + { + m_reverse = m_distance < 0.0; + } + + bool apply(qreal timeDelta) + { + qreal dist = timeDelta * item()->angularSpeed() * (m_reverse ? -1.0 : 1.0); + bool done = false; + if (qAbs(m_distance) < qAbs(dist)) { + done = true; + dist = m_distance; + } + m_distance -= dist; + + item()->setDirection(item()->direction() + dist); + return !done; + } + +private: + qreal m_distance; + bool m_reverse; +}; + +TankItem::TankItem(QObject *parent) + : GameItem(parent), m_currentAction(0), m_currentDirection(0.0), m_enabled(true) +{ + connect(this, SIGNAL(cannonFired()), this, SIGNAL(actionCompleted())); +} + +void TankItem::idle(qreal elapsed) +{ + if (m_enabled) { + if (m_currentAction != 0) { + if (!m_currentAction->apply(elapsed)) { + setAction(0); + emit actionCompleted(); + } + + QGraphicsItem *item = 0; + qreal distance = distanceToObstacle(&item); + if (TankItem *tankItem = qgraphicsitem_cast(item)) + emit tankSpotted(tankItem->direction(), distance); + } + } +} + +void TankItem::hitByRocket() +{ + deleteLater(); +} + +void TankItem::setAction(Action *newAction) +{ + if (m_currentAction != 0) + delete m_currentAction; + + m_currentAction = newAction; +} + +void TankItem::fireCannon() +{ + emit cannonFired(); +} + +void TankItem::moveForwards(qreal length) +{ + setAction(new MoveAction(this, length)); +} + +void TankItem::moveBackwards(qreal length) +{ + setAction(new MoveAction(this, -length)); +} + +void TankItem::turn(qreal degrees) +{ + setAction(new TurnAction(this, degrees)); +} + +void TankItem::turnTo(qreal degrees) +{ + setAction(new TurnAction(this, degrees - direction())); +} + +void TankItem::stop() +{ + setAction(0); +} + +QVariant TankItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) +{ + if (change == ItemPositionChange && scene()) { + QPointF requestedPosition = value.toPointF(); + QLineF collidedLine; + QPointF nextPoint = tryMove(requestedPosition, &collidedLine); + if (nextPoint != requestedPosition) + emit collision(collidedLine); + return nextPoint; + } else { + return QGraphicsItem::itemChange(change, value); + } +} + + +void TankItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + QRectF brect = boundingRect(); + + painter->setBrush(m_color); + painter->setPen(Qt::black); + + // body + painter->drawRect(brect.adjusted(0.0, 4.0, -2.0, -4.0)); + + // cannon + QRectF cannonBase = brect.adjusted(10.0, 6.0, -12.0, -6.0); + painter->drawEllipse(cannonBase); + + painter->drawRect(QRectF(QPointF(cannonBase.center().x(), cannonBase.center().y() - 2.0), + QPointF(brect.right(), cannonBase.center().y() + 2.0))); + + // left track + painter->setBrush(QBrush(Qt::black, Qt::VerPattern)); + QRectF leftTrackRect = QRectF(brect.topLeft(), QPointF(brect.right() - 2.0, brect.top() + 4.0)); + painter->fillRect(leftTrackRect, Qt::darkYellow); + painter->drawRect(leftTrackRect); + + // right track + QRectF rightTrackRect = QRectF(QPointF(brect.left(), brect.bottom() - 4.0), + QPointF(brect.right() - 2.0, brect.bottom())); + painter->fillRect(rightTrackRect, Qt::darkYellow); + painter->drawRect(rightTrackRect); + + if (!m_enabled) { + painter->setPen(QPen(Qt::red, 5)); + + painter->drawEllipse(brect); + + QPainterPath path; + path.addEllipse(brect); + painter->setClipPath(path); + painter->drawLine(brect.topRight(), brect.bottomLeft()); + } +} + +QRectF TankItem::boundingRect() const +{ + return QRectF(-20.0, -10.0, 40.0, 20.0); +} + +qreal TankItem::direction() const +{ + return m_currentDirection; +} + +void TankItem::setDirection(qreal newDirection) +{ + int fullRotations = int(newDirection) / 360; + newDirection -= fullRotations * 360.0; + + qreal diff = newDirection - m_currentDirection; + m_currentDirection = newDirection; + rotate(diff); +} + +qreal TankItem::distanceToObstacle(QGraphicsItem **obstacle) const +{ + qreal dist = sqrt(pow(scene()->sceneRect().width(), 2) + pow(scene()->sceneRect().height(), 2)); + + qreal a = m_currentDirection * M_PI / 180.0; + + qreal yd = dist * sin(a); + qreal xd = dist * sin(M_PI / 2.0 - a); + + QPointF requestedPosition = pos() + QPointF(xd, yd); + QGraphicsItem *collidedItem = 0; + QPointF nextPosition = tryMove(requestedPosition, 0, &collidedItem); + if (collidedItem != 0) { + if (obstacle != 0) + *obstacle = collidedItem; + + QPointF d = nextPosition - pos(); + return sqrt(pow(d.x(), 2) + pow(d.y(), 2)); + } else { + return 0.0; + } +} + +qreal TankItem::distanceToObstacle() const +{ + return distanceToObstacle(0); +} + + + diff --git a/examples/statemachine/tankgame/tankitem.h b/examples/statemachine/tankgame/tankitem.h new file mode 100644 index 0000000..66f05aa --- /dev/null +++ b/examples/statemachine/tankgame/tankitem.h @@ -0,0 +1,67 @@ +#ifndef TANKITEM_H +#define TANKITEM_H + +#include "gameitem.h" + +#include + +class Action; +class TankItem: public GameItem +{ + Q_OBJECT + Q_PROPERTY(bool enabled READ enabled WRITE setEnabled) + Q_PROPERTY(qreal direction READ direction WRITE turnTo) + Q_PROPERTY(qreal distanceToObstacle READ distanceToObstacle) +public: + TankItem(QObject *parent = 0); + + void setColor(const QColor &color) { m_color = color; } + QColor color() const { return m_color; } + + void idle(qreal elapsed); + void setDirection(qreal newDirection); + + qreal speed() const { return 90.0; } + qreal angularSpeed() const { return 90.0; } + + QRectF boundingRect() const; + + void hitByRocket(); + + void setEnabled(bool b) { m_enabled = b; } + bool enabled() const { return m_enabled; } + + qreal direction() const; + qreal distanceToObstacle() const; + qreal distanceToObstacle(QGraphicsItem **item) const; + +//! [0] +signals: + void tankSpotted(qreal direction, qreal distance); + void collision(const QLineF &collidedLine); + void actionCompleted(); + void cannonFired(); + +public slots: + void moveForwards(qreal length = 10.0); + void moveBackwards(qreal length = 10.0); + void turn(qreal degrees = 30.0); + void turnTo(qreal degrees = 0.0); + void stop(); + void fireCannon(); +//! [0] + +protected: + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value); + +private: + void setAction(Action *newAction); + + Action *m_currentAction; + qreal m_currentDirection; + QColor m_color; + bool m_enabled; +}; + +#endif diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai.pro b/examples/statemachine/tankgameplugins/random_ai/random_ai.pro new file mode 100644 index 0000000..5bc0b26 --- /dev/null +++ b/examples/statemachine/tankgameplugins/random_ai/random_ai.pro @@ -0,0 +1,13 @@ +TEMPLATE = lib +CONFIG += plugin +INCLUDEPATH += ../.. +HEADERS = random_ai_plugin.h +SOURCES = random_ai_plugin.cpp +TARGET = $$qtLibraryTarget(random_ai) +DESTDIR = ../../tankgame/plugins + +#! [0] +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS random_ai.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/random_ai \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp new file mode 100644 index 0000000..c196247 --- /dev/null +++ b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp @@ -0,0 +1,38 @@ +#include "random_ai_plugin.h" + +#include +#include + +#include + +QState *RandomAiPlugin::create(QState *parentState, QObject *tank) +{ + qsrand(uint(time(NULL))); + + QState *topLevel = new QState(parentState); + + QState *selectNextActionState = new SelectActionState(topLevel); + topLevel->setInitialState(selectNextActionState); + + QState *fireState = new RandomDistanceState(topLevel); + connect(fireState, SIGNAL(distanceComputed(qreal)), tank, SLOT(fireCannon())); + selectNextActionState->addTransition(selectNextActionState, SIGNAL(fireSelected()), fireState); + + QState *moveForwardsState = new RandomDistanceState(topLevel); + connect(moveForwardsState, SIGNAL(distanceComputed(qreal)), tank, SLOT(moveForwards(qreal))); + selectNextActionState->addTransition(selectNextActionState, SIGNAL(moveForwardsSelected()), moveForwardsState); + + QState *moveBackwardsState = new RandomDistanceState(topLevel); + connect(moveBackwardsState, SIGNAL(distanceComputed(qreal)), tank, SLOT(moveBackwards(qreal))); + selectNextActionState->addTransition(selectNextActionState, SIGNAL(moveBackwardsSelected()), moveBackwardsState); + + QState *turnState = new RandomDistanceState(topLevel); + connect(turnState, SIGNAL(distanceComputed(qreal)), tank, SLOT(turn(qreal))); + selectNextActionState->addTransition(selectNextActionState, SIGNAL(turnSelected()), turnState); + + topLevel->addTransition(tank, SIGNAL(actionCompleted()), selectNextActionState); + + return topLevel; +} + +Q_EXPORT_PLUGIN2(random_ai, RandomAiPlugin) diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h new file mode 100644 index 0000000..f5e3b6f --- /dev/null +++ b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h @@ -0,0 +1,64 @@ +#ifndef RANDOM_AI_PLUGIN_H +#define RANDOM_AI_PLUGIN_H + +#include +#include + +#include + +class SelectActionState: public QState +{ + Q_OBJECT +public: + SelectActionState(QState *parent = 0) : QState(parent) + { + } + +signals: + void fireSelected(); + void moveForwardsSelected(); + void moveBackwardsSelected(); + void turnSelected(); + +protected: + void onEntry(QEvent *) + { + int rand = qrand() % 4; + switch (rand) { + case 0: emit fireSelected(); break; + case 1: emit moveForwardsSelected(); break; + case 2: emit moveBackwardsSelected(); break; + case 3: emit turnSelected(); break; + }; + } +}; + +class RandomDistanceState: public QState +{ + Q_OBJECT +public: + RandomDistanceState(QState *parent = 0) : QState(parent) + { + } + +signals: + void distanceComputed(qreal distance); + +protected: + void onEntry(QEvent *) + { + emit distanceComputed(qreal(qrand() % 180)); + } +}; + +class RandomAiPlugin: public QObject, public Plugin +{ + Q_OBJECT + Q_INTERFACES(Plugin) +public: + RandomAiPlugin() { setObjectName("Random"); } + + virtual QState *create(QState *parentState, QObject *tank); +}; + +#endif // RANDOM_AI_PLUGIN_H diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp new file mode 100644 index 0000000..2fb05d4 --- /dev/null +++ b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp @@ -0,0 +1,48 @@ +#include "seek_ai.h" + +QState *SeekAi::create(QState *parentState, QObject *tank) +{ + QState *topLevel = new QState(parentState); + topLevel->setObjectName("topLevel"); + + QState *seek = new QState(topLevel); + seek->setObjectName("seek"); + topLevel->setInitialState(seek); + + QState *lookForNearestWall = new SearchState(tank, seek); + lookForNearestWall->setObjectName("lookForNearestWall"); + seek->setInitialState(lookForNearestWall); + + QState *driveToFirstObstacle = new QState(seek); + driveToFirstObstacle->setObjectName("driveToFirstObstacle"); + lookForNearestWall->addTransition(lookForNearestWall, SIGNAL(nearestObstacleStraightAhead()), + driveToFirstObstacle); + + QState *drive = new QState(driveToFirstObstacle); + drive->setObjectName("drive"); + driveToFirstObstacle->setInitialState(drive); + connect(drive, SIGNAL(entered()), tank, SLOT(moveForwards())); + connect(drive, SIGNAL(exited()), tank, SLOT(stop())); + + // Go in loop + QState *finishedDriving = new QState(driveToFirstObstacle); + finishedDriving->setObjectName("finishedDriving"); + drive->addTransition(tank, SIGNAL(actionCompleted()), finishedDriving); + finishedDriving->addTransition(drive); + + QState *turnTo = new QState(seek); + turnTo->setObjectName("turnTo"); + driveToFirstObstacle->addTransition(new CollisionTransition(tank, turnTo)); + + turnTo->addTransition(tank, SIGNAL(actionCompleted()), driveToFirstObstacle); + + ChaseState *chase = new ChaseState(tank, topLevel); + chase->setObjectName("chase"); + seek->addTransition(new TankSpottedTransition(tank, chase)); + chase->addTransition(chase, SIGNAL(finished()), driveToFirstObstacle); + chase->addTransition(new TankSpottedTransition(tank, chase)); + + return topLevel; +} + +Q_EXPORT_PLUGIN2(seek_ai, SeekAi) diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h new file mode 100644 index 0000000..2835988 --- /dev/null +++ b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h @@ -0,0 +1,204 @@ +#ifndef SEEK_AI_H +#define SEEK_AI_H + +#include + +#include +#include +#include +#include +#include +#include +#include + +class SearchState: public QState +{ + Q_OBJECT +public: + SearchState(QObject *tank, QState *parentState = 0) + : QState(parentState), + m_tank(tank), + m_distanceToTurn(360.0), + m_nearestDistance(-1.0), + m_directionOfNearestObstacle(0.0) + { + } + +public slots: + void turnAlittle() + { + qreal dist = m_tank->property("distanceToObstacle").toDouble(); + + if (m_nearestDistance < 0.0 || dist < m_nearestDistance) { + m_nearestDistance = dist; + m_directionOfNearestObstacle = m_tank->property("direction").toDouble(); + } + + m_distanceToTurn -= 10.0; + if (m_distanceToTurn < 0.0) { + disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); + connect(m_tank, SIGNAL(actionCompleted()), this, SIGNAL(nearestObstacleStraightAhead())); + m_tank->setProperty("direction", m_directionOfNearestObstacle); + } + + qreal currentDirection = m_tank->property("direction").toDouble(); + m_tank->setProperty("direction", currentDirection + 10.0); + } + +signals: + void nearestObstacleStraightAhead(); + +protected: + void onEntry(QEvent *) + { + connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); + turnAlittle(); + } + + void onExit(QEvent *) + { + disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); + disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(nearestObstacleStraightAhead())); + } + +private: + QObject *m_tank; + + qreal m_distanceToTurn; + qreal m_nearestDistance; + qreal m_directionOfNearestObstacle; +}; + +class CollisionTransition: public QSignalTransition +{ +public: + CollisionTransition(QObject *tank, QState *turnTo) + : QSignalTransition(tank, SIGNAL(collision(QLineF))), + m_tank(tank), + m_turnTo(turnTo) + { + setTargetState(turnTo); + } + +protected: + bool eventTest(QEvent *event) const + { + bool b = QSignalTransition::eventTest(event); + if (b) { + QSignalEvent *se = static_cast(event); + m_lastLine = se->arguments().at(0).toLineF(); + } + return b; + } + + void onTransition(QEvent *) + { + qreal angleOfWall = m_lastLine.angle(); + + qreal newDirection; + if (qrand() % 2 == 0) + newDirection = angleOfWall; + else + newDirection = angleOfWall - 180.0; + + m_turnTo->assignProperty(m_tank, "direction", newDirection); + } + +private: + mutable QLineF m_lastLine; + QObject *m_tank; + QState *m_turnTo; +}; + +class ChaseState: public QState +{ + class GoToLocationState: public QState + { + public: + GoToLocationState(QObject *tank, QState *parentState = 0) + : QState(parentState), m_tank(tank), m_distance(0.0) + { + } + + void setDistance(qreal distance) { m_distance = distance; } + + protected: + void onEntry() + { + QMetaObject::invokeMethod(m_tank, "moveForwards", Q_ARG(qreal, m_distance)); + } + + private: + QObject *m_tank; + qreal m_distance; + }; + +public: + ChaseState(QObject *tank, QState *parentState = 0) : QState(parentState), m_tank(tank) + { + QState *fireCannon = new QState(this); + connect(fireCannon, SIGNAL(entered()), tank, SLOT(fireCannon())); + setInitialState(fireCannon); + + m_goToLocation = new GoToLocationState(this); + fireCannon->addTransition(tank, SIGNAL(actionCompleted()), m_goToLocation); + + m_turnToDirection = new QState(this); + m_goToLocation->addTransition(tank, SIGNAL(actionCompleted()), m_turnToDirection); + + QFinalState *finalState = new QFinalState(this); + m_turnToDirection->addTransition(tank, SIGNAL(actionCompleted()), finalState); + } + + void setDirection(qreal direction) + { + m_turnToDirection->assignProperty(m_tank, "direction", direction); + } + + void setDistance(qreal distance) + { + m_goToLocation->setDistance(distance); + } + +private: + QObject *m_tank; + GoToLocationState *m_goToLocation; + QState *m_turnToDirection; + +}; + +class TankSpottedTransition: public QSignalTransition +{ +public: + TankSpottedTransition(QObject *tank, ChaseState *target) : QSignalTransition(tank, SIGNAL(tankSpotted(qreal,qreal))), m_chase(target) + { + setTargetState(target); + } + +protected: + bool eventTest(QEvent *event) const + { + bool b = QSignalTransition::eventTest(event); + if (b) { + QSignalEvent *se = static_cast(event); + m_chase->setDirection(se->arguments().at(0).toDouble()); + m_chase->setDistance(se->arguments().at(1).toDouble()); + } + return b; + } + +private: + ChaseState *m_chase; +}; + +class SeekAi: public QObject, public Plugin +{ + Q_OBJECT + Q_INTERFACES(Plugin) +public: + SeekAi() { setObjectName("Seek and destroy"); } + + virtual QState *create(QState *parentState, QObject *tank); +}; + +#endif diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro new file mode 100644 index 0000000..0d8bf2e --- /dev/null +++ b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro @@ -0,0 +1,13 @@ +TEMPLATE = lib +CONFIG += plugin +INCLUDEPATH += ../.. +HEADERS = seek_ai.h +SOURCES = seek_ai.cpp +TARGET = $$qtLibraryTarget(seek_ai) +DESTDIR = ../../tankgame/plugins + +#! [0] +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS seek_ai.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/seek_ai \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp new file mode 100644 index 0000000..de95f41 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp @@ -0,0 +1,29 @@ +#include "spin_ai.h" + +#include + +QState *SpinAi::create(QState *parentState, QObject *tank) +{ + QState *topLevel = new QState(parentState); + QState *spinState = new SpinState(tank, topLevel); + topLevel->setInitialState(spinState); + + // When tank is spotted, fire two times and go back to spin state + QState *fireState = new QState(topLevel); + + QState *fireOnce = new QState(fireState); + fireState->setInitialState(fireOnce); + connect(fireOnce, SIGNAL(entered()), tank, SLOT(fireCannon())); + + QState *fireTwice = new QState(fireState); + connect(fireTwice, SIGNAL(entered()), tank, SLOT(fireCannon())); + + fireOnce->addTransition(tank, SIGNAL(actionCompleted()), fireTwice); + fireTwice->addTransition(tank, SIGNAL(actionCompleted()), spinState); + + spinState->addTransition(tank, SIGNAL(tankSpotted(qreal,qreal)), fireState); + + return topLevel; +} + +Q_EXPORT_PLUGIN2(spin_ai, SpinAi) diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h new file mode 100644 index 0000000..a331a3e --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h @@ -0,0 +1,46 @@ +#ifndef SPIN_AI_H +#define SPIN_AI_H + +#include + +#include +#include +#include + +class SpinState: public QState +{ + Q_OBJECT +public: + SpinState(QObject *tank, QState *parent) : QState(parent), m_tank(tank) + { + } + +public slots: + void spin() + { + m_tank->setProperty("direction", 90.0); + } + +protected: + void onEntry(QEvent *) + { + connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); + spin(); + } + +private: + QObject *m_tank; + +}; + +class SpinAi: public QObject, public Plugin +{ + Q_OBJECT + Q_INTERFACES(Plugin) +public: + SpinAi() { setObjectName("Spin and destroy"); } + + virtual QState *create(QState *parentState, QObject *tank); +}; + +#endif diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro new file mode 100644 index 0000000..8ab4da0 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro @@ -0,0 +1,13 @@ +TEMPLATE = lib +CONFIG += plugin +INCLUDEPATH += ../.. +HEADERS = spin_ai.h +SOURCES = spin_ai.cpp +TARGET = $$qtLibraryTarget(spin_ai) +DESTDIR = ../../tankgame/plugins + +#! [0] +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS spin_ai.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/spin_ai \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp new file mode 100644 index 0000000..5499ba3 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp @@ -0,0 +1,29 @@ +#include "spin_ai_with_error.h" + +#include + +QState *SpinAiWithError::create(QState *parentState, QObject *tank) +{ + QState *topLevel = new QState(parentState); + QState *spinState = new SpinState(tank, topLevel); + topLevel->setInitialState(spinState); + + // When tank is spotted, fire two times and go back to spin state + // (no initial state set for fireState will lead to run-time error in machine) + QState *fireState = new QState(topLevel); + + QState *fireOnce = new QState(fireState); + connect(fireOnce, SIGNAL(entered()), tank, SLOT(fireCannon())); + + QState *fireTwice = new QState(fireState); + connect(fireTwice, SIGNAL(entered()), tank, SLOT(fireCannon())); + + fireOnce->addTransition(tank, SIGNAL(actionCompleted()), fireTwice); + fireTwice->addTransition(tank, SIGNAL(actionCompleted()), spinState); + + spinState->addTransition(tank, SIGNAL(tankSpotted(qreal,qreal)), fireState); + + return topLevel; +} + +Q_EXPORT_PLUGIN2(spin_ai_with_error, SpinAiWithError) diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h new file mode 100644 index 0000000..5cfb364 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h @@ -0,0 +1,46 @@ +#ifndef SPIN_AI_WITH_ERROR_H +#define SPIN_AI_WITH_ERROR_H + +#include + +#include +#include +#include + +class SpinState: public QState +{ + Q_OBJECT +public: + SpinState(QObject *tank, QState *parent) : QState(parent), m_tank(tank) + { + } + +public slots: + void spin() + { + m_tank->setProperty("direction", 90.0); + } + +protected: + void onEntry(QEvent *) + { + connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); + spin(); + } + +private: + QObject *m_tank; + +}; + +class SpinAiWithError: public QObject, public Plugin +{ + Q_OBJECT + Q_INTERFACES(Plugin) +public: + SpinAiWithError() { setObjectName("Spin and destroy with runtime error in state machine"); } + + virtual QState *create(QState *parentState, QObject *tank); +}; + +#endif diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro new file mode 100644 index 0000000..124cf98 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro @@ -0,0 +1,13 @@ +TEMPLATE = lib +CONFIG += plugin +INCLUDEPATH += ../.. +HEADERS = spin_ai_with_error.h +SOURCES = spin_ai_with_error.cpp +TARGET = $$qtLibraryTarget(spin_ai_with_error) +DESTDIR = ../../tankgame/plugins + +#! [0] +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS spin_ai_with_error.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/spin_ai_with_error \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/tankgameplugins.pro b/examples/statemachine/tankgameplugins/tankgameplugins.pro new file mode 100644 index 0000000..a098e03 --- /dev/null +++ b/examples/statemachine/tankgameplugins/tankgameplugins.pro @@ -0,0 +1,11 @@ +TEMPLATE = subdirs +SUBDIRS = random_ai \ + spin_ai_with_error \ + spin_ai \ + seek_ai + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS tankgameplugins.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins +INSTALLS += target sources -- cgit v0.12