1.推箱子小游戏
- QT./代表的当前目录位置
- 项目结构
- 效果图
- GameMap.h
#ifndef GAMEMAP_H
#define GAMEMAP_H
#include <QObject>
#include <QPainter>
enum MapElement
{
Road,
Wall,
Box,
Point,
InPoint
};
class GameMap : public QObject
{
Q_OBJECT
public:
explicit GameMap(QObject *parent = nullptr);
~GameMap();
bool InitByFile(QString fileName);
void Clear();
void Paint(QPainter* _p,QPoint _Pos);
int mRow;
int mCol;
int** mPArr;
signals:
public slots:
};
#endif
#include "GameMap.h"
#include <QFile>
#include <QDebug>
GameMap::GameMap(QObject *parent) : QObject(parent)
{
mRow = 0;
mCol = 0;
mPArr = nullptr;
}
GameMap::~GameMap()
{
Clear();
}
void GameMap::Clear()
{
if(mPArr != nullptr)
{
for(int i = 0;i < mRow;i++)
{
delete[] mPArr[i];
}
delete[] mPArr;
}
}
bool GameMap::InitByFile(QString fileName)
{
QFile file(fileName);
if(!file.open(QIODevice::ReadOnly))
{
return false;
}
QByteArray arrAll = file.readAll();
arrAll.replace("\r\n","\n");
QList<QByteArray> lineList = arrAll.split('\n');
mRow = lineList.size();
mPArr = new int*[mRow];
for(int i = 0;i < mRow;i++)
{
QList<QByteArray> colList = lineList[i].split(',');
mCol = colList.size();
mPArr[i] = new int[mCol];
for(int j = 0;j < mCol;j++)
{
mPArr[i][j] = colList[j].toInt();
}
}
}
void GameMap::Paint(QPainter* _p, QPoint _Pos)
{
for(int i = 0;i <mRow;i++)
{
for(int j = 0;j < mCol;j++)
{
QString imgUrl;
switch (mPArr[i][j])
{
case Road: imgUrl = "://Image/sky.png";break;
case Wall: imgUrl = "://Image/wall.png";break;
case Box: imgUrl = "://Image/case.png";break;
case Point: imgUrl = "://Image/end.png";break;
case InPoint: imgUrl = "://Image/win.png";break;
}
QImage img(imgUrl);
_p->drawImage(QRect(_Pos.x() + j*img.width(),_Pos.y() +i*img.height(),img.width(),img.height()),img);
}
}
}
#ifndef ROLE_H
#define ROLE_H
#include <QObject>
#include <QPoint>
#include <QImage>
class Role : public QObject
{
Q_OBJECT
public:
explicit Role(QObject *parent = nullptr);
int mRow;
int mCol;
QPoint mPaintPos;
QImage mImg;
void Move(int _dRow,int _dCol);
void Paint(QPainter* _p,QPoint _pos);
signals:
public slots:
};
#endif
#include "Role.h"
#include <QPainter>
Role::Role(QObject *parent) : QObject(parent)
{
mRow = 1;
mCol = 1;
mImg = QImage("://Image/people.png");
mPaintPos = QPoint(mCol,mRow) * mImg.width();
}
void Role::Move(int _dRow,int _dCol)
{
mRow += _dRow;
mCol += _dCol;
mPaintPos = QPoint(mCol,mRow) * mImg.width();
}
void Role::Paint(QPainter* _p,QPoint _pos)
{
_p->drawImage(mPaintPos + _pos,mImg);
}
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "GameMap.h"
#include "Role.h"
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
virtual void paintEvent(QPaintEvent* event);
virtual void keyPressEvent(QKeyEvent* event);
void Collision(int _dRow,int _dCol);
~Widget();
private:
Ui::Widget *ui;
GameMap* mPMap;
QPainter* mMapPainter;
Role* mRole;
QTimer* mTimer;
};
#endif
#include "Widget.h"
#include "ui_widget.h"
#include <QFileDialog>
#include <QPainter>
#include <QMessageBox>
#include <QKeyEvent>
#include <QtDebug>
#include <QTimer>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
mPMap = new GameMap(this);
if(!mPMap->InitByFile("./Map/lv1.txt"))
{
QMessageBox::warning(this,"警告","文件打开失败");
}
mMapPainter = new QPainter(this);
mRole = new Role(this);
mTimer = new QTimer(this);
mTimer->start(100);
connect(mTimer,&QTimer::timeout,[this](){this->update();});
setFixedSize(1024,768);
}
Widget::~Widget()
{
delete ui;
}
void Widget::paintEvent(QPaintEvent *event)
{
mMapPainter->begin(this);
QPainter bgPainter(this);
bgPainter.drawImage(QRect(0,0,1024,768),QImage("://Image/ground.png"));
mPMap->Paint(mMapPainter,QPoint(10,200));
mRole->Paint(mMapPainter,QPoint(10,200));
mMapPainter->end();
}
void Widget::keyPressEvent(QKeyEvent* event)
{
switch (event->key())
{
case Qt::Key_W:
case Qt::Key_Up:
{
Collision(-1,0);
break;
}
case Qt::Key_S:
case Qt::Key_Down:
{
Collision(1,0);
break;
}
case Qt::Key_A:
case Qt::Key_Left:
{
Collision(0,-1);
break;
}
case Qt::Key_D:
case Qt::Key_Right:
{
Collision(0,1);
break;
}
}
}
void Widget::Collision(int _dRow,int _dCol)
{
int newRow = mRole->mRow + _dRow;
int newCol = mRole->mCol + _dCol;
if(mPMap->mPArr[newRow][newCol] == Wall)
{
return;
}
else if(mPMap->mPArr[newRow][newCol] == Box)
{
if(mPMap->mPArr[newRow+_dRow][newCol + _dCol] == Road)
{
mPMap->mPArr[newRow+_dRow][newCol + _dCol] = Box;
mPMap->mPArr[newRow][newCol] = Road;
}
else if(mPMap->mPArr[newRow+_dRow][newCol + _dCol] == Point)
{
mPMap->mPArr[newRow+_dRow][newCol + _dCol] = InPoint;
mPMap->mPArr[newRow][newCol] = Road;
}
else
{
return;
}
}
else if(mPMap->mPArr[newRow][newCol] == InPoint)
{
if(mPMap->mPArr[newRow+_dRow][newCol + _dCol] == Road)
{
mPMap->mPArr[newRow+_dRow][newCol + _dCol] = Box;
mPMap->mPArr[newRow][newCol] = Point;
}
else if(mPMap->mPArr[newRow+_dRow][newCol + _dCol] == Point)
{
mPMap->mPArr[newRow+_dRow][newCol + _dCol] = InPoint;
mPMap->mPArr[newRow][newCol] = Point;
}
else
{
return;
}
}
mRole->Move(_dRow,_dCol);
qDebug() << "人物绘制位置:" << mRole->mPaintPos;
}
2.飞机大战项目实战
2.1注意事项
- 如何制作合适的图片
p48集12:40开始看 - 子弹位置的设计
2.2目录结构
2.3代码
- 程序运行结果图
- bullet.h
#ifndef BULLET_H
#define BULLET_H
#include "gameobject.h"
class Bullet : public GameObject
{
public:
enum BulletType
{
BT_Player,
BT_Enemy
};
explicit Bullet(QObject *parent = nullptr);
Bullet(QPoint _pos,QPixmap _pixmap,int _type);
void BulletMove(QPoint _dir = QPoint(0,-1));
void Init(QPoint _pos,QPixmap _pixmap);
~Bullet()
{
qDebug() << "子弹被释放";
}
protected:
int mBulletType;
int mSpeed;
QMediaPlayer mMedia;
};
#endif
#include "bullet.h"
Bullet::Bullet(QObject *parent)
{
mObjectType = GameObject::OT_BulletPlayer;
}
Bullet::Bullet(QPoint _pos, QPixmap _pixmap, int _type)
{
this->setPos(_pos);
this->setPixmap(_pixmap);
this->mBulletType = _type;
mSpeed = 6;
}
void Bullet::BulletMove(QPoint _dir)
{
this->moveBy(_dir.x()*mSpeed,_dir.y()*mSpeed);
}
void Bullet::Init(QPoint _pos, QPixmap _pixmap)
{
this->setPos(_pos);
this->setPixmap(_pixmap);
this->setScale(0.5);
this->setX(this->x() - this->scale() * pixmap().width()/2);
}
#ifndef ENEMY_H
#define ENEMY_H
#include "plane.h"
class Enemy : public Plane
{
public:
Enemy()
{
mObjectType = GameObject::OT_Enemy;
}
Enemy(QPoint _pos,QPixmap _pixmap);
void EnemyMove(QPoint _dir = QPoint(0,1));
void Init(QPoint _pos,QPixmap _pixmap);
};
#endif
#include "enemy.h"
Enemy::Enemy(QPoint _pos, QPixmap _pixmap)
{
this->mMoveSpeed = 3;
this->mShootSpeed = 1000;
this->setPos(_pos);
this->setPixmap(_pixmap);
}
void Enemy::EnemyMove(QPoint _dir)
{
this->moveBy(_dir.x()*mMoveSpeed ,_dir.y()*mMoveSpeed);
}
void Enemy::Init(QPoint _pos, QPixmap _pixmap)
{
this->setPos(_pos);
this->setPixmap(_pixmap);
this->mMoveSpeed = 3;
this->mShootSpeed = 1000;
}
#ifndef ENEMYBULLET_H
#define ENEMYBULLET_H
#include "bullet.h"
class EnemyBullet : public Bullet
{
public:
explicit EnemyBullet(QObject *parent = nullptr);
void PlaySound();
};
#endif
-enemybullet.cpp
#include "enemybullet.h"
EnemyBullet::EnemyBullet(QObject *parent)
{
mObjectType = GameObject::OT_EnemyBullet;
}
void EnemyBullet::PlaySound()
{
mMedia.setMedia(QUrl("qrc:/sound/music/weapon_enemy.wav"));
mMedia.play();
}
#ifndef GAMECONTROL_H
#define GAMECONTROL_H
#include "gamedefine.h"
#include "widget.h"
class GameControl : public QObject
{
GameControl(QWidget* parent = nullptr);
static GameControl* instance;
public:
static GameControl* Instance()
{
if(instance == nullptr)
{
return instance = new GameControl(Widget::widget);
}
return instance;
}
~GameControl()
{
qDebug() << "游戏控制释放";
}
void GameInit();
void LoadStartScene();
void LoadGameScene();
void GameStart();
void GameOver();
void BGMove();
void PlaneMove();
void PlaneBulletShoot();
void CreateEnemy();
void Collision();
QList<int> mKeyList;
protected:
QGraphicsView mGameView;
QGraphicsScene mGameScene;
QGraphicsScene mStartScene;
QGraphicsPixmapItem mBackGround1;
QGraphicsPixmapItem mBackGround2;
Player mPlane;
QTimer* mBGMoveTimer;
QTimer* mPlaneMoveTimer;
QTimer* mPlaneShootTimer;
QTimer* mBulletMoveTimer;
QTimer* mEnemyCreateTimer;
QTimer* mEnemyMoveTimer;
QList<Bullet*> mBulletList;
QList<Enemy*> mEnemyList;
QMediaPlayer* mMediaBG;
};
#endif
#include "gamecontrol.h"
#include "gamedefine.h"
#include "gameobjectpool.h"
GameControl* GameControl::instance = nullptr;
GameControl::GameControl(QWidget* parent) : QObject (parent)
{
}
void GameControl::BGMove()
{
mBackGround2.moveBy(0,2);
mBackGround1.moveBy(0,2);
if(mBackGround1.y() >= mBackGround1.pixmap().height())
{
mBackGround1.setY(-mBackGround1.pixmap().height());
}
else if(mBackGround2.y() >= mBackGround2.pixmap().height())
{
mBackGround2.setY(-mBackGround2.pixmap().height());
}
}
void GameControl::GameInit()
{
GameObjectPool::Instance()->Init();
mGameView.setParent(Widget::widget);
LoadStartScene();
mBGMoveTimer = new QTimer(Widget::widget);
mPlaneMoveTimer = new QTimer(Widget::widget);
mPlaneShootTimer = new QTimer(Widget::widget);
mBulletMoveTimer = new QTimer(Widget::widget);
mEnemyCreateTimer = new QTimer(Widget::widget);
mEnemyMoveTimer = new QTimer(Widget::widget);
connect(mBGMoveTimer,&QTimer::timeout,this,&GameControl::BGMove);
connect(mPlaneMoveTimer,&QTimer::timeout,this,&GameControl::PlaneMove);
connect(mPlaneShootTimer,&QTimer::timeout,this,&GameControl::PlaneBulletShoot);
connect(mEnemyCreateTimer,&QTimer::timeout,this,&GameControl::CreateEnemy);
connect(mBulletMoveTimer,&QTimer::timeout,[this](){
for(auto bullet : mBulletList)
{
bullet->BulletMove();
if(bullet->y() < -200)
{
bullet->GameObjectDelete(&mGameScene);
mBulletList.removeOne(bullet);
}
}
Collision();
});
connect(mEnemyMoveTimer,&QTimer::timeout,[this](){
for(auto enemy : mEnemyList)
{
enemy->EnemyMove();
if(enemy->y() > GameDefine::ScreenHeight + enemy->pixmap().height())
{
enemy->GameObjectDelete(&mGameScene);
mEnemyList.removeOne(enemy);
}
}
});
}
void GameControl::LoadStartScene()
{
mStartScene.setSceneRect(QRect(0,0,512,768));
mStartScene.addPixmap(QPixmap(":/img/Image/img_bg_logo.jpg"));
auto startBtn = new QToolButton();
startBtn->setAutoRaise(true);
startBtn->setIcon(QIcon(":/img/Image/startBtn.fw.png"));
startBtn->setIconSize(QSize(171,45));
startBtn->move(256-171/2,384);
connect(startBtn,&QToolButton::clicked,[this](){
this->LoadGameScene();
this->GameStart();
});
mStartScene.addWidget(startBtn);
mGameView.setScene(&mStartScene);
mGameView.show();
}
void GameControl::LoadGameScene()
{
mGameScene.setSceneRect(QRect(0,0,512,768));
mBackGround1.setPixmap(QPixmap(":/img/Image/img_bg_level_2.jpg"));
mBackGround2.setPixmap(QPixmap(":/img/Image/img_bg_level_2.jpg"));
mPlane.setPixmap(QPixmap(":/img/Image/MyPlane1.fw.png"));
mBackGround2.setPos(0,-mBackGround2.pixmap().height());
mGameScene.addItem(&mBackGround1);
mGameScene.addItem(&mBackGround2);
mGameScene.addItem(&mPlane);
mGameView.setScene(&mGameScene);
mGameView.show();
this->mMediaBG = new QMediaPlayer(Widget::widget);
this->mMediaBG->setMedia(QUrl("qrc:/sound/music/starwars.mp3"));
this->mMediaBG->play();
}
void GameControl::GameStart()
{
mBGMoveTimer->start(GameDefine::BackgroundUpdateTime);
mPlaneMoveTimer->start(GameDefine::PlayerMoveUpdateTime);
mPlaneShootTimer->start(GameDefine::PlaneShootUpdateTime);
mBulletMoveTimer->start(GameDefine::BulletMoveUpdateTime);
mEnemyCreateTimer->start(GameDefine::EnemyCreateTime);
mEnemyMoveTimer->start(GameDefine::EnemyMoveUpdateTime);
}
void GameControl::GameOver()
{
}
void GameControl::PlaneMove()
{
for(int keyCode : mKeyList)
{
switch (keyCode)
{
case Qt::Key_W: mPlane.moveBy(0,-1 * mPlane.MoveSpeed());break;
case Qt::Key_S: mPlane.moveBy(0,1*mPlane.MoveSpeed());break;
case Qt::Key_A: mPlane.moveBy(-1*mPlane.MoveSpeed(),0);break;
case Qt::Key_D: mPlane.moveBy(1*mPlane.MoveSpeed(),0);break;
}
}
if(mPlane.x() < 0)
{
mPlane.setX(0);
}
if(mPlane.y() < 0)
{
mPlane.setY(0);
}
if(mPlane.x() > GameDefine::ScreenWidth - mPlane.pixmap().width())
{
mPlane.setX(GameDefine::ScreenWidth - mPlane.pixmap().width());
}
if(mPlane.y() > GameDefine::ScreenHeight - mPlane.pixmap().height())
{
mPlane.setY(GameDefine::ScreenHeight - mPlane.pixmap().height());
}
}
void GameControl::PlaneBulletShoot()
{
QPixmap bulletImg(":/img/Image/bulletPlane.fw.png");
QPoint pos(mPlane.x() + mPlane.pixmap().width()/2,mPlane.y());
GameObject* obj = GameObjectPool::Instance()->GetGameObject(GameObject::OT_BulletPlayer);
PlayerBullet* bullet = (PlayerBullet*)obj;
bullet->Init(pos,bulletImg);
bullet->PlaySound();
mGameScene.addItem(bullet);
mBulletList.append(bullet);
}
void GameControl::CreateEnemy()
{
QPixmap pixmap(":/img/Image/enemy1.fw.png");
int randX = qrand()%(512-pixmap.width());
GameObject* obj = GameObjectPool::Instance()->GetGameObject(GameObject::OT_Enemy);
Enemy* enemy = (Enemy*)obj;
enemy->Init(QPoint(randX,-200),pixmap);
mGameScene.addItem(enemy);
mEnemyList.append(enemy);
}
void GameControl::Collision()
{
for(int i = 0;i < mBulletList.size();i++)
{
for(int j = 0;j < mEnemyList.size();j++)
{
if(mBulletList[i]->collidesWithItem(mEnemyList[j]))
{
mBulletList[i]->GameObjectDelete(&mGameScene);
mEnemyList[j]->GameObjectDelete(&mGameScene);
mBulletList.removeOne(mBulletList[i]);
mEnemyList.removeOne(mEnemyList[j]);
}
}
}
}
#ifndef GAMEDEFINE_H
#define GAMEDEFINE_H
#include <QtDebug>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QTimer>
#include <QList>
#include <QToolButton>
#include <QMediaPlayer>
#include "bullet.h"
#include "enemy.h"
#include "player.h"
#include "playerbullet.h"
#include "enemybullet.h"
class GameDefine
{
public:
GameDefine();
static const int PlaneShootUpdateTime = 500;
static const int PlayerMoveUpdateTime = 20;
static const int EnemyMoveUpdateTime = 20;
static const int BulletMoveUpdateTime = 10;
static const int BackgroundUpdateTime = 50;
static const int EnemyCreateTime = 2000;
static const int ScreenWidth = 512;
static const int ScreenHeight = 768;
};
#endif
#include "gamedefine.h"
GameDefine::GameDefine()
{
}
#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <QGraphicsPixmapItem>
#include <QDebug>
#include <QMediaPlayer>
class GameObject : public QGraphicsPixmapItem
{
public:
enum ObjectType
{
OT_BulletPlayer,
OT_Enemy,
OT_Player,
OT_EnemyBullet
};
explicit GameObject(QObject *parent = nullptr);
int GetType()
{
return mObjectType;
}
void GameObjectDelete(QGraphicsScene* _scene);
static int createCount;
~GameObject()
{
qDebug() << "当前释放第" + QString::number(createCount--) + "个对象";
}
protected:
int mObjectType;
};
#endif
#include "gameobject.h"
#include <QGraphicsScene>
#include "gameobjectpool.h"
#include <QDebug>
int GameObject::createCount = 0;
GameObject::GameObject(QObject *parent)
{
createCount++;
qDebug() << "当前创建" + QString::number(createCount) + "个对象";
}
void GameObject::GameObjectDelete(QGraphicsScene* _scene)
{
_scene->removeItem(this);
GameObjectPool::Instance()->RecoveryGameObject(this);
}
#ifndef GAMEOBJECTPOOL_H
#define GAMEOBJECTPOOL_H
#include <QObject>
#include "gamedefine.h"
#include "widget.h"
class GameObjectPool : public QObject
{
GameObjectPool(QObject *parent = nullptr);
static GameObjectPool* instance;
public:
static GameObjectPool* Instance()
{
if(instance == nullptr)
{
return instance = new GameObjectPool(Widget::widget);
}
return instance;
}
void Init();
GameObject* GetGameObject(int _objectType);
void RecoveryGameObject(GameObject* _object);
void Clear();
~GameObjectPool();
protected:
QList<PlayerBullet*> mBulletPool;
QList<Enemy*> mEnemyPool;
};
#endif
#include "gameobjectpool.h"
GameObjectPool* GameObjectPool::instance = nullptr;
GameObjectPool::GameObjectPool(QObject *parent) : QObject(parent)
{
}
void GameObjectPool::Init()
{
for (int i = 0;i < 20; i++)
{
PlayerBullet* bullet = new PlayerBullet();
mBulletPool.append(bullet);
Enemy* enemy = new Enemy();
mEnemyPool.append(enemy);
}
}
GameObject *GameObjectPool::GetGameObject(int _objectType)
{
switch (_objectType)
{
case GameObject::OT_BulletPlayer://子弹
{
PlayerBullet* bullet = mBulletPool.first();
mBulletPool.pop_front();
return bullet;
}
case GameObject::OT_Enemy://敌机
{
Enemy* enemy = mEnemyPool.first();
mEnemyPool.pop_front();
return enemy;
}
}
}
void GameObjectPool::RecoveryGameObject(GameObject *_object)
{
switch (_object->GetType())
{
case GameObject::OT_BulletPlayer://子弹
{
mBulletPool.append((PlayerBullet*)_object);
break;
}
case GameObject::OT_Enemy://敌机
{
mEnemyPool.append((Enemy*)_object);
break;
}
}
}
void GameObjectPool::Clear()
{
for(auto pBullet : mBulletPool)
{
delete pBullet;
}
for(auto pEnemy :mEnemyPool)
{
delete pEnemy;
}
}
GameObjectPool::~GameObjectPool()
{
Clear();
}
#ifndef PLANE_H
#define PLANE_H
#include "gameobject.h"
class Plane : public GameObject
{
public:
explicit Plane(QObject *parent = nullptr);
float MoveSpeed()
{
return mMoveSpeed;
}
protected:
float mMoveSpeed;
int mShootSpeed;
};
#endif
#include "plane.h"
Plane::Plane(QObject *parent)
{
mObjectType = GameObject::OT_Player;
}
#ifndef MYPLANE_H
#define MYPLANE_H
#include "plane.h"
class Player : public Plane
{
public:
Player();
};
#endif
#include "player.h"
Player::Player()
{
this->setPixmap(QPixmap(":/img/Image/MyPlane1.fw.png"));
this->setPos(256,500);
mMoveSpeed = 5;
mShootSpeed = 500;
}
#ifndef PLAYERBULLET_H
#define PLAYERBULLET_H
#include "bullet.h"
class PlayerBullet : public Bullet
{
public:
explicit PlayerBullet(QObject *parent = nullptr);
void PlaySound();
signals:
public slots:
};
#endif
#include "playerbullet.h"
PlayerBullet::PlayerBullet(QObject *parent)
{
mObjectType = GameObject::OT_BulletPlayer;
mSpeed = 6;
}
void PlayerBullet::PlaySound()
{
mMedia.setMedia(QUrl("qrc:/sound/music/weapon_player.wav"));
mMedia.play();
}
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QList>
#include "enemy.h"
#include "player.h"
#include "bullet.h"
#include <QMediaPlayer>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
static Widget* widget;
void keyPressEvent(QKeyEvent* event);
void keyReleaseEvent(QKeyEvent* event);
private:
Ui::Widget *ui;
};
#endif
#include "widget.h"
#include "ui_widget.h"
#include "gamecontrol.h"
#include "student.h"
Widget* Widget::widget = nullptr;
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->setFixedSize(512,768);
widget = this;
GameControl::Instance()->setParent(this);
}
Widget::~Widget()
{
delete ui;
}
void Widget::keyPressEvent(QKeyEvent *event)
{
switch (event->key())
{
case Qt::Key_W:
case Qt::Key_S:
case Qt::Key_A:
case Qt::Key_D:
GameControl::Instance()->mKeyList.append(event->key());
break;
}
}
void Widget::keyReleaseEvent(QKeyEvent *event)
{
if(GameControl::Instance()->mKeyList.contains(event->key()))
{
GameControl::Instance()->mKeyList.removeOne(event->key());
}
}
#include <QApplication>
#include "gamecontrol.h"
#include "student.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
GameControl::Instance()->GameInit();
return a.exec();
}
3.XMl学习
3.1注意点
- 快速判断xml文件是否写错
将文件直接拖入浏览器中,如果能正常打开就是没错的 - HeroInfo.xml
- Config.xml
3.2目录结构
- 目录结构
3.2代码
#ifndef HERO_H
#define HERO_H
#include <QObject>
class Hero
{
public:
Hero();
Hero(QString name,int atk,int def,int hp,QString des)
{
mName = name;
mAtk =atk;
mHp = hp;
mDef = def;
mDescript = des;
}
QString mName;
int mAtk;
int mDef;
int mHp;
QString mDescript;
};
#endif
#include "Hero.h"
Hero::Hero()
{
}
-Widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private slots:
void on_LoadBtn_clicked();
void on_SaveBtn_clicked();
private:
Ui::Widget *ui;
};
#endif
#include "Widget.h"
#include "ui_widget.h"
#include <QtXML>
#include "Hero.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
ui->textEdit->setReadOnly(true);
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_LoadBtn_clicked()
{
QFile file("HeroInfo.xml");
if(!file.open(QIODevice::ReadOnly))
return;
QDomDocument doc;
doc.setContent(&file);
QDomElement root = doc.firstChildElement("Root");
QDomElement hero = root.firstChildElement("Hero");
QString text;
while (!hero.isNull())
{
text += "Name:" + hero.attribute("name");
text += " Atk:" + hero.attribute("atk");
text += " Def:" + hero.attribute("def");
text += " HP:" + hero.attribute("hp");
text += " Des:" + hero.text()+"\n";
hero = hero.nextSiblingElement("Hero");
}
ui->textEdit->setText(text);
file.close();
}
void Widget::on_SaveBtn_clicked()
{
QVector<Hero> vec;
vec.push_back(Hero("曹操",100,25,2000,"曹孟德"));
vec.push_back(Hero("曹丕",100,25,2000,"曹子桓"));
vec.push_back(Hero("曹植",100,25,2000,"曹子建"));
vec.push_back(Hero("曹彰",100,25,2000,"曹xx"));
vec.push_back(Hero("曹真",100,25,2000,"曹xx"));
QDomDocument doc;
QDomElement root = doc.createElement("Root");
for(int i =0;i < vec.count();i++)
{
QDomElement hero = doc.createElement("Hero");
root.appendChild(hero);
hero.setAttribute("Name",vec[i].mName);
hero.setAttribute("Atk",vec[i].mAtk);
hero.setAttribute("Def",vec[i].mDef);
hero.setAttribute("HP",vec[i].mHp);
QDomText text = doc.createTextNode(vec[i].mDescript);
hero.appendChild(text);
}
doc.appendChild(root);
QFile file("./Config.xml");
if(!file.open(QIODevice::WriteOnly))
return;
QTextStream outStream(&file);
doc.save(outStream,4);
file.close();
}
|