void GameScene::setGameState(GameState gameState) { qDebug() << "Game state set " << gameState; // If the gameState was game over, restart the level if(m_gameState == GameOver && gameState == GameRunning) { setLevel(level()); } this->m_gameState = gameState; if(gameState == GameStarted) { pauseGame(); } if(gameState == GamePaused) { pauseGame(); } if(gameState == GameOver) { pauseGame(); } if(gameState == GameRunning) { setLevelUpgrade(false); continueGame(); } if(gameState == GameInstructionPause) { pauseGame(); } emit gameStateChanged(gameState); }
MainWidget::MainWidget(Settings *settings, QWidget *parent) : QWidget(parent) , m_settings(settings) , m_scene(-105, -175, 808, 533) , m_centralWidgetRect(355, 176, 808, 533) , gameField(new Game(m_centralWidgetRect, &m_scene)) , about(new aboutWidget(m_centralWidgetRect)) , menu(new mainMenu(m_centralWidgetRect)) , manage(new manageWidget(m_centralWidgetRect)) , st(new QStackedWidget(this)) , recordsView(new recordsWidget(m_centralWidgetRect)) , m_settingsWidget(new SettingsWidget(m_centralWidgetRect, settings)) , settings(new QSettings("karama", "WolfAndEggs", this)) , isUpdated(false) { loadSettings(); recordsView->printRecords(gameField->getRecords()); setWindowFlags(Qt::FramelessWindowHint); initStackedWidget(); initButtons(); showMaximized(); QObject::connect(this,SIGNAL(pauseGame()),gameField,SLOT(pauseGame())); QObject::connect(recordsView->newBut,SIGNAL(clicked()),this,SLOT(newGameStart())); }
void HoldLine::keyPressEvent(QKeyEvent *event){ switch (event->key()){ case Qt::Key_Up: if(!paused) moveProtagonist(0,-6); break; case Qt::Key_Down: if(!paused) moveProtagonist(0,6); break; case Qt::Key_Right: if(!paused) moveProtagonist(6,0); break; case Qt::Key_Left: if(!paused) moveProtagonist(-6,0); break; case Qt::Key_X: if(!paused && remainingArrows != 0) shootArrow(); break; case Qt::Key_Z: if(!paused && remainingTraps != 0) deployTrap(); break; case Qt::Key_Escape: qApp->exit(); break; case Qt::Key_P: pauseGame(); break; case Qt::Key_S: startGame(); break; default: QWidget::keyPressEvent(event); } }
void S9xDoAction(unsigned char action) { if (action & kActionQuickLoad1) S9xLoadState(1); if (action & kActionQuickLoad2) S9xLoadState(2); if (action & kActionQuickLoad3) S9xLoadState(3); if (action & kActionQuickSave1) S9xSaveState(1); if (action & kActionQuickSave2) S9xSaveState(2); if (action & kActionQuickSave3) S9xSaveState(3); if (action & kActionMenu) { S9xAudioOutputEnable(false); //Save state -- both SRAM and autosave { //SRAM Memory.SaveSRAM(S9xGetFilename(FILE_SRAM)); //autosave (if enabled) pauseGame(); } eMenuResponse r = optionsMenu(); if ( r == MENU_RESPONSE_ROMSELECTOR ) Config.running = false; else S9xAudioOutputEnable(true); } }
/** * create the action events create the gui. */ void KJezzball::initXMLUI() { m_newAction = KStdGameAction::gameNew( this, SLOT(newGame()), actionCollection() ); // AB: originally KBounce/KJezzball used Space for new game - but Ctrl+N is // default. We solve this by providing space as an alternative key KShortcut s = m_newAction->shortcut(); s.append(KKeySequence(QKeySequence(Key_Space))); m_newAction->setShortcut(s); KStdGameAction::quit(this, SLOT(close()), actionCollection() ); KStdGameAction::highscores(this, SLOT(showHighscore()), actionCollection() ); m_pauseButton = KStdGameAction::pause(this, SLOT(pauseGame()), actionCollection()); KStdGameAction::end(this, SLOT(closeGame()), actionCollection()); KStdGameAction::configureHighscores(this, SLOT(configureHighscores()),actionCollection()); new KAction( i18n("&Select Background Folder..."), 0, this, SLOT(selectBackground()), actionCollection(), "background_select" ); m_backgroundShowAction = new KToggleAction( i18n("Show &Backgrounds"), 0, this, SLOT(showBackground()), actionCollection(), "background_show" ); m_backgroundShowAction->setCheckedState(i18n("Hide &Backgrounds")); m_backgroundShowAction->setEnabled( !m_backgroundDir.isEmpty() ); m_backgroundShowAction->setChecked( m_showBackground ); m_soundAction = new KToggleAction( i18n("&Play Sounds"), 0, 0, 0, actionCollection(), "toggle_sound"); }
void Game::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Left: snake->dir = Snake::LEFT; break; case Qt::Key_Right: snake->dir = Snake::RIGHT; break; case Qt::Key_Up: snake->dir = Snake::UP; break; case Qt::Key_Down: snake->dir = Snake::DOWN; break; case Qt::Key_P: pauseGame(); break; case Qt::Key_Space: startGame(); break; case Qt::Key_Escape: qApp->exit(); break; default: QWidget::keyPressEvent(event); } repaint(); }
void HudLayer::onInput(IMainGame* game, Character* player, Music bg) { SDL_Event evnt; while (SDL_PollEvent(&evnt)) { gui->onSDLEvent(evnt); switch (evnt.type) { case SDL_MOUSEBUTTONDOWN: for (size_t i = 0; i < gui->GUIElements.size(); i++) { if (gui->GUIElements.at(i)->m_eCurrentState == ButtonState::PRESSED) { if (gui->GUIElements.at(i)->getButtonName() == "pause") { pauseGame(game, bg); } if (gui->GUIElements.at(i)->getButtonName() == "up") { player->jump(); } if (gui->GUIElements.at(i)->getButtonName() == "down") { player->fall(); } if (gui->GUIElements.at(i)->getButtonName() == "slide") { player->slide(); } } } //break; default: break; } } }
void RingworldDemoGame::processEvent(Event &event) { if (event.eventType == EVENT_KEYPRESS) { switch (event.kbd.keycode) { case Common::KEYCODE_F1: // F1 - Help MessageDialog::show(DEMO_HELP_MSG, OK_BTN_STRING); break; case Common::KEYCODE_F2: { // F2 - Sound Options ConfigDialog *dlg = new ConfigDialog(); dlg->runModal(); delete dlg; g_globals->_soundManager.syncSounds(); g_globals->_events.setCursorFromFlag(); break; } case Common::KEYCODE_F3: // F3 - Quit quitGame(); event.handled = false; break; default: break; } } else if (event.eventType == EVENT_BUTTON_DOWN) { pauseGame(); event.handled = true; } }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), canvasWidget(new CanvasWidget(this)), gameIsPaused(true), thereIsAnotherDialog(false) { Item::setCanvas(canvasWidget); new Background; // the background put's itself into the canvasWidget gameEngine = new GameEngine(this); // must be called after Item::setCanvas() #if defined ANDROID setAttribute(Qt::WA_AcceptTouchEvents); #endif connect(canvasWidget, SIGNAL(mouseMoved(int)), gameEngine, SLOT(moveBar(int))); connect(canvasWidget, SIGNAL(barMovedLeft()), gameEngine, SLOT(moveBarLeft())); connect(canvasWidget, SIGNAL(barMovedRight()), gameEngine, SLOT(moveBarRight())); connect(canvasWidget, SIGNAL(focusLost()), this, SLOT(pauseGame())); connect(gameEngine, SIGNAL(gamePaused()), canvasWidget, SLOT(handleGamePaused())); connect(gameEngine, SIGNAL(gameResumed()), canvasWidget, SLOT(handleGameResumed())); connect(gameEngine, SIGNAL(gameResumed()), this, SLOT(handleGameResumed())); connect(gameEngine, SIGNAL(resetMousePosition()), canvasWidget, SLOT(handleResetMousePosition())); connect(gameEngine, SIGNAL(gameEnded(int,int,int)), SLOT(handleEndedGame(int,int,int))); // cheating keys, debugging and testing only TODO: REMOVE connect(canvasWidget, SIGNAL(cheatSkipLevel()), gameEngine, SLOT(cheatSkipLevel())); connect(canvasWidget, SIGNAL(cheatAddLife()), gameEngine, SLOT(cheatAddLife())); connect(gameEngine, SIGNAL(levelChanged()), this, SLOT(handleLevelChanged())); connect(Settings::self(), SIGNAL(themeChanged()), canvasWidget, SLOT(reloadSprites())); setCentralWidget(canvasWidget); setupActions(); setFocusProxy(canvasWidget); QSize defaultSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); // show here (instead of in main) else the mouse can't be grabbed show(); gameEngine->start(Settings::self()->getLevelset()); }
void CFBMatch::resumeMatch() { pauseGame(false); m_matchStep = FBDefs::MATCH_STEP::MATCHING; if (m_teamsInMatch[(int)SIDE::SELF]->isAttacking()) { m_matchUI->showAttackMenu(true); } m_matchUI->onPauseGame(false); }
static void saveGameInSlot() { saveGame(menu.index - 1); freeMessageQueue(); setInfoBoxMessage(60, 255, 255, 255, _("Game Saved")); pauseGame(); }
static void quitToTitle() { menu.index = 0; pauseGame(); setTransition(TRANSITION_OUT, &titleScreen); fadeOutMusic(500); }
void Game::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event) { Scene* nowScene = Director::getInstance()->getRunningScene(); Vector<Node*> suoyou = nowScene->getChildren(); if (suoyou.at(suoyou.size() - 1) != this) return; if (keyCode == EventKeyboard::KeyCode::KEY_ESCAPE) { pauseGame(); } }
void CFBMatch::onInstructionEnd() { pauseGame(false); m_recentEndedFlow = m_currentInstruction->getInstructionType(); m_currentInstruction = nullptr; m_matchUI->onInstrunctionEnd(); checkEncounterInPenaltyArea(); }
void KJezzball::closeGame() { if ( m_state!=Idle ) { int old_state = m_state; if (old_state == Running) pauseGame(); int ret = KMessageBox::questionYesNo( this, i18n("Do you really want to close the running game?"), QString::null, KStdGuiItem::close(), KStdGuiItem::cancel() ); if ( ret==KMessageBox::Yes ) { stopLevel(); m_state = Idle; highscore(); } else if (old_state == Running) { pauseGame(); // Unpause } } }
void GameScene::focusOutEvent(QFocusEvent *event) { //窗口脱离焦点后暂停游戏 if(inSence){ inSence=false; camera->unBind(); pauseGame(); mouseUnLock(); opWidgetProxy->show(); inOpWidget=true; } }
void kMancalaMain::historyShow(int currentRow) { if ( currentRow == -1 ) return; _manageToolbarItems(); if ( _historyListWidget->count() == 1 ) { _historyListWidget->setCurrentRow(-1); return; } qDebug("Restoring board ... to item: %d", currentRow); kMancalaHistoryItem *i = _historyListWidget->getState(currentRow); player **p = i->getPlayers(); int currentPlayer = i->getPlayerOnTurn(); _board = new board(i->getBoard()); _players[0] = new player(p[0]); _players[1] = new player(p[1]); _controller->setCurrentPlayer(i->getPlayerOnTurn()); emit playersUpdated(_players, currentPlayer); emit updateBoard(_board); emit clearGameOver(); if ( !_controller->gameOn(_board) ) { // if ( _gameOver ) return; int winner = _controller->winner(_board); player *p_winner = NULL; qDebug("Winner is %d", winner); if ( winner != -1 ) p_winner = _players[winner]; qDebug("History Game Over"); _guiBoard->play(); qDebug("Emitting gameOver"); emit gameOver(p_winner); stopGame(); qDebug("historyShow done"); } else { qDebug("Not game over ..."); _gameOver = false; _gamePaused = false; pauseGame(); } }
void keyDown(sf::Keyboard::Key key) { switch(key) { case sf::Keyboard::Escape: { if(bPause) exit(0); else { printf("Esc was pressed, press again to exit.\n"); pauseGame(); } } break; case sf::Keyboard::P: pauseGame(); break; case sf::Keyboard::G: gGodMode = !gGodMode; break; case sf::Keyboard::Num0: show_debugging = !show_debugging; break; case sf::Keyboard::Num8: { mouseSensitivity *= .75; if (mouseSensitivity < .1) mouseSensitivity = .1; } break; case sf::Keyboard::Num9: { mouseSensitivity *= 1.5; if (mouseSensitivity > 2.0) mouseSensitivity = 2.0; } break; default: break; } }
void PlatformState::handleAction(Controls::Action action, Controls::KeyState keystate) { handleOverlayAction(action, keystate); if(mPaused) return; mPlayer->handleAction(action, keystate); if(keystate == Controls::RELEASED) { if(action == Controls::MENU) { getOverlay(PAUSE).setEnabled(true); pauseGame(); } if(action == Controls::DEBUG) mDrawDebugShapes = !mDrawDebugShapes; } }
int Breakout::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: scoreChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 1: levelChanged((*reinterpret_cast< int(*)>(_a[1]))); break; case 2: startGame(); break; case 3: pauseGame(); break; case 4: stopGame(); break; default: ; } _id -= 5; } return _id; }
void KBlocksWin::setupGUILayout() { QAction *action; action = KStandardGameAction::gameNew(this, SLOT(singleGame()), actionCollection()); action->setText(i18n("Single Game")); actionCollection()->addAction(QStringLiteral("newGame"), action); action = new QAction(this); action->setText(i18n("Human vs AI")); actionCollection()->addAction(QStringLiteral("pve_step"), action); connect(action, &QAction::triggered, this, &KBlocksWin::pveStepGame); m_pauseAction = KStandardGameAction::pause(this, SLOT(pauseGame()), actionCollection()); actionCollection()->addAction(QStringLiteral("pauseGame"), m_pauseAction); m_pauseAction->setEnabled(false); action = KStandardGameAction::highscores(this, SLOT(showHighscore()), actionCollection()); actionCollection()->addAction(QStringLiteral("showHighscores"), action); action = KStandardGameAction::quit(this, SLOT(close()), actionCollection()); actionCollection()->addAction(QStringLiteral("quit"), action); KStandardAction::preferences(this, SLOT(configureSettings()), actionCollection()); KToggleAction *soundAction = new KToggleAction(i18n("&Play sounds"), this); soundAction->setChecked(Settings::sounds()); actionCollection()->addAction(QStringLiteral("sounds"), soundAction); connect(soundAction, &KToggleAction::triggered, this, &KBlocksWin::setSoundsEnabled); // TODO mScore = new QLabel(i18n("Points: 0 - Lines: 0 - Level: 0")); statusBar()->addPermanentWidget(mScore); connect(mpGameScene, &KBlocksScene::scoreChanged, this, &KBlocksWin::onScoreChanged); connect(mpGameScene, &KBlocksScene::isHighscore, this, &KBlocksWin::onIsHighscore); Kg::difficulty()->addStandardLevelRange( KgDifficultyLevel::Easy, KgDifficultyLevel::Hard ); KgDifficultyGUI::init(this); connect(Kg::difficulty(), &KgDifficulty::currentLevelChanged, this, &KBlocksWin::levelChanged); setupGUI(); }
void KBlocksWin::setupGUILayout() { QAction *action; action = KStandardGameAction::gameNew(this, SLOT(singleGame()), actionCollection()); action->setText(i18n("Single Game")); actionCollection()->addAction( QLatin1String( "newGame" ), action); action = new KAction(this); action->setText(i18n("Human vs AI")); actionCollection()->addAction( QLatin1String( "pve_step" ), action); connect(action, SIGNAL(triggered(bool)), this, SLOT(pveStepGame())); m_pauseAction = KStandardGameAction::pause(this, SLOT(pauseGame()), actionCollection()); actionCollection()->addAction( QLatin1String( "pauseGame" ), m_pauseAction); action = KStandardGameAction::highscores(this, SLOT(showHighscore()), actionCollection()); actionCollection()->addAction( QLatin1String( "showHighscores" ), action); action = KStandardGameAction::quit(this, SLOT(close()), actionCollection()); actionCollection()->addAction( QLatin1String( "quit" ), action); KStandardAction::preferences(this, SLOT(configureSettings()), actionCollection()); KAction* soundAction = new KToggleAction(i18n("&Play sounds"), this); soundAction->setChecked(Settings::sounds()); actionCollection()->addAction( QLatin1String( "sounds" ), soundAction); connect(soundAction, SIGNAL(triggered(bool)), this, SLOT(setSoundsEnabled(bool))); // TODO statusBar()->insertItem( i18n("Points: 0 - Lines: 0 - Level: 0"), 0 ); connect(mpGameScene, SIGNAL(scoreChanged(int,int,int,int)), this, SLOT(onScoreChanged(int,int,int,int))); connect(mpGameScene, SIGNAL(isHighscore(int,int,int)), this, SLOT(onIsHighscore(int,int,int))); Kg::difficulty()->addStandardLevelRange( KgDifficultyLevel::Easy, KgDifficultyLevel::Hard ); KgDifficultyGUI::init(this); connect(Kg::difficulty(), SIGNAL(currentLevelChanged(const KgDifficultyLevel*)), SLOT(levelChanged())); setupGUI(); }
bool GameScene::confirmExit() { if (gameProfile->isGameStarted()) { pauseGame(); } if (menu->isActive()) menu->hide(); if (dconfirm->exec(tr("Any unsaved progress will be lost.\nAre you sure you want to quit JAG?"))) return true; if (menu->isActive()) menu->showNormal(); if (gameProfile->isGamePaused()) { menu->activate(false); continueGame(); } return false; }
//------------------------------------------------------------------------------ void Window::createActions(){ pNewGame = new QAction("&New Game", this); pNewGame->setShortcut(QKeySequence(Qt::Key_N)); pNewGame->setStatusTip("Start a new game"); connect(pNewGame, SIGNAL(triggered()), glWidget, SLOT(newGame())); pPauseGame = new QAction("&Pause Game", this); pPauseGame->setShortcut(QKeySequence(Qt::Key_P)); pPauseGame->setStatusTip("Pause the current game"); connect(pPauseGame, SIGNAL(triggered()), glWidget, SLOT(pauseGame())); pQuitGame = new QAction("&Quit", this); pQuitGame->setShortcut(QKeySequence(Qt::Key_Q)); pQuitGame->setStatusTip("Quit VexTris"); connect(pQuitGame, SIGNAL(triggered()), this, SLOT(close())); pAboutGame = new QAction("&About", this); pAboutGame->setShortcut(QKeySequence(Qt::Key_A)); pAboutGame->setStatusTip("About VexTrix"); connect(pAboutGame, SIGNAL(triggered()), this, SLOT(aboutVexTris())); }
int Board::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QWidget::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: pauseChecked((*reinterpret_cast< bool(*)>(_a[1]))); break; case 1: pauseAvailable((*reinterpret_cast< bool(*)>(_a[1]))); break; case 2: finished((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< int(*)>(_a[2])),(*reinterpret_cast< int(*)>(_a[3])),(*reinterpret_cast< int(*)>(_a[4]))); break; case 3: newGame(); break; case 4: loadGame(); break; case 5: saveGame(); break; case 6: pauseGame((*reinterpret_cast< bool(*)>(_a[1]))); break; case 7: loadSettings(); break; case 8: focusChanged(); break; case 9: updateStatusMessage(); break; case 10: move(); break; default: ; } _id -= 11; } return _id; }
int check_keys(XEvent *e, Game *g){ g->mouseThrustOn=false; //keyboard input? static int shift=0; int key = XLookupKeysym(&e->xkey, 0); //Log("key: %i\n", key); if (e->type == KeyRelease) { keys[key]=0; if (key == XK_Shift_L || key == XK_Shift_R) shift=0; if(key == XK_w){ paddle1YVel = 0; paddle1.setYPos(paddle1.getYPos()); } if(key == XK_s){ paddle1YVel = 0; paddle1.setYPos(paddle1.getYPos()); } if(key == XK_o){ paddle2YVel = 0; paddle2.setYPos(paddle2.getYPos()); } if(key == XK_l){ paddle2YVel = 0; paddle2.setYPos(paddle2.getYPos()); } return 0; } if (e->type == KeyPress) { keys[key]=1; if (key == XK_Shift_L || key == XK_Shift_R) { shift=1; return 0; } if(key == XK_Return) { //printf("Enter pressed\n"); createSound2(); hud->setPaused(false); gameStarted = true; hud->setPlayer1Health(100); hud->setPlayer2Health(100); if (is_gameover == true){ hud->setIsShowWelcome(true); gameStarted = false; intro = 0; } else{ hud->setIsShowWelcome(false); init_ball_paddles(); //REINITIALIZE OBSTACLE POSITION AND VELIOCITY: obstacle->setXPos((1250 / 2.0) - 25); obstacle->setYPos(900 / 2.0); obstacle->setYVel(-5.0f); intro = 1; } is_gameover = false; timer.reset(); timer.start(); } if (hud->isShowHelpMenu()==false && hud->isShowWelcome()==false){ if (key == XK_p && hud->isPaused()==true){ hud->setPaused(false); resumeGame(); } else if (key == XK_p && hud->isPaused()==false){ hud->setPaused(true); pauseGame(); } else if (key == XK_q){//to quit out of game hud->setIsShowWelcome(true); hud->setPaused(false); gameStarted = false; intro = 0; } } if (hud->isShowWelcome() == true){ if (key == XK_Left) { bgTexture = generateTexture(bgTexture, bgImage1); selected_screen = LEFT; level = 1; } else if (key == XK_Right) { bgTexture = generateTexture(bgTexture, bgImage2); selected_screen = RIGHT; level = 2; } else if (key == XK_Up) { hud->setAI(false);//player 2 is human paddle2.setCpuPlayer(false); } else if (key == XK_Down){ hud->setAI(true);//player 2 is computer paddle2.setCpuPlayer(true); } else if (key == XK_h) { hud->setIsShowWelcome(false); hud->setIsShowHelpMenu(true); } return 0; } if (hud->isShowHelpMenu() == true){ if (key == XK_b){ //SHOW HELP MENU: hud->setIsShowHelpMenu(false); hud->setIsShowWelcome(true); } } } else { return 0; } float paddleSpeed = 20.0f; if (shift){} switch(key) { case XK_Escape: return 1; case XK_w: paddle1YVel = paddleSpeed; break; case XK_s: paddle1YVel = -paddleSpeed; break; case XK_a: break; case XK_d: break; case XK_o: paddle2YVel = paddleSpeed; break; case XK_l: paddle2YVel = -paddleSpeed; break; } return 0; }
void Game::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Up: { int x = six->getRect().x(); int y = six->getRect().y(); if(lockup==false) six->moveUp(x,y--); if(step==1)step=2; else if(step==2)step=1; if(step==3)step=4; else if(step==4)step=3; break; } case Qt::Key_Down: { int x = six->getRect().x(); int y = six->getRect().y(); if(lockdown==false) six->moveDown(x,y++); if(step==4)step=3; else if(step==3)step=4; if(step==2)step=1; else if(step==1)step=2; break; } case Qt::Key_Left: { int x = six->getRect().x(); if(lockleft==false) six->moveLeft(x--); if(step>2){ if(step==4)step=3; else if (step==3)step=4;//get step to set image } else step=3; break; } case Qt::Key_Right: {int x = six->getRect().x(); if(lockright==false) six->moveRight(x++); if(step<3){ if(step==1)step=2; else if (step==2)step=1;//get step to set image } else step=1; break; } case Qt::Key_P: { pauseGame(); } break; case Qt::Key_Space: { startGame(); cover->setOFF(false); } break; case Qt::Key_Escape: { qApp->exit(); } case Qt::Key_R://reset { gameStarted=false; startGame(); } break; default: QWidget::keyPressEvent(event); } }
Window::Window(QWidget *parent, Qt::WindowFlags wf) : QMainWindow(parent, wf) { QWidget* contents = new QWidget(this); setCentralWidget(contents); // Create preview m_preview = new QLabel(contents); m_preview->setFixedSize(80, 100); m_preview->setAutoFillBackground(true); { QPalette palette = m_preview->palette(); palette.setColor(m_preview->backgroundRole(), Qt::black); m_preview->setPalette(palette); } // Create level display m_level = new QLabel("0", contents); m_level->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_level->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); m_level->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); // Create lines display m_lines = new QLabel("0", contents); m_lines->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_lines->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); m_lines->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); // Create score display m_score = new QLabel("0", contents); m_score->setAlignment(Qt::AlignRight | Qt::AlignVCenter); m_score->setFrameStyle(QFrame::StyledPanel | QFrame::Sunken); m_score->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); // Create scoreboard m_score_board = new ScoreBoard(this); // Create board m_board = new Board(contents); connect(m_board, &Board::pauseAvailable, this, &Window::pauseAvailable); connect(m_board, &Board::nextPieceAvailable, m_preview, &QLabel::setPixmap); connect(m_board, &Board::levelUpdated, m_level, static_cast<void (QLabel::*)(int)>(&QLabel::setNum)); connect(m_board, &Board::linesRemovedUpdated, m_lines, static_cast<void (QLabel::*)(int)>(&QLabel::setNum)); connect(m_board, &Board::scoreUpdated, this, &Window::scoreUpdated); connect(m_board, static_cast<void (Board::*)(int,int,int)>(&Board::gameOver), m_score_board, &ScoreBoard::addHighScore); connect(m_board, static_cast<void (Board::*)(int,int,int)>(&Board::gameOver), this, &Window::gameOver); connect(m_board, &Board::gameStarted, this, &Window::newGame); // Create overlay message QLabel* message = new QLabel(tr("Click to start a new game."), contents); message->setAttribute(Qt::WA_TransparentForMouseEvents); message->setAlignment(Qt::AlignCenter); message->setStyleSheet( "QLabel {" "background-color: rgba(255, 255, 255, 200);" "color: black;" "margin: 0;" "padding: 0.5em;" "border-radius: 0.5em;" "}"); message->setWordWrap(true); connect(m_board, &Board::showMessage, message, &QLabel::show); connect(m_board, &Board::showMessage, message, &QLabel::setText); connect(m_board, &Board::hideMessage, message, &QLabel::hide); connect(m_board, &Board::hideMessage, message, &QLabel::clear); // Create menus QMenu* menu = menuBar()->addMenu(tr("&Game")); menu->addAction(tr("&New"), m_board, SLOT(newGame()), QKeySequence::New); m_pause_action = menu->addAction(tr("&Pause"), m_board, SLOT(pauseGame()), tr("P")); m_pause_action->setEnabled(false); m_resume_action = menu->addAction(tr("&Resume"), m_board, SLOT(resumeGame()), tr("P")); m_resume_action->setVisible(false); menu->addSeparator(); menu->addAction(tr("&Scores"), m_score_board, SLOT(show())); menu->addSeparator(); QAction* action = menu->addAction(tr("&Quit"), this, SLOT(close()), QKeySequence::Quit); action->setMenuRole(QAction::QuitRole); menu = menuBar()->addMenu(tr("&Settings")); menu->addAction(tr("Application &Language..."), this, SLOT(setLocale())); menu = menuBar()->addMenu(tr("&Help")); action = menu->addAction(tr("&About"), this, SLOT(about())); action->setMenuRole(QAction::AboutRole); action = menu->addAction(tr("About &Qt"), qApp, SLOT(aboutQt())); action->setMenuRole(QAction::AboutQtRole); // Layout window QGridLayout* layout = new QGridLayout(contents); layout->setMargin(12); layout->setSpacing(0); layout->setColumnStretch(0, 1); layout->setColumnMinimumWidth(1, 12); layout->setRowStretch(11, 1); layout->setRowMinimumHeight(2, 24); layout->setRowMinimumHeight(5, 24); layout->setRowMinimumHeight(8, 24); layout->addWidget(m_board, 0, 0, 12, 1); layout->addWidget(message, 0, 0, 12, 1, Qt::AlignCenter); layout->addWidget(new QLabel(tr("Next Piece"), contents), 0, 2, 1, 1, Qt::AlignCenter); layout->addWidget(m_preview, 1, 2, Qt::AlignCenter); layout->addWidget(new QLabel(tr("Level"), contents), 3, 2, 1, 1, Qt::AlignCenter); layout->addWidget(m_level, 4, 2); layout->addWidget(new QLabel(tr("Removed Lines"), contents), 6, 2, 1, 1, Qt::AlignCenter); layout->addWidget(m_lines, 7, 2); layout->addWidget(new QLabel(tr("Score"), contents), 9, 2, 1, 1, Qt::AlignCenter); layout->addWidget(m_score, 10, 2); // Restore window restoreGeometry(QSettings().value("Geometry").toByteArray()); }
/*! \brief Carries out the required actions for the specific key. * Precondition: a QKeyEvent is called. (a key is pressed) * Postcondition: Actions for specified key are carried out. * \param *event QT event pointer*/ void Game::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Left: // Left arrow was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } else if(!introPrompt1 && !introPrompt2) { if(paused) {pauseGame();} // unpause game if(lastDir != 'L' && gameStarted) { snake->goLeft(wrapAround); // Move snake left one block checkCollision(); // Check if snake collided with anything changedDir = TRUE; // Set changedDir to true lastDir = 'L'; // Set lastDir to 'L' repaint(); // calls a paint event } } } break; case Qt::Key_Right: // Right arrow was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } else if(!introPrompt1 && !introPrompt2) { if(paused) {pauseGame();} // unpause game if(lastDir != 'R' && gameStarted) { snake->goRight(wrapAround); // Move snake right one block checkCollision(); // Check if snake collided with anything changedDir = TRUE; // Set changedDir to true lastDir = 'R'; // Set lastDir to 'R' repaint(); // calls a paint event } } } break; case Qt::Key_Up: // Up arrow was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } else if(!introPrompt1 && !introPrompt2) { if(paused) {pauseGame();} // unpause game if(lastDir != 'U' && gameStarted) { snake->goUp(wrapAround); // Move snake Up one block checkCollision(); // Check if snake collided with anything changedDir = TRUE; // Set changedDir to true lastDir = 'U'; // Set lastDir to 'U' repaint(); // calls a paint event } } } break; case Qt::Key_Down: // Down arrow was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } else if(!introPrompt1 && !introPrompt2) { if(paused) {pauseGame();} // unpause game if(lastDir != 'D' && gameStarted) { snake->goDown(wrapAround); // Move snake down one block checkCollision(); // Check if snake collided with anything changedDir = TRUE; // Set changedDir to true lastDir = 'D'; // Set lastDir to 'D' repaint(); // calls a paint event } } } break; case Qt::Key_P: // 'P' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } else { pauseGame(); // pause/unpause game } } break; case Qt::Key_R: // 'R' was pressed { if(introPrompt2) //If intro prompt 2 screen is displayed, go back to intro screen 1 { //sets up variables for intro prompt 1 introPrompt1 =TRUE; introPrompt2 =FALSE; repaint(); // calls a paint event } else if(!introPrompt1) { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } /* Reloving UnPause/Resume/Restart ISSUES */ if(paused) { pauseGame(); //unpause game } stopGame(); // set up variables to end game and dispaly game over screen //sets up variables for intro prompt 1 introPrompt1 =TRUE; gameOver = FALSE; gameWon = FALSE; gameEnded = FALSE; repaint(); // calls a paint event } } break; // Move the apple case Qt::Key_M: // 'M' was pressed case Qt::Key_A: // 'A' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } /* Reloving Paused ISSUES */ else if(paused) { // do nothing } else if(gameStarted) //If game has started move the apple and switch food images { // Sets up variable to switch food images switchFood++;// increments Apple logo switcher switchFood %= 2; // if Apple logo switch equals 2, set it back to zero // Move the apple and making sure the apple is not on top oof any other object do{ if(winSpawn) food->moveFood(foodWinner,switchFood); else if(deathSpawn) food->moveFood(specialFood,switchFood); else food->moveFood(switchFood); }while(snake->checkBadFood(food)); } } break; // Grow the snake, but don't increase points case Qt::Key_G: // 'G' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } /* Reloving Paused ISSUES */ else if(paused) { // do nothing } else if(gameStarted && lastDir != ' ') { // grow snake, but don't increase points snake->grow(); growCount++; // If needed, Fix the growCount if(fixCount == TRUE) { growCount--; fixCount = FALSE; } } } break; // set up variable to paint specialFood and move specialFood (the Windows 8 logo) case Qt::Key_W: // 'W' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } /* Reloving Paused ISSUES */ else if(paused) { // do nothing } else if(gameStarted) { // set up variable to paint specialFood deathSpawn = TRUE; doOneTime = FALSE; // move specialFood making sure it is not on top oof any other object do{ specialFood->moveFood(food); }while(snake->checkBadFood(specialFood)); } } break; // set up variables to dispaly blue screen of death case Qt::Key_8: // '8' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } /* Reloving Paused ISSUES */ else if(paused) { // do nothing } else if(gameStarted) { blueScreenDeath(); // set up variables to dispaly blue screen of death } } break; // set up variable to paint foodWinner (the Linux logo) case Qt::Key_L: // 'L' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } /* Reloving Paused ISSUES */ else if(paused) { // do nothing } else if(gameStarted) { // set up variable to paint foodWinner (the Linux logo) spawnWinnerCount = 1000; doOneTime = TRUE; } } break; // set up variables to dispaly victory screen case Qt::Key_V: // 'V' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } /* Reloving Paused ISSUES */ else if(paused) { // do nothing } else if(gameStarted) { victory(); // set up variables to dispaly victory screen } } break; // During intro screen 2, this enables wrapAround and starts the game case Qt::Key_Y: // 'Y' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } if(introPrompt2) { wrapAround = TRUE; // enables wrapAround // starts the game introPrompt2 = FALSE; startGame(); } } break; // During intro screen 2, this disables wrapAround, doubles the points multiplier, and starts the game case Qt::Key_N: // 'N' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } if(introPrompt2) { wrapAround = FALSE;// disables wrapAround // starts the game introPrompt2 = FALSE; pointMulti = pointMulti*2; // doubles the points multiplier startGame(); } } break; // During intro screen 1, this sets up speed delay and points multiplier, // and then it will set up the variable for intro screen 2 case Qt::Key_1: // '1' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } if(introPrompt1) { // disables intro screen 1 introPrompt1 = FALSE; // sets up speed delay and points multiplier pointMulti = 1; speedDelay = 200; // set up the variable for intro screen 2 introPrompt2 = TRUE; repaint(); // calls a paint event } } break; // During intro screen 1, this sets up speed delay and points multiplier, // and then it will set up the variable for intro screen 2 case Qt::Key_2: // '2' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } if(introPrompt1) { // disables intro screen 1 introPrompt1 = FALSE; // sets up speed delay and points multiplier pointMulti = 2; speedDelay = 169; // set up the variable for intro screen 2 introPrompt2 = TRUE; repaint(); // calls a paint event } } break; // During intro screen 1, this sets up speed delay and points multiplier, // and then it will set up the variable for intro screen 2 case Qt::Key_3: // '3' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } if(introPrompt1) { // disables intro screen 1 introPrompt1 = FALSE; // sets up speed delay and points multiplier pointMulti = 3; speedDelay = 138; // set up the variable for intro screen 2 introPrompt2 = TRUE; repaint(); // calls a paint event } } break; // During intro screen 1, this sets up speed delay and points multiplier, // and then it will set up the variable for intro screen 2 case Qt::Key_4: // '4' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } if(introPrompt1) { // disables intro screen 1 introPrompt1 = FALSE; // sets up speed delay and points multiplier pointMulti = 4; speedDelay = 107; // set up the variable for intro screen 2 introPrompt2 = TRUE; repaint(); // calls a paint event } } break; // During intro screen 1, this sets up speed delay and points multiplier, // and then it will set up the variable for intro screen 2 case Qt::Key_5: // '5' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } if(introPrompt1) { // disables intro screen 1 introPrompt1 = FALSE; // sets up speed delay and points multiplier pointMulti = 5; speedDelay = 75; // set up the variable for intro screen 2 introPrompt2 = TRUE; repaint(); // calls a paint event } } break; // During intro screen 1, this sets up speed delay and points multiplier, // and then it will set up the variable for intro screen 2 case Qt::Key_9: // '9' was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } if(introPrompt1) { // disables intro screen 1 introPrompt1 = FALSE; // sets up speed delay and points multiplier pointMulti = 1000; speedDelay = 0; // set up the variable for intro screen 2 introPrompt2 = TRUE; repaint(); // calls a paint event } } break; // If Victory or Game Over screen, sets up the variables for intro screen 1. // If BSOD, then sets up variables to end game and dispaly game over screen. case Qt::Key_Space: // The Space Bar was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } else if(!introPrompt1 && !introPrompt2 && gameEnded) { // sets up the variables for intro screen 1 introPrompt1 =TRUE; gameOver = FALSE; gameWon = FALSE; gameEnded = FALSE; repaint(); // calls a paint event } } break; // Exits App case Qt::Key_Escape: // The Esc key was pressed { qApp->exit(); } break; // During BSOD, sets up variables to end game and dispaly game over screen default: // Any other Key was pressed { if(bSOD) { bSOD = FALSE; // set up variable to disable blue screen of death stopGame(); // set up variables to end game and dispaly game over screen } } QWidget::keyPressEvent(event); } }
MainWindow::MainWindow() : QMainWindow(){ // Initialize variables pvx = 0; pvy = 0; attack = 1; pattack = false; paused = false; maxhp = 10; level = 1; pauseMe = 0; human = NULL; anim = 0; // Master Timer timer = new QTimer; gameSpeed = 14; timer->setInterval(gameSpeed); srand(time(0)); // Secondary Timer timer2 = new QTimer; timer2->setInterval(100); // Load ALL THE PICTURES ab1 = new QPixmap("images/actualblue-1.png"); ab2 = new QPixmap("images/actualblue-2.png"); ag1 = new QPixmap("images/actualgreen-1.png"); ag2 = new QPixmap("images/actualgreen-2.png"); apl = new QPixmap("images/actualplayer.png"); ap = new QPixmap("images/actualpurple.png"); ar1 = new QPixmap("images/actualred-1.png"); ar2 = new QPixmap("images/actualred-2.png"); ar3 = new QPixmap("images/actualred-3.png"); ay = new QPixmap("images/actualyellow.png"); app = new QPixmap("images/actualpink.png"); pbullet = new QPixmap("images/bullet.png"); bbullet = new QPixmap("images/bluebullet.png"); gbullet = new QPixmap("images/greenbullet.png"); ppbullet = new QPixmap("images/pinkbullet.png"); ybullet = new QPixmap("images/yellowbullet.png"); widebulletpic = new QPixmap("images/redbullet.png"); heartpic = new QPixmap("images/heart.png"); rainbow = new QPixmap("images/rainbow.png"); bg1 = new QPixmap("images/background.png"); bg2 = new QPixmap("images/background2.png"); bg3 = new QPixmap("images/background3.png"); // This is for the hearts h1 = new QGraphicsPixmapItem(*heartpic); h1->setPos(400, 575); h1->setVisible(false); h2 = new QGraphicsPixmapItem(*heartpic); h2->setPos(375, 575); h2->setVisible(false); h3 = new QGraphicsPixmapItem(*heartpic); h3->setPos(350, 575); h3->setVisible(false); h4 = new QGraphicsPixmapItem(*heartpic); h4->setPos(325, 575); h4->setVisible(false); h5 = new QGraphicsPixmapItem(*heartpic); h5->setPos(300, 575); h5->setVisible(false); // Initialize the Scenes and Views gameScene = new GScene(this); gameView = new QGraphicsView(gameScene); mainScene = new QGraphicsScene; mainView = new QGraphicsView(mainScene); mainView->setWindowTitle("Starships (were meant to fly...)"); // Now add the hearts gameScene->addItem(h1); gameScene->addItem(h2); gameScene->addItem(h3); gameScene->addItem(h4); gameScene->addItem(h5); // Make the layouts holder = new QWidget; holder2 = new QWidget; holder3 = new QWidget; layout = new QVBoxLayout(holder); layout2 = new QHBoxLayout(holder2); layout3 = new QHBoxLayout(holder3); //Set the attributes to the game scene QBrush bg(*bg1); gameScene->setBackgroundBrush(bg); gameScene->setSceneRect(0,0,425,600); gameView->setFixedSize(430,605); gameView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); gameView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Make buttons // Players love buttons startB = new QPushButton("Start"); startB->setGeometry(160, 475, 100, 60); startB->setStyleSheet("background-color:rgba(0,0,0,0); color:#ffffff; font-size:36px;"); gameScene->addWidget(startB); restartB = new QPushButton("Start"); restartB->setFixedHeight(28); pauseB = new QPushButton("Pause"); pauseB->setFixedHeight(28); endB = new QPushButton("Quit"); endB->setFixedHeight(28); nameB = new QTextEdit; nameB->setFixedHeight(28); nameB->setStyleSheet("background-color:rgb(0,0,0); color:#ffffff;"); // Connecting the timers and buttons connect(timer, SIGNAL(timeout()), this, SLOT(handleTimer())); connect(timer2, SIGNAL(timeout()), this, SLOT(nextLevel())); connect(startB, SIGNAL(clicked()), this, SLOT(startGame())); connect(pauseB, SIGNAL(clicked()), this, SLOT(pauseGame())); connect(endB, SIGNAL(clicked()), this , SLOT(quitGame())); connect(restartB, SIGNAL(clicked()), this , SLOT(restartGame())); // Make the labels nameL = new QTextEdit; nameL->setStyleSheet("background-color:rgb(0,0,0); color:#ffffff;"); nameL->setFixedHeight(28); nameL->setFixedWidth(200); nameL->setReadOnly(true); layout3->addWidget(nameL); scoreL = new QTextEdit; scoreL->setStyleSheet("background-color:rgb(0,0,0); color:#ffffff;"); scoreL->setFixedHeight(28); scoreL->setFixedWidth(130); scoreL->setReadOnly(true); layout3->addWidget(scoreL); hpL = new QTextEdit; hpL->setStyleSheet("background-color:rgb(0,0,0); color:#ffffff;"); hpL->setFixedHeight(28); hpL->setFixedWidth(80); hpL->setReadOnly(true); layout3->addWidget(hpL); errorL = new QLabel; errorL->setStyleSheet("background-color:rgba(0,0,0,1); color:#ffffff; font-size:24px;"); errorL->setGeometry(QRect(60,520,380,80)); gameScene->addWidget(errorL); nextWave = new QLabel("Get ready for the next wave!"); nextWave->setStyleSheet("background-color:rgba(0,0,0,1); color:#ffffff; font-size:24px;"); nextWave->setGeometry(QRect(55,220,380,80)); nextWave->hide(); gameScene->addWidget(nextWave); endScore = new QLabel; endScore->setStyleSheet("background-color:rgba(0,0,0,1); color:#ffffff; font-size:26px;"); endScore->setGeometry(QRect(0,40,425,80)); endScore->setAlignment(Qt::AlignCenter); endScore->hide(); gameScene->addWidget(endScore); scoreList = new QLabel; scoreList->setStyleSheet("background-color:rgba(0,0,0,1); color:#ffffff; font-size:26px;"); scoreList->setGeometry(QRect(0,55,425,500)); scoreList->setAlignment(Qt::AlignCenter); scoreList->hide(); gameScene->addWidget(scoreList); // Set the layouts layout2->addWidget(restartB); layout2->addWidget(pauseB); layout2->addWidget(endB); layout->addWidget(holder2); layout->addWidget(gameView); layout->addWidget(nameB); holder3->setVisible(false); layout->addWidget(holder3); layout->setContentsMargins(0, 0, 0, 0); layout->setMargin(0); layout2->setContentsMargins(0, 0, 0, 0); layout2->setMargin(0); layout3->setContentsMargins(0, 0, 0, 0); layout3->setMargin(0); mainScene->addWidget(holder); mainView->setFixedSize(460,710); mainView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); mainView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); // Setting these for faster rendering gameView->setAttribute(Qt::WA_OpaquePaintEvent); gameView->setAttribute(Qt::WA_NoSystemBackground); mainView->setAttribute(Qt::WA_OpaquePaintEvent); mainView->setAttribute(Qt::WA_NoSystemBackground); mainView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); gameView->setViewportUpdateMode(QGraphicsView::FullViewportUpdate); }