Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/trunk/src/modules/tetris/Tetris.cc @ 12412

Last change on this file since 12412 was 11716, checked in by landauf, 7 years ago

[Highscore_HS16] moved logic to compare old an new score to Highscore; fixed formatting in Gametypes

  • Property svn:eol-style set to native
File size: 16.5 KB
RevLine 
[8249]1/*
2 *   ORXONOX - the hottest 3D action shooter ever to exist
3 *                    > www.orxonox.net <
4 *
5 *
6 *   License notice:
7 *
8 *   This program is free software; you can redistribute it and/or
9 *   modify it under the terms of the GNU General Public License
10 *   as published by the Free Software Foundation; either version 2
11 *   of the License, or (at your option) any later version.
12 *
13 *   This program is distributed in the hope that it will be useful,
14 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
15 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 *   GNU General Public License for more details.
17 *
18 *   You should have received a copy of the GNU General Public License
19 *   along with this program; if not, write to the Free Software
20 *   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
21 *
22 *   Author:
23 *      ...
24 *   Co-authors:
[9348]25 *      Johannes Ritz
[8249]26 *
[9348]27 *
28 *
29 *
30 *TASK c) end the game in a nicer way
31 *TASK d) save the highscore
32 *TASK e) eye candy
[8249]33 */
34
35/**
36    @file Tetris.cc
37    @brief Implementation of the Tetris class.
38*/
39
40#include "Tetris.h"
[11356]41#include "Highscore.h"
[8249]42
43#include "core/CoreIncludes.h"
44#include "core/EventIncludes.h"
45#include "core/command/Executor.h"
46
47#include "gamestates/GSLevel.h"
48
49#include "TetrisCenterpoint.h"
50#include "TetrisStone.h"
[9348]51#include "TetrisBrick.h"
[8249]52#include "infos/PlayerInfo.h"
[9801]53#include <cmath>
[8249]54
55namespace orxonox
56{
57
[9667]58    RegisterUnloadableClass(Tetris);
[8249]59
60    /**
61    @brief
62        Constructor. Registers and initializes the object.
[9348]63    @ingroup Tetris
[8249]64    */
[9667]65    Tetris::Tetris(Context* context) : Deathmatch(context)
[8249]66    {
67        RegisterObject(Tetris);
68
[11071]69        this->activeBrick_ = nullptr;
[8249]70
71        // Pre-set the timer, but don't start it yet.
[9348]72        this->starttimer_.setTimer(1.0, false, createExecutor(createFunctor(&Tetris::startBrick, this)));
[8249]73        this->starttimer_.stopTimer();
[8564]74
[11071]75        this->player_ = nullptr;
[9348]76        this->setHUDTemplate("TetrisHUD");
[11071]77        this->futureBrick_ = nullptr;
[8249]78    }
79
80    /**
81    @brief
82        Destructor. Cleans up, if initialized.
83    */
84    Tetris::~Tetris()
85    {
86        if (this->isInitialized())
87            this->cleanup();
88    }
89
90    /**
91    @brief
92        Cleans up the Gametype.
93    */
94    void Tetris::cleanup()
95    {
[9348]96        if (this->activeBrick_)
97        {
98            this->activeBrick_->destroy();
[11071]99            this->activeBrick_ = nullptr;
[9348]100        }
101        if (this->futureBrick_)
102        {
103            this->futureBrick_->destroy();
[11071]104            this->futureBrick_ = nullptr;
[9348]105        }
[8564]106
[11071]107        for (TetrisStone* stone : this->stones_)
108            stone->destroy();
[9348]109        this->stones_.clear();
[8249]110    }
[8537]111
[8249]112    void Tetris::tick(float dt)
113    {
114        SUPER(Tetris, tick, dt);
[8537]115
[11071]116        if((this->activeBrick_ != nullptr)&&(!this->hasEnded()))
[8537]117        {
[9348]118            if(!this->isValidBrickPosition(this->activeBrick_))
[8563]119            {
[9348]120                for (unsigned int i = 0; i < this->activeBrick_->getNumberOfStones(); i++)
121                    this->stones_.push_back(this->activeBrick_->getStone(i));
122                this->activeBrick_->setVelocity(Vector3::ZERO);
123                this->activeBrick_->releaseStones(this->center_);
124                this->findFullRows();
125                this->startBrick();
[8563]126            }
[9803]127        } 
[8537]128    }
129
[8566]130    bool Tetris::isValidMove(TetrisStone* stone, const Vector3& position)
[8537]131    {
132        assert(stone);
[8563]133
[8537]134        if(position.x < this->center_->getStoneSize()/2.0)  //!< If the stone touches the left edge of the level
[8566]135            return false;
[8537]136        else if(position.x > (this->center_->getWidth()-0.5)*this->center_->getStoneSize()) //!< If the stone touches the right edge of the level
[8566]137            return false;
[8488]138
[11071]139        for(TetrisStone* someStone : this->stones_)
[8563]140        {
[11071]141            const Vector3& currentStonePosition = someStone->getPosition(); //!< Saves the position of the currentStone
[8563]142
[11083]143            if((position.x == currentStonePosition.x) && std::abs(position.y-currentStonePosition.y) < this->center_->getStoneSize())
[8566]144                return false;
[8565]145        }
146
[8566]147        return true;
[8565]148    }
149
[9348]150    /**
151    @brief
152        Check for each stone in a brick if it is moved the right way.
153    */
154    bool Tetris::isValidMove(TetrisBrick* brick, const Vector3& position, bool isRotation = false)
155    {
156        assert(brick);
157
158        for (unsigned int i = 0; i < brick->getNumberOfStones(); i++ )
159        {
160            TetrisStone* stone = brick->getStone(i);
161            Vector3 stonePosition; //the current stone's offset to position
162            if(isRotation)
163                stonePosition = rotateVector(stone->getPosition(), brick->getRotationCount()+1);
164            else
165                stonePosition = rotateVector(stone->getPosition(), brick->getRotationCount());
166
167            if(! this->isValidMove(stone, position + stonePosition ))
168            {
169                return false;
170            }
171
172            //catch illegal rotation (such that collisions with ground are not permitted)
173            if(isRotation)
174            {
175                if((position + stonePosition).y < this->center_->getStoneSize()/2.0f) //!< If the stone has reached the bottom of the level
176                {
177                    return false;
178                }
179            }
180        }
181        return true;
182
183    }
184
185
[9802]186    /**
187     * @brief Returns true, if NO collision was detected.
188     * Else returns false and the active brick is repositioned as side-effect.
189     */
190    bool Tetris::checkStoneStoneCollision(TetrisStone* stone, const Vector3& position)
[8565]191    {
192        assert(stone);
193
[9348]194        // check for collisions with all stones
[11071]195        for(TetrisStone* someStone : this->stones_)
[8565]196        {
[9348]197            //Vector3 currentStonePosition = rotateVector((*it)->getPosition(), this->activeBrick_->getRotationCount());
[11071]198            const Vector3& currentStonePosition = someStone->getPosition(); //!< Saves the position of the currentStone
[8565]199
[9348]200            //filter out cases where the falling stone is already below a steady stone
201            if(position.y < currentStonePosition.y - this->center_->getStoneSize()/2.0f)
202                continue;
[8565]203            if((position.x == currentStonePosition.x) && (position.y < currentStonePosition.y + this->center_->getStoneSize()))
[8563]204            {
[9348]205                float y_offset = static_cast<int>((this->activeBrick_->getPosition().y-currentStonePosition.y+10)/10)*10 + currentStonePosition.y;
206                if(y_offset < 0) //filter out extreme cases (very rare bug)
207                    y_offset = 0;
208                this->activeBrick_->setPosition(Vector3(this->activeBrick_->getPosition().x, y_offset, this->activeBrick_->getPosition().z));
[8567]209                return false;
[8563]210            }// This case applies if the stones overlap partially vertically
211        }
212
[9802]213        return true;
214    }
215   
216    /**
217     * @brief Returns true, if NO collision was detected.
218     * Else returns false and the active brick is repositioned as side-effect.
219     */
220    bool Tetris::checkStoneBottomCollision(TetrisStone* stone, const Vector3& position)
221    {
222        assert(stone);
[8661]223        if(position.y < this->center_->getStoneSize()/2.0f) //!< If the stone has reached the bottom of the level
224        {
[11083]225            float baseOffset = std::abs(stone->getPosition().y);
[9801]226            if (this->activeBrick_->getRotationCount() == 1 || this->activeBrick_->getRotationCount() == 3)
[11083]227                baseOffset = std::abs(stone->getPosition().x);
[9801]228            float yOffset = baseOffset + this->center_->getStoneSize()/2.0f;//calculate offset
[9348]229            if(yOffset < 0) //catch brake-throughs
230                yOffset = 0;
231            this->activeBrick_->setPosition(Vector3(this->activeBrick_->getPosition().x, yOffset, this->activeBrick_->getPosition().z));
[8661]232            return false;
233        }
[8567]234        return true;
[8249]235    }
[9802]236   
[9348]237    /**
238     * @brief This function determines wether a brick touches another brick or the ground.
239     *
240     */
241    bool Tetris::isValidBrickPosition(TetrisBrick* brick)
242    {
243        assert(brick);
[8249]244
[9348]245        const Vector3& brickPosition = this->activeBrick_->getPosition();
246
247        // check all stones in the brick
248        for (unsigned int i = 0; i < brick->getNumberOfStones(); i++ )
249        {
250            TetrisStone* stone = brick->getStone(i);
251            const Vector3& stonePosition = rotateVector(stone->getPosition(), brick->getRotationCount());
[9802]252            if(! this->checkStoneStoneCollision(stone, brickPosition + stonePosition) )
[9348]253            {
254                return false;
255            }
256        }
[9802]257        // check all stones in the brick
258        for (unsigned int i = 0; i < brick->getNumberOfStones(); i++ )
259        {
260            TetrisStone* stone = brick->getStone(i);
261            const Vector3& stonePosition = rotateVector(stone->getPosition(), brick->getRotationCount());
262            if(! this->checkStoneBottomCollision(stone, brickPosition + stonePosition) )
263            {
264                return false;
265            }
266        }
267       
[9348]268        return true;
269    }
270
[8249]271    /**
272    @brief
[9348]273        A Vector3 is rolled 90 * degrees * amount (anticlockwise rotation)
274    */
275    Vector3 Tetris::rotateVector(Vector3 position, unsigned int amount)
276    {
277        float temp = 0;
278        for(unsigned int i = 0; i < amount; i++)
279        {
280            temp = position.x;
281            position.x = -position.y;
282            position.y = temp;
283        }
284        return position;
285    }
286
287    /**
288    @brief
[8249]289        Starts the Tetris minigame.
290    */
291    void Tetris::start()
292    {
[11071]293        if (this->center_ != nullptr) // There needs to be a TetrisCenterpoint, i.e. the area the game takes place.
[8249]294        {
[9348]295            // Create the first brick.
296            this->createBrick();
[8249]297        }
298        else // If no centerpoint was specified, an error is thrown and the level is exited.
299        {
[8858]300            orxout(internal_error) << "Tetris: No Centerpoint specified." << endl;
[8249]301            GSLevel::startMainMenu();
302            return;
303        }
304
[8537]305        // Start the timer. After it has expired the stone is started.
[8249]306        this->starttimer_.startTimer();
307
308        // Set variable to temporarily force the player to spawn.
309        bool temp = this->bForceSpawn_;
310        this->bForceSpawn_ = true;
311
312        // Call start for the parent class.
313        Deathmatch::start();
314
315        // Reset the variable.
316        this->bForceSpawn_ = temp;
317    }
318
319    /**
320    @brief
321        Ends the Tetris minigame.
322    */
323    void Tetris::end()
324    {
[9348]325        this->activeBrick_->setVelocity(Vector3::ZERO);
[11071]326        if(this->activeBrick_ != nullptr)
[9348]327        {
328            this->player_->stopControl();
329        }
[11716]330        if (Highscore::exists())
331        {
332            int score = this->getScore(this->getPlayer());
333            Highscore::getInstance().storeScore("Tetris", score, this->getPlayer());
334        }
[8249]335        this->cleanup();
336
337        // Call end for the parent class.
338        Deathmatch::end();
339    }
340
341    /**
342    @brief
343        Spawns player.
344    */
345    void Tetris::spawnPlayersIfRequested()
346    {
347        // Spawn a human player.
[11071]348        for (const auto& mapEntry : this->players_)
349            if (mapEntry.first->isHumanPlayer() && (mapEntry.first->isReadyToSpawn() || this->bForceSpawn_))
350                this->spawnPlayer(mapEntry.first);
[8249]351    }
[9833]352   
353    bool Tetris::playerLeft(PlayerInfo* player)
354    {
355        bool left = Gametype::playerLeft(player);
356        if(player && player->isHumanPlayer())
357        {
[11071]358            if(this->activeBrick_ != nullptr)
[9834]359            {
360                this->player_->stopControl();
361            }
362            this->cleanup();
[9833]363        }
364        return left;
365    }
[8249]366
367    /**
368    @brief
369        Spawns the input player.
370    @param player
371        The player to be spawned.
372    */
373    void Tetris::spawnPlayer(PlayerInfo* player)
374    {
375        assert(player);
376
[11071]377        if(this->player_ == nullptr)
[8249]378        {
379            this->player_ = player;
380            this->players_[player].state_ = PlayerState::Alive;
381        }
382    }
383
[9348]384
385
386    void Tetris::startBrick(void)
[8249]387    {
[11071]388        if(this->player_ == nullptr)
[8249]389            return;
[8680]390
391        unsigned int cameraIndex = 0;
[11071]392        if(this->activeBrick_ != nullptr)
[8680]393        {
394            // Get camera settings
[9348]395            cameraIndex = this->activeBrick_->getCurrentCameraIndex();
[8249]396            this->player_->stopControl();
[9348]397            // destroy old active brick
398            this->activeBrick_->destroy();
[8680]399        }
[9348]400
401        // Make the last brick to be created the active brick.
402        this->activeBrick_ = this->futureBrick_;
[11071]403        this->futureBrick_ = nullptr;
[9348]404
405        // set its position
406        this->player_->startControl(this->activeBrick_);
407        float xPos = (this->center_->getWidth()/2 + ((this->center_->getWidth() % 2)*2-1)/2.0f)*this->center_->getStoneSize();
408        float yPos = (this->center_->getHeight()-0.5f)*this->center_->getStoneSize();
409        this->activeBrick_->setPosition(xPos, yPos, 0.0f);
410        this->activeBrick_->setVelocity(0.0f, -this->center_->getStoneSpeed(), 0.0f);
411        this->activeBrick_->setCameraPosition(cameraIndex);
412
413        // create a new future brick
414        this->createBrick();
415
416        // check if the new brick is in a valid position, otherwise end the game
417        if (!this->isValidBrickPosition(this->activeBrick_))
418            this->end();
[8249]419    }
420
[9348]421    void Tetris::createBrick(void)             //TODO: random rotation offset between 0 and 3 (times 90°)
[8249]422    {
[9348]423        // create new futureBrick_
[9667]424        this->futureBrick_ = new TetrisBrick(this->center_->getContext());
[9348]425
426
[8249]427        // Apply the stone template to the stone.
[9348]428        this->futureBrick_->addTemplate(this->center_->getBrickTemplate());
429
430        // Attach the brick to the Centerpoint and set the position of the brick to be at the left side.
431        this->center_->attach(this->futureBrick_);
432        float xPos = (this->center_->getWidth()*1.6f + ((this->center_->getWidth() % 2)*2-1)/2.0f)*this->center_->getStoneSize();
433        float yPos = (this->center_->getHeight()-5.1f)*this->center_->getStoneSize();
[9801]434       
[9348]435        this->futureBrick_->setPosition(xPos, yPos, 0.0f);
436        this->futureBrick_->setGame(this);
[8249]437    }
438
[9348]439
[8249]440    /**
441    @brief
442        Get the player.
443    @return
[11071]444        Returns a pointer to the player. If there is no player, nullptr is returned.
[8249]445    */
446    PlayerInfo* Tetris::getPlayer(void) const
447    {
448        return this->player_;
449    }
450
[9348]451    /*TetrisCenterpoint* Tetris::getCenterpoint(void) const
452    {
453        return this->center_;
454    }*/
455
[8537]456    /**
457    @brief Set the TetrisCenterpoint (the playing field).
458    @param center A pointer to the TetrisCenterpoint to be set.
459    */
460    void Tetris::setCenterpoint(TetrisCenterpoint* center)
461    {
462        this->center_ = center;
463    }
464
[9348]465    /**
466    @brief Check each row if it is full. Removes all full rows. Update
467    @brief Manages score.
468    */
469    void Tetris::findFullRows()
470    {
471        unsigned int correctPosition = 0;
472        unsigned int stonesPerRow = 0;
473        for (unsigned int row = 0; row < this->center_->getHeight(); row++)
474        {
475            stonesPerRow = 0;
[11071]476            for(std::list<StrongPtr<TetrisStone>>::iterator it = this->stones_.begin(); it != this->stones_.end(); )
[9348]477            {
[11071]478                std::list<StrongPtr<TetrisStone>>::iterator it_temp = it++;
[9348]479                correctPosition = static_cast<unsigned int>(((*it_temp)->getPosition().y - 5)/this->center_->getStoneSize());
480                if(correctPosition == row)
481                {
482                    stonesPerRow++;
483                    if(stonesPerRow == this->center_->getWidth())
484                    {
485                        clearRow(row);
486                        row--; //the row counter has to be decreased in order to detect multiple rows!
487                        this->playerScored(this->player_);// add points
488                        //increase the stone's speed
489                        this->center_->setStoneSpeed(this->center_->getStoneSpeed()+1.0f);
490                    }
491                }
492            }
493        }
494    }
495
496    void Tetris::clearRow(unsigned int row)
497    {// clear the full row
[11071]498        for(std::list<StrongPtr<TetrisStone>>::iterator it = this->stones_.begin(); it != this->stones_.end(); )
[9348]499        {
500            if(static_cast<unsigned int>(((*it)->getPosition().y - 5)/this->center_->getStoneSize()) == row)
501            {
502                (*it)->destroy();
503                this->stones_.erase(it++);
504            }
505            else
506                ++it;
507        }
508      // adjust height of stones above the deleted row //TODO: check if this could be a source of a bug.
[11071]509        for(TetrisStone* stone : this->stones_)
[9348]510        {
[11071]511            if(static_cast<unsigned int>((stone->getPosition().y - 5)/this->center_->getStoneSize()) > row)
512                stone->setPosition(stone->getPosition()-Vector3(0,10,0));
[9348]513        }
514
515    }
516
517
[8249]518}
Note: See TracBrowser for help on using the repository browser.