qt飞机大战小游戏代码
时间: 2023-08-01 19:13:32 浏览: 110
C++基于QT实现的飞机大战小游戏源码
以下是一个简单的Qt飞机大战小游戏的代码示例:
```cpp
#include <QApplication>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QTimer>
#include <QKeyEvent>
// 飞机类
class Player : public QGraphicsRectItem {
public:
void keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Left) {
setPos(x() - 10, y());
} else if (event->key() == Qt::Key_Right) {
setPos(x() + 10, y());
}
}
};
// 子弹类
class Bullet : public QObject, public QGraphicsRectItem {
Q_OBJECT
public:
Bullet() {
QTimer *timer = new QTimer();
connect(timer, SIGNAL(timeout()), this, SLOT(move()));
timer->start(50);
}
public slots:
void move() {
setPos(x(), y() - 10);
if (pos().y() < 0) {
scene()->removeItem(this);
delete this;
}
}
};
// 敌机类
class Enemy : public QObject, public QGraphicsRectItem {
Q_OBJECT
public:
Enemy() {
QTimer *timer = new QTimer();
connect(timer, SIGNAL(timeout()), this, SLOT(move()));
timer->start(50);
}
public slots:
void move() {
setPos(x(), y() + 10);
if (pos().y() > 600) {
scene()->removeItem(this);
delete this;
}
}
};
int main(int argc, char *argv[]) {
QApplication a(argc, argv);
// 创建场景和视图
QGraphicsScene scene;
QGraphicsView view(&scene);
view.setFixedSize(800, 600);
view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
view.show();
// 创建飞机并添加到场景中
Player player;
player.setRect(0, 0, 100, 100);
player.setPos(350, 500);
scene.addItem(&player);
player.setFlag(QGraphicsItem::ItemIsFocusable);
player.setFocus();
// 按键事件处理
QObject::connect(&player, SIGNAL(keyPressEvent(QKeyEvent*)), &player, SLOT(keyPressEvent(QKeyEvent*)));
// 创建敌机并添加到场景中
QTimer enemyTimer;
QObject::connect(&enemyTimer, SIGNAL(timeout()), [&]() {
Enemy *enemy = new Enemy();
enemy->setRect(0, 0, 100, 100);
enemy->setPos(qrand() % 700, 0);
scene.addItem(enemy);
});
enemyTimer.start(1000);
return a.exec();
}
#include "main.moc"
```
这只是一个简单的示例代码,实现了一个基本的飞机大战小游戏。你可以根据自己的需求进行进一步的修改和扩展。希望对你有所帮助!
阅读全文