如何为我的游戏设置主菜单场景?QT C++

How do I set a Main Menu Scene to my game? QT C++

本文关键字:QT C++ 菜单 我的 游戏 设置      更新时间:2023-10-16

我对QT和C++完全陌生。我遵循了在线教程,并使用QT创建了我的第一个游戏。游戏基本上是这样的。我是一辆坦克,我可以将坦克移动到场景底角的左右。炸弹从现场的顶部随机落到地面上。我可以通过按空格键向他们射击。当子弹击中炸弹时,分数正在计算......

我的游戏只有一个场景。当我运行程序时,游戏在那个时候开始。我希望我的程序在运行游戏时首先打开主菜单。主菜单应包含两个QPush按钮。它们是开始游戏退出。我不知道如何实现该部分。

游戏.h

#ifndef GAME_H
#define GAME_H
#include <QGraphicsView>
#include <QWidget>
#include <QGraphicsScene>
#include "Score.h"
#include "Health.h"
#include "Player.h"

class Game: public QGraphicsView{
public:
Game(QWidget * parent=0);
QGraphicsScene * scene;
Player * player;
Score * score;
Health * health;
};
#endif // GAME_H

游戏.cpp

#include "Game.h"
#include "Health.h"
#include <QTimer>
#include <QGraphicsTextItem>
#include <QFont>
#include "Enemy.h"
#include <QMediaPlayer>

Game::Game(QWidget *parent){
// create the scene
scene = new QGraphicsScene();
scene->setSceneRect(0,0,800,600); // make the scene 800x600 instead of infinity by infinity (default)
//Set the Background
setBackgroundBrush(QBrush(QImage(":/images/background.jpg")));
// make the newly created scene the scene to visualize (since Game is a QGraphicsView Widget,
// it can be used to visualize scenes)
setScene(scene);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setFixedSize(800,600);
// create the player
player = new Player();
// change the rect from 0x0 (default) to 100x100 pixels
player->setPos(400,500); // TODO generalize to always be in the middle bottom of screen
// make the player focusable and set it to be the current focus
player->setFlag(QGraphicsItem::ItemIsFocusable);
player->setFocus();
// add the player to the scene
scene->addItem(player);
// create the score/health
score = new Score();
scene->addItem(score);
health = new Health();
health->setPos(health->x(),health->y()+25);
scene->addItem(health);
// spawn enemies
QTimer * timer = new QTimer();
QObject::connect(timer,SIGNAL(timeout()),player,SLOT(spawn()));
timer->start(2000);
//Playing the Background Music
QMediaPlayer * music = new QMediaPlayer();
music->setMedia(QUrl("qrc:/sounds/bgmusic.mp3"));
music->play();
show();
}

主.cpp

#include <QApplication>
#include "Game.h"
#include <QGraphicsScene>
Game * game;
int main(int argc, char *argv[]){
QApplication a(argc, argv);
game = new Game();
game->show();
return a.exec();
}

一种直接的方法是创建一个子类 QGraphicsRectObject 的GameMenu类,使用您当前用于创建其他游戏内对象(如PlayerScoreHealth(的相同方法,除了GameMenu对象将被绘制为矩形(或其他任何内容(并在其中绘制适当的菜单文本选项(作为子类 paint 方法的一部分(。 然后,您只需将GameMenu对象放入QGraphicsScene的中心即可。 您还需要在代码中添加条件逻辑,以便在GameMenu对象可见时游戏玩法的行为有所不同(即,在 GameMenu 可见时不要生成敌方坦克,并处理箭头键按下以更新 GameMenu 对象的选择选项,而不是移动玩家的坦克(。