用图形视图框架编写一个有趣的射击小游戏

发布时间:2024-06-23 18:51:26 浏览量:169次

要求:按空格键,玩家发射子弹,子弹(长条形)从玩家所在位置自行向上运动。敌人在顶部随机位置出现,向下运动。子弹和敌人碰撞时消失,子弹离开边界时自行消失。

用图形视图矿建编写的简单射击游戏

编程要点:

1. 类需使用connect函数,需要继承QObject类,头文件需包含<QObject>。

2. 利用定时器QTimer和connect槽函数实现子弹和敌人的自动运动。

3. 设置玩家的焦点特性,接受键盘事件,空格键发射子弹。

4. 重写键盘事件,使用光标键控制玩家移动,空格键发射子弹。

5. 视图窗体固定大小,防止场景扩大导致滚动。

6. 子弹和敌人碰撞时,删除并释放内存。

7. 子弹和敌人离开视图窗体边界时,删除节省内存。

这里给出子弹类的代码:

-----------------bullet.h------------------

#ifndef BULLET_H

#define BULLET_H

#include <QGraphicsRectItem>

#include <QObject>

class Bullet: public QObject, public QGraphicsRectItem

{

Q_OBJECT

public:

Bullet();

public slots:

void move();

};

#endif // BULLET_H

-----------------bullet.cpp------------------

#include "bullet.h"

#include "Enemy.h"

#include <QGraphicsRectItem>

#include <QTimer>

#include <QGraphicsItem>

#include <QObject>

#include <QGraphicsScene>

#include <QDebug>

#include <QList>

Bullet::Bullet()

{

setRect(0,0,10,50);

QTimer *timer = new QTimer();

connect(timer, SIGNAL(timeout()), this, SLOT(move()));

timer->start(20);

}

void Bullet::move() {

QList <QGraphicsItem*> colliding_items = collidingItems();

for(int i=0, n=colliding_items.size(); i<n; i++)

{

if(typeid(*(colliding_items[i])) == typeid(Enemy))

{

scene()->removeItem(colliding_items[i]);

scene()->removeItem(this);

delete colliding_items[i];

delete this;

return;

}

}

setPos(x(), y()-10);

if(this->pos().y() + this->rect().height() < 0)

{

scene()->removeItem(this);

delete this;

qDebug()<<"bullet deleted";

}

热门课程推荐

热门资讯

请绑定手机号

x

同学您好!

您已成功报名0元试学活动,老师会在第一时间与您取得联系,请保持电话畅通!
确定