Пример #1
0
void playSound(QString path) {
    QMediaPlayer *player = new QMediaPlayer;
    player->setMedia(QUrl(path));
    player->play();

    QObject::connect(player, &QMediaPlayer::stateChanged, &QMediaPlayer::deleteLater);
}
Пример #2
0
void MainWindow::timeIsOut()
{
	if(ui->checkBox->isChecked()&&++currentSegIndex<segTime.count()){
		timer->stop();
		ui->listWidget->setCurrentRow(currentSegIndex);
		on_start_clicked();
		ui->label_4->setText(QString::number(currentSegIndex+1));
	}
	else if(ui->checkBox_2->isChecked()&&++currentSegIndex<segTime.count()){
		timer->stop();
		if(fnames.count()>0)
			player.play();
		ui->start->setText(QString::fromLocal8Bit("開始"));
		ui->listWidget->setCurrentRow(currentSegIndex);
	}
	else{
		timer->stop();
		if(fnames.count()>0)
			player.play();
		if(ui->listWidget->currentRow()>=0){
			ui->spinBox->setEnabled(true);
			ui->spinBox_2->setEnabled(true);
			ui->spinBox_3->setEnabled(true);
		}
		ui->checkBox->setEnabled(true);
		ui->start->setText(QString::fromLocal8Bit("開始"));
		currentSegSec=0;
		currentSegIndex=-1;
	}
}
void Audio::play(const QString &filename, const bool doubleVolume)
{
    if (SoundCache == nullptr)
        return;
    QMediaPlayer *sound = nullptr;
    if (!SoundCache->contains(filename))
    {
        sound = new QMediaPlayer;
        sound->setMedia(QUrl(filename));
        SoundCache->insert(filename, sound);
    }
    else
    {
        sound = SoundCache->object(filename);
        if (sound->state() == QMediaPlayer::PlayingState)
        {
            return;
        }
    }

    if (sound == nullptr)
        return;

    sound->setVolume((doubleVolume ? 2 : 1) * Config.EffectVolume * 100);
    sound->play();
}
Пример #4
0
int main(int argc, char *argv[])
{
	QApplication::setAttribute(Qt::AA_ShareOpenGLContexts, true);
	QApplication a(argc, argv);

	const QString fileAbsPath = a.arguments().at(1);
	qDebug("Opening %s...", qPrintable(fileAbsPath));

	QMediaPlayer p;
	p.setMedia(QMediaContent(QUrl(fileAbsPath)));

	QGraphicsVideoItem* item = new QGraphicsVideoItem;
	QGraphicsScene* scene = new QGraphicsScene;
	scene->addText("TEST");
	p.setVideoOutput(item);
	scene->addItem(item);
	scene->addRect(0, 0, 100, 100, QPen(Qt::red), QBrush(Qt::red));
	item->setPos(0, 0);

	//QImage image(1920, 1080, QImage::Format_ARGB32);
	//image.fill(Qt::blue);

	//QPainter painter(&image);
	//painter.setRenderHint(QPainter::Antialiasing);
	//scene->render(&painter);

	QGraphicsView view(scene);
	//view.scene()->addItem(item);
	view.setViewport(new QOpenGLWidget);
	view.show();

	p.play();

	return a.exec();
}
Пример #5
0
void MainWindow::on_pushButton_2_clicked()
{
    QString str = QString::fromStdString(std_str) ;
    ui->label_2->setText("the delay is " + str);
    player.stop();
    player2.stop();
}
Пример #6
0
void Tank::deleteTank()
{
    alive = false;
    head->setPixmap(QPixmap(":/images/images/empty.png").scaled(pixsize,pixsize));
    setPixmap(QPixmap(":/images/images/empty.png").scaled(pixsize,pixsize));

    int stime;
    long ltime;
    int random;
    ltime = time(NULL);
    stime = (unsigned) ltime/2;
    srand(stime);
    random = rand()%3 +1;

    QMediaPlayer *explode = new QMediaPlayer();
    explode->setMedia(QUrl("qrc:/sounds/sounds/tank/explode" + QString::number(random) + ".mp3"));
    explode->play();

    // анимация
    gif_anim = new QLabel();
    gif_anim->setStyleSheet("background-color: transparent;");
    QMovie *movie = new QMovie(":/images/images/anim/Explo.gif");
    gif_anim->setMovie(movie);
    gif_anim->move(x()-25,y()-25);
    movie->setScaledSize(QSize(250,250));
    movie->start();
    QGraphicsProxyWidget *proxy = game->scene->addWidget(gif_anim);
    QTimer::singleShot(2500, this, SLOT(deleteGif()));
}
Пример #7
0
int             main(int argc, char *argv[])
{
    QApplication    a(argc, argv);
    QVideoWidget    *videoOutputWidget = new QVideoWidget();
    QMediaPlayer    *player = new QMediaPlayer();
    QVideoProbe     *probe = new QVideoProbe();
    DemoCoq*        demo = new DemoCoq();
    QTimer*         timer = new QTimer();

    probe->setSource(player);
    player->setMedia(QUrl::fromLocalFile("C:/Users/louis/Desktop/Cinefeel/Video.avi"));

    player->setVideoOutput(videoOutputWidget);

    videoOutputWidget->show();

    player->play();

    demo->connect(timer, SIGNAL(timeout()), SLOT(updateColor()));
    timer->start(1000 / 10);
    demo->addAPIConnector(new APIConnector("192.168.43.254:34000"));
//    demo->addAPIConnector(new APIConnector("192.168.43.254:34000"));
//    demo->addAPIConnector(new APIConnector("192.168.43.254:34000"));
//    demo->addAPIConnector(new APIConnector("192.168.43.254:34000"));
    //demo.launch();

    VideoDebugger   *videoDebugger = new VideoDebugger((QObject *)0, true);
    QObject::connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)), videoDebugger, SLOT(mediaCheck(QMediaPlayer::MediaStatus)));
    QObject::connect(probe, SIGNAL(videoFrameProbed(QVideoFrame)), videoDebugger, SLOT(processFrame(QVideoFrame)));
    return a.exec();
}
Пример #8
0
void WaveformView::playSegment(LipsyncPhrase *fPhrase, LipsyncWord *fWord, LipsyncPhoneme *fPhoneme, int32 fScrubFrame)
{
    bool playSegment = false;
    QMediaPlayer *audioPlayer = fDoc->GetAudioPlayer();
    int32 startFrame;
    fAudioStopFrame = -1;
    if (audioPlayer)
    {
        if (fPhrase)
        {
            playSegment = true;
            startFrame = fPhrase->fStartFrame;
            fAudioStopFrame = fPhrase->fEndFrame + 1;
        }
        else if (fWord)
        {
            playSegment = true;
            startFrame = fWord->fStartFrame;
            fAudioStopFrame = fWord->fEndFrame + 1;
        }
        else if (fPhoneme)
        {
            playSegment = true;
            startFrame = fPhoneme->fFrame;
            fAudioStopFrame = startFrame + 1;
        }
        if (playSegment)
        {
            float f = ((real)startFrame / (real)fDoc->Fps()) * 1000.0f;
            audioPlayer->setPosition(PG_ROUND(f));
            audioPlayer->play();
            emit(frameChanged(fScrubFrame));
        }
    }
}
Пример #9
0
/**
 * Nofication.beep - http://docs.phonegap.com/phonegap_notification_notification.md.html#notification.beep
 */
void Notification::beep( int scId, int ecId, int p_times ) {
    Q_UNUSED(scId)
    Q_UNUSED(ecId)
    Q_UNUSED(p_times)
    QMediaPlayer* player = new QMediaPlayer;
    player->setVolume(100);
    player->setMedia(QUrl::fromLocalFile("/usr/share/sounds/ui-tones/snd_default_beep.wav"));
    player->play();
}
Пример #10
0
int main(int argc, char *argv[])
{
    QMediaPlayer player;

    QVideoWidget videoWidget;
    player->setVideoOutput(videoWidget);

    videoWidget->show();
    player.setMedia(QUrl::fromLocalFile());
    player->play();

    return a.exec();
}
Пример #11
0
void Form::getVoice()
{
    QMediaPlayer* player = new QMediaPlayer();

    QUrl url(m_word.voice_url);

    player->setMedia(url);
    player->setVolume(100);
    player->play();

    m_reply = m_net_manager.get(QNetworkRequest(url));
    connect(m_reply,SIGNAL(finished()),this,SLOT(downloadFinished()));
}
Пример #12
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    //QSystemTrayIcon tray;
    //tray.show();
    QMediaPlayer player;
    player.setVolume(100);
    QMediaPlaylist myList;
    player.setPlaylist(&myList);
    PlayerWindow w(0, &player);
    w.show();


    return a.exec();
}
Пример #13
0
void MainWindow::on_clear_clicked()
{
	timer->stop();
	uiTimer->stop();
	ui->lcdNumber_4->display(0);
	ui->lcdNumber->display(0);
	ui->lcdNumber_2->display(0);
	ui->lcdNumber_3->display(0);

	ui->lcdNumber_8->display(0);
	ui->lcdNumber_5->display(0);
	ui->lcdNumber_6->display(0);
	ui->lcdNumber_7->display(0);
	isCounting=false;
	firstStart=true;
	currentSegSec=totalMS=0;
	ui->checkBox->setEnabled(true);
	if(ui->listWidget->currentRow()>=0){
		ui->spinBox->setEnabled(true);
		ui->spinBox_2->setEnabled(true);
		ui->spinBox_3->setEnabled(true);
	}
	ui->start->setText(QString::fromLocal8Bit("開始"));
	ui->progressBar->setValue(0);
	ui->progressBar_2->setValue(0);
	currentSegIndex=-1;
	player.pause();
}
Пример #14
0
Game::Game(QWidget *parent){
    // create the scene
    scene = new QGraphicsScene();
    scene->setSceneRect(0,0,1000,800); // make the scene 800x600 instead of infinity by infinity (default)

    setBackgroundBrush(QBrush(QImage(":/images/bg.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(1000,800);

    // create the player
    player = new MyRect();
    //player->setRect(0,0,100,100); // 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);



    // play background music
    QMediaPlayer * music = new QMediaPlayer();
    music->setMedia(QUrl("qrc:/sounds/Counter-strike_1.6-Zak_Belica_(glavnaya_tema_-_fonovaya_muzyka_v_nachale_igry).mp3"));
    music->play();



    show();
}
Пример #15
0
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QPixmap startPixmap(":/new/icon/icon/flower.gif");
    startPixmap.size();
    QSplashScreen splash(startPixmap);
    splash.show();
    for(long i=0; i<100000000;i++);
    MainWindow w;
    w.show();
    splash.finish(&w);
    QMediaPlayer *player = new QMediaPlayer;
    player->setMedia(QUrl::fromUserInput("qrc:/new/sound/1.wav"));
    player->setVolume(50);
    player->play();
    return a.exec();
}
Пример #16
0
Game::Game(QWidget *parent)
{
    QRect rec = QApplication::desktop()->screenGeometry();
    int height = rec.height();
    int width = rec.width();

    QGraphicsScene *scene = new QGraphicsScene();
    scene->setSceneRect(0,0,width,height);

    QGraphicsView *view = new QGraphicsView(scene);

    scene->setBackgroundBrush(QImage("://img/bg.png"));

    //player
    ship *player=new ship();
    scene->addItem(player);
    player->setPos(width/2, height-70);

    //scoring
    score = new Score();
    scene->addItem(score);

    //life
    life = new Life();
    life->setPos(life->x(),life->y()+25);
    scene->addItem(life);

    player->setFlag(QGraphicsItem::ItemIsFocusable);
    player->setFocus();

    //enemies
    QTimer*timer=new QTimer();
    QObject::connect(timer,SIGNAL(timeout()),player,SLOT(spawn()));
    timer->start(2000);

    //music
    QMediaPlayer * music = new QMediaPlayer();
    music->setMedia(QUrl("qrc:/sounds/bgmusic.mp3"));
    music->play();

    view->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    view->showFullScreen();
}
Пример #17
0
int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QMediaPlayer player;

    PSMoveRotationReaderThread thread(&player);

    QString filename = QDir().absoluteFilePath(INPUT_FILENAME);
    QUrl url = QUrl::fromLocalFile(filename);
    player.setMedia(QMediaContent(url));

    /* Start with a really slow playback rate */
    player.setPlaybackRate(.01);
    player.play();

    thread.start();

    return app.exec();
}
Пример #18
0
/*  moves the projectile from left to right
 * deleted if collides with bird Enemy
*/
void Projectile::move()
{
    //projectiles capture birds
    QList<QGraphicsItem*> c = collidingItems();
    for(int i = 0, n = c.size(); i<n; ++i){
        if (typeid(*(c[i]))== typeid(Enemy)){
            // add to score
            Board->score->increase();


            //remove from scene and delete colliding items
            scene()->removeItem(c[i]);
            scene()->removeItem(this);
            // projectile sound effect
            QMediaPlayer* caught = new QMediaPlayer();
            caught->setMedia(QUrl("qrc:/audio/catch.wav"));
            caught->play();

            delete c[i];
            delete this;
            return;
        }
    }

    //rotate
    setTransformOriginPoint(-10,-10);
    setRotation(rotation()+15);


    //to the right and up
    setPos(x()+5,y()-1);

    //if off the screen to the right delete and count as a miss
    if(pos().x() > 800){
        //add a miss to the score
        Board->score->miss();


        scene()->removeItem(this);
        delete this;
    }
}
Пример #19
0
void MainWindow::showEvent(QShowEvent *)
{
    // play music
    QMediaPlayer *player = new QMediaPlayer();
    player->setMedia(QUrl("qrc:/sound/Fight.mp3"));
    player->setVolume(60);
    player->play();

    // Setting the QGraphicsScene
    scene = new QGraphicsScene(0,0,960,540);
    ui->graphicsView->setScene(scene);
    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff );
    // Create world
    world = new b2World(b2Vec2(0.0f, -9.8f));
    // Create self listener and set to the world
    myContactListener = new myContactChecker();
    world->SetContactListener(myContactListener);
    // Setting Size
    GameItem::setGlobalSize(QSizeF(64,36), QSizeF(960,540));

    // Create manager
    mySceneManager = new sceneManager(&timer,world,scene);
    myBirdManager = new birdManager(&timer,world,scene);

    // Game process
    // set up start page
    mySceneManager->buildStartScene();
    this->buildStartButton();
    // wait user to click play button
    // go see 'onStartButton'(1st)

    //mySceneManager->buildLossScene();
    //this->buildEndButton();

    // Timer
    connect(&timer,SIGNAL(timeout()),this,SLOT(tick()));
    connect(this,SIGNAL(quitGame()),this,SLOT(QUITSLOT()));
    timer.start(100/6);

}
Пример #20
0
MovieDisplay::MovieDisplay(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::MovieDisplay)
{
    ui->setupUi(this);

    //This block of code displays Llama gif when a riddle is anwsered correctly
    QMovie *movie = new QMovie("://images/pm8gm.gif");
    QLabel *processLabel = new QLabel(this);
    processLabel->setGeometry(QRect(0,-75,300,300));
    processLabel->setMovie(movie);
    movie->start();

    //This block of code plays an audio file when a riddle is answered correctly.
    //IMPORTANT::Audio path must be hard coded to location of file!
    QMediaPlayer *player = new QMediaPlayer(this);
    player->setVolume(50);
    player->setMedia(QUrl("http://shredder.resnet.bju/sound/649341_SOUNDDOGS__an.mp3"));
    player->setVolume(100);
    player->play();
}
Пример #21
0
Bullet::Bullet()
    :QObject(),
     QGraphicsPixmapItem()
{
    setPixmap(QPixmap(":/images/rocket.png"));

    QTimer *timer = new QTimer();
    QObject::connect(timer, SIGNAL(timeout()), this, SLOT(move()));

    timer->start(50);

    //sound bullet
    QMediaPlayer *bulletSound = new QMediaPlayer();
    bulletSound->setMedia(QUrl("qrc:/sounds/shoot.wav"));

    //sound
    if (bulletSound->state() == QMediaPlayer::PlayingState)
    {
        bulletSound->setPosition(0); //rewind
    }
    else bulletSound->play(); //it should be in QMediaPlayer::StoppedState
}
Пример #22
0
HomePage::HomePage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HomePage)
{
    ui->setupUi(this);

    //Initialize the splash screen and allow user to exit if they click on it
    QMovie *splashImg = new QMovie(":/icons/resources_icons/ProjectLogo_LoopOnce.gif");
    ui->label->setMovie(splashImg);
    ui->label->setFixedSize(900,450);

    QMediaPlayer *player = new QMediaPlayer;
    player->setMedia(QUrl("qrc:/audio/resources_icons/ProjectLogoSound.mp3"));
    player->setVolume(100);
    player->setPlaybackRate(0.85);
    player->play();


    //Connect the signal on every frame change to check for last frame since it loops infinitely
    connect(splashImg, SIGNAL(finished()), this, SLOT(EmitFinished()));
    splashImg->start();

}
Пример #23
0
void MainWindow::on_actionWav_triggered()//open music file
{
	//Open Dialog and Return files Directory
	fnames=QFileDialog::getOpenFileNames(this,"Open Music File" ,
										 "../" , "Music(*.wav;*.mp3);;All(*)");
	if(fnames.count()>0){
		QFile f(fnames[0]);

		//Open File and test whether it is error
		if(!f.open(QIODevice::ReadOnly)) ui->label_5->setText(fnames[0]+"[Open File Error]");

		player.setMedia(QUrl::fromLocalFile(fnames[0]));
		ui->label_5->setText(fnames[0]);
	}
}
Пример #24
0
void MainWindow::on_pushButton_clicked()
{
    player.stop();
    float number;
    std::istringstream iss(std_str);
    iss >> number ;

    int num = number *1000;
    player.setMedia(QUrl::fromLocalFile(QFileInfo(file_main).absoluteFilePath()));
    player.setVolume(100);
    player.play();

    delay(num+2);
    qDebug() << num << endl;
    player2.setMedia(QUrl::fromLocalFile(QFileInfo(file_ref).absoluteFilePath()));
    player2.setVolume(100);
    player2.play();
}
Пример #25
0
void MainWindow::on_start_clicked()
{
	if(firstStart){
		if(currentSegSec==0)
			return;
		timer->start(currentSegSec*1000);
		elapsedTimer.start();
		uiTimer->start(50);
		firstStart=false;
		isCounting=true;
		ui->start->setText(QString::fromLocal8Bit("暫停"));
		ui->checkBox->setEnabled(false);
		ui->spinBox->setEnabled(false);
		ui->spinBox_2->setEnabled(false);
		ui->spinBox_3->setEnabled(false);
		currentSegIndex=ui->listWidget->currentRow();
		player.pause();
		return;
	}
	if(isCounting){
		timer->stop();
		uiTimer->stop();
		currentTempTime.ms=ui->lcdNumber_4->value();
		currentTempTime.s=ui->lcdNumber->intValue();
		currentTempTime.m=ui->lcdNumber_2->intValue();
		currentTempTime.h=ui->lcdNumber_3->intValue();

		totalMS=ui->lcdNumber_8->value()+
				(ui->lcdNumber_5->value()+ui->lcdNumber_6->value()*60+ui->lcdNumber_7->value()*3600)*1000;
		ui->start->setText(QString::fromLocal8Bit("繼續"));
	}
	else{
		timer->start((currentTempTime.h*3600+currentTempTime.m*60+currentTempTime.s)*1000+currentTempTime.ms);
		elapsedTimer.start();
		uiTimer->start(50);
		ui->start->setText(QString::fromLocal8Bit("暫停"));
	}
	isCounting=!isCounting;
}
Пример #26
0
void TSR::syncedPlay2(QString file)
{
    TIMER_STATE ts2 = ts;

    QMediaPlayer player;
    player.setMedia(QUrl::fromLocalFile(file));
    player.play();

    totalTime = player.duration() / 1000;
    time.start();

    while(player.state() == QMediaPlayer::PlayingState)
    {
        totalTime = player.duration() / 1000;
        elapsedTime = player.position() / 1000;
        QCoreApplication::processEvents();
        if(ts == TS_STOPPED) break;
        if(ts != ts2) break;
        QThread::msleep(20);
    }

    elapsedTime = 0; totalTime = 0;
}
Пример #27
0
void Player::keyActions() // player действия при нажатии клавиши
{
    game->centerOn(this);

    lastX = x();
    lastY = y();
    lastDeg = degree;
    lastHDeg = hdegree;
    lastHealth = health;

    // эффект получения урона (должен стоять перед движением)
    if (wou)
    {
        /*
        int x1 = centralX();
        int y1 = centralY();
        wound->setPos(x1-game->width()/2,y1-game->height()/2);
        */
    }

    // движение вперед, назад
    if (mf)
    {
        moveForward();
        if (game->createBots)
            *bot << "mf ";
    }
    if (mb)
    {
        moveBack();
        if (game->createBots)
            *bot << "mb ";
    }

    // если player вышел за границы
    if (this->x() < game->dop - pixsize/2 ||
        this->x() > game->scene->width()-game->dop*2 + 20 ||
        this->y() < game->dop - pixsize/2 ||
        this->y() > game->scene->height()-game->dop*2 + 20)
    {
        // координата Х в центре экрана
        int x1 = centralX();

        // координата Y в центре экрана
        int y1 = centralY();

        if (out == false)
        {
            out = true;
            outTime = QTime::currentTime();
            outTimer = outMaxTime;

            QString image = ":/images/images/out.png";
            caution = new Caution(image, "CAUTION", 5);
            caution->setPos(x1-200,y1-88);
            game->scene->addItem(caution);
        }
        caution->setPos(x1-200, y1-88);

        if (outTime.msecsTo(QTime::currentTime()) > 1000)
        {
            if (outTimer > 0)
            {
                outTimer--;
                outTime = outTime.addSecs(1);
                caution->decTimer();
            }
            else
            {
                // DIE M**********R!
                //qDebug() << "you died";
                out = false;
                outTimer = outMaxTime;
                delete caution;

                // убить
                killPlayer();
                // BUHAHA
            }
        }
    }
    else
    {
        if (out == true)
        {
            out = false;
            outTimer = outMaxTime;
            delete caution;
        }
    }

    // универсальный поворот
    if (rl || rr)
    {
        playerRotate();
        spin++;
    }

    // ты ничего не видел
    if (rl == false && rr == false)
        spin = 0;
    // совершенно ничего
    if (spin == 540)
    {
        QMediaPlayer *sound = new QMediaPlayer();
        sound->setMedia(QUrl("qrc:/sounds/sounds/spin.mp3"));
        sound->play();
    }

    // поворот башни
    if (hl)
    {
        headLeft();
        if (game->createBots)
            *bot << "hl ";
    }
    if (hr)
    {
        headRight();
        if (game->createBots)
            *bot << "hr ";
    }

    // звук поворота башни
    if ((hr || hl) &&  tankhrotate->state() == QMediaPlayer::StoppedState) // если звук поворота еще не проигрывался
        tankhrotate->play();

    if (hr == false && hl == false && tankhrotate->state() == QMediaPlayer::PlayingState)
        tankhrotate->stop();

    // стрельба + звуки стрельбы
    if (fr && fireReady)
    {
        playerFire();
        reloading = false; // звук перезарядки еще на начат
        isFiring = 1;

        // анимация перезарядки
        reloadAnim = new QLabel();
        reloadAnim->setStyleSheet("background-color: transparent;");
        QMovie *movie = new QMovie(":/images/images/anim/Reload.gif");
        reloadAnim->setMovie(movie);
        reloadAnim->move(x()+20,y()+20);
        movie->setScaledSize(QSize(180,180));
        //movie->setSpeed(100);
        movie->start();
        QGraphicsProxyWidget *proxy = game->scene->addWidget(reloadAnim);

        if (game->createBots)
            *bot << "fr ";
    }
    if (fireReady == false) // счетчик для ожидания между выстрелами
    {
        fireCount += keyDelay;

        reloadAnim->move(x()+20,y()+20);
    }
    if ((fireCount > fireTime - bulletready->duration()) && reloading == false) // звук перезарядки
    {
        reloading = true; // перезарядка уже начата (защита от нескольких)
        bulletready->play();
    }
    if (fireCount > fireTime) // готовность выстрела
    {
        fireReady = true;
        fireCount = 0;

        delete reloadAnim;
    }

    if (game->createBots)
        *bot << endl;

    if (lastX != x() || lastY != y() || lastDeg != degree || lastHDeg != hdegree || lastHealth != health)
        emit KeyPressed();

    if (alive == false || (mf == false && mb == false && rl == false && rr == false && hl == false && hr == false && fr == false &&
                          fireReady == true && tankhrotate->state() == QMediaPlayer::StoppedState && out == false))
    {
        action = false;
        timer->stop();
    }
}
Пример #28
0
    /*!
     * \brief Run
     * Programe principale du jeux
     */
    void Run()
    {
#ifdef __WIN32__
        QThread Thread; // on crée un objet QThread pour le Timer de QMediaPlayer
        QMediaPlayer player; // on crée un lecteur de Musique
        player.moveToThread(&Thread); // on le place dans le Thread
        player.setVolume(50); // on modifie le volume
        QVector<QUrl> playlist; // on affecte une playlist d'URL

        playlist.push_back(QUrl(QString::fromStdString(KIntroSound)));
        playlist.push_back(QUrl(QString::fromStdString(KEndSound)));
        playlist.push_back(QUrl(QString::fromStdString(KGameOverSound)));
        playlist.push_back(QUrl(QString::fromStdString(KHistoSound)));
        playlist.push_back(QUrl(QString::fromStdString(KGameSound)));

        player.setMedia(playlist[0]);
        player.play(); // On joue la musque d'introduction au jeux
#endif
        srand (time(NULL));
        set_input_mode();
        MainFont(); // On affiche un Invader
        CVString Space; // On crée la variable qui est la grille de jeux
        int FinalScore(0); // variable qui stock le score
        unsigned Level(0); // variable qui stock le niveau atteint par le joueur
        for( ; Level<5 && (Level==0 || !LoseTest(Space, Space.size()-1)) ; ++Level)
        {
            unsigned PosInvader(KBegInvader), PosMe(KBegMe); // Variable stockant la position de l'invader et du joueur
            unsigned LineInvader(0); // ligne de l'invader
            unsigned FirstInvaderCount (KInvadersSize);  // Compteur du nombre d'invaders restant
            if(Level>2)
                FirstInvaderCount = KInvadersSize*2/3;
            unsigned PlayerLife (KMyLife); // Variable stockant la vie du joueur
            int Score(0); // score du joueur
            bool Increment(true); // variable qui donne le sens de déplacement de l'invader
            int FireWait(0); // Variable evitant que le joueur puisse tiré rapidement
            initSpace(Space, PosMe, LineInvader); // Variable initialisant
            cout << CleanScreen(); // on efface l'écran pour rafraichir l'image

#ifdef __WIN32__
            player.stop();
            player.setMedia(playlist[3]); // on joue la musique de scenario

            player.play();
#endif
            ManageScenar(Level); // démarage de l'affichage du scénario
#ifdef __WIN32__
            player.stop();
            player.setMedia(playlist[4]); // a la fin du scenario on lance la musique de jeux

            player.play();
#endif
            cout << CleanScreen(); // on efface l'écran
            unsigned Turn(0); // nombre de tours écoulés
            while(!WinTest(Space, LineInvader) && !LoseTest(Space, Space.size()-1)) // on boucle tan que le joueur ou l'invader n'a pas gagne ou qu'il soit arrive sur la dernier ligne
            {
                Score -= 10; // on decremente le score à chaque tours de l'invader


                for(unsigned i(0) ; i<KRatioMeInvaders &&  (!WinTest(Space, LineInvader) && !LoseTest(Space, Space.size()-1)); ++i, ++Turn) // boucle pour equilibré le ration
                {
                    unsigned LastInvaderCount (FirstInvaderCount); // on sauvegarde le nombre d'invaders avant de faire se déplacer les missile

                    ManageMissileAndTorpedo(Space, FirstInvaderCount, PlayerLife, Score);

                    if(LastInvaderCount != FirstInvaderCount) // si il manque un ou plusieurs invaders on incrémente le score et on fait apparaitre un bonus
                    {
                        ManageBonus(Space, LineInvader);
                        Score += 100;
                    }

                    if(Turn%KMissileRatio == 0) // on respecte un ratio pour les tirs de missile
                        ManageInvaderShoot(Space, LineInvader, PosInvader, PlayerLife);

                    chrono::high_resolution_clock::time_point t1 = chrono::high_resolution_clock::now(); // on recupère le temps de début
                    ManageMe(Space, PosMe, FireWait, PlayerLife, Score); // on donne le tour au joueur
                    cout << GotoXY(0,0) << "\t\t\t" << SetColorAndBack(KNoir, KRouge) << string(KSizeLine+2,'-') << Reset() << endl; // place le haut de la grille
                    for(const string &Line : Space)
                    {
                        cout << "\t\t\t" << SetColorAndBack(KNoir, KRouge) << '|' << Reset(); // on affiche la grille de jeux
                        PrintGameLine(Line);
                        cout << SetColorAndBack(KNoir, KRouge) << '|' << Reset() << endl;
                    }
                    cout << "\t\t\t" << SetColorAndBack(KNoir, KRouge) << string(KSizeLine+2,'-') << Reset() << endl;
                    cout << SetColorAndBack(KCyan, KRouge) << resizeText("             Score : " + to_string(Score) + " Player Life : " + to_string(PlayerLife), 60) << Reset() << endl; // afficher les info du jeux
                    cout << SetColorAndBack(KCyan, KRouge) << resizeText("   FinalScore : " + to_string(Score + FinalScore) + " Invader Count : " + to_string(FirstInvaderCount),60)<< Reset() << endl;
                    chrono::high_resolution_clock::time_point t2 = chrono::high_resolution_clock::now();
                    auto duration = chrono::duration_cast<chrono::microseconds>( t2 - t1 ).count(); // on fait la différence pour eviter que le jeux aille trop vite
                    if(duration<350000)
                        usleep(350000-duration); // on attend que le temps manquant ce soit écoulé
                }
#ifdef __WIN32__
                if(player.state() != QMediaPlayer::PlayingState) // si la musique s'arrete on la relance
                    player.play();
#endif

                ManageInvaderMove(Space, Increment,  LineInvader, PosInvader); // on déplace l'invader
            }
            if(PlayerLife==0)
            {
#ifdef __WIN32__
                player.stop();
                player.setMedia(playlist[2]); // on joue la musique de game over
                player.play();
#endif
                MainFont(KNoir,KRouge, KNoir); // image de game over
            }
            FinalScore += Score;
            if(Level == 4)
            {
#ifdef __WIN32__
                player.stop();
                player.setMedia(playlist[1]); // musique de victoire
                player.play();
#endif
                MainFont(KNoir,KVert, KNoir); // image de victoire
                cout << "Score Final "<< FinalScore; // affichage du score final

            }
        }
    }
Пример #29
0
void WaveformView::paintEvent(QPaintEvent *event)
{
	PG_UNUSED(event);

	QPainter	dc(this);

	int32		clientWidth = width();
	int32		clientHeight = height();

	if (fDoc == NULL)
	{
		dc.drawText(QRect(0, 0, clientWidth, clientHeight), Qt::AlignHCenter | Qt::AlignVCenter, tr("Drop WAV audio file here"));
		return;
	}

	int32		topBorder = 16; // should be the height of frame label text
	int32		halfClientHeight;
	int32		sampleHeight, halfSampleHeight, textHeight;
	int32		fps = fDoc->Fps();
	int32		x = 0;
	int32		frameX;
	int32		sample = 0;
	int32		frame = 0;
	bool		drawPlayMarker = false;
	QRect		r;
	QColor		textCol(64, 64, 64);
	QColor		sampleFillCol(162, 205, 242);
	QColor		sampleOutlineCol(30, 121, 198);
	QColor		playBackCol(255, 127, 127);
	QColor		playForeCol(209, 102, 121, 128);
	QColor		playOutlineCol(128, 0, 0);
	QColor		frameCol(192, 192, 192);
	QColor		phraseFillCol(205, 242, 162);
	QColor		phraseOutlineCol(121, 198, 30);
	QColor		wordFillCol(242, 205, 162);
	QColor		wordOutlineCol(198, 121, 30);
	QColor		wordMissingFillCol(255, 127, 127);
	QColor		wordMissingOutlineCol(255, 0, 0);
	QColor		phonemeFillCol(231, 185, 210);
	QColor		phonemeOutlineCol(173, 114, 146);
	QMediaPlayer	*audioPlayer = fDoc->GetAudioPlayer();

	textHeight = dc.fontMetrics().height() + 4;
	topBorder = textHeight;
	halfClientHeight = (clientHeight - textHeight) / 2;

	if (audioPlayer && audioPlayer->state() == QMediaPlayer::PlayingState)
	{
		drawPlayMarker = true;
		x = fCurFrame * fFrameWidth;
		dc.fillRect(QRect(x, 0, fFrameWidth, clientHeight), playBackCol);
	}

	x = 0;
	for (int32 i = 0; i < fNumSamples; i++)
	{
		if (((sample + 1) % fSamplesPerFrame) == 0)
		{
			dc.setPen(frameCol);
			// draw frame marker
			frameX = (frame + 1) * fFrameWidth;
			if (fSampleWidth >= 2 && ((fFrameWidth > 2) || ((frame + 2) % fps == 0)))
			{
				dc.drawLine(frameX, topBorder, frameX, clientHeight);
			}
			// draw frame label
			if ((fFrameWidth > 30) || ((frame + 2) % fps == 0))
			{
				dc.drawLine(frameX, 0, frameX, topBorder);
				dc.drawText(frameX + 2, textHeight - 4, QString::number(frame + 2));
			}
		}

		sampleHeight = PG_ROUND(fAmp[i] * (real)(clientHeight - topBorder));
		halfSampleHeight = sampleHeight / 2;
		r.setRect(x, topBorder + halfClientHeight - halfSampleHeight, fSampleWidth + 1, sampleHeight);
		dc.fillRect(r, sampleFillCol);
		dc.setPen(sampleOutlineCol);
		dc.drawLine(r.topLeft(), r.topRight());
		dc.drawLine(r.bottomLeft(), r.bottomRight());
		dc.drawLine(r.topRight(), r.bottomRight());
		if (i == 0)
		{
			dc.drawLine(r.topLeft(), r.bottomLeft());
		}
		else if (fAmp[i] > fAmp[i - 1])
		{
			sampleHeight = PG_ROUND(fAmp[i - 1] * (real)(clientHeight - topBorder));
			halfSampleHeight = sampleHeight / 2;
			dc.drawLine(r.topLeft(), QPoint(r.left(), topBorder + halfClientHeight - halfSampleHeight));
			dc.drawLine(r.bottomLeft(), QPoint(r.left(), topBorder + halfClientHeight - halfSampleHeight + sampleHeight - 1));
		}

		x += fSampleWidth;
		sample++;
		if ((sample % fSamplesPerFrame) == 0)
			frame++;
	}

	if (fDoc->fCurrentVoice)
	{
		topBorder += 4;
		for (int32 p = 0; p < fDoc->fCurrentVoice->fPhrases.size(); p++)
		{
			LipsyncPhrase *phrase = fDoc->fCurrentVoice->fPhrases[p];
			r = QRect(phrase->fStartFrame * fFrameWidth, topBorder, (phrase->fEndFrame - phrase->fStartFrame + 1) * fFrameWidth, textHeight);
			phrase->fTop = r.top();
			phrase->fBottom = r.bottom();
			dc.fillRect(r, phraseFillCol);
			dc.setPen(phraseOutlineCol);
			dc.drawRect(r);
			dc.setClipRect(r);
			dc.setPen(textCol);
			r = r.marginsRemoved(QMargins(2, 2, 2, 2));
			dc.drawText(QPoint(r.left(), r.bottom() - 2), phrase->fText);
			dc.setClipping(false);

			for (int32 w = 0; w < phrase->fWords.size(); w++)
			{
				LipsyncWord *word = phrase->fWords[w];
				r = QRect(word->fStartFrame * fFrameWidth, topBorder + 4 + textHeight, (word->fEndFrame - word->fStartFrame + 1) * fFrameWidth, textHeight);
				if (w & 1)
					r.translate(0, textHeight - textHeight / 4);
				word->fTop = r.top();
				word->fBottom = r.bottom();
				if (word->fPhonemes.size() == 0)
				{
					dc.fillRect(r, wordMissingFillCol);
					dc.setPen(wordMissingOutlineCol);
				}
				else
				{
					dc.fillRect(r, wordFillCol);
					dc.setPen(wordOutlineCol);
				}
				dc.drawRect(r);
				dc.setClipRect(r);
				dc.setPen(textCol);
				r = r.marginsRemoved(QMargins(2, 2, 2, 2));
				dc.drawText(QPoint(r.left(), r.bottom() - 2), word->fText);
				dc.setClipping(false);

				for (int32 i = 0; i < word->fPhonemes.size(); i++)
				{
					LipsyncPhoneme *phoneme = word->fPhonemes[i];
					r = QRect(phoneme->fFrame * fFrameWidth, clientHeight - 4 - textHeight, fFrameWidth, textHeight);
					if (i & 1)
						r.translate(0, -(textHeight - textHeight / 4));
					phoneme->fTop = r.top();
					phoneme->fBottom = r.bottom();
					dc.fillRect(r, phonemeFillCol);
					dc.setPen(phonemeOutlineCol);
					dc.drawRect(r);
					dc.setPen(textCol);
					r = r.marginsRemoved(QMargins(2, 2, 2, 2));
					dc.drawText(QPoint(r.left(), r.bottom() - 2), phoneme->fText);
				} // for i
			} // for w
		} // for p
	}

	if (drawPlayMarker)
	{
		x = fCurFrame * fFrameWidth;
		dc.fillRect(QRect(x, 0, fFrameWidth, clientHeight), playForeCol);
		dc.setPen(playOutlineCol);
		dc.drawRect(QRect(x, 0, fFrameWidth, clientHeight));
	}
}
Пример #30
0
void Plane::keyPressEvent(QKeyEvent *event)
{
    switch(event->key())
    {
    case Qt::Key_Right:
        if(x() < 1130) {
        rAnimation->setStartValue(x());
        rAnimation->setEndValue(x() + 40);
        rAnimation->start();
        }
        break;

    case Qt::Key_Left:
        if(x() > 0){
        lAnimation->setStartValue(x());
        lAnimation->setEndValue(x() - 40);
        lAnimation->start();
        }
        break;

    case Qt::Key_Up:
        if(y() > 30){
        uAnimation->setStartValue(y());
        uAnimation->setEndValue(y() - 40);
        uAnimation->start();
        }
        break;

    case Qt::Key_Down:
        if(y() < 580){
        dAnimation->setStartValue(y());
        dAnimation->setEndValue(y() + 40);
        dAnimation->start();
        }
        break;

    case Qt::Key_Space:{
        if(!missileCount)
            break;
        rocket * myRocket = new rocket();
        scene()->addItem(myRocket);
        myRocket->setPos(x() + 35, y() + 20);
        myRocket->shoot();
        game->lvl->miss->decrease();
        break;
    }

    case Qt::Key_Control:{
        shootAnimation->setStartValue(y());
        shootAnimation->setEndValue(y());
        shootAnimation->setKeyValueAt(0.5, y() + 10);
        shootAnimation->start();
        int regionCount = bulletPower + 3;
        qreal baseAngel = 180 / regionCount;
        for(int i = 0; i < bulletPower; i++){
            bullet * newBullet = new bullet((i+2) * baseAngel);
            newBullet->setPos(x() + 35, y() + 10);
            scene()->addItem(newBullet);
        }

        QMediaPlayer * bulletsound = new QMediaPlayer();
        bulletsound->setMedia(QUrl("qrc:/sound/bullet.mp3"));
        bulletsound->play();
        break;
    }

    case Qt::Key_W:
        bulletPower++;
        break;

    case Qt::Key_S:
        bulletPower--;
        break;

    default:
        break;
    }
}