Пример #1
1
int main()
{
    enum GameState
    {
        MainMenu,
        Playing,
        GameOver
    };

    GameState state = GameState::MainMenu;
    VideoMode videoMode(SCREEN_WIDTH, SCREEN_HEIGHT);
    RenderWindow renderWindow(videoMode, "SFML Tetris");
    Event gameEvent;
    Texture backgroundTexture;
    Texture brickPreviewBackground;
    Texture gameOverBackground;
    Texture mainMenuBackground;
    Sprite mainMenuBackgroundSprite;
    Sprite brickPreviewSprite;
    Sprite backgroundSprite;
    Sprite gameOverBackgroundSprite;
    SoundBuffer dropSoundBuffer;
    Sound dropSound;
    Music music;
    Text scoreHeaderText("Score: ");
    Text scoreDisplayText;
    Text levelHeaderText("Level: ");
    Text levelDisplayText;
    Text nextBrickText("Next: ");
    Text gameOverHeaderText("\t  GAME OVER!\nHere are your final stats:");
    Text mainMenuHeaderText("SFML TETRIS!");
    Text mainMenuStartText("Start");
    Text mainMenuQuitText("Quit");
    Text brickCountText[NUMBER_OF_BRICK_TYPES];
    bool gameBoard[GB_HEIGHT][GB_WIDTH];
    unsigned int score = 0;
    unsigned int level = 1;
    unsigned int totalLines = 0;
    unsigned int brickCount[NUMBER_OF_BRICK_TYPES] = {0};
    vector<Brick> brickQueue;
    vector<Brick> brickList;
    Clock brickLockTimer;
    Clock brickFallTimer;
    bool isCheckingLockTime = false;

    backgroundTexture.LoadFromFile("Images/background.png");
    brickPreviewBackground.LoadFromFile("Images/previewBG.png");
    gameOverBackground.LoadFromFile("Images/gameOverBG.png");
    mainMenuBackground.LoadFromFile("Images/mainMenuBG.png");

    brickPreviewSprite.SetTexture(brickPreviewBackground);
    brickPreviewSprite.SetPosition(450, 150);

    backgroundSprite.SetTexture(backgroundTexture);

    gameOverBackgroundSprite.SetTexture(gameOverBackground);
    gameOverBackgroundSprite.SetPosition(110, 82);

    mainMenuBackgroundSprite.SetTexture(mainMenuBackground);

    scoreHeaderText.SetCharacterSize(TEXT_CHAR_SIZE);
    scoreHeaderText.SetPosition(450, 20);

    char* scoreDisplayBuffer = new char;
    scoreDisplayText.SetCharacterSize(TEXT_CHAR_SIZE);
    scoreDisplayText.SetPosition(520, 20);

    levelHeaderText.SetCharacterSize(TEXT_CHAR_SIZE);
    levelHeaderText.SetPosition(450, 60);

    char* levelDisplayBuffer = new char;
    levelDisplayText.SetCharacterSize(TEXT_CHAR_SIZE);
    levelDisplayText.SetPosition(520, 60);

    nextBrickText.SetCharacterSize(TEXT_CHAR_SIZE);
    nextBrickText.SetPosition(450, 120);

    gameOverHeaderText.SetCharacterSize(TEXT_CHAR_SIZE);
    gameOverHeaderText.SetPosition(210, 265);

    mainMenuHeaderText.SetCharacterSize(40);
    mainMenuHeaderText.SetPosition(180, 50);

    mainMenuStartText.SetCharacterSize(32);
    mainMenuStartText.SetPosition(285, 210);

    mainMenuQuitText.SetCharacterSize(32);
    mainMenuQuitText.SetPosition(285, 310);

    char* brickCountTextBuffer[NUMBER_OF_BRICK_TYPES];
    for (int i = 0; i < NUMBER_OF_BRICK_TYPES; i++)
    {
        brickCountTextBuffer[i] = new char;
        brickCountText[i].SetPosition(100, 50 * (i + 1));
    }

    dropSoundBuffer.LoadFromFile("Sounds/drop.wav");
    dropSound.SetBuffer(dropSoundBuffer);

    for (int i = 0; i < GB_HEIGHT; i++)
    {
        for (int j = 0; j < GB_WIDTH; j++)
        {
            gameBoard[i][j] = false;
        }
    }

    RefillBrickQueue(&brickQueue);
    Brick activeBrick = PullBrickFromQueue(&brickQueue);
    Brick previewBrick = PullBrickFromQueue(&brickQueue);
    previewBrick.SetPreviewPosition();

    bool isGameOver = false;

    while (renderWindow.IsOpen())
    {
        switch (state)
        {
        case GameState::MainMenu:
        {
            while (renderWindow.PollEvent(gameEvent))
            {
                if (gameEvent.Type == Event::Closed || gameEvent.Key.Code == Keyboard::Escape)
                {
                    renderWindow.Close();
                }
                else if (gameEvent.Type == Event::MouseButtonPressed)
                {
                    Vector2i mousePos = Mouse::GetPosition(renderWindow);

                    if (mousePos.x >= 220 && mousePos.x <= 420 &&
                            mousePos.y >= 200 && mousePos.y <= 260)
                    {
                        state = GameState::Playing;
                    }
                    else if ((mousePos.x >= 220 && mousePos.x <= 420 &&
                              mousePos.y >= 300 && mousePos.y <= 360) ||
                             gameEvent.Key.Code == Keyboard::Escape)
                    {
                        renderWindow.Close();
                    }
                }
            }

            renderWindow.Draw(mainMenuBackgroundSprite);
            renderWindow.Draw(mainMenuHeaderText);
            renderWindow.Draw(mainMenuStartText);
            renderWindow.Draw(mainMenuQuitText);
            renderWindow.Display();
            break;
        }

        case GameState::GameOver:
        {
            Text gameOverScoreHeaderText = scoreHeaderText;
            gameOverScoreHeaderText.SetPosition(130, 320);
            Text gameOverScoreDisplayText = scoreDisplayText;
            gameOverScoreDisplayText.SetPosition(210, 320);
            Text gameOverLevelHeaderText = levelHeaderText;
            gameOverLevelHeaderText.SetPosition(130, 350);
            Text gameOverLevelDisplayText = levelDisplayText;
            gameOverLevelDisplayText.SetPosition(210, 350);

            while (renderWindow.PollEvent(gameEvent))
            {
                if (gameEvent.Type == Event::Closed || gameEvent.Key.Code == Keyboard::Escape)
                {
                    renderWindow.Close();
                }
            }

            renderWindow.Draw(gameOverBackgroundSprite);
            renderWindow.Draw(gameOverHeaderText);
            renderWindow.Draw(gameOverScoreHeaderText);
            renderWindow.Draw(gameOverScoreDisplayText);
            renderWindow.Draw(gameOverLevelHeaderText);
            renderWindow.Draw(gameOverLevelDisplayText);
            renderWindow.Display();
            break;
        }

        case GameState::Playing:
        {
            if (activeBrick.IsLocked())
            {
                dropSound.Play();
                brickList.push_back(activeBrick);
                brickCount[(int)activeBrick.GetBrickType()]++;
                int linesCleared = 0;

                for (int i = 0; i < SPRITES_IN_BRICK; i++)
                {
                    if (activeBrick.GetSpriteYPosition(i) < BRICK_UPPER_BOUNDRY)
                    {
                        state = GameState::GameOver;
                        break;
                    }
                    else
                    {
                        gameBoard[activeBrick.GetSpriteYPosition(i)][activeBrick.GetSpriteXPosition(i)] = true;
                    }
                }

                if (state == GameState::GameOver)
                {
                    break;
                }

                //Check if there are any full rows that need to be cleared.
                for (int i = BRICK_UPPER_BOUNDRY; i < GB_HEIGHT; i++)
                {
                    for (int j = 0; j < GB_WIDTH; j++)
                    {
                        if (gameBoard[i][j])
                        {
                            if (j == GB_WIDTH - 1)
                            {
                                ClearRow(&brickList, i, gameBoard);
                                linesCleared++;
                                totalLines++;

                                if (totalLines % 8 == 0 && level < LEVEL_MAX)
                                {
                                    level++;
                                }
                            }
                            else
                            {
                                continue;
                            }
                        }
                        else
                        {
                            break;
                        }
                    }
                }

                if (linesCleared > 0)
                {
                    if (linesCleared > 1 && linesCleared < 4)
                    {
                        score += (linesCleared * MULTI_LINE_CLEAR_SCORE) + BRICK_LOCK_SCORE;
                    }
                    else if (linesCleared == 4)
                    {
                        score += TETRIS_CLEAR_SCORE + BRICK_LOCK_SCORE;
                    }
                    else
                    {
                        score += SINGLE_LINE_CLEAR_SCORE + BRICK_LOCK_SCORE;
                    }
                }
                else
                {
                    score += BRICK_LOCK_SCORE;
                }

                activeBrick = previewBrick;
                activeBrick.SetActivePosition();
                previewBrick = PullBrickFromQueue(&brickQueue);
                previewBrick.SetPreviewPosition();
            }

            else
            {
                Time fallTimer = brickFallTimer.GetElapsedTime();
                Time lockTimer = brickLockTimer.GetElapsedTime();
                float dropSpeed = 1 - (float)(level * 0.05f);

                if (!IsBottomCollision(activeBrick, gameBoard) && fallTimer.AsSeconds() >= dropSpeed)
                {
                    for (int i = 0; i < SPRITES_IN_BRICK; i++)
                    {
                        activeBrick.SetSpriteYPosition(i, 1);
                        brickFallTimer.Restart();
                        isCheckingLockTime = false;
                    }
                }

                else if (IsBottomCollision(activeBrick, gameBoard))
                {
                    if (!isCheckingLockTime)
                    {
                        isCheckingLockTime = true;
                        brickLockTimer.Restart();
                    }

                    else if (lockTimer.AsSeconds() >= 0.5f)
                    {
                        activeBrick.LockBrick();
                        isCheckingLockTime = false;
                    }
                }

            }

            while (renderWindow.PollEvent(gameEvent))
            {
                if (gameEvent.Type == Event::Closed || gameEvent.Key.Code == Keyboard::Escape)
                {
                    renderWindow.Close();
                }

                if (gameEvent.Type == Event::KeyPressed)
                {
                    CheckInput(&gameEvent, &activeBrick, gameBoard, &score);
                }
            }

            scoreDisplayText.SetString(_itoa(score, scoreDisplayBuffer, 10));
            levelDisplayText.SetString(_itoa(level, levelDisplayBuffer, 10));

            for (int i = 0; i < NUMBER_OF_BRICK_TYPES; i++)
            {
                brickCountText[i].SetString(_itoa(brickCount[i], brickCountTextBuffer[i], 10));
            }

            renderWindow.Clear(Color(0, 255, 255));
            renderWindow.Draw(backgroundSprite);
            renderWindow.Draw(scoreHeaderText);
            renderWindow.Draw(scoreDisplayText);
            renderWindow.Draw(levelHeaderText);
            renderWindow.Draw(levelDisplayText);
            renderWindow.Draw(brickPreviewSprite);
            renderWindow.Draw(nextBrickText);

            for (int i = 0; i < NUMBER_OF_BRICK_TYPES; i++)
            {
                renderWindow.Draw(brickCountText[i]);
            }

            for (int i = 0; i < brickList.size(); i++)
            {
                for (int j = 0; j < SPRITES_IN_BRICK; j++)
                {
                    renderWindow.Draw(brickList[i].GetSpriteArray()[j]);
                }
            }

            for (int i = 0; i < SPRITES_IN_BRICK; i++)
            {
                renderWindow.Draw(activeBrick.GetSpriteArray()[i]);
                renderWindow.Draw(previewBrick.GetSpriteArray()[i]);
            }
            renderWindow.Display();
            break;

        }	//END CASE

        }	//END SWITCH

    } //END GAME LOOP

    return 0;
}
Пример #2
0
int main()
{
    // Create main window
    WindowSettings Settings;
    //Settings.AntialiasingLevel = 4;
    RenderWindow application(VideoMode(800, 600), "Game", (Style::Close | Style::Resize), Settings);
    application.PreserveOpenGLStates(true);
    application.UseVerticalSync(true);

    // Setup rendering
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LEQUAL);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClearColor(0.f, 0.f, 0.f, 0.f);

    // Setup an ortho projection
    glViewport(0, 0, 800, 600);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.f, 800.f, 600.f, 0.f, 0.f, 100.f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // Gather a pointer to the input system
    const Input& input = application.GetInput();

    // Create a clock for measuring the time elapsed
    Clock clock;

    // Create the game object
    Game game(input);
    game.init();

    // Start game loop
    while (application.IsOpened())
    {
        // Give the game mouse screen related's position
        game.setMousePosition(input.GetMouseX(), input.GetMouseY());

        // Process events
        Event event;
        while (application.GetEvent(event))
        {
            // Close window : exit
            if (event.Type == Event::KeyPressed && event.Key.Code == Key::Escape)
            {
                application.Close();
            }

            switch (event.Type)
            {
                case Event::Closed:
                    application.Close();
                    break;

                case Event::Resized:
                    game.onEvent(&event);
                    onWindowResized(event.Size.Width, event.Size.Height);
                    break;

                case Event::MouseButtonPressed:
                    game.onEvent(&event);
                    break;

                case Event::LostFocus:
                case Event::GainedFocus:
                case Event::TextEntered:
                case Event::KeyPressed:
                case Event::KeyReleased:
                case Event::MouseWheelMoved:
                case Event::MouseButtonReleased:
                case Event::MouseMoved:
                case Event::MouseEntered:
                case Event::MouseLeft:
                case Event::JoyButtonPressed:
                case Event::JoyButtonReleased:
                case Event::JoyMoved:
                case Event::Count:
                    break;
            }
        }

        // Clear depth buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        //Update
        game.update(clock.GetElapsedTime());
        clock.Reset();

        // Draw...
        game.draw();

        // Finally, display the rendered frame on screen
        application.Display();
    }

    return EXIT_SUCCESS;
}
Пример #3
0
// Engine
bool Game::Update() {
        while(GetEvent(_event)) {
            // FABRICATION DE LA JAUGE
            if ( _event.Type == Event::KeyPressed && _event.Key.Code == Key::Space ) {
                if ( space == false && refire == true) {
                    space = true;
                    fire = false;
                    refire = false;
                    ratio = 0.0;
                    btime.Reset();
                }
            }
            if ( _event.Type == Event::MouseButtonPressed && _event.MouseButton.Button == Mouse::Left ) {
                Projectile * p = new Projectile();
                Artillery * a = static_cast<Artillery*>(_units[0]);
                a->LoadProjectile(p);
                _projectiles.push_back(p);
                _world->AddObject(p);
            }
            if ( _event.Type == Event::MouseButtonPressed && _event.MouseButton.Button == Mouse::Right ) {
                for( vector<Projectile*>::iterator it = _projectiles.begin(); it != _projectiles.end();) {
                    _world->DelObject((*it));
                    delete (*it);
                    _projectiles.erase(it);
                }
            }
            if ( _event.Type == Event::KeyPressed && _event.Key.Code == Key::H )
                hitbox ^= 1;

            if ( _event.Type == Event::KeyPressed && _event.Key.Code == Key::P )
                pause ^= 1;

            if ( _event.Type == Event::KeyPressed && _event.Key.Code == Key::N )
                if ( pause ) _world->Update();
        }
        /* INPUTS */
        if ( _win->GetInput().IsKeyDown(Key::Right) ) CameraMove(20);
        else if ( _win->GetInput().IsKeyDown(Key::Left)) CameraMove(-20);

        /* [Camera] Zoom Control */
        if ( _win->GetInput().IsKeyDown(Key::Down ) ) {
            if ( _baseZoom - 0.1 >= 0.3) {
                _baseZoom -= 0.1;
                float tmpmv = 382 *(-_baseZoom + 1);
                _camera.SetFromRect( FloatRect(_baseMoveX, 0-tmpmv, _baseMoveX+1024, 768-tmpmv  ));
                _camera.Zoom(_baseZoom);
            }
        }

        if ( _win->GetInput().IsKeyDown(Key::Up ) ) {
            if ( _baseZoom + 0.1 <= 1.0) {
                _baseZoom += 0.1;
                float tmpmv = 382 *(-_baseZoom + 1);
                _camera.SetFromRect( FloatRect(_baseMoveX, 0-tmpmv, _baseMoveX+1024, 768-tmpmv));
                _camera.Zoom(_baseZoom);
            }
        }


        if ( _win->GetInput().IsKeyDown(Key::Space ) ) {
            if ( space == true && fire == false ) {
                ratio = btime.GetElapsedTime() / 2.0;
                if ( ratio >= 1.0 ) {
                    ratio = 1.0;
                    fire = true;
                    space = false;
                }
                float angle = 90.0 - ( 180 * ratio);
                _HUD.GetElement(_idArrow)->SetRotation(angle);
            }

        }  else { if ( space == true ) { space = false; fire = true; } refire = true;}

        if ( fire ) {
                fire = false;
                _motions->AddMotion( _db->GetMotion("Catapult_Attack"), _units[0]);
        }

        /* PHYS ENGINE */
        if ( !pause ) _world->Update();

        /* ANIMATIONS */
        MotionSystem::MResp * resp = _motions->Compute();
        if ( resp ) {
            if ( resp->_value == MotionSystem::Fire )
                resp->_unit->Fire(ratio);
                Artillery * a = static_cast<Artillery*>(resp->_unit);
                a->CanonRotate(0);
        }

        return 1;
}
Пример #4
0
int main()
{
    // Create main window
    WindowSettings Settings;
    Settings.AntialiasingLevel = 4;
    Settings.StencilBits = 8;
    RenderWindow application(VideoMode(SCREEN_WIDTH, SCREEN_HEIGHT), "Game", (Style::Close | Style::Resize), Settings);
    application.PreserveOpenGLStates(true);
    application.UseVerticalSync(false);
    application.SetFramerateLimit(0);

    // Setup rendering
    glShadeModel(GL_SMOOTH);
    glCullFace(GL_FRONT);
    //glEnable(GL_POINT_SMOOTH);
    //glEnable(GL_LINE_SMOOTH);
    //glHint(GL_POINT_SMOOTH_HINT, GL_NICEST);
    //glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
    glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

    // Vertex buffer objects
    #if USE_VBO
    glEnableClientState(GL_COLOR_ARRAY);
    glEnableClientState(GL_NORMAL_ARRAY);
    glEnableClientState(GL_VERTEX_ARRAY);
    #endif

    // Default values
    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    glDisable(GL_STENCIL_TEST);
    glDepthMask(GL_FALSE);
    glColorMask(GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO);

    // Clear values
    glClearDepth(GL_ONE);
    glClearStencil(GL_ZERO);
    glClearColor(GL_ZERO, GL_ZERO, GL_ZERO, GL_ZERO);

    // Setup window
    setupWindow(SCREEN_WIDTH, SCREEN_HEIGHT);

    // Gather a pointer to the input system
    const Input& input = application.GetInput();

    // Create a clocks for measuring the time elapsed
    Clock gameClock;
    Clock clock;

    // Create the game object
    Game game;
    game.init();

    // Start game loop
    while (application.IsOpened())
    {
        // Give the game mouse screen related's position
        game.setMousePosition(input.GetMouseX(), input.GetMouseY());

        // Process events
        Event event;
        while (application.GetEvent(event))
        {
            // Close window : exit
            if (event.Type == Event::KeyPressed && event.Key.Code == Key::Escape)
            {
                application.Close();
            }

            switch (event.Type)
            {
                case Event::Closed:
                    application.Close();
                    break;

                case Event::Resized:
                    game.onEvent(&event);
                    onWindowResized(event.Size.Width, event.Size.Height);
                    break;

                case Event::MouseButtonPressed:
                    game.onEvent(&event);
                    break;

                case Event::LostFocus:
                case Event::GainedFocus:
                case Event::TextEntered:
                case Event::KeyPressed:
                case Event::KeyReleased:
                case Event::MouseWheelMoved:
                case Event::MouseButtonReleased:
                case Event::MouseMoved:
                case Event::MouseEntered:
                case Event::MouseLeft:
                case Event::JoyButtonPressed:
                case Event::JoyButtonReleased:
                case Event::JoyMoved:
                case Event::Count:
                    break;
            }
        }

        // Reset matix
        glLoadIdentity();

        // Isometric angle
        glRotatef(30.f, 1.f, 0.f, 0.f);
        glRotatef(-45.f, 0.f, 1.f, 0.f);

        // Scale
        glScaled(sqrt(1/2.0), sqrt(1/3.0), sqrt(1/2.0));

        //Update
        game.update(gameClock.GetElapsedTime());
        gameClock.Reset();

        // Framerate
        frameCount ++;
        if (clock.GetElapsedTime() >= 1.f)
        {
            std::cout << "Framerate: " << (frameCount * clock.GetElapsedTime()) << " FPS" << std::endl;
            frameCount = 0;
            clock.Reset();
        }

        //Draw...
        game.draw();

        // Finally, display the rendered frame on screen
        application.Display();
    }

    return EXIT_SUCCESS;
}