C++(qt)游戏实战项目:坦克大战(二)

来源:互联网 发布:淘宝怎么查看买家信用 编辑:程序博客网 时间:2024/05/29 12:52

地图的表示

前面讲到了地图块类,我们想一想地图是地图块or地图包含地图块,是前者用继承,明显这里是包含的关系。地图对象里管理着所有的地图块对象,我们用二维数组cells[INUM][JNUM]存储各个地图块对象的指针(想一想为什么不直接存储地图块对象?),前面说过整个游戏地图被分成很多的地图块,cells[i][j]表示i行j列的地图块。

//file gamemap.h

#ifndef GAMEMAP_H#define GAMEMAP_H#include"mapcell.h"#include<QRect>#include"main.h"#include<fstream>class GameMap{private:Mapcell *cells[INUM][JNUM];public:    GameMap();    ~GameMap();    void Display(QPainter &paint);};#endif // GAMEMAP_H
//file gamemap.cpp#include "gamemap.h"GameMap::GameMap(){for(int i=0;i<INUM;i++)    for(int j=0;j<JNUM;j++)        cells[i][j]=NULL;for(int i=0;i<INUM;i++)   for(int j=0;j<JNUM;j++)       cells[i][j]=new Mapcell(i,j,0);//暂时所有地图块都为0号样式}GameMap::~GameMap(){    for(int i=0;i<INUM;i++)        for(int j=0;j<JNUM;j++)            if(cells[i][j])           {delete cells[i][j] ;cells[i][j]=NULL;}}void GameMap::Display(QPainter &paint){paint.drawImage(QRect(0,0,WIDTH,HEIGHT),QImage(":/images/background.bmp"));for(int i=0;i<INUM;i++)    for(int j=0;j<JNUM;j++)    {        if(cells[i][j]!=NULL)            cells[i][j]->Display(paint);    }}

说了那么多还没显示界面出来,接下来我们在新建项目时Qt自动生成mainwindow.h里添加代码

//游戏类#ifndef MAINWINDOW_H#define MAINWINDOW_H#include <QMainWindow>#include<QPainter>#include"main.h"#include "gamemap.h"class MainWindow : public QMainWindow{    Q_OBJECTpublic:    enum Gamestatus{mapedit=520,gameing,pause};//游戏状态,今天5 20纪念单身万岁    MainWindow(QWidget *parent = 0);    ~MainWindow();private slots:void paintEvent(QPaintEvent *event);private:void setgame(Gamestatus status){gamestatus=status;}//设置游戏状态Gamestatus gamestatus;//GameMap gamemap;//};#endif // MAINWINDOW_H

在mainwindow.cpp里添加代码

#include "mainwindow.h"#include"QRect"MainWindow::MainWindow(QWidget *parent)    : QMainWindow(parent){gamestatus=gameing;}MainWindow::~MainWindow(){}void MainWindow::paintEvent(QPaintEvent *event){    Q_UNUSED(event);setFixedSize(WIDTH,HEIGHT);QPainter paint(this);paint.begin(this);gamemap.Display(paint);paint.end();}

运行就可以看到地图了
后面C++(qt)游戏实战项目:坦克大战(三)将继续给地图的类添加功能,并且第一次用到和用户交互,实现地图编辑和保存。
本文章为作者原创
转载请标明本系列文章地址:http://blog.csdn.net/qq_26046771/article/details/72643740

原创粉丝点击